diff --git a/.gitignore b/.gitignore index 171615f97..45faf757d 100644 --- a/.gitignore +++ b/.gitignore @@ -80,4 +80,6 @@ docs/api # Rider .idea/ -.idea_modules/ \ No newline at end of file +.idea_modules/node_modules/ +package-lock.json +package.json diff --git a/node_modules/.bin/conformance b/node_modules/.bin/conformance new file mode 120000 index 000000000..477ea6a13 --- /dev/null +++ b/node_modules/.bin/conformance @@ -0,0 +1 @@ +../@modelcontextprotocol/conformance/dist/index.js \ No newline at end of file diff --git a/node_modules/.bin/node-which b/node_modules/.bin/node-which new file mode 120000 index 000000000..6f8415ec5 --- /dev/null +++ b/node_modules/.bin/node-which @@ -0,0 +1 @@ +../which/bin/node-which \ No newline at end of file diff --git a/node_modules/.bin/yaml b/node_modules/.bin/yaml new file mode 120000 index 000000000..036832479 --- /dev/null +++ b/node_modules/.bin/yaml @@ -0,0 +1 @@ +../yaml/bin.mjs \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 000000000..aabb7825a --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,1170 @@ +{ + "name": "csharp-sdk", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@hono/node-server": { + "version": "1.19.9", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.9.tgz", + "integrity": "sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw==", + "license": "MIT", + "engines": { + "node": ">=18.14.1" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@modelcontextprotocol/conformance": { + "version": "0.1.11", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/conformance/-/conformance-0.1.11.tgz", + "integrity": "sha512-cqayAmyTUhnRsyrOuTqZ+kCc2w/goppxnqZ+XrOsVd/M25No/HiZ1GbZI92sFA7ONYzonqRja56G9IiISIns3A==", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/sdk": "^1.25.2", + "commander": "^14.0.2", + "eventsource-parser": "^3.0.6", + "express": "^5.1.0", + "jose": "^6.1.2", + "undici": "^7.19.0", + "yaml": "^2.8.2", + "zod": "^3.25.76" + }, + "bin": { + "conformance": "dist/index.js" + } + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.25.3", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.25.3.tgz", + "integrity": "sha512-vsAMBMERybvYgKbg/l4L1rhS7VXV1c0CtyJg72vwxONVX0l4ZfKVAnZEWTQixJGTzKnELjQ59e4NbdFDALRiAQ==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.0.1", + "express-rate-limit": "^7.5.0", + "jose": "^6.1.1", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/body-parser": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", + "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.1", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/commander": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.2.tgz", + "integrity": "sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "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==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "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==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "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==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "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==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz", + "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "7.5.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.1.tgz", + "integrity": "sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "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==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.11.5", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.11.5.tgz", + "integrity": "sha512-WemPi9/WfyMwZs+ZUXdiwcCh9Y+m7L+8vki9MzDw3jJ+W9Lc+12HGsd368Qc1vZi1xwW8BWMMsnK5efYKPdt4g==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "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==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.1.3.tgz", + "integrity": "sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "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==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "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==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "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==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", + "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "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==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.14.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", + "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "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==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "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==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/undici": { + "version": "7.19.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.19.1.tgz", + "integrity": "sha512-Gpq0iNm5M6cQWlyHQv9MV+uOj1jWk7LpkoE5vSp/7zjb4zMdAcUD+VL5y0nH4p9EbUklq00eVIIX/XcDHzu5xg==", + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "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==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/yaml": { + "version": "2.8.2", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.2.tgz", + "integrity": "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.1", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz", + "integrity": "sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25 || ^4" + } + } + } +} diff --git a/node_modules/@hono/node-server/README.md b/node_modules/@hono/node-server/README.md new file mode 100644 index 000000000..e0c5f796f --- /dev/null +++ b/node_modules/@hono/node-server/README.md @@ -0,0 +1,357 @@ +# Node.js Adapter for Hono + +This adapter `@hono/node-server` allows you to run your Hono application on Node.js. +Initially, Hono wasn't designed for Node.js, but with this adapter, you can now use Hono on Node.js. +It utilizes web standard APIs implemented in Node.js version 18 or higher. + +## Benchmarks + +Hono is 3.5 times faster than Express. + +Express: + +```txt +$ bombardier -d 10s --fasthttp http://localhost:3000/ + +Statistics Avg Stdev Max + Reqs/sec 16438.94 1603.39 19155.47 + Latency 7.60ms 7.51ms 559.89ms + HTTP codes: + 1xx - 0, 2xx - 164494, 3xx - 0, 4xx - 0, 5xx - 0 + others - 0 + Throughput: 4.55MB/s +``` + +Hono + `@hono/node-server`: + +```txt +$ bombardier -d 10s --fasthttp http://localhost:3000/ + +Statistics Avg Stdev Max + Reqs/sec 58296.56 5512.74 74403.56 + Latency 2.14ms 1.46ms 190.92ms + HTTP codes: + 1xx - 0, 2xx - 583059, 3xx - 0, 4xx - 0, 5xx - 0 + others - 0 + Throughput: 12.56MB/s +``` + +## Requirements + +It works on Node.js versions greater than 18.x. The specific required Node.js versions are as follows: + +- 18.x => 18.14.1+ +- 19.x => 19.7.0+ +- 20.x => 20.0.0+ + +Essentially, you can simply use the latest version of each major release. + +## Installation + +You can install it from the npm registry with `npm` command: + +```sh +npm install @hono/node-server +``` + +Or use `yarn`: + +```sh +yarn add @hono/node-server +``` + +## Usage + +Just import `@hono/node-server` at the top and write the code as usual. +The same code that runs on Cloudflare Workers, Deno, and Bun will work. + +```ts +import { serve } from '@hono/node-server' +import { Hono } from 'hono' + +const app = new Hono() +app.get('/', (c) => c.text('Hono meets Node.js')) + +serve(app, (info) => { + console.log(`Listening on http://localhost:${info.port}`) // Listening on http://localhost:3000 +}) +``` + +For example, run it using `ts-node`. Then an HTTP server will be launched. The default port is `3000`. + +```sh +ts-node ./index.ts +``` + +Open `http://localhost:3000` with your browser. + +## Options + +### `port` + +```ts +serve({ + fetch: app.fetch, + port: 8787, // Port number, default is 3000 +}) +``` + +### `createServer` + +```ts +import { createServer } from 'node:https' +import fs from 'node:fs' + +//... + +serve({ + fetch: app.fetch, + createServer: createServer, + serverOptions: { + key: fs.readFileSync('test/fixtures/keys/agent1-key.pem'), + cert: fs.readFileSync('test/fixtures/keys/agent1-cert.pem'), + }, +}) +``` + +### `overrideGlobalObjects` + +The default value is `true`. The Node.js Adapter rewrites the global Request/Response and uses a lightweight Request/Response to improve performance. If you don't want to do that, set `false`. + +```ts +serve({ + fetch: app.fetch, + overrideGlobalObjects: false, +}) +``` + +### `autoCleanupIncoming` + +The default value is `true`. The Node.js Adapter automatically cleans up (explicitly call `destroy()` method) if application is not finished to consume the incoming request. If you don't want to do that, set `false`. + +If the application accepts connections from arbitrary clients, this cleanup must be done otherwise incomplete requests from clients may cause the application to stop responding. If your application only accepts connections from trusted clients, such as in a reverse proxy environment and there is no process that returns a response without reading the body of the POST request all the way through, you can improve performance by setting it to `false`. + +```ts +serve({ + fetch: app.fetch, + autoCleanupIncoming: false, +}) +``` + +## Middleware + +Most built-in middleware also works with Node.js. +Read [the documentation](https://hono.dev/middleware/builtin/basic-auth) and use the Middleware of your liking. + +```ts +import { serve } from '@hono/node-server' +import { Hono } from 'hono' +import { prettyJSON } from 'hono/pretty-json' + +const app = new Hono() + +app.get('*', prettyJSON()) +app.get('/', (c) => c.json({ 'Hono meets': 'Node.js' })) + +serve(app) +``` + +## Serve Static Middleware + +Use Serve Static Middleware that has been created for Node.js. + +```ts +import { serveStatic } from '@hono/node-server/serve-static' + +//... + +app.use('/static/*', serveStatic({ root: './' })) +``` + +If using a relative path, `root` will be relative to the current working directory from which the app was started. + +This can cause confusion when running your application locally. + +Imagine your project structure is: + +``` +my-hono-project/ + src/ + index.ts + static/ + index.html +``` + +Typically, you would run your app from the project's root directory (`my-hono-project`), +so you would need the following code to serve the `static` folder: + +```ts +app.use('/static/*', serveStatic({ root: './static' })) +``` + +Notice that `root` here is not relative to `src/index.ts`, rather to `my-hono-project`. + +### Options + +#### `rewriteRequestPath` + +If you want to serve files in `./.foojs` with the request path `/__foo/*`, you can write like the following. + +```ts +app.use( + '/__foo/*', + serveStatic({ + root: './.foojs/', + rewriteRequestPath: (path: string) => path.replace(/^\/__foo/, ''), + }) +) +``` + +#### `onFound` + +You can specify handling when the requested file is found with `onFound`. + +```ts +app.use( + '/static/*', + serveStatic({ + // ... + onFound: (_path, c) => { + c.header('Cache-Control', `public, immutable, max-age=31536000`) + }, + }) +) +``` + +#### `onNotFound` + +The `onNotFound` is useful for debugging. You can write a handle for when a file is not found. + +```ts +app.use( + '/static/*', + serveStatic({ + root: './non-existent-dir', + onNotFound: (path, c) => { + console.log(`${path} is not found, request to ${c.req.path}`) + }, + }) +) +``` + +#### `precompressed` + +The `precompressed` option checks if files with extensions like `.br` or `.gz` are available and serves them based on the `Accept-Encoding` header. It prioritizes Brotli, then Zstd, and Gzip. If none are available, it serves the original file. + +```ts +app.use( + '/static/*', + serveStatic({ + precompressed: true, + }) +) +``` + +## ConnInfo Helper + +You can use the [ConnInfo Helper](https://hono.dev/docs/helpers/conninfo) by importing `getConnInfo` from `@hono/node-server/conninfo`. + +```ts +import { getConnInfo } from '@hono/node-server/conninfo' + +app.get('/', (c) => { + const info = getConnInfo(c) // info is `ConnInfo` + return c.text(`Your remote address is ${info.remote.address}`) +}) +``` + +## Accessing Node.js API + +You can access the Node.js API from `c.env` in Node.js. For example, if you want to specify a type, you can write the following. + +```ts +import { serve } from '@hono/node-server' +import type { HttpBindings } from '@hono/node-server' +import { Hono } from 'hono' + +const app = new Hono<{ Bindings: HttpBindings }>() + +app.get('/', (c) => { + return c.json({ + remoteAddress: c.env.incoming.socket.remoteAddress, + }) +}) + +serve(app) +``` + +The APIs that you can get from `c.env` are as follows. + +```ts +type HttpBindings = { + incoming: IncomingMessage + outgoing: ServerResponse +} + +type Http2Bindings = { + incoming: Http2ServerRequest + outgoing: Http2ServerResponse +} +``` + +## Direct response from Node.js API + +You can directly respond to the client from the Node.js API. +In that case, the response from Hono should be ignored, so return `RESPONSE_ALREADY_SENT`. + +> [!NOTE] +> This feature can be used when migrating existing Node.js applications to Hono, but we recommend using Hono's API for new applications. + +```ts +import { serve } from '@hono/node-server' +import type { HttpBindings } from '@hono/node-server' +import { RESPONSE_ALREADY_SENT } from '@hono/node-server/utils/response' +import { Hono } from 'hono' + +const app = new Hono<{ Bindings: HttpBindings }>() + +app.get('/', (c) => { + const { outgoing } = c.env + outgoing.writeHead(200, { 'Content-Type': 'text/plain' }) + outgoing.end('Hello World\n') + + return RESPONSE_ALREADY_SENT +}) + +serve(app) +``` + +## Listen to a UNIX domain socket + +You can configure the HTTP server to listen to a UNIX domain socket instead of a TCP port. + +```ts +import { createAdaptorServer } from '@hono/node-server' + +// ... + +const socketPath ='/tmp/example.sock' + +const server = createAdaptorServer(app) +server.listen(socketPath, () => { + console.log(`Listening on ${socketPath}`) +}) +``` + +## Related projects + +- Hono - +- Hono GitHub repository - + +## Author + +Yusuke Wada + +## License + +MIT diff --git a/node_modules/@hono/node-server/dist/conninfo.d.mts b/node_modules/@hono/node-server/dist/conninfo.d.mts new file mode 100644 index 000000000..4c756d139 --- /dev/null +++ b/node_modules/@hono/node-server/dist/conninfo.d.mts @@ -0,0 +1,10 @@ +import { GetConnInfo } from 'hono/conninfo'; + +/** + * ConnInfo Helper for Node.js + * @param c Context + * @returns ConnInfo + */ +declare const getConnInfo: GetConnInfo; + +export { getConnInfo }; diff --git a/node_modules/@hono/node-server/dist/conninfo.d.ts b/node_modules/@hono/node-server/dist/conninfo.d.ts new file mode 100644 index 000000000..4c756d139 --- /dev/null +++ b/node_modules/@hono/node-server/dist/conninfo.d.ts @@ -0,0 +1,10 @@ +import { GetConnInfo } from 'hono/conninfo'; + +/** + * ConnInfo Helper for Node.js + * @param c Context + * @returns ConnInfo + */ +declare const getConnInfo: GetConnInfo; + +export { getConnInfo }; diff --git a/node_modules/@hono/node-server/dist/conninfo.js b/node_modules/@hono/node-server/dist/conninfo.js new file mode 100644 index 000000000..131934dbc --- /dev/null +++ b/node_modules/@hono/node-server/dist/conninfo.js @@ -0,0 +1,42 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/conninfo.ts +var conninfo_exports = {}; +__export(conninfo_exports, { + getConnInfo: () => getConnInfo +}); +module.exports = __toCommonJS(conninfo_exports); +var getConnInfo = (c) => { + const bindings = c.env.server ? c.env.server : c.env; + const address = bindings.incoming.socket.remoteAddress; + const port = bindings.incoming.socket.remotePort; + const family = bindings.incoming.socket.remoteFamily; + return { + remote: { + address, + port, + addressType: family === "IPv4" ? "IPv4" : family === "IPv6" ? "IPv6" : void 0 + } + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + getConnInfo +}); diff --git a/node_modules/@hono/node-server/dist/conninfo.mjs b/node_modules/@hono/node-server/dist/conninfo.mjs new file mode 100644 index 000000000..ab3cc95ba --- /dev/null +++ b/node_modules/@hono/node-server/dist/conninfo.mjs @@ -0,0 +1,17 @@ +// src/conninfo.ts +var getConnInfo = (c) => { + const bindings = c.env.server ? c.env.server : c.env; + const address = bindings.incoming.socket.remoteAddress; + const port = bindings.incoming.socket.remotePort; + const family = bindings.incoming.socket.remoteFamily; + return { + remote: { + address, + port, + addressType: family === "IPv4" ? "IPv4" : family === "IPv6" ? "IPv6" : void 0 + } + }; +}; +export { + getConnInfo +}; diff --git a/node_modules/@hono/node-server/dist/globals.d.mts b/node_modules/@hono/node-server/dist/globals.d.mts new file mode 100644 index 000000000..c9247d453 --- /dev/null +++ b/node_modules/@hono/node-server/dist/globals.d.mts @@ -0,0 +1,2 @@ + +export { } diff --git a/node_modules/@hono/node-server/dist/globals.d.ts b/node_modules/@hono/node-server/dist/globals.d.ts new file mode 100644 index 000000000..c9247d453 --- /dev/null +++ b/node_modules/@hono/node-server/dist/globals.d.ts @@ -0,0 +1,2 @@ + +export { } diff --git a/node_modules/@hono/node-server/dist/globals.js b/node_modules/@hono/node-server/dist/globals.js new file mode 100644 index 000000000..4704d2c00 --- /dev/null +++ b/node_modules/@hono/node-server/dist/globals.js @@ -0,0 +1,29 @@ +"use strict"; +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 __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 +)); + +// src/globals.ts +var import_node_crypto = __toESM(require("crypto")); +if (typeof global.crypto === "undefined") { + global.crypto = import_node_crypto.default; +} diff --git a/node_modules/@hono/node-server/dist/globals.mjs b/node_modules/@hono/node-server/dist/globals.mjs new file mode 100644 index 000000000..45daa06f6 --- /dev/null +++ b/node_modules/@hono/node-server/dist/globals.mjs @@ -0,0 +1,5 @@ +// src/globals.ts +import crypto from "crypto"; +if (typeof global.crypto === "undefined") { + global.crypto = crypto; +} diff --git a/node_modules/@hono/node-server/dist/index.d.mts b/node_modules/@hono/node-server/dist/index.d.mts new file mode 100644 index 000000000..b9f383b1f --- /dev/null +++ b/node_modules/@hono/node-server/dist/index.d.mts @@ -0,0 +1,8 @@ +export { createAdaptorServer, serve } from './server.mjs'; +export { getRequestListener } from './listener.mjs'; +export { RequestError } from './request.mjs'; +export { Http2Bindings, HttpBindings, ServerType } from './types.mjs'; +import 'node:net'; +import 'node:http'; +import 'node:http2'; +import 'node:https'; diff --git a/node_modules/@hono/node-server/dist/index.d.ts b/node_modules/@hono/node-server/dist/index.d.ts new file mode 100644 index 000000000..7a03b52a2 --- /dev/null +++ b/node_modules/@hono/node-server/dist/index.d.ts @@ -0,0 +1,8 @@ +export { createAdaptorServer, serve } from './server.js'; +export { getRequestListener } from './listener.js'; +export { RequestError } from './request.js'; +export { Http2Bindings, HttpBindings, ServerType } from './types.js'; +import 'node:net'; +import 'node:http'; +import 'node:http2'; +import 'node:https'; diff --git a/node_modules/@hono/node-server/dist/index.js b/node_modules/@hono/node-server/dist/index.js new file mode 100644 index 000000000..5b00ade9d --- /dev/null +++ b/node_modules/@hono/node-server/dist/index.js @@ -0,0 +1,613 @@ +"use strict"; +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 __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 __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 +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + RequestError: () => RequestError, + createAdaptorServer: () => createAdaptorServer, + getRequestListener: () => getRequestListener, + serve: () => serve +}); +module.exports = __toCommonJS(src_exports); + +// src/server.ts +var import_node_http = require("http"); + +// src/listener.ts +var import_node_http22 = require("http2"); + +// src/request.ts +var import_node_http2 = require("http2"); +var import_node_stream = require("stream"); +var RequestError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "RequestError"; + } +}; +var toRequestError = (e) => { + if (e instanceof RequestError) { + return e; + } + return new RequestError(e.message, { cause: e }); +}; +var GlobalRequest = global.Request; +var Request = class extends GlobalRequest { + constructor(input, options) { + if (typeof input === "object" && getRequestCache in input) { + input = input[getRequestCache](); + } + if (typeof options?.body?.getReader !== "undefined") { + ; + options.duplex ??= "half"; + } + super(input, options); + } +}; +var newHeadersFromIncoming = (incoming) => { + const headerRecord = []; + const rawHeaders = incoming.rawHeaders; + for (let i = 0; i < rawHeaders.length; i += 2) { + const { [i]: key, [i + 1]: value } = rawHeaders; + if (key.charCodeAt(0) !== /*:*/ + 58) { + headerRecord.push([key, value]); + } + } + return new Headers(headerRecord); +}; +var wrapBodyStream = Symbol("wrapBodyStream"); +var newRequestFromIncoming = (method, url, headers, incoming, abortController) => { + const init = { + method, + headers, + signal: abortController.signal + }; + if (method === "TRACE") { + init.method = "GET"; + const req = new Request(url, init); + Object.defineProperty(req, "method", { + get() { + return "TRACE"; + } + }); + return req; + } + if (!(method === "GET" || method === "HEAD")) { + if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { + init.body = new ReadableStream({ + start(controller) { + controller.enqueue(incoming.rawBody); + controller.close(); + } + }); + } else if (incoming[wrapBodyStream]) { + let reader; + init.body = new ReadableStream({ + async pull(controller) { + try { + reader ||= import_node_stream.Readable.toWeb(incoming).getReader(); + const { done, value } = await reader.read(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + } catch (error) { + controller.error(error); + } + } + }); + } else { + init.body = import_node_stream.Readable.toWeb(incoming); + } + } + return new Request(url, init); +}; +var getRequestCache = Symbol("getRequestCache"); +var requestCache = Symbol("requestCache"); +var incomingKey = Symbol("incomingKey"); +var urlKey = Symbol("urlKey"); +var headersKey = Symbol("headersKey"); +var abortControllerKey = Symbol("abortControllerKey"); +var getAbortController = Symbol("getAbortController"); +var requestPrototype = { + get method() { + return this[incomingKey].method || "GET"; + }, + get url() { + return this[urlKey]; + }, + get headers() { + return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); + }, + [getAbortController]() { + this[getRequestCache](); + return this[abortControllerKey]; + }, + [getRequestCache]() { + this[abortControllerKey] ||= new AbortController(); + return this[requestCache] ||= newRequestFromIncoming( + this.method, + this[urlKey], + this.headers, + this[incomingKey], + this[abortControllerKey] + ); + } +}; +[ + "body", + "bodyUsed", + "cache", + "credentials", + "destination", + "integrity", + "mode", + "redirect", + "referrer", + "referrerPolicy", + "signal", + "keepalive" +].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + get() { + return this[getRequestCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + value: function() { + return this[getRequestCache]()[k](); + } + }); +}); +Object.setPrototypeOf(requestPrototype, Request.prototype); +var newRequest = (incoming, defaultHostname) => { + const req = Object.create(requestPrototype); + req[incomingKey] = incoming; + const incomingUrl = incoming.url || ""; + if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. + (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { + if (incoming instanceof import_node_http2.Http2ServerRequest) { + throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); + } + try { + const url2 = new URL(incomingUrl); + req[urlKey] = url2.href; + } catch (e) { + throw new RequestError("Invalid absolute URL", { cause: e }); + } + return req; + } + const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; + if (!host) { + throw new RequestError("Missing host header"); + } + let scheme; + if (incoming instanceof import_node_http2.Http2ServerRequest) { + scheme = incoming.scheme; + if (!(scheme === "http" || scheme === "https")) { + throw new RequestError("Unsupported scheme"); + } + } else { + scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; + } + const url = new URL(`${scheme}://${host}${incomingUrl}`); + if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) { + throw new RequestError("Invalid host header"); + } + req[urlKey] = url.href; + return req; +}; + +// src/response.ts +var responseCache = Symbol("responseCache"); +var getResponseCache = Symbol("getResponseCache"); +var cacheKey = Symbol("cache"); +var GlobalResponse = global.Response; +var Response2 = class _Response { + #body; + #init; + [getResponseCache]() { + delete this[cacheKey]; + return this[responseCache] ||= new GlobalResponse(this.#body, this.#init); + } + constructor(body, init) { + let headers; + this.#body = body; + if (init instanceof _Response) { + const cachedGlobalResponse = init[responseCache]; + if (cachedGlobalResponse) { + this.#init = cachedGlobalResponse; + this[getResponseCache](); + return; + } else { + this.#init = init.#init; + headers = new Headers(init.#init.headers); + } + } else { + this.#init = init; + } + if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { + headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" }; + this[cacheKey] = [init?.status || 200, body, headers]; + } + } + get headers() { + const cache = this[cacheKey]; + if (cache) { + if (!(cache[2] instanceof Headers)) { + cache[2] = new Headers(cache[2]); + } + return cache[2]; + } + return this[getResponseCache]().headers; + } + get status() { + return this[cacheKey]?.[0] ?? this[getResponseCache]().status; + } + get ok() { + const status = this.status; + return status >= 200 && status < 300; + } +}; +["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + get() { + return this[getResponseCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + value: function() { + return this[getResponseCache]()[k](); + } + }); +}); +Object.setPrototypeOf(Response2, GlobalResponse); +Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); + +// src/utils.ts +async function readWithoutBlocking(readPromise) { + return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); +} +function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { + const cancel = (error) => { + reader.cancel(error).catch(() => { + }); + }; + writable.on("close", cancel); + writable.on("error", cancel); + (currentReadPromise ?? reader.read()).then(flow, handleStreamError); + return reader.closed.finally(() => { + writable.off("close", cancel); + writable.off("error", cancel); + }); + function handleStreamError(error) { + if (error) { + writable.destroy(error); + } + } + function onDrain() { + reader.read().then(flow, handleStreamError); + } + function flow({ done, value }) { + try { + if (done) { + writable.end(); + } else if (!writable.write(value)) { + writable.once("drain", onDrain); + } else { + return reader.read().then(flow, handleStreamError); + } + } catch (e) { + handleStreamError(e); + } + } +} +function writeFromReadableStream(stream, writable) { + if (stream.locked) { + throw new TypeError("ReadableStream is locked."); + } else if (writable.destroyed) { + return; + } + return writeFromReadableStreamDefaultReader(stream.getReader(), writable); +} +var buildOutgoingHttpHeaders = (headers) => { + const res = {}; + if (!(headers instanceof Headers)) { + headers = new Headers(headers ?? void 0); + } + const cookies = []; + for (const [k, v] of headers) { + if (k === "set-cookie") { + cookies.push(v); + } else { + res[k] = v; + } + } + if (cookies.length > 0) { + res["set-cookie"] = cookies; + } + res["content-type"] ??= "text/plain; charset=UTF-8"; + return res; +}; + +// src/utils/response/constants.ts +var X_ALREADY_SENT = "x-hono-already-sent"; + +// src/globals.ts +var import_node_crypto = __toESM(require("crypto")); +if (typeof global.crypto === "undefined") { + global.crypto = import_node_crypto.default; +} + +// src/listener.ts +var outgoingEnded = Symbol("outgoingEnded"); +var handleRequestError = () => new Response(null, { + status: 400 +}); +var handleFetchError = (e) => new Response(null, { + status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 +}); +var handleResponseError = (e, outgoing) => { + const err = e instanceof Error ? e : new Error("unknown error", { cause: e }); + if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { + console.info("The user aborted a request."); + } else { + console.error(e); + if (!outgoing.headersSent) { + outgoing.writeHead(500, { "Content-Type": "text/plain" }); + } + outgoing.end(`Error: ${err.message}`); + outgoing.destroy(err); + } +}; +var flushHeaders = (outgoing) => { + if ("flushHeaders" in outgoing && outgoing.writable) { + outgoing.flushHeaders(); + } +}; +var responseViaCache = async (res, outgoing) => { + let [status, body, header] = res[cacheKey]; + if (header instanceof Headers) { + header = buildOutgoingHttpHeaders(header); + } + if (typeof body === "string") { + header["Content-Length"] = Buffer.byteLength(body); + } else if (body instanceof Uint8Array) { + header["Content-Length"] = body.byteLength; + } else if (body instanceof Blob) { + header["Content-Length"] = body.size; + } + outgoing.writeHead(status, header); + if (typeof body === "string" || body instanceof Uint8Array) { + outgoing.end(body); + } else if (body instanceof Blob) { + outgoing.end(new Uint8Array(await body.arrayBuffer())); + } else { + flushHeaders(outgoing); + await writeFromReadableStream(body, outgoing)?.catch( + (e) => handleResponseError(e, outgoing) + ); + } + ; + outgoing[outgoingEnded]?.(); +}; +var isPromise = (res) => typeof res.then === "function"; +var responseViaResponseObject = async (res, outgoing, options = {}) => { + if (isPromise(res)) { + if (options.errorHandler) { + try { + res = await res; + } catch (err) { + const errRes = await options.errorHandler(err); + if (!errRes) { + return; + } + res = errRes; + } + } else { + res = await res.catch(handleFetchError); + } + } + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); + if (res.body) { + const reader = res.body.getReader(); + const values = []; + let done = false; + let currentReadPromise = void 0; + if (resHeaderRecord["transfer-encoding"] !== "chunked") { + let maxReadCount = 2; + for (let i = 0; i < maxReadCount; i++) { + currentReadPromise ||= reader.read(); + const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => { + console.error(e); + done = true; + }); + if (!chunk) { + if (i === 1) { + await new Promise((resolve) => setTimeout(resolve)); + maxReadCount = 3; + continue; + } + break; + } + currentReadPromise = void 0; + if (chunk.value) { + values.push(chunk.value); + } + if (chunk.done) { + done = true; + break; + } + } + if (done && !("content-length" in resHeaderRecord)) { + resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0); + } + } + outgoing.writeHead(res.status, resHeaderRecord); + values.forEach((value) => { + ; + outgoing.write(value); + }); + if (done) { + outgoing.end(); + } else { + if (values.length === 0) { + flushHeaders(outgoing); + } + await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise); + } + } else if (resHeaderRecord[X_ALREADY_SENT]) { + } else { + outgoing.writeHead(res.status, resHeaderRecord); + outgoing.end(); + } + ; + outgoing[outgoingEnded]?.(); +}; +var getRequestListener = (fetchCallback, options = {}) => { + const autoCleanupIncoming = options.autoCleanupIncoming ?? true; + if (options.overrideGlobalObjects !== false && global.Request !== Request) { + Object.defineProperty(global, "Request", { + value: Request + }); + Object.defineProperty(global, "Response", { + value: Response2 + }); + } + return async (incoming, outgoing) => { + let res, req; + try { + req = newRequest(incoming, options.hostname); + let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD"; + if (!incomingEnded) { + ; + incoming[wrapBodyStream] = true; + incoming.on("end", () => { + incomingEnded = true; + }); + if (incoming instanceof import_node_http22.Http2ServerRequest) { + ; + outgoing[outgoingEnded] = () => { + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + outgoing.destroy(); + }); + } + }); + } + }; + } + } + outgoing.on("close", () => { + const abortController = req[abortControllerKey]; + if (abortController) { + if (incoming.errored) { + req[abortControllerKey].abort(incoming.errored.toString()); + } else if (!outgoing.writableFinished) { + req[abortControllerKey].abort("Client connection prematurely closed."); + } + } + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + }); + } + }); + } + }); + res = fetchCallback(req, { incoming, outgoing }); + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + } catch (e) { + if (!res) { + if (options.errorHandler) { + res = await options.errorHandler(req ? e : toRequestError(e)); + if (!res) { + return; + } + } else if (!req) { + res = handleRequestError(); + } else { + res = handleFetchError(e); + } + } else { + return handleResponseError(e, outgoing); + } + } + try { + return await responseViaResponseObject(res, outgoing, options); + } catch (e) { + return handleResponseError(e, outgoing); + } + }; +}; + +// src/server.ts +var createAdaptorServer = (options) => { + const fetchCallback = options.fetch; + const requestListener = getRequestListener(fetchCallback, { + hostname: options.hostname, + overrideGlobalObjects: options.overrideGlobalObjects, + autoCleanupIncoming: options.autoCleanupIncoming + }); + const createServer = options.createServer || import_node_http.createServer; + const server = createServer(options.serverOptions || {}, requestListener); + return server; +}; +var serve = (options, listeningListener) => { + const server = createAdaptorServer(options); + server.listen(options?.port ?? 3e3, options.hostname, () => { + const serverInfo = server.address(); + listeningListener && listeningListener(serverInfo); + }); + return server; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + RequestError, + createAdaptorServer, + getRequestListener, + serve +}); diff --git a/node_modules/@hono/node-server/dist/index.mjs b/node_modules/@hono/node-server/dist/index.mjs new file mode 100644 index 000000000..b30aec91c --- /dev/null +++ b/node_modules/@hono/node-server/dist/index.mjs @@ -0,0 +1,573 @@ +// src/server.ts +import { createServer as createServerHTTP } from "http"; + +// src/listener.ts +import { Http2ServerRequest as Http2ServerRequest2 } from "http2"; + +// src/request.ts +import { Http2ServerRequest } from "http2"; +import { Readable } from "stream"; +var RequestError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "RequestError"; + } +}; +var toRequestError = (e) => { + if (e instanceof RequestError) { + return e; + } + return new RequestError(e.message, { cause: e }); +}; +var GlobalRequest = global.Request; +var Request = class extends GlobalRequest { + constructor(input, options) { + if (typeof input === "object" && getRequestCache in input) { + input = input[getRequestCache](); + } + if (typeof options?.body?.getReader !== "undefined") { + ; + options.duplex ??= "half"; + } + super(input, options); + } +}; +var newHeadersFromIncoming = (incoming) => { + const headerRecord = []; + const rawHeaders = incoming.rawHeaders; + for (let i = 0; i < rawHeaders.length; i += 2) { + const { [i]: key, [i + 1]: value } = rawHeaders; + if (key.charCodeAt(0) !== /*:*/ + 58) { + headerRecord.push([key, value]); + } + } + return new Headers(headerRecord); +}; +var wrapBodyStream = Symbol("wrapBodyStream"); +var newRequestFromIncoming = (method, url, headers, incoming, abortController) => { + const init = { + method, + headers, + signal: abortController.signal + }; + if (method === "TRACE") { + init.method = "GET"; + const req = new Request(url, init); + Object.defineProperty(req, "method", { + get() { + return "TRACE"; + } + }); + return req; + } + if (!(method === "GET" || method === "HEAD")) { + if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { + init.body = new ReadableStream({ + start(controller) { + controller.enqueue(incoming.rawBody); + controller.close(); + } + }); + } else if (incoming[wrapBodyStream]) { + let reader; + init.body = new ReadableStream({ + async pull(controller) { + try { + reader ||= Readable.toWeb(incoming).getReader(); + const { done, value } = await reader.read(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + } catch (error) { + controller.error(error); + } + } + }); + } else { + init.body = Readable.toWeb(incoming); + } + } + return new Request(url, init); +}; +var getRequestCache = Symbol("getRequestCache"); +var requestCache = Symbol("requestCache"); +var incomingKey = Symbol("incomingKey"); +var urlKey = Symbol("urlKey"); +var headersKey = Symbol("headersKey"); +var abortControllerKey = Symbol("abortControllerKey"); +var getAbortController = Symbol("getAbortController"); +var requestPrototype = { + get method() { + return this[incomingKey].method || "GET"; + }, + get url() { + return this[urlKey]; + }, + get headers() { + return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); + }, + [getAbortController]() { + this[getRequestCache](); + return this[abortControllerKey]; + }, + [getRequestCache]() { + this[abortControllerKey] ||= new AbortController(); + return this[requestCache] ||= newRequestFromIncoming( + this.method, + this[urlKey], + this.headers, + this[incomingKey], + this[abortControllerKey] + ); + } +}; +[ + "body", + "bodyUsed", + "cache", + "credentials", + "destination", + "integrity", + "mode", + "redirect", + "referrer", + "referrerPolicy", + "signal", + "keepalive" +].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + get() { + return this[getRequestCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + value: function() { + return this[getRequestCache]()[k](); + } + }); +}); +Object.setPrototypeOf(requestPrototype, Request.prototype); +var newRequest = (incoming, defaultHostname) => { + const req = Object.create(requestPrototype); + req[incomingKey] = incoming; + const incomingUrl = incoming.url || ""; + if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. + (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { + if (incoming instanceof Http2ServerRequest) { + throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); + } + try { + const url2 = new URL(incomingUrl); + req[urlKey] = url2.href; + } catch (e) { + throw new RequestError("Invalid absolute URL", { cause: e }); + } + return req; + } + const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; + if (!host) { + throw new RequestError("Missing host header"); + } + let scheme; + if (incoming instanceof Http2ServerRequest) { + scheme = incoming.scheme; + if (!(scheme === "http" || scheme === "https")) { + throw new RequestError("Unsupported scheme"); + } + } else { + scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; + } + const url = new URL(`${scheme}://${host}${incomingUrl}`); + if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) { + throw new RequestError("Invalid host header"); + } + req[urlKey] = url.href; + return req; +}; + +// src/response.ts +var responseCache = Symbol("responseCache"); +var getResponseCache = Symbol("getResponseCache"); +var cacheKey = Symbol("cache"); +var GlobalResponse = global.Response; +var Response2 = class _Response { + #body; + #init; + [getResponseCache]() { + delete this[cacheKey]; + return this[responseCache] ||= new GlobalResponse(this.#body, this.#init); + } + constructor(body, init) { + let headers; + this.#body = body; + if (init instanceof _Response) { + const cachedGlobalResponse = init[responseCache]; + if (cachedGlobalResponse) { + this.#init = cachedGlobalResponse; + this[getResponseCache](); + return; + } else { + this.#init = init.#init; + headers = new Headers(init.#init.headers); + } + } else { + this.#init = init; + } + if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { + headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" }; + this[cacheKey] = [init?.status || 200, body, headers]; + } + } + get headers() { + const cache = this[cacheKey]; + if (cache) { + if (!(cache[2] instanceof Headers)) { + cache[2] = new Headers(cache[2]); + } + return cache[2]; + } + return this[getResponseCache]().headers; + } + get status() { + return this[cacheKey]?.[0] ?? this[getResponseCache]().status; + } + get ok() { + const status = this.status; + return status >= 200 && status < 300; + } +}; +["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + get() { + return this[getResponseCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + value: function() { + return this[getResponseCache]()[k](); + } + }); +}); +Object.setPrototypeOf(Response2, GlobalResponse); +Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); + +// src/utils.ts +async function readWithoutBlocking(readPromise) { + return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); +} +function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { + const cancel = (error) => { + reader.cancel(error).catch(() => { + }); + }; + writable.on("close", cancel); + writable.on("error", cancel); + (currentReadPromise ?? reader.read()).then(flow, handleStreamError); + return reader.closed.finally(() => { + writable.off("close", cancel); + writable.off("error", cancel); + }); + function handleStreamError(error) { + if (error) { + writable.destroy(error); + } + } + function onDrain() { + reader.read().then(flow, handleStreamError); + } + function flow({ done, value }) { + try { + if (done) { + writable.end(); + } else if (!writable.write(value)) { + writable.once("drain", onDrain); + } else { + return reader.read().then(flow, handleStreamError); + } + } catch (e) { + handleStreamError(e); + } + } +} +function writeFromReadableStream(stream, writable) { + if (stream.locked) { + throw new TypeError("ReadableStream is locked."); + } else if (writable.destroyed) { + return; + } + return writeFromReadableStreamDefaultReader(stream.getReader(), writable); +} +var buildOutgoingHttpHeaders = (headers) => { + const res = {}; + if (!(headers instanceof Headers)) { + headers = new Headers(headers ?? void 0); + } + const cookies = []; + for (const [k, v] of headers) { + if (k === "set-cookie") { + cookies.push(v); + } else { + res[k] = v; + } + } + if (cookies.length > 0) { + res["set-cookie"] = cookies; + } + res["content-type"] ??= "text/plain; charset=UTF-8"; + return res; +}; + +// src/utils/response/constants.ts +var X_ALREADY_SENT = "x-hono-already-sent"; + +// src/globals.ts +import crypto from "crypto"; +if (typeof global.crypto === "undefined") { + global.crypto = crypto; +} + +// src/listener.ts +var outgoingEnded = Symbol("outgoingEnded"); +var handleRequestError = () => new Response(null, { + status: 400 +}); +var handleFetchError = (e) => new Response(null, { + status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 +}); +var handleResponseError = (e, outgoing) => { + const err = e instanceof Error ? e : new Error("unknown error", { cause: e }); + if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { + console.info("The user aborted a request."); + } else { + console.error(e); + if (!outgoing.headersSent) { + outgoing.writeHead(500, { "Content-Type": "text/plain" }); + } + outgoing.end(`Error: ${err.message}`); + outgoing.destroy(err); + } +}; +var flushHeaders = (outgoing) => { + if ("flushHeaders" in outgoing && outgoing.writable) { + outgoing.flushHeaders(); + } +}; +var responseViaCache = async (res, outgoing) => { + let [status, body, header] = res[cacheKey]; + if (header instanceof Headers) { + header = buildOutgoingHttpHeaders(header); + } + if (typeof body === "string") { + header["Content-Length"] = Buffer.byteLength(body); + } else if (body instanceof Uint8Array) { + header["Content-Length"] = body.byteLength; + } else if (body instanceof Blob) { + header["Content-Length"] = body.size; + } + outgoing.writeHead(status, header); + if (typeof body === "string" || body instanceof Uint8Array) { + outgoing.end(body); + } else if (body instanceof Blob) { + outgoing.end(new Uint8Array(await body.arrayBuffer())); + } else { + flushHeaders(outgoing); + await writeFromReadableStream(body, outgoing)?.catch( + (e) => handleResponseError(e, outgoing) + ); + } + ; + outgoing[outgoingEnded]?.(); +}; +var isPromise = (res) => typeof res.then === "function"; +var responseViaResponseObject = async (res, outgoing, options = {}) => { + if (isPromise(res)) { + if (options.errorHandler) { + try { + res = await res; + } catch (err) { + const errRes = await options.errorHandler(err); + if (!errRes) { + return; + } + res = errRes; + } + } else { + res = await res.catch(handleFetchError); + } + } + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); + if (res.body) { + const reader = res.body.getReader(); + const values = []; + let done = false; + let currentReadPromise = void 0; + if (resHeaderRecord["transfer-encoding"] !== "chunked") { + let maxReadCount = 2; + for (let i = 0; i < maxReadCount; i++) { + currentReadPromise ||= reader.read(); + const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => { + console.error(e); + done = true; + }); + if (!chunk) { + if (i === 1) { + await new Promise((resolve) => setTimeout(resolve)); + maxReadCount = 3; + continue; + } + break; + } + currentReadPromise = void 0; + if (chunk.value) { + values.push(chunk.value); + } + if (chunk.done) { + done = true; + break; + } + } + if (done && !("content-length" in resHeaderRecord)) { + resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0); + } + } + outgoing.writeHead(res.status, resHeaderRecord); + values.forEach((value) => { + ; + outgoing.write(value); + }); + if (done) { + outgoing.end(); + } else { + if (values.length === 0) { + flushHeaders(outgoing); + } + await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise); + } + } else if (resHeaderRecord[X_ALREADY_SENT]) { + } else { + outgoing.writeHead(res.status, resHeaderRecord); + outgoing.end(); + } + ; + outgoing[outgoingEnded]?.(); +}; +var getRequestListener = (fetchCallback, options = {}) => { + const autoCleanupIncoming = options.autoCleanupIncoming ?? true; + if (options.overrideGlobalObjects !== false && global.Request !== Request) { + Object.defineProperty(global, "Request", { + value: Request + }); + Object.defineProperty(global, "Response", { + value: Response2 + }); + } + return async (incoming, outgoing) => { + let res, req; + try { + req = newRequest(incoming, options.hostname); + let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD"; + if (!incomingEnded) { + ; + incoming[wrapBodyStream] = true; + incoming.on("end", () => { + incomingEnded = true; + }); + if (incoming instanceof Http2ServerRequest2) { + ; + outgoing[outgoingEnded] = () => { + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + outgoing.destroy(); + }); + } + }); + } + }; + } + } + outgoing.on("close", () => { + const abortController = req[abortControllerKey]; + if (abortController) { + if (incoming.errored) { + req[abortControllerKey].abort(incoming.errored.toString()); + } else if (!outgoing.writableFinished) { + req[abortControllerKey].abort("Client connection prematurely closed."); + } + } + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + }); + } + }); + } + }); + res = fetchCallback(req, { incoming, outgoing }); + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + } catch (e) { + if (!res) { + if (options.errorHandler) { + res = await options.errorHandler(req ? e : toRequestError(e)); + if (!res) { + return; + } + } else if (!req) { + res = handleRequestError(); + } else { + res = handleFetchError(e); + } + } else { + return handleResponseError(e, outgoing); + } + } + try { + return await responseViaResponseObject(res, outgoing, options); + } catch (e) { + return handleResponseError(e, outgoing); + } + }; +}; + +// src/server.ts +var createAdaptorServer = (options) => { + const fetchCallback = options.fetch; + const requestListener = getRequestListener(fetchCallback, { + hostname: options.hostname, + overrideGlobalObjects: options.overrideGlobalObjects, + autoCleanupIncoming: options.autoCleanupIncoming + }); + const createServer = options.createServer || createServerHTTP; + const server = createServer(options.serverOptions || {}, requestListener); + return server; +}; +var serve = (options, listeningListener) => { + const server = createAdaptorServer(options); + server.listen(options?.port ?? 3e3, options.hostname, () => { + const serverInfo = server.address(); + listeningListener && listeningListener(serverInfo); + }); + return server; +}; +export { + RequestError, + createAdaptorServer, + getRequestListener, + serve +}; diff --git a/node_modules/@hono/node-server/dist/listener.d.mts b/node_modules/@hono/node-server/dist/listener.d.mts new file mode 100644 index 000000000..a48eaffde --- /dev/null +++ b/node_modules/@hono/node-server/dist/listener.d.mts @@ -0,0 +1,13 @@ +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Http2ServerRequest, Http2ServerResponse } from 'node:http2'; +import { FetchCallback, CustomErrorHandler } from './types.mjs'; +import 'node:https'; + +declare const getRequestListener: (fetchCallback: FetchCallback, options?: { + hostname?: string; + errorHandler?: CustomErrorHandler; + overrideGlobalObjects?: boolean; + autoCleanupIncoming?: boolean; +}) => (incoming: IncomingMessage | Http2ServerRequest, outgoing: ServerResponse | Http2ServerResponse) => Promise; + +export { getRequestListener }; diff --git a/node_modules/@hono/node-server/dist/listener.d.ts b/node_modules/@hono/node-server/dist/listener.d.ts new file mode 100644 index 000000000..2bb0b8fa1 --- /dev/null +++ b/node_modules/@hono/node-server/dist/listener.d.ts @@ -0,0 +1,13 @@ +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Http2ServerRequest, Http2ServerResponse } from 'node:http2'; +import { FetchCallback, CustomErrorHandler } from './types.js'; +import 'node:https'; + +declare const getRequestListener: (fetchCallback: FetchCallback, options?: { + hostname?: string; + errorHandler?: CustomErrorHandler; + overrideGlobalObjects?: boolean; + autoCleanupIncoming?: boolean; +}) => (incoming: IncomingMessage | Http2ServerRequest, outgoing: ServerResponse | Http2ServerResponse) => Promise; + +export { getRequestListener }; diff --git a/node_modules/@hono/node-server/dist/listener.js b/node_modules/@hono/node-server/dist/listener.js new file mode 100644 index 000000000..cb081d2ac --- /dev/null +++ b/node_modules/@hono/node-server/dist/listener.js @@ -0,0 +1,581 @@ +"use strict"; +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 __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 __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 +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/listener.ts +var listener_exports = {}; +__export(listener_exports, { + getRequestListener: () => getRequestListener +}); +module.exports = __toCommonJS(listener_exports); +var import_node_http22 = require("http2"); + +// src/request.ts +var import_node_http2 = require("http2"); +var import_node_stream = require("stream"); +var RequestError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "RequestError"; + } +}; +var toRequestError = (e) => { + if (e instanceof RequestError) { + return e; + } + return new RequestError(e.message, { cause: e }); +}; +var GlobalRequest = global.Request; +var Request = class extends GlobalRequest { + constructor(input, options) { + if (typeof input === "object" && getRequestCache in input) { + input = input[getRequestCache](); + } + if (typeof options?.body?.getReader !== "undefined") { + ; + options.duplex ??= "half"; + } + super(input, options); + } +}; +var newHeadersFromIncoming = (incoming) => { + const headerRecord = []; + const rawHeaders = incoming.rawHeaders; + for (let i = 0; i < rawHeaders.length; i += 2) { + const { [i]: key, [i + 1]: value } = rawHeaders; + if (key.charCodeAt(0) !== /*:*/ + 58) { + headerRecord.push([key, value]); + } + } + return new Headers(headerRecord); +}; +var wrapBodyStream = Symbol("wrapBodyStream"); +var newRequestFromIncoming = (method, url, headers, incoming, abortController) => { + const init = { + method, + headers, + signal: abortController.signal + }; + if (method === "TRACE") { + init.method = "GET"; + const req = new Request(url, init); + Object.defineProperty(req, "method", { + get() { + return "TRACE"; + } + }); + return req; + } + if (!(method === "GET" || method === "HEAD")) { + if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { + init.body = new ReadableStream({ + start(controller) { + controller.enqueue(incoming.rawBody); + controller.close(); + } + }); + } else if (incoming[wrapBodyStream]) { + let reader; + init.body = new ReadableStream({ + async pull(controller) { + try { + reader ||= import_node_stream.Readable.toWeb(incoming).getReader(); + const { done, value } = await reader.read(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + } catch (error) { + controller.error(error); + } + } + }); + } else { + init.body = import_node_stream.Readable.toWeb(incoming); + } + } + return new Request(url, init); +}; +var getRequestCache = Symbol("getRequestCache"); +var requestCache = Symbol("requestCache"); +var incomingKey = Symbol("incomingKey"); +var urlKey = Symbol("urlKey"); +var headersKey = Symbol("headersKey"); +var abortControllerKey = Symbol("abortControllerKey"); +var getAbortController = Symbol("getAbortController"); +var requestPrototype = { + get method() { + return this[incomingKey].method || "GET"; + }, + get url() { + return this[urlKey]; + }, + get headers() { + return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); + }, + [getAbortController]() { + this[getRequestCache](); + return this[abortControllerKey]; + }, + [getRequestCache]() { + this[abortControllerKey] ||= new AbortController(); + return this[requestCache] ||= newRequestFromIncoming( + this.method, + this[urlKey], + this.headers, + this[incomingKey], + this[abortControllerKey] + ); + } +}; +[ + "body", + "bodyUsed", + "cache", + "credentials", + "destination", + "integrity", + "mode", + "redirect", + "referrer", + "referrerPolicy", + "signal", + "keepalive" +].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + get() { + return this[getRequestCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + value: function() { + return this[getRequestCache]()[k](); + } + }); +}); +Object.setPrototypeOf(requestPrototype, Request.prototype); +var newRequest = (incoming, defaultHostname) => { + const req = Object.create(requestPrototype); + req[incomingKey] = incoming; + const incomingUrl = incoming.url || ""; + if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. + (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { + if (incoming instanceof import_node_http2.Http2ServerRequest) { + throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); + } + try { + const url2 = new URL(incomingUrl); + req[urlKey] = url2.href; + } catch (e) { + throw new RequestError("Invalid absolute URL", { cause: e }); + } + return req; + } + const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; + if (!host) { + throw new RequestError("Missing host header"); + } + let scheme; + if (incoming instanceof import_node_http2.Http2ServerRequest) { + scheme = incoming.scheme; + if (!(scheme === "http" || scheme === "https")) { + throw new RequestError("Unsupported scheme"); + } + } else { + scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; + } + const url = new URL(`${scheme}://${host}${incomingUrl}`); + if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) { + throw new RequestError("Invalid host header"); + } + req[urlKey] = url.href; + return req; +}; + +// src/response.ts +var responseCache = Symbol("responseCache"); +var getResponseCache = Symbol("getResponseCache"); +var cacheKey = Symbol("cache"); +var GlobalResponse = global.Response; +var Response2 = class _Response { + #body; + #init; + [getResponseCache]() { + delete this[cacheKey]; + return this[responseCache] ||= new GlobalResponse(this.#body, this.#init); + } + constructor(body, init) { + let headers; + this.#body = body; + if (init instanceof _Response) { + const cachedGlobalResponse = init[responseCache]; + if (cachedGlobalResponse) { + this.#init = cachedGlobalResponse; + this[getResponseCache](); + return; + } else { + this.#init = init.#init; + headers = new Headers(init.#init.headers); + } + } else { + this.#init = init; + } + if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { + headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" }; + this[cacheKey] = [init?.status || 200, body, headers]; + } + } + get headers() { + const cache = this[cacheKey]; + if (cache) { + if (!(cache[2] instanceof Headers)) { + cache[2] = new Headers(cache[2]); + } + return cache[2]; + } + return this[getResponseCache]().headers; + } + get status() { + return this[cacheKey]?.[0] ?? this[getResponseCache]().status; + } + get ok() { + const status = this.status; + return status >= 200 && status < 300; + } +}; +["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + get() { + return this[getResponseCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + value: function() { + return this[getResponseCache]()[k](); + } + }); +}); +Object.setPrototypeOf(Response2, GlobalResponse); +Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); + +// src/utils.ts +async function readWithoutBlocking(readPromise) { + return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); +} +function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { + const cancel = (error) => { + reader.cancel(error).catch(() => { + }); + }; + writable.on("close", cancel); + writable.on("error", cancel); + (currentReadPromise ?? reader.read()).then(flow, handleStreamError); + return reader.closed.finally(() => { + writable.off("close", cancel); + writable.off("error", cancel); + }); + function handleStreamError(error) { + if (error) { + writable.destroy(error); + } + } + function onDrain() { + reader.read().then(flow, handleStreamError); + } + function flow({ done, value }) { + try { + if (done) { + writable.end(); + } else if (!writable.write(value)) { + writable.once("drain", onDrain); + } else { + return reader.read().then(flow, handleStreamError); + } + } catch (e) { + handleStreamError(e); + } + } +} +function writeFromReadableStream(stream, writable) { + if (stream.locked) { + throw new TypeError("ReadableStream is locked."); + } else if (writable.destroyed) { + return; + } + return writeFromReadableStreamDefaultReader(stream.getReader(), writable); +} +var buildOutgoingHttpHeaders = (headers) => { + const res = {}; + if (!(headers instanceof Headers)) { + headers = new Headers(headers ?? void 0); + } + const cookies = []; + for (const [k, v] of headers) { + if (k === "set-cookie") { + cookies.push(v); + } else { + res[k] = v; + } + } + if (cookies.length > 0) { + res["set-cookie"] = cookies; + } + res["content-type"] ??= "text/plain; charset=UTF-8"; + return res; +}; + +// src/utils/response/constants.ts +var X_ALREADY_SENT = "x-hono-already-sent"; + +// src/globals.ts +var import_node_crypto = __toESM(require("crypto")); +if (typeof global.crypto === "undefined") { + global.crypto = import_node_crypto.default; +} + +// src/listener.ts +var outgoingEnded = Symbol("outgoingEnded"); +var handleRequestError = () => new Response(null, { + status: 400 +}); +var handleFetchError = (e) => new Response(null, { + status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 +}); +var handleResponseError = (e, outgoing) => { + const err = e instanceof Error ? e : new Error("unknown error", { cause: e }); + if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { + console.info("The user aborted a request."); + } else { + console.error(e); + if (!outgoing.headersSent) { + outgoing.writeHead(500, { "Content-Type": "text/plain" }); + } + outgoing.end(`Error: ${err.message}`); + outgoing.destroy(err); + } +}; +var flushHeaders = (outgoing) => { + if ("flushHeaders" in outgoing && outgoing.writable) { + outgoing.flushHeaders(); + } +}; +var responseViaCache = async (res, outgoing) => { + let [status, body, header] = res[cacheKey]; + if (header instanceof Headers) { + header = buildOutgoingHttpHeaders(header); + } + if (typeof body === "string") { + header["Content-Length"] = Buffer.byteLength(body); + } else if (body instanceof Uint8Array) { + header["Content-Length"] = body.byteLength; + } else if (body instanceof Blob) { + header["Content-Length"] = body.size; + } + outgoing.writeHead(status, header); + if (typeof body === "string" || body instanceof Uint8Array) { + outgoing.end(body); + } else if (body instanceof Blob) { + outgoing.end(new Uint8Array(await body.arrayBuffer())); + } else { + flushHeaders(outgoing); + await writeFromReadableStream(body, outgoing)?.catch( + (e) => handleResponseError(e, outgoing) + ); + } + ; + outgoing[outgoingEnded]?.(); +}; +var isPromise = (res) => typeof res.then === "function"; +var responseViaResponseObject = async (res, outgoing, options = {}) => { + if (isPromise(res)) { + if (options.errorHandler) { + try { + res = await res; + } catch (err) { + const errRes = await options.errorHandler(err); + if (!errRes) { + return; + } + res = errRes; + } + } else { + res = await res.catch(handleFetchError); + } + } + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); + if (res.body) { + const reader = res.body.getReader(); + const values = []; + let done = false; + let currentReadPromise = void 0; + if (resHeaderRecord["transfer-encoding"] !== "chunked") { + let maxReadCount = 2; + for (let i = 0; i < maxReadCount; i++) { + currentReadPromise ||= reader.read(); + const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => { + console.error(e); + done = true; + }); + if (!chunk) { + if (i === 1) { + await new Promise((resolve) => setTimeout(resolve)); + maxReadCount = 3; + continue; + } + break; + } + currentReadPromise = void 0; + if (chunk.value) { + values.push(chunk.value); + } + if (chunk.done) { + done = true; + break; + } + } + if (done && !("content-length" in resHeaderRecord)) { + resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0); + } + } + outgoing.writeHead(res.status, resHeaderRecord); + values.forEach((value) => { + ; + outgoing.write(value); + }); + if (done) { + outgoing.end(); + } else { + if (values.length === 0) { + flushHeaders(outgoing); + } + await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise); + } + } else if (resHeaderRecord[X_ALREADY_SENT]) { + } else { + outgoing.writeHead(res.status, resHeaderRecord); + outgoing.end(); + } + ; + outgoing[outgoingEnded]?.(); +}; +var getRequestListener = (fetchCallback, options = {}) => { + const autoCleanupIncoming = options.autoCleanupIncoming ?? true; + if (options.overrideGlobalObjects !== false && global.Request !== Request) { + Object.defineProperty(global, "Request", { + value: Request + }); + Object.defineProperty(global, "Response", { + value: Response2 + }); + } + return async (incoming, outgoing) => { + let res, req; + try { + req = newRequest(incoming, options.hostname); + let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD"; + if (!incomingEnded) { + ; + incoming[wrapBodyStream] = true; + incoming.on("end", () => { + incomingEnded = true; + }); + if (incoming instanceof import_node_http22.Http2ServerRequest) { + ; + outgoing[outgoingEnded] = () => { + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + outgoing.destroy(); + }); + } + }); + } + }; + } + } + outgoing.on("close", () => { + const abortController = req[abortControllerKey]; + if (abortController) { + if (incoming.errored) { + req[abortControllerKey].abort(incoming.errored.toString()); + } else if (!outgoing.writableFinished) { + req[abortControllerKey].abort("Client connection prematurely closed."); + } + } + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + }); + } + }); + } + }); + res = fetchCallback(req, { incoming, outgoing }); + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + } catch (e) { + if (!res) { + if (options.errorHandler) { + res = await options.errorHandler(req ? e : toRequestError(e)); + if (!res) { + return; + } + } else if (!req) { + res = handleRequestError(); + } else { + res = handleFetchError(e); + } + } else { + return handleResponseError(e, outgoing); + } + } + try { + return await responseViaResponseObject(res, outgoing, options); + } catch (e) { + return handleResponseError(e, outgoing); + } + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + getRequestListener +}); diff --git a/node_modules/@hono/node-server/dist/listener.mjs b/node_modules/@hono/node-server/dist/listener.mjs new file mode 100644 index 000000000..d6942d693 --- /dev/null +++ b/node_modules/@hono/node-server/dist/listener.mjs @@ -0,0 +1,546 @@ +// src/listener.ts +import { Http2ServerRequest as Http2ServerRequest2 } from "http2"; + +// src/request.ts +import { Http2ServerRequest } from "http2"; +import { Readable } from "stream"; +var RequestError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "RequestError"; + } +}; +var toRequestError = (e) => { + if (e instanceof RequestError) { + return e; + } + return new RequestError(e.message, { cause: e }); +}; +var GlobalRequest = global.Request; +var Request = class extends GlobalRequest { + constructor(input, options) { + if (typeof input === "object" && getRequestCache in input) { + input = input[getRequestCache](); + } + if (typeof options?.body?.getReader !== "undefined") { + ; + options.duplex ??= "half"; + } + super(input, options); + } +}; +var newHeadersFromIncoming = (incoming) => { + const headerRecord = []; + const rawHeaders = incoming.rawHeaders; + for (let i = 0; i < rawHeaders.length; i += 2) { + const { [i]: key, [i + 1]: value } = rawHeaders; + if (key.charCodeAt(0) !== /*:*/ + 58) { + headerRecord.push([key, value]); + } + } + return new Headers(headerRecord); +}; +var wrapBodyStream = Symbol("wrapBodyStream"); +var newRequestFromIncoming = (method, url, headers, incoming, abortController) => { + const init = { + method, + headers, + signal: abortController.signal + }; + if (method === "TRACE") { + init.method = "GET"; + const req = new Request(url, init); + Object.defineProperty(req, "method", { + get() { + return "TRACE"; + } + }); + return req; + } + if (!(method === "GET" || method === "HEAD")) { + if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { + init.body = new ReadableStream({ + start(controller) { + controller.enqueue(incoming.rawBody); + controller.close(); + } + }); + } else if (incoming[wrapBodyStream]) { + let reader; + init.body = new ReadableStream({ + async pull(controller) { + try { + reader ||= Readable.toWeb(incoming).getReader(); + const { done, value } = await reader.read(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + } catch (error) { + controller.error(error); + } + } + }); + } else { + init.body = Readable.toWeb(incoming); + } + } + return new Request(url, init); +}; +var getRequestCache = Symbol("getRequestCache"); +var requestCache = Symbol("requestCache"); +var incomingKey = Symbol("incomingKey"); +var urlKey = Symbol("urlKey"); +var headersKey = Symbol("headersKey"); +var abortControllerKey = Symbol("abortControllerKey"); +var getAbortController = Symbol("getAbortController"); +var requestPrototype = { + get method() { + return this[incomingKey].method || "GET"; + }, + get url() { + return this[urlKey]; + }, + get headers() { + return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); + }, + [getAbortController]() { + this[getRequestCache](); + return this[abortControllerKey]; + }, + [getRequestCache]() { + this[abortControllerKey] ||= new AbortController(); + return this[requestCache] ||= newRequestFromIncoming( + this.method, + this[urlKey], + this.headers, + this[incomingKey], + this[abortControllerKey] + ); + } +}; +[ + "body", + "bodyUsed", + "cache", + "credentials", + "destination", + "integrity", + "mode", + "redirect", + "referrer", + "referrerPolicy", + "signal", + "keepalive" +].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + get() { + return this[getRequestCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + value: function() { + return this[getRequestCache]()[k](); + } + }); +}); +Object.setPrototypeOf(requestPrototype, Request.prototype); +var newRequest = (incoming, defaultHostname) => { + const req = Object.create(requestPrototype); + req[incomingKey] = incoming; + const incomingUrl = incoming.url || ""; + if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. + (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { + if (incoming instanceof Http2ServerRequest) { + throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); + } + try { + const url2 = new URL(incomingUrl); + req[urlKey] = url2.href; + } catch (e) { + throw new RequestError("Invalid absolute URL", { cause: e }); + } + return req; + } + const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; + if (!host) { + throw new RequestError("Missing host header"); + } + let scheme; + if (incoming instanceof Http2ServerRequest) { + scheme = incoming.scheme; + if (!(scheme === "http" || scheme === "https")) { + throw new RequestError("Unsupported scheme"); + } + } else { + scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; + } + const url = new URL(`${scheme}://${host}${incomingUrl}`); + if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) { + throw new RequestError("Invalid host header"); + } + req[urlKey] = url.href; + return req; +}; + +// src/response.ts +var responseCache = Symbol("responseCache"); +var getResponseCache = Symbol("getResponseCache"); +var cacheKey = Symbol("cache"); +var GlobalResponse = global.Response; +var Response2 = class _Response { + #body; + #init; + [getResponseCache]() { + delete this[cacheKey]; + return this[responseCache] ||= new GlobalResponse(this.#body, this.#init); + } + constructor(body, init) { + let headers; + this.#body = body; + if (init instanceof _Response) { + const cachedGlobalResponse = init[responseCache]; + if (cachedGlobalResponse) { + this.#init = cachedGlobalResponse; + this[getResponseCache](); + return; + } else { + this.#init = init.#init; + headers = new Headers(init.#init.headers); + } + } else { + this.#init = init; + } + if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { + headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" }; + this[cacheKey] = [init?.status || 200, body, headers]; + } + } + get headers() { + const cache = this[cacheKey]; + if (cache) { + if (!(cache[2] instanceof Headers)) { + cache[2] = new Headers(cache[2]); + } + return cache[2]; + } + return this[getResponseCache]().headers; + } + get status() { + return this[cacheKey]?.[0] ?? this[getResponseCache]().status; + } + get ok() { + const status = this.status; + return status >= 200 && status < 300; + } +}; +["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + get() { + return this[getResponseCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + value: function() { + return this[getResponseCache]()[k](); + } + }); +}); +Object.setPrototypeOf(Response2, GlobalResponse); +Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); + +// src/utils.ts +async function readWithoutBlocking(readPromise) { + return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); +} +function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { + const cancel = (error) => { + reader.cancel(error).catch(() => { + }); + }; + writable.on("close", cancel); + writable.on("error", cancel); + (currentReadPromise ?? reader.read()).then(flow, handleStreamError); + return reader.closed.finally(() => { + writable.off("close", cancel); + writable.off("error", cancel); + }); + function handleStreamError(error) { + if (error) { + writable.destroy(error); + } + } + function onDrain() { + reader.read().then(flow, handleStreamError); + } + function flow({ done, value }) { + try { + if (done) { + writable.end(); + } else if (!writable.write(value)) { + writable.once("drain", onDrain); + } else { + return reader.read().then(flow, handleStreamError); + } + } catch (e) { + handleStreamError(e); + } + } +} +function writeFromReadableStream(stream, writable) { + if (stream.locked) { + throw new TypeError("ReadableStream is locked."); + } else if (writable.destroyed) { + return; + } + return writeFromReadableStreamDefaultReader(stream.getReader(), writable); +} +var buildOutgoingHttpHeaders = (headers) => { + const res = {}; + if (!(headers instanceof Headers)) { + headers = new Headers(headers ?? void 0); + } + const cookies = []; + for (const [k, v] of headers) { + if (k === "set-cookie") { + cookies.push(v); + } else { + res[k] = v; + } + } + if (cookies.length > 0) { + res["set-cookie"] = cookies; + } + res["content-type"] ??= "text/plain; charset=UTF-8"; + return res; +}; + +// src/utils/response/constants.ts +var X_ALREADY_SENT = "x-hono-already-sent"; + +// src/globals.ts +import crypto from "crypto"; +if (typeof global.crypto === "undefined") { + global.crypto = crypto; +} + +// src/listener.ts +var outgoingEnded = Symbol("outgoingEnded"); +var handleRequestError = () => new Response(null, { + status: 400 +}); +var handleFetchError = (e) => new Response(null, { + status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 +}); +var handleResponseError = (e, outgoing) => { + const err = e instanceof Error ? e : new Error("unknown error", { cause: e }); + if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { + console.info("The user aborted a request."); + } else { + console.error(e); + if (!outgoing.headersSent) { + outgoing.writeHead(500, { "Content-Type": "text/plain" }); + } + outgoing.end(`Error: ${err.message}`); + outgoing.destroy(err); + } +}; +var flushHeaders = (outgoing) => { + if ("flushHeaders" in outgoing && outgoing.writable) { + outgoing.flushHeaders(); + } +}; +var responseViaCache = async (res, outgoing) => { + let [status, body, header] = res[cacheKey]; + if (header instanceof Headers) { + header = buildOutgoingHttpHeaders(header); + } + if (typeof body === "string") { + header["Content-Length"] = Buffer.byteLength(body); + } else if (body instanceof Uint8Array) { + header["Content-Length"] = body.byteLength; + } else if (body instanceof Blob) { + header["Content-Length"] = body.size; + } + outgoing.writeHead(status, header); + if (typeof body === "string" || body instanceof Uint8Array) { + outgoing.end(body); + } else if (body instanceof Blob) { + outgoing.end(new Uint8Array(await body.arrayBuffer())); + } else { + flushHeaders(outgoing); + await writeFromReadableStream(body, outgoing)?.catch( + (e) => handleResponseError(e, outgoing) + ); + } + ; + outgoing[outgoingEnded]?.(); +}; +var isPromise = (res) => typeof res.then === "function"; +var responseViaResponseObject = async (res, outgoing, options = {}) => { + if (isPromise(res)) { + if (options.errorHandler) { + try { + res = await res; + } catch (err) { + const errRes = await options.errorHandler(err); + if (!errRes) { + return; + } + res = errRes; + } + } else { + res = await res.catch(handleFetchError); + } + } + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); + if (res.body) { + const reader = res.body.getReader(); + const values = []; + let done = false; + let currentReadPromise = void 0; + if (resHeaderRecord["transfer-encoding"] !== "chunked") { + let maxReadCount = 2; + for (let i = 0; i < maxReadCount; i++) { + currentReadPromise ||= reader.read(); + const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => { + console.error(e); + done = true; + }); + if (!chunk) { + if (i === 1) { + await new Promise((resolve) => setTimeout(resolve)); + maxReadCount = 3; + continue; + } + break; + } + currentReadPromise = void 0; + if (chunk.value) { + values.push(chunk.value); + } + if (chunk.done) { + done = true; + break; + } + } + if (done && !("content-length" in resHeaderRecord)) { + resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0); + } + } + outgoing.writeHead(res.status, resHeaderRecord); + values.forEach((value) => { + ; + outgoing.write(value); + }); + if (done) { + outgoing.end(); + } else { + if (values.length === 0) { + flushHeaders(outgoing); + } + await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise); + } + } else if (resHeaderRecord[X_ALREADY_SENT]) { + } else { + outgoing.writeHead(res.status, resHeaderRecord); + outgoing.end(); + } + ; + outgoing[outgoingEnded]?.(); +}; +var getRequestListener = (fetchCallback, options = {}) => { + const autoCleanupIncoming = options.autoCleanupIncoming ?? true; + if (options.overrideGlobalObjects !== false && global.Request !== Request) { + Object.defineProperty(global, "Request", { + value: Request + }); + Object.defineProperty(global, "Response", { + value: Response2 + }); + } + return async (incoming, outgoing) => { + let res, req; + try { + req = newRequest(incoming, options.hostname); + let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD"; + if (!incomingEnded) { + ; + incoming[wrapBodyStream] = true; + incoming.on("end", () => { + incomingEnded = true; + }); + if (incoming instanceof Http2ServerRequest2) { + ; + outgoing[outgoingEnded] = () => { + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + outgoing.destroy(); + }); + } + }); + } + }; + } + } + outgoing.on("close", () => { + const abortController = req[abortControllerKey]; + if (abortController) { + if (incoming.errored) { + req[abortControllerKey].abort(incoming.errored.toString()); + } else if (!outgoing.writableFinished) { + req[abortControllerKey].abort("Client connection prematurely closed."); + } + } + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + }); + } + }); + } + }); + res = fetchCallback(req, { incoming, outgoing }); + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + } catch (e) { + if (!res) { + if (options.errorHandler) { + res = await options.errorHandler(req ? e : toRequestError(e)); + if (!res) { + return; + } + } else if (!req) { + res = handleRequestError(); + } else { + res = handleFetchError(e); + } + } else { + return handleResponseError(e, outgoing); + } + } + try { + return await responseViaResponseObject(res, outgoing, options); + } catch (e) { + return handleResponseError(e, outgoing); + } + }; +}; +export { + getRequestListener +}; diff --git a/node_modules/@hono/node-server/dist/request.d.mts b/node_modules/@hono/node-server/dist/request.d.mts new file mode 100644 index 000000000..92727aabc --- /dev/null +++ b/node_modules/@hono/node-server/dist/request.d.mts @@ -0,0 +1,25 @@ +import { IncomingMessage } from 'node:http'; +import { Http2ServerRequest } from 'node:http2'; + +declare class RequestError extends Error { + constructor(message: string, options?: { + cause?: unknown; + }); +} +declare const toRequestError: (e: unknown) => RequestError; +declare const GlobalRequest: { + new (input: RequestInfo | URL, init?: RequestInit): globalThis.Request; + prototype: globalThis.Request; +}; +declare class Request extends GlobalRequest { + constructor(input: string | Request, options?: RequestInit); +} +type IncomingMessageWithWrapBodyStream = IncomingMessage & { + [wrapBodyStream]: boolean; +}; +declare const wrapBodyStream: unique symbol; +declare const abortControllerKey: unique symbol; +declare const getAbortController: unique symbol; +declare const newRequest: (incoming: IncomingMessage | Http2ServerRequest, defaultHostname?: string) => any; + +export { GlobalRequest, IncomingMessageWithWrapBodyStream, Request, RequestError, abortControllerKey, getAbortController, newRequest, toRequestError, wrapBodyStream }; diff --git a/node_modules/@hono/node-server/dist/request.d.ts b/node_modules/@hono/node-server/dist/request.d.ts new file mode 100644 index 000000000..92727aabc --- /dev/null +++ b/node_modules/@hono/node-server/dist/request.d.ts @@ -0,0 +1,25 @@ +import { IncomingMessage } from 'node:http'; +import { Http2ServerRequest } from 'node:http2'; + +declare class RequestError extends Error { + constructor(message: string, options?: { + cause?: unknown; + }); +} +declare const toRequestError: (e: unknown) => RequestError; +declare const GlobalRequest: { + new (input: RequestInfo | URL, init?: RequestInit): globalThis.Request; + prototype: globalThis.Request; +}; +declare class Request extends GlobalRequest { + constructor(input: string | Request, options?: RequestInit); +} +type IncomingMessageWithWrapBodyStream = IncomingMessage & { + [wrapBodyStream]: boolean; +}; +declare const wrapBodyStream: unique symbol; +declare const abortControllerKey: unique symbol; +declare const getAbortController: unique symbol; +declare const newRequest: (incoming: IncomingMessage | Http2ServerRequest, defaultHostname?: string) => any; + +export { GlobalRequest, IncomingMessageWithWrapBodyStream, Request, RequestError, abortControllerKey, getAbortController, newRequest, toRequestError, wrapBodyStream }; diff --git a/node_modules/@hono/node-server/dist/request.js b/node_modules/@hono/node-server/dist/request.js new file mode 100644 index 000000000..a0a3ad283 --- /dev/null +++ b/node_modules/@hono/node-server/dist/request.js @@ -0,0 +1,227 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/request.ts +var request_exports = {}; +__export(request_exports, { + GlobalRequest: () => GlobalRequest, + Request: () => Request, + RequestError: () => RequestError, + abortControllerKey: () => abortControllerKey, + getAbortController: () => getAbortController, + newRequest: () => newRequest, + toRequestError: () => toRequestError, + wrapBodyStream: () => wrapBodyStream +}); +module.exports = __toCommonJS(request_exports); +var import_node_http2 = require("http2"); +var import_node_stream = require("stream"); +var RequestError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "RequestError"; + } +}; +var toRequestError = (e) => { + if (e instanceof RequestError) { + return e; + } + return new RequestError(e.message, { cause: e }); +}; +var GlobalRequest = global.Request; +var Request = class extends GlobalRequest { + constructor(input, options) { + if (typeof input === "object" && getRequestCache in input) { + input = input[getRequestCache](); + } + if (typeof options?.body?.getReader !== "undefined") { + ; + options.duplex ??= "half"; + } + super(input, options); + } +}; +var newHeadersFromIncoming = (incoming) => { + const headerRecord = []; + const rawHeaders = incoming.rawHeaders; + for (let i = 0; i < rawHeaders.length; i += 2) { + const { [i]: key, [i + 1]: value } = rawHeaders; + if (key.charCodeAt(0) !== /*:*/ + 58) { + headerRecord.push([key, value]); + } + } + return new Headers(headerRecord); +}; +var wrapBodyStream = Symbol("wrapBodyStream"); +var newRequestFromIncoming = (method, url, headers, incoming, abortController) => { + const init = { + method, + headers, + signal: abortController.signal + }; + if (method === "TRACE") { + init.method = "GET"; + const req = new Request(url, init); + Object.defineProperty(req, "method", { + get() { + return "TRACE"; + } + }); + return req; + } + if (!(method === "GET" || method === "HEAD")) { + if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { + init.body = new ReadableStream({ + start(controller) { + controller.enqueue(incoming.rawBody); + controller.close(); + } + }); + } else if (incoming[wrapBodyStream]) { + let reader; + init.body = new ReadableStream({ + async pull(controller) { + try { + reader ||= import_node_stream.Readable.toWeb(incoming).getReader(); + const { done, value } = await reader.read(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + } catch (error) { + controller.error(error); + } + } + }); + } else { + init.body = import_node_stream.Readable.toWeb(incoming); + } + } + return new Request(url, init); +}; +var getRequestCache = Symbol("getRequestCache"); +var requestCache = Symbol("requestCache"); +var incomingKey = Symbol("incomingKey"); +var urlKey = Symbol("urlKey"); +var headersKey = Symbol("headersKey"); +var abortControllerKey = Symbol("abortControllerKey"); +var getAbortController = Symbol("getAbortController"); +var requestPrototype = { + get method() { + return this[incomingKey].method || "GET"; + }, + get url() { + return this[urlKey]; + }, + get headers() { + return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); + }, + [getAbortController]() { + this[getRequestCache](); + return this[abortControllerKey]; + }, + [getRequestCache]() { + this[abortControllerKey] ||= new AbortController(); + return this[requestCache] ||= newRequestFromIncoming( + this.method, + this[urlKey], + this.headers, + this[incomingKey], + this[abortControllerKey] + ); + } +}; +[ + "body", + "bodyUsed", + "cache", + "credentials", + "destination", + "integrity", + "mode", + "redirect", + "referrer", + "referrerPolicy", + "signal", + "keepalive" +].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + get() { + return this[getRequestCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + value: function() { + return this[getRequestCache]()[k](); + } + }); +}); +Object.setPrototypeOf(requestPrototype, Request.prototype); +var newRequest = (incoming, defaultHostname) => { + const req = Object.create(requestPrototype); + req[incomingKey] = incoming; + const incomingUrl = incoming.url || ""; + if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. + (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { + if (incoming instanceof import_node_http2.Http2ServerRequest) { + throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); + } + try { + const url2 = new URL(incomingUrl); + req[urlKey] = url2.href; + } catch (e) { + throw new RequestError("Invalid absolute URL", { cause: e }); + } + return req; + } + const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; + if (!host) { + throw new RequestError("Missing host header"); + } + let scheme; + if (incoming instanceof import_node_http2.Http2ServerRequest) { + scheme = incoming.scheme; + if (!(scheme === "http" || scheme === "https")) { + throw new RequestError("Unsupported scheme"); + } + } else { + scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; + } + const url = new URL(`${scheme}://${host}${incomingUrl}`); + if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) { + throw new RequestError("Invalid host header"); + } + req[urlKey] = url.href; + return req; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + GlobalRequest, + Request, + RequestError, + abortControllerKey, + getAbortController, + newRequest, + toRequestError, + wrapBodyStream +}); diff --git a/node_modules/@hono/node-server/dist/request.mjs b/node_modules/@hono/node-server/dist/request.mjs new file mode 100644 index 000000000..1e5cb6472 --- /dev/null +++ b/node_modules/@hono/node-server/dist/request.mjs @@ -0,0 +1,195 @@ +// src/request.ts +import { Http2ServerRequest } from "http2"; +import { Readable } from "stream"; +var RequestError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "RequestError"; + } +}; +var toRequestError = (e) => { + if (e instanceof RequestError) { + return e; + } + return new RequestError(e.message, { cause: e }); +}; +var GlobalRequest = global.Request; +var Request = class extends GlobalRequest { + constructor(input, options) { + if (typeof input === "object" && getRequestCache in input) { + input = input[getRequestCache](); + } + if (typeof options?.body?.getReader !== "undefined") { + ; + options.duplex ??= "half"; + } + super(input, options); + } +}; +var newHeadersFromIncoming = (incoming) => { + const headerRecord = []; + const rawHeaders = incoming.rawHeaders; + for (let i = 0; i < rawHeaders.length; i += 2) { + const { [i]: key, [i + 1]: value } = rawHeaders; + if (key.charCodeAt(0) !== /*:*/ + 58) { + headerRecord.push([key, value]); + } + } + return new Headers(headerRecord); +}; +var wrapBodyStream = Symbol("wrapBodyStream"); +var newRequestFromIncoming = (method, url, headers, incoming, abortController) => { + const init = { + method, + headers, + signal: abortController.signal + }; + if (method === "TRACE") { + init.method = "GET"; + const req = new Request(url, init); + Object.defineProperty(req, "method", { + get() { + return "TRACE"; + } + }); + return req; + } + if (!(method === "GET" || method === "HEAD")) { + if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { + init.body = new ReadableStream({ + start(controller) { + controller.enqueue(incoming.rawBody); + controller.close(); + } + }); + } else if (incoming[wrapBodyStream]) { + let reader; + init.body = new ReadableStream({ + async pull(controller) { + try { + reader ||= Readable.toWeb(incoming).getReader(); + const { done, value } = await reader.read(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + } catch (error) { + controller.error(error); + } + } + }); + } else { + init.body = Readable.toWeb(incoming); + } + } + return new Request(url, init); +}; +var getRequestCache = Symbol("getRequestCache"); +var requestCache = Symbol("requestCache"); +var incomingKey = Symbol("incomingKey"); +var urlKey = Symbol("urlKey"); +var headersKey = Symbol("headersKey"); +var abortControllerKey = Symbol("abortControllerKey"); +var getAbortController = Symbol("getAbortController"); +var requestPrototype = { + get method() { + return this[incomingKey].method || "GET"; + }, + get url() { + return this[urlKey]; + }, + get headers() { + return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); + }, + [getAbortController]() { + this[getRequestCache](); + return this[abortControllerKey]; + }, + [getRequestCache]() { + this[abortControllerKey] ||= new AbortController(); + return this[requestCache] ||= newRequestFromIncoming( + this.method, + this[urlKey], + this.headers, + this[incomingKey], + this[abortControllerKey] + ); + } +}; +[ + "body", + "bodyUsed", + "cache", + "credentials", + "destination", + "integrity", + "mode", + "redirect", + "referrer", + "referrerPolicy", + "signal", + "keepalive" +].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + get() { + return this[getRequestCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + value: function() { + return this[getRequestCache]()[k](); + } + }); +}); +Object.setPrototypeOf(requestPrototype, Request.prototype); +var newRequest = (incoming, defaultHostname) => { + const req = Object.create(requestPrototype); + req[incomingKey] = incoming; + const incomingUrl = incoming.url || ""; + if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. + (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { + if (incoming instanceof Http2ServerRequest) { + throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); + } + try { + const url2 = new URL(incomingUrl); + req[urlKey] = url2.href; + } catch (e) { + throw new RequestError("Invalid absolute URL", { cause: e }); + } + return req; + } + const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; + if (!host) { + throw new RequestError("Missing host header"); + } + let scheme; + if (incoming instanceof Http2ServerRequest) { + scheme = incoming.scheme; + if (!(scheme === "http" || scheme === "https")) { + throw new RequestError("Unsupported scheme"); + } + } else { + scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; + } + const url = new URL(`${scheme}://${host}${incomingUrl}`); + if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) { + throw new RequestError("Invalid host header"); + } + req[urlKey] = url.href; + return req; +}; +export { + GlobalRequest, + Request, + RequestError, + abortControllerKey, + getAbortController, + newRequest, + toRequestError, + wrapBodyStream +}; diff --git a/node_modules/@hono/node-server/dist/response.d.mts b/node_modules/@hono/node-server/dist/response.d.mts new file mode 100644 index 000000000..d61ca0ebf --- /dev/null +++ b/node_modules/@hono/node-server/dist/response.d.mts @@ -0,0 +1,26 @@ +import { OutgoingHttpHeaders } from 'node:http'; + +declare const getResponseCache: unique symbol; +declare const cacheKey: unique symbol; +type InternalCache = [ + number, + string | ReadableStream, + Record | Headers | OutgoingHttpHeaders +]; +declare const GlobalResponse: { + new (body?: BodyInit | null, init?: ResponseInit): globalThis.Response; + prototype: globalThis.Response; + error(): globalThis.Response; + json(data: any, init?: ResponseInit): globalThis.Response; + redirect(url: string | URL, status?: number): globalThis.Response; +}; +declare class Response { + #private; + [getResponseCache](): globalThis.Response; + constructor(body?: BodyInit | null, init?: ResponseInit); + get headers(): Headers; + get status(): number; + get ok(): boolean; +} + +export { GlobalResponse, InternalCache, Response, cacheKey }; diff --git a/node_modules/@hono/node-server/dist/response.d.ts b/node_modules/@hono/node-server/dist/response.d.ts new file mode 100644 index 000000000..d61ca0ebf --- /dev/null +++ b/node_modules/@hono/node-server/dist/response.d.ts @@ -0,0 +1,26 @@ +import { OutgoingHttpHeaders } from 'node:http'; + +declare const getResponseCache: unique symbol; +declare const cacheKey: unique symbol; +type InternalCache = [ + number, + string | ReadableStream, + Record | Headers | OutgoingHttpHeaders +]; +declare const GlobalResponse: { + new (body?: BodyInit | null, init?: ResponseInit): globalThis.Response; + prototype: globalThis.Response; + error(): globalThis.Response; + json(data: any, init?: ResponseInit): globalThis.Response; + redirect(url: string | URL, status?: number): globalThis.Response; +}; +declare class Response { + #private; + [getResponseCache](): globalThis.Response; + constructor(body?: BodyInit | null, init?: ResponseInit); + get headers(): Headers; + get status(): number; + get ok(): boolean; +} + +export { GlobalResponse, InternalCache, Response, cacheKey }; diff --git a/node_modules/@hono/node-server/dist/response.js b/node_modules/@hono/node-server/dist/response.js new file mode 100644 index 000000000..1a8532993 --- /dev/null +++ b/node_modules/@hono/node-server/dist/response.js @@ -0,0 +1,99 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/response.ts +var response_exports = {}; +__export(response_exports, { + GlobalResponse: () => GlobalResponse, + Response: () => Response, + cacheKey: () => cacheKey +}); +module.exports = __toCommonJS(response_exports); +var responseCache = Symbol("responseCache"); +var getResponseCache = Symbol("getResponseCache"); +var cacheKey = Symbol("cache"); +var GlobalResponse = global.Response; +var Response = class _Response { + #body; + #init; + [getResponseCache]() { + delete this[cacheKey]; + return this[responseCache] ||= new GlobalResponse(this.#body, this.#init); + } + constructor(body, init) { + let headers; + this.#body = body; + if (init instanceof _Response) { + const cachedGlobalResponse = init[responseCache]; + if (cachedGlobalResponse) { + this.#init = cachedGlobalResponse; + this[getResponseCache](); + return; + } else { + this.#init = init.#init; + headers = new Headers(init.#init.headers); + } + } else { + this.#init = init; + } + if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { + headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" }; + this[cacheKey] = [init?.status || 200, body, headers]; + } + } + get headers() { + const cache = this[cacheKey]; + if (cache) { + if (!(cache[2] instanceof Headers)) { + cache[2] = new Headers(cache[2]); + } + return cache[2]; + } + return this[getResponseCache]().headers; + } + get status() { + return this[cacheKey]?.[0] ?? this[getResponseCache]().status; + } + get ok() { + const status = this.status; + return status >= 200 && status < 300; + } +}; +["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { + Object.defineProperty(Response.prototype, k, { + get() { + return this[getResponseCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(Response.prototype, k, { + value: function() { + return this[getResponseCache]()[k](); + } + }); +}); +Object.setPrototypeOf(Response, GlobalResponse); +Object.setPrototypeOf(Response.prototype, GlobalResponse.prototype); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + GlobalResponse, + Response, + cacheKey +}); diff --git a/node_modules/@hono/node-server/dist/response.mjs b/node_modules/@hono/node-server/dist/response.mjs new file mode 100644 index 000000000..547e4ad2a --- /dev/null +++ b/node_modules/@hono/node-server/dist/response.mjs @@ -0,0 +1,72 @@ +// src/response.ts +var responseCache = Symbol("responseCache"); +var getResponseCache = Symbol("getResponseCache"); +var cacheKey = Symbol("cache"); +var GlobalResponse = global.Response; +var Response = class _Response { + #body; + #init; + [getResponseCache]() { + delete this[cacheKey]; + return this[responseCache] ||= new GlobalResponse(this.#body, this.#init); + } + constructor(body, init) { + let headers; + this.#body = body; + if (init instanceof _Response) { + const cachedGlobalResponse = init[responseCache]; + if (cachedGlobalResponse) { + this.#init = cachedGlobalResponse; + this[getResponseCache](); + return; + } else { + this.#init = init.#init; + headers = new Headers(init.#init.headers); + } + } else { + this.#init = init; + } + if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { + headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" }; + this[cacheKey] = [init?.status || 200, body, headers]; + } + } + get headers() { + const cache = this[cacheKey]; + if (cache) { + if (!(cache[2] instanceof Headers)) { + cache[2] = new Headers(cache[2]); + } + return cache[2]; + } + return this[getResponseCache]().headers; + } + get status() { + return this[cacheKey]?.[0] ?? this[getResponseCache]().status; + } + get ok() { + const status = this.status; + return status >= 200 && status < 300; + } +}; +["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { + Object.defineProperty(Response.prototype, k, { + get() { + return this[getResponseCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(Response.prototype, k, { + value: function() { + return this[getResponseCache]()[k](); + } + }); +}); +Object.setPrototypeOf(Response, GlobalResponse); +Object.setPrototypeOf(Response.prototype, GlobalResponse.prototype); +export { + GlobalResponse, + Response, + cacheKey +}; diff --git a/node_modules/@hono/node-server/dist/serve-static.d.mts b/node_modules/@hono/node-server/dist/serve-static.d.mts new file mode 100644 index 000000000..d10584b2c --- /dev/null +++ b/node_modules/@hono/node-server/dist/serve-static.d.mts @@ -0,0 +1,17 @@ +import { Env, Context, MiddlewareHandler } from 'hono'; + +type ServeStaticOptions = { + /** + * Root path, relative to current working directory from which the app was started. Absolute paths are not supported. + */ + root?: string; + path?: string; + index?: string; + precompressed?: boolean; + rewriteRequestPath?: (path: string, c: Context) => string; + onFound?: (path: string, c: Context) => void | Promise; + onNotFound?: (path: string, c: Context) => void | Promise; +}; +declare const serveStatic: (options?: ServeStaticOptions) => MiddlewareHandler; + +export { ServeStaticOptions, serveStatic }; diff --git a/node_modules/@hono/node-server/dist/serve-static.d.ts b/node_modules/@hono/node-server/dist/serve-static.d.ts new file mode 100644 index 000000000..d10584b2c --- /dev/null +++ b/node_modules/@hono/node-server/dist/serve-static.d.ts @@ -0,0 +1,17 @@ +import { Env, Context, MiddlewareHandler } from 'hono'; + +type ServeStaticOptions = { + /** + * Root path, relative to current working directory from which the app was started. Absolute paths are not supported. + */ + root?: string; + path?: string; + index?: string; + precompressed?: boolean; + rewriteRequestPath?: (path: string, c: Context) => string; + onFound?: (path: string, c: Context) => void | Promise; + onNotFound?: (path: string, c: Context) => void | Promise; +}; +declare const serveStatic: (options?: ServeStaticOptions) => MiddlewareHandler; + +export { ServeStaticOptions, serveStatic }; diff --git a/node_modules/@hono/node-server/dist/serve-static.js b/node_modules/@hono/node-server/dist/serve-static.js new file mode 100644 index 000000000..956482d5f --- /dev/null +++ b/node_modules/@hono/node-server/dist/serve-static.js @@ -0,0 +1,163 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/serve-static.ts +var serve_static_exports = {}; +__export(serve_static_exports, { + serveStatic: () => serveStatic +}); +module.exports = __toCommonJS(serve_static_exports); +var import_mime = require("hono/utils/mime"); +var import_node_fs = require("fs"); +var import_node_path = require("path"); +var import_node_process = require("process"); +var import_node_stream = require("stream"); +var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i; +var ENCODINGS = { + br: ".br", + zstd: ".zst", + gzip: ".gz" +}; +var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS); +var pr54206Applied = () => { + const [major, minor] = import_node_process.versions.node.split(".").map((component) => parseInt(component)); + return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18; +}; +var useReadableToWeb = pr54206Applied(); +var createStreamBody = (stream) => { + if (useReadableToWeb) { + return import_node_stream.Readable.toWeb(stream); + } + const body = new ReadableStream({ + start(controller) { + stream.on("data", (chunk) => { + controller.enqueue(chunk); + }); + stream.on("error", (err) => { + controller.error(err); + }); + stream.on("end", () => { + controller.close(); + }); + }, + cancel() { + stream.destroy(); + } + }); + return body; +}; +var getStats = (path) => { + let stats; + try { + stats = (0, import_node_fs.statSync)(path); + } catch { + } + return stats; +}; +var serveStatic = (options = { root: "" }) => { + const root = options.root || ""; + const optionPath = options.path; + if (root !== "" && !(0, import_node_fs.existsSync)(root)) { + console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`); + } + return async (c, next) => { + if (c.finalized) { + return next(); + } + let filename; + if (optionPath) { + filename = optionPath; + } else { + try { + filename = decodeURIComponent(c.req.path); + if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) { + throw new Error(); + } + } catch { + await options.onNotFound?.(c.req.path, c); + return next(); + } + } + let path = (0, import_node_path.join)( + root, + !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename + ); + let stats = getStats(path); + if (stats && stats.isDirectory()) { + const indexFile = options.index ?? "index.html"; + path = (0, import_node_path.join)(path, indexFile); + stats = getStats(path); + } + if (!stats) { + await options.onNotFound?.(path, c); + return next(); + } + const mimeType = (0, import_mime.getMimeType)(path); + c.header("Content-Type", mimeType || "application/octet-stream"); + if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) { + const acceptEncodingSet = new Set( + c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()) + ); + for (const encoding of ENCODINGS_ORDERED_KEYS) { + if (!acceptEncodingSet.has(encoding)) { + continue; + } + const precompressedStats = getStats(path + ENCODINGS[encoding]); + if (precompressedStats) { + c.header("Content-Encoding", encoding); + c.header("Vary", "Accept-Encoding", { append: true }); + stats = precompressedStats; + path = path + ENCODINGS[encoding]; + break; + } + } + } + let result; + const size = stats.size; + const range = c.req.header("range") || ""; + if (c.req.method == "HEAD" || c.req.method == "OPTIONS") { + c.header("Content-Length", size.toString()); + c.status(200); + result = c.body(null); + } else if (!range) { + c.header("Content-Length", size.toString()); + result = c.body(createStreamBody((0, import_node_fs.createReadStream)(path)), 200); + } else { + c.header("Accept-Ranges", "bytes"); + c.header("Date", stats.birthtime.toUTCString()); + const parts = range.replace(/bytes=/, "").split("-", 2); + const start = parseInt(parts[0], 10) || 0; + let end = parseInt(parts[1], 10) || size - 1; + if (size < end - start + 1) { + end = size - 1; + } + const chunksize = end - start + 1; + const stream = (0, import_node_fs.createReadStream)(path, { start, end }); + c.header("Content-Length", chunksize.toString()); + c.header("Content-Range", `bytes ${start}-${end}/${stats.size}`); + result = c.body(createStreamBody(stream), 206); + } + await options.onFound?.(path, c); + return result; + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + serveStatic +}); diff --git a/node_modules/@hono/node-server/dist/serve-static.mjs b/node_modules/@hono/node-server/dist/serve-static.mjs new file mode 100644 index 000000000..64ecf2cab --- /dev/null +++ b/node_modules/@hono/node-server/dist/serve-static.mjs @@ -0,0 +1,138 @@ +// src/serve-static.ts +import { getMimeType } from "hono/utils/mime"; +import { createReadStream, statSync, existsSync } from "fs"; +import { join } from "path"; +import { versions } from "process"; +import { Readable } from "stream"; +var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i; +var ENCODINGS = { + br: ".br", + zstd: ".zst", + gzip: ".gz" +}; +var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS); +var pr54206Applied = () => { + const [major, minor] = versions.node.split(".").map((component) => parseInt(component)); + return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18; +}; +var useReadableToWeb = pr54206Applied(); +var createStreamBody = (stream) => { + if (useReadableToWeb) { + return Readable.toWeb(stream); + } + const body = new ReadableStream({ + start(controller) { + stream.on("data", (chunk) => { + controller.enqueue(chunk); + }); + stream.on("error", (err) => { + controller.error(err); + }); + stream.on("end", () => { + controller.close(); + }); + }, + cancel() { + stream.destroy(); + } + }); + return body; +}; +var getStats = (path) => { + let stats; + try { + stats = statSync(path); + } catch { + } + return stats; +}; +var serveStatic = (options = { root: "" }) => { + const root = options.root || ""; + const optionPath = options.path; + if (root !== "" && !existsSync(root)) { + console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`); + } + return async (c, next) => { + if (c.finalized) { + return next(); + } + let filename; + if (optionPath) { + filename = optionPath; + } else { + try { + filename = decodeURIComponent(c.req.path); + if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) { + throw new Error(); + } + } catch { + await options.onNotFound?.(c.req.path, c); + return next(); + } + } + let path = join( + root, + !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename + ); + let stats = getStats(path); + if (stats && stats.isDirectory()) { + const indexFile = options.index ?? "index.html"; + path = join(path, indexFile); + stats = getStats(path); + } + if (!stats) { + await options.onNotFound?.(path, c); + return next(); + } + const mimeType = getMimeType(path); + c.header("Content-Type", mimeType || "application/octet-stream"); + if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) { + const acceptEncodingSet = new Set( + c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()) + ); + for (const encoding of ENCODINGS_ORDERED_KEYS) { + if (!acceptEncodingSet.has(encoding)) { + continue; + } + const precompressedStats = getStats(path + ENCODINGS[encoding]); + if (precompressedStats) { + c.header("Content-Encoding", encoding); + c.header("Vary", "Accept-Encoding", { append: true }); + stats = precompressedStats; + path = path + ENCODINGS[encoding]; + break; + } + } + } + let result; + const size = stats.size; + const range = c.req.header("range") || ""; + if (c.req.method == "HEAD" || c.req.method == "OPTIONS") { + c.header("Content-Length", size.toString()); + c.status(200); + result = c.body(null); + } else if (!range) { + c.header("Content-Length", size.toString()); + result = c.body(createStreamBody(createReadStream(path)), 200); + } else { + c.header("Accept-Ranges", "bytes"); + c.header("Date", stats.birthtime.toUTCString()); + const parts = range.replace(/bytes=/, "").split("-", 2); + const start = parseInt(parts[0], 10) || 0; + let end = parseInt(parts[1], 10) || size - 1; + if (size < end - start + 1) { + end = size - 1; + } + const chunksize = end - start + 1; + const stream = createReadStream(path, { start, end }); + c.header("Content-Length", chunksize.toString()); + c.header("Content-Range", `bytes ${start}-${end}/${stats.size}`); + result = c.body(createStreamBody(stream), 206); + } + await options.onFound?.(path, c); + return result; + }; +}; +export { + serveStatic +}; diff --git a/node_modules/@hono/node-server/dist/server.d.mts b/node_modules/@hono/node-server/dist/server.d.mts new file mode 100644 index 000000000..a8e95432c --- /dev/null +++ b/node_modules/@hono/node-server/dist/server.d.mts @@ -0,0 +1,10 @@ +import { AddressInfo } from 'node:net'; +import { Options, ServerType } from './types.mjs'; +import 'node:http'; +import 'node:http2'; +import 'node:https'; + +declare const createAdaptorServer: (options: Options) => ServerType; +declare const serve: (options: Options, listeningListener?: (info: AddressInfo) => void) => ServerType; + +export { createAdaptorServer, serve }; diff --git a/node_modules/@hono/node-server/dist/server.d.ts b/node_modules/@hono/node-server/dist/server.d.ts new file mode 100644 index 000000000..b63928303 --- /dev/null +++ b/node_modules/@hono/node-server/dist/server.d.ts @@ -0,0 +1,10 @@ +import { AddressInfo } from 'node:net'; +import { Options, ServerType } from './types.js'; +import 'node:http'; +import 'node:http2'; +import 'node:https'; + +declare const createAdaptorServer: (options: Options) => ServerType; +declare const serve: (options: Options, listeningListener?: (info: AddressInfo) => void) => ServerType; + +export { createAdaptorServer, serve }; diff --git a/node_modules/@hono/node-server/dist/server.js b/node_modules/@hono/node-server/dist/server.js new file mode 100644 index 000000000..bec6481fe --- /dev/null +++ b/node_modules/@hono/node-server/dist/server.js @@ -0,0 +1,607 @@ +"use strict"; +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 __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 __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 +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/server.ts +var server_exports = {}; +__export(server_exports, { + createAdaptorServer: () => createAdaptorServer, + serve: () => serve +}); +module.exports = __toCommonJS(server_exports); +var import_node_http = require("http"); + +// src/listener.ts +var import_node_http22 = require("http2"); + +// src/request.ts +var import_node_http2 = require("http2"); +var import_node_stream = require("stream"); +var RequestError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "RequestError"; + } +}; +var toRequestError = (e) => { + if (e instanceof RequestError) { + return e; + } + return new RequestError(e.message, { cause: e }); +}; +var GlobalRequest = global.Request; +var Request = class extends GlobalRequest { + constructor(input, options) { + if (typeof input === "object" && getRequestCache in input) { + input = input[getRequestCache](); + } + if (typeof options?.body?.getReader !== "undefined") { + ; + options.duplex ??= "half"; + } + super(input, options); + } +}; +var newHeadersFromIncoming = (incoming) => { + const headerRecord = []; + const rawHeaders = incoming.rawHeaders; + for (let i = 0; i < rawHeaders.length; i += 2) { + const { [i]: key, [i + 1]: value } = rawHeaders; + if (key.charCodeAt(0) !== /*:*/ + 58) { + headerRecord.push([key, value]); + } + } + return new Headers(headerRecord); +}; +var wrapBodyStream = Symbol("wrapBodyStream"); +var newRequestFromIncoming = (method, url, headers, incoming, abortController) => { + const init = { + method, + headers, + signal: abortController.signal + }; + if (method === "TRACE") { + init.method = "GET"; + const req = new Request(url, init); + Object.defineProperty(req, "method", { + get() { + return "TRACE"; + } + }); + return req; + } + if (!(method === "GET" || method === "HEAD")) { + if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { + init.body = new ReadableStream({ + start(controller) { + controller.enqueue(incoming.rawBody); + controller.close(); + } + }); + } else if (incoming[wrapBodyStream]) { + let reader; + init.body = new ReadableStream({ + async pull(controller) { + try { + reader ||= import_node_stream.Readable.toWeb(incoming).getReader(); + const { done, value } = await reader.read(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + } catch (error) { + controller.error(error); + } + } + }); + } else { + init.body = import_node_stream.Readable.toWeb(incoming); + } + } + return new Request(url, init); +}; +var getRequestCache = Symbol("getRequestCache"); +var requestCache = Symbol("requestCache"); +var incomingKey = Symbol("incomingKey"); +var urlKey = Symbol("urlKey"); +var headersKey = Symbol("headersKey"); +var abortControllerKey = Symbol("abortControllerKey"); +var getAbortController = Symbol("getAbortController"); +var requestPrototype = { + get method() { + return this[incomingKey].method || "GET"; + }, + get url() { + return this[urlKey]; + }, + get headers() { + return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); + }, + [getAbortController]() { + this[getRequestCache](); + return this[abortControllerKey]; + }, + [getRequestCache]() { + this[abortControllerKey] ||= new AbortController(); + return this[requestCache] ||= newRequestFromIncoming( + this.method, + this[urlKey], + this.headers, + this[incomingKey], + this[abortControllerKey] + ); + } +}; +[ + "body", + "bodyUsed", + "cache", + "credentials", + "destination", + "integrity", + "mode", + "redirect", + "referrer", + "referrerPolicy", + "signal", + "keepalive" +].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + get() { + return this[getRequestCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + value: function() { + return this[getRequestCache]()[k](); + } + }); +}); +Object.setPrototypeOf(requestPrototype, Request.prototype); +var newRequest = (incoming, defaultHostname) => { + const req = Object.create(requestPrototype); + req[incomingKey] = incoming; + const incomingUrl = incoming.url || ""; + if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. + (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { + if (incoming instanceof import_node_http2.Http2ServerRequest) { + throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); + } + try { + const url2 = new URL(incomingUrl); + req[urlKey] = url2.href; + } catch (e) { + throw new RequestError("Invalid absolute URL", { cause: e }); + } + return req; + } + const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; + if (!host) { + throw new RequestError("Missing host header"); + } + let scheme; + if (incoming instanceof import_node_http2.Http2ServerRequest) { + scheme = incoming.scheme; + if (!(scheme === "http" || scheme === "https")) { + throw new RequestError("Unsupported scheme"); + } + } else { + scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; + } + const url = new URL(`${scheme}://${host}${incomingUrl}`); + if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) { + throw new RequestError("Invalid host header"); + } + req[urlKey] = url.href; + return req; +}; + +// src/response.ts +var responseCache = Symbol("responseCache"); +var getResponseCache = Symbol("getResponseCache"); +var cacheKey = Symbol("cache"); +var GlobalResponse = global.Response; +var Response2 = class _Response { + #body; + #init; + [getResponseCache]() { + delete this[cacheKey]; + return this[responseCache] ||= new GlobalResponse(this.#body, this.#init); + } + constructor(body, init) { + let headers; + this.#body = body; + if (init instanceof _Response) { + const cachedGlobalResponse = init[responseCache]; + if (cachedGlobalResponse) { + this.#init = cachedGlobalResponse; + this[getResponseCache](); + return; + } else { + this.#init = init.#init; + headers = new Headers(init.#init.headers); + } + } else { + this.#init = init; + } + if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { + headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" }; + this[cacheKey] = [init?.status || 200, body, headers]; + } + } + get headers() { + const cache = this[cacheKey]; + if (cache) { + if (!(cache[2] instanceof Headers)) { + cache[2] = new Headers(cache[2]); + } + return cache[2]; + } + return this[getResponseCache]().headers; + } + get status() { + return this[cacheKey]?.[0] ?? this[getResponseCache]().status; + } + get ok() { + const status = this.status; + return status >= 200 && status < 300; + } +}; +["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + get() { + return this[getResponseCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + value: function() { + return this[getResponseCache]()[k](); + } + }); +}); +Object.setPrototypeOf(Response2, GlobalResponse); +Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); + +// src/utils.ts +async function readWithoutBlocking(readPromise) { + return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); +} +function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { + const cancel = (error) => { + reader.cancel(error).catch(() => { + }); + }; + writable.on("close", cancel); + writable.on("error", cancel); + (currentReadPromise ?? reader.read()).then(flow, handleStreamError); + return reader.closed.finally(() => { + writable.off("close", cancel); + writable.off("error", cancel); + }); + function handleStreamError(error) { + if (error) { + writable.destroy(error); + } + } + function onDrain() { + reader.read().then(flow, handleStreamError); + } + function flow({ done, value }) { + try { + if (done) { + writable.end(); + } else if (!writable.write(value)) { + writable.once("drain", onDrain); + } else { + return reader.read().then(flow, handleStreamError); + } + } catch (e) { + handleStreamError(e); + } + } +} +function writeFromReadableStream(stream, writable) { + if (stream.locked) { + throw new TypeError("ReadableStream is locked."); + } else if (writable.destroyed) { + return; + } + return writeFromReadableStreamDefaultReader(stream.getReader(), writable); +} +var buildOutgoingHttpHeaders = (headers) => { + const res = {}; + if (!(headers instanceof Headers)) { + headers = new Headers(headers ?? void 0); + } + const cookies = []; + for (const [k, v] of headers) { + if (k === "set-cookie") { + cookies.push(v); + } else { + res[k] = v; + } + } + if (cookies.length > 0) { + res["set-cookie"] = cookies; + } + res["content-type"] ??= "text/plain; charset=UTF-8"; + return res; +}; + +// src/utils/response/constants.ts +var X_ALREADY_SENT = "x-hono-already-sent"; + +// src/globals.ts +var import_node_crypto = __toESM(require("crypto")); +if (typeof global.crypto === "undefined") { + global.crypto = import_node_crypto.default; +} + +// src/listener.ts +var outgoingEnded = Symbol("outgoingEnded"); +var handleRequestError = () => new Response(null, { + status: 400 +}); +var handleFetchError = (e) => new Response(null, { + status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 +}); +var handleResponseError = (e, outgoing) => { + const err = e instanceof Error ? e : new Error("unknown error", { cause: e }); + if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { + console.info("The user aborted a request."); + } else { + console.error(e); + if (!outgoing.headersSent) { + outgoing.writeHead(500, { "Content-Type": "text/plain" }); + } + outgoing.end(`Error: ${err.message}`); + outgoing.destroy(err); + } +}; +var flushHeaders = (outgoing) => { + if ("flushHeaders" in outgoing && outgoing.writable) { + outgoing.flushHeaders(); + } +}; +var responseViaCache = async (res, outgoing) => { + let [status, body, header] = res[cacheKey]; + if (header instanceof Headers) { + header = buildOutgoingHttpHeaders(header); + } + if (typeof body === "string") { + header["Content-Length"] = Buffer.byteLength(body); + } else if (body instanceof Uint8Array) { + header["Content-Length"] = body.byteLength; + } else if (body instanceof Blob) { + header["Content-Length"] = body.size; + } + outgoing.writeHead(status, header); + if (typeof body === "string" || body instanceof Uint8Array) { + outgoing.end(body); + } else if (body instanceof Blob) { + outgoing.end(new Uint8Array(await body.arrayBuffer())); + } else { + flushHeaders(outgoing); + await writeFromReadableStream(body, outgoing)?.catch( + (e) => handleResponseError(e, outgoing) + ); + } + ; + outgoing[outgoingEnded]?.(); +}; +var isPromise = (res) => typeof res.then === "function"; +var responseViaResponseObject = async (res, outgoing, options = {}) => { + if (isPromise(res)) { + if (options.errorHandler) { + try { + res = await res; + } catch (err) { + const errRes = await options.errorHandler(err); + if (!errRes) { + return; + } + res = errRes; + } + } else { + res = await res.catch(handleFetchError); + } + } + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); + if (res.body) { + const reader = res.body.getReader(); + const values = []; + let done = false; + let currentReadPromise = void 0; + if (resHeaderRecord["transfer-encoding"] !== "chunked") { + let maxReadCount = 2; + for (let i = 0; i < maxReadCount; i++) { + currentReadPromise ||= reader.read(); + const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => { + console.error(e); + done = true; + }); + if (!chunk) { + if (i === 1) { + await new Promise((resolve) => setTimeout(resolve)); + maxReadCount = 3; + continue; + } + break; + } + currentReadPromise = void 0; + if (chunk.value) { + values.push(chunk.value); + } + if (chunk.done) { + done = true; + break; + } + } + if (done && !("content-length" in resHeaderRecord)) { + resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0); + } + } + outgoing.writeHead(res.status, resHeaderRecord); + values.forEach((value) => { + ; + outgoing.write(value); + }); + if (done) { + outgoing.end(); + } else { + if (values.length === 0) { + flushHeaders(outgoing); + } + await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise); + } + } else if (resHeaderRecord[X_ALREADY_SENT]) { + } else { + outgoing.writeHead(res.status, resHeaderRecord); + outgoing.end(); + } + ; + outgoing[outgoingEnded]?.(); +}; +var getRequestListener = (fetchCallback, options = {}) => { + const autoCleanupIncoming = options.autoCleanupIncoming ?? true; + if (options.overrideGlobalObjects !== false && global.Request !== Request) { + Object.defineProperty(global, "Request", { + value: Request + }); + Object.defineProperty(global, "Response", { + value: Response2 + }); + } + return async (incoming, outgoing) => { + let res, req; + try { + req = newRequest(incoming, options.hostname); + let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD"; + if (!incomingEnded) { + ; + incoming[wrapBodyStream] = true; + incoming.on("end", () => { + incomingEnded = true; + }); + if (incoming instanceof import_node_http22.Http2ServerRequest) { + ; + outgoing[outgoingEnded] = () => { + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + outgoing.destroy(); + }); + } + }); + } + }; + } + } + outgoing.on("close", () => { + const abortController = req[abortControllerKey]; + if (abortController) { + if (incoming.errored) { + req[abortControllerKey].abort(incoming.errored.toString()); + } else if (!outgoing.writableFinished) { + req[abortControllerKey].abort("Client connection prematurely closed."); + } + } + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + }); + } + }); + } + }); + res = fetchCallback(req, { incoming, outgoing }); + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + } catch (e) { + if (!res) { + if (options.errorHandler) { + res = await options.errorHandler(req ? e : toRequestError(e)); + if (!res) { + return; + } + } else if (!req) { + res = handleRequestError(); + } else { + res = handleFetchError(e); + } + } else { + return handleResponseError(e, outgoing); + } + } + try { + return await responseViaResponseObject(res, outgoing, options); + } catch (e) { + return handleResponseError(e, outgoing); + } + }; +}; + +// src/server.ts +var createAdaptorServer = (options) => { + const fetchCallback = options.fetch; + const requestListener = getRequestListener(fetchCallback, { + hostname: options.hostname, + overrideGlobalObjects: options.overrideGlobalObjects, + autoCleanupIncoming: options.autoCleanupIncoming + }); + const createServer = options.createServer || import_node_http.createServer; + const server = createServer(options.serverOptions || {}, requestListener); + return server; +}; +var serve = (options, listeningListener) => { + const server = createAdaptorServer(options); + server.listen(options?.port ?? 3e3, options.hostname, () => { + const serverInfo = server.address(); + listeningListener && listeningListener(serverInfo); + }); + return server; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + createAdaptorServer, + serve +}); diff --git a/node_modules/@hono/node-server/dist/server.mjs b/node_modules/@hono/node-server/dist/server.mjs new file mode 100644 index 000000000..c24137822 --- /dev/null +++ b/node_modules/@hono/node-server/dist/server.mjs @@ -0,0 +1,571 @@ +// src/server.ts +import { createServer as createServerHTTP } from "http"; + +// src/listener.ts +import { Http2ServerRequest as Http2ServerRequest2 } from "http2"; + +// src/request.ts +import { Http2ServerRequest } from "http2"; +import { Readable } from "stream"; +var RequestError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "RequestError"; + } +}; +var toRequestError = (e) => { + if (e instanceof RequestError) { + return e; + } + return new RequestError(e.message, { cause: e }); +}; +var GlobalRequest = global.Request; +var Request = class extends GlobalRequest { + constructor(input, options) { + if (typeof input === "object" && getRequestCache in input) { + input = input[getRequestCache](); + } + if (typeof options?.body?.getReader !== "undefined") { + ; + options.duplex ??= "half"; + } + super(input, options); + } +}; +var newHeadersFromIncoming = (incoming) => { + const headerRecord = []; + const rawHeaders = incoming.rawHeaders; + for (let i = 0; i < rawHeaders.length; i += 2) { + const { [i]: key, [i + 1]: value } = rawHeaders; + if (key.charCodeAt(0) !== /*:*/ + 58) { + headerRecord.push([key, value]); + } + } + return new Headers(headerRecord); +}; +var wrapBodyStream = Symbol("wrapBodyStream"); +var newRequestFromIncoming = (method, url, headers, incoming, abortController) => { + const init = { + method, + headers, + signal: abortController.signal + }; + if (method === "TRACE") { + init.method = "GET"; + const req = new Request(url, init); + Object.defineProperty(req, "method", { + get() { + return "TRACE"; + } + }); + return req; + } + if (!(method === "GET" || method === "HEAD")) { + if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { + init.body = new ReadableStream({ + start(controller) { + controller.enqueue(incoming.rawBody); + controller.close(); + } + }); + } else if (incoming[wrapBodyStream]) { + let reader; + init.body = new ReadableStream({ + async pull(controller) { + try { + reader ||= Readable.toWeb(incoming).getReader(); + const { done, value } = await reader.read(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + } catch (error) { + controller.error(error); + } + } + }); + } else { + init.body = Readable.toWeb(incoming); + } + } + return new Request(url, init); +}; +var getRequestCache = Symbol("getRequestCache"); +var requestCache = Symbol("requestCache"); +var incomingKey = Symbol("incomingKey"); +var urlKey = Symbol("urlKey"); +var headersKey = Symbol("headersKey"); +var abortControllerKey = Symbol("abortControllerKey"); +var getAbortController = Symbol("getAbortController"); +var requestPrototype = { + get method() { + return this[incomingKey].method || "GET"; + }, + get url() { + return this[urlKey]; + }, + get headers() { + return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); + }, + [getAbortController]() { + this[getRequestCache](); + return this[abortControllerKey]; + }, + [getRequestCache]() { + this[abortControllerKey] ||= new AbortController(); + return this[requestCache] ||= newRequestFromIncoming( + this.method, + this[urlKey], + this.headers, + this[incomingKey], + this[abortControllerKey] + ); + } +}; +[ + "body", + "bodyUsed", + "cache", + "credentials", + "destination", + "integrity", + "mode", + "redirect", + "referrer", + "referrerPolicy", + "signal", + "keepalive" +].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + get() { + return this[getRequestCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + value: function() { + return this[getRequestCache]()[k](); + } + }); +}); +Object.setPrototypeOf(requestPrototype, Request.prototype); +var newRequest = (incoming, defaultHostname) => { + const req = Object.create(requestPrototype); + req[incomingKey] = incoming; + const incomingUrl = incoming.url || ""; + if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. + (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { + if (incoming instanceof Http2ServerRequest) { + throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); + } + try { + const url2 = new URL(incomingUrl); + req[urlKey] = url2.href; + } catch (e) { + throw new RequestError("Invalid absolute URL", { cause: e }); + } + return req; + } + const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; + if (!host) { + throw new RequestError("Missing host header"); + } + let scheme; + if (incoming instanceof Http2ServerRequest) { + scheme = incoming.scheme; + if (!(scheme === "http" || scheme === "https")) { + throw new RequestError("Unsupported scheme"); + } + } else { + scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; + } + const url = new URL(`${scheme}://${host}${incomingUrl}`); + if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) { + throw new RequestError("Invalid host header"); + } + req[urlKey] = url.href; + return req; +}; + +// src/response.ts +var responseCache = Symbol("responseCache"); +var getResponseCache = Symbol("getResponseCache"); +var cacheKey = Symbol("cache"); +var GlobalResponse = global.Response; +var Response2 = class _Response { + #body; + #init; + [getResponseCache]() { + delete this[cacheKey]; + return this[responseCache] ||= new GlobalResponse(this.#body, this.#init); + } + constructor(body, init) { + let headers; + this.#body = body; + if (init instanceof _Response) { + const cachedGlobalResponse = init[responseCache]; + if (cachedGlobalResponse) { + this.#init = cachedGlobalResponse; + this[getResponseCache](); + return; + } else { + this.#init = init.#init; + headers = new Headers(init.#init.headers); + } + } else { + this.#init = init; + } + if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { + headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" }; + this[cacheKey] = [init?.status || 200, body, headers]; + } + } + get headers() { + const cache = this[cacheKey]; + if (cache) { + if (!(cache[2] instanceof Headers)) { + cache[2] = new Headers(cache[2]); + } + return cache[2]; + } + return this[getResponseCache]().headers; + } + get status() { + return this[cacheKey]?.[0] ?? this[getResponseCache]().status; + } + get ok() { + const status = this.status; + return status >= 200 && status < 300; + } +}; +["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + get() { + return this[getResponseCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + value: function() { + return this[getResponseCache]()[k](); + } + }); +}); +Object.setPrototypeOf(Response2, GlobalResponse); +Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); + +// src/utils.ts +async function readWithoutBlocking(readPromise) { + return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); +} +function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { + const cancel = (error) => { + reader.cancel(error).catch(() => { + }); + }; + writable.on("close", cancel); + writable.on("error", cancel); + (currentReadPromise ?? reader.read()).then(flow, handleStreamError); + return reader.closed.finally(() => { + writable.off("close", cancel); + writable.off("error", cancel); + }); + function handleStreamError(error) { + if (error) { + writable.destroy(error); + } + } + function onDrain() { + reader.read().then(flow, handleStreamError); + } + function flow({ done, value }) { + try { + if (done) { + writable.end(); + } else if (!writable.write(value)) { + writable.once("drain", onDrain); + } else { + return reader.read().then(flow, handleStreamError); + } + } catch (e) { + handleStreamError(e); + } + } +} +function writeFromReadableStream(stream, writable) { + if (stream.locked) { + throw new TypeError("ReadableStream is locked."); + } else if (writable.destroyed) { + return; + } + return writeFromReadableStreamDefaultReader(stream.getReader(), writable); +} +var buildOutgoingHttpHeaders = (headers) => { + const res = {}; + if (!(headers instanceof Headers)) { + headers = new Headers(headers ?? void 0); + } + const cookies = []; + for (const [k, v] of headers) { + if (k === "set-cookie") { + cookies.push(v); + } else { + res[k] = v; + } + } + if (cookies.length > 0) { + res["set-cookie"] = cookies; + } + res["content-type"] ??= "text/plain; charset=UTF-8"; + return res; +}; + +// src/utils/response/constants.ts +var X_ALREADY_SENT = "x-hono-already-sent"; + +// src/globals.ts +import crypto from "crypto"; +if (typeof global.crypto === "undefined") { + global.crypto = crypto; +} + +// src/listener.ts +var outgoingEnded = Symbol("outgoingEnded"); +var handleRequestError = () => new Response(null, { + status: 400 +}); +var handleFetchError = (e) => new Response(null, { + status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 +}); +var handleResponseError = (e, outgoing) => { + const err = e instanceof Error ? e : new Error("unknown error", { cause: e }); + if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { + console.info("The user aborted a request."); + } else { + console.error(e); + if (!outgoing.headersSent) { + outgoing.writeHead(500, { "Content-Type": "text/plain" }); + } + outgoing.end(`Error: ${err.message}`); + outgoing.destroy(err); + } +}; +var flushHeaders = (outgoing) => { + if ("flushHeaders" in outgoing && outgoing.writable) { + outgoing.flushHeaders(); + } +}; +var responseViaCache = async (res, outgoing) => { + let [status, body, header] = res[cacheKey]; + if (header instanceof Headers) { + header = buildOutgoingHttpHeaders(header); + } + if (typeof body === "string") { + header["Content-Length"] = Buffer.byteLength(body); + } else if (body instanceof Uint8Array) { + header["Content-Length"] = body.byteLength; + } else if (body instanceof Blob) { + header["Content-Length"] = body.size; + } + outgoing.writeHead(status, header); + if (typeof body === "string" || body instanceof Uint8Array) { + outgoing.end(body); + } else if (body instanceof Blob) { + outgoing.end(new Uint8Array(await body.arrayBuffer())); + } else { + flushHeaders(outgoing); + await writeFromReadableStream(body, outgoing)?.catch( + (e) => handleResponseError(e, outgoing) + ); + } + ; + outgoing[outgoingEnded]?.(); +}; +var isPromise = (res) => typeof res.then === "function"; +var responseViaResponseObject = async (res, outgoing, options = {}) => { + if (isPromise(res)) { + if (options.errorHandler) { + try { + res = await res; + } catch (err) { + const errRes = await options.errorHandler(err); + if (!errRes) { + return; + } + res = errRes; + } + } else { + res = await res.catch(handleFetchError); + } + } + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); + if (res.body) { + const reader = res.body.getReader(); + const values = []; + let done = false; + let currentReadPromise = void 0; + if (resHeaderRecord["transfer-encoding"] !== "chunked") { + let maxReadCount = 2; + for (let i = 0; i < maxReadCount; i++) { + currentReadPromise ||= reader.read(); + const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => { + console.error(e); + done = true; + }); + if (!chunk) { + if (i === 1) { + await new Promise((resolve) => setTimeout(resolve)); + maxReadCount = 3; + continue; + } + break; + } + currentReadPromise = void 0; + if (chunk.value) { + values.push(chunk.value); + } + if (chunk.done) { + done = true; + break; + } + } + if (done && !("content-length" in resHeaderRecord)) { + resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0); + } + } + outgoing.writeHead(res.status, resHeaderRecord); + values.forEach((value) => { + ; + outgoing.write(value); + }); + if (done) { + outgoing.end(); + } else { + if (values.length === 0) { + flushHeaders(outgoing); + } + await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise); + } + } else if (resHeaderRecord[X_ALREADY_SENT]) { + } else { + outgoing.writeHead(res.status, resHeaderRecord); + outgoing.end(); + } + ; + outgoing[outgoingEnded]?.(); +}; +var getRequestListener = (fetchCallback, options = {}) => { + const autoCleanupIncoming = options.autoCleanupIncoming ?? true; + if (options.overrideGlobalObjects !== false && global.Request !== Request) { + Object.defineProperty(global, "Request", { + value: Request + }); + Object.defineProperty(global, "Response", { + value: Response2 + }); + } + return async (incoming, outgoing) => { + let res, req; + try { + req = newRequest(incoming, options.hostname); + let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD"; + if (!incomingEnded) { + ; + incoming[wrapBodyStream] = true; + incoming.on("end", () => { + incomingEnded = true; + }); + if (incoming instanceof Http2ServerRequest2) { + ; + outgoing[outgoingEnded] = () => { + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + outgoing.destroy(); + }); + } + }); + } + }; + } + } + outgoing.on("close", () => { + const abortController = req[abortControllerKey]; + if (abortController) { + if (incoming.errored) { + req[abortControllerKey].abort(incoming.errored.toString()); + } else if (!outgoing.writableFinished) { + req[abortControllerKey].abort("Client connection prematurely closed."); + } + } + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + }); + } + }); + } + }); + res = fetchCallback(req, { incoming, outgoing }); + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + } catch (e) { + if (!res) { + if (options.errorHandler) { + res = await options.errorHandler(req ? e : toRequestError(e)); + if (!res) { + return; + } + } else if (!req) { + res = handleRequestError(); + } else { + res = handleFetchError(e); + } + } else { + return handleResponseError(e, outgoing); + } + } + try { + return await responseViaResponseObject(res, outgoing, options); + } catch (e) { + return handleResponseError(e, outgoing); + } + }; +}; + +// src/server.ts +var createAdaptorServer = (options) => { + const fetchCallback = options.fetch; + const requestListener = getRequestListener(fetchCallback, { + hostname: options.hostname, + overrideGlobalObjects: options.overrideGlobalObjects, + autoCleanupIncoming: options.autoCleanupIncoming + }); + const createServer = options.createServer || createServerHTTP; + const server = createServer(options.serverOptions || {}, requestListener); + return server; +}; +var serve = (options, listeningListener) => { + const server = createAdaptorServer(options); + server.listen(options?.port ?? 3e3, options.hostname, () => { + const serverInfo = server.address(); + listeningListener && listeningListener(serverInfo); + }); + return server; +}; +export { + createAdaptorServer, + serve +}; diff --git a/node_modules/@hono/node-server/dist/types.d.mts b/node_modules/@hono/node-server/dist/types.d.mts new file mode 100644 index 000000000..adde70c9d --- /dev/null +++ b/node_modules/@hono/node-server/dist/types.d.mts @@ -0,0 +1,44 @@ +import { IncomingMessage, ServerResponse, Server, ServerOptions as ServerOptions$1, createServer } from 'node:http'; +import { Http2ServerRequest, Http2ServerResponse, Http2Server, Http2SecureServer, ServerOptions as ServerOptions$3, createServer as createServer$2, SecureServerOptions, createSecureServer } from 'node:http2'; +import { ServerOptions as ServerOptions$2, createServer as createServer$1 } from 'node:https'; + +type HttpBindings = { + incoming: IncomingMessage; + outgoing: ServerResponse; +}; +type Http2Bindings = { + incoming: Http2ServerRequest; + outgoing: Http2ServerResponse; +}; +type FetchCallback = (request: Request, env: HttpBindings | Http2Bindings) => Promise | unknown; +type NextHandlerOption = { + fetch: FetchCallback; +}; +type ServerType = Server | Http2Server | Http2SecureServer; +type createHttpOptions = { + serverOptions?: ServerOptions$1; + createServer?: typeof createServer; +}; +type createHttpsOptions = { + serverOptions?: ServerOptions$2; + createServer?: typeof createServer$1; +}; +type createHttp2Options = { + serverOptions?: ServerOptions$3; + createServer?: typeof createServer$2; +}; +type createSecureHttp2Options = { + serverOptions?: SecureServerOptions; + createServer?: typeof createSecureServer; +}; +type ServerOptions = createHttpOptions | createHttpsOptions | createHttp2Options | createSecureHttp2Options; +type Options = { + fetch: FetchCallback; + overrideGlobalObjects?: boolean; + autoCleanupIncoming?: boolean; + port?: number; + hostname?: string; +} & ServerOptions; +type CustomErrorHandler = (err: unknown) => void | Response | Promise; + +export { CustomErrorHandler, FetchCallback, Http2Bindings, HttpBindings, NextHandlerOption, Options, ServerOptions, ServerType }; diff --git a/node_modules/@hono/node-server/dist/types.d.ts b/node_modules/@hono/node-server/dist/types.d.ts new file mode 100644 index 000000000..adde70c9d --- /dev/null +++ b/node_modules/@hono/node-server/dist/types.d.ts @@ -0,0 +1,44 @@ +import { IncomingMessage, ServerResponse, Server, ServerOptions as ServerOptions$1, createServer } from 'node:http'; +import { Http2ServerRequest, Http2ServerResponse, Http2Server, Http2SecureServer, ServerOptions as ServerOptions$3, createServer as createServer$2, SecureServerOptions, createSecureServer } from 'node:http2'; +import { ServerOptions as ServerOptions$2, createServer as createServer$1 } from 'node:https'; + +type HttpBindings = { + incoming: IncomingMessage; + outgoing: ServerResponse; +}; +type Http2Bindings = { + incoming: Http2ServerRequest; + outgoing: Http2ServerResponse; +}; +type FetchCallback = (request: Request, env: HttpBindings | Http2Bindings) => Promise | unknown; +type NextHandlerOption = { + fetch: FetchCallback; +}; +type ServerType = Server | Http2Server | Http2SecureServer; +type createHttpOptions = { + serverOptions?: ServerOptions$1; + createServer?: typeof createServer; +}; +type createHttpsOptions = { + serverOptions?: ServerOptions$2; + createServer?: typeof createServer$1; +}; +type createHttp2Options = { + serverOptions?: ServerOptions$3; + createServer?: typeof createServer$2; +}; +type createSecureHttp2Options = { + serverOptions?: SecureServerOptions; + createServer?: typeof createSecureServer; +}; +type ServerOptions = createHttpOptions | createHttpsOptions | createHttp2Options | createSecureHttp2Options; +type Options = { + fetch: FetchCallback; + overrideGlobalObjects?: boolean; + autoCleanupIncoming?: boolean; + port?: number; + hostname?: string; +} & ServerOptions; +type CustomErrorHandler = (err: unknown) => void | Response | Promise; + +export { CustomErrorHandler, FetchCallback, Http2Bindings, HttpBindings, NextHandlerOption, Options, ServerOptions, ServerType }; diff --git a/node_modules/@hono/node-server/dist/types.js b/node_modules/@hono/node-server/dist/types.js new file mode 100644 index 000000000..14bbc9e0e --- /dev/null +++ b/node_modules/@hono/node-server/dist/types.js @@ -0,0 +1,18 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +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/types.ts +var types_exports = {}; +module.exports = __toCommonJS(types_exports); diff --git a/node_modules/@hono/node-server/dist/types.mjs b/node_modules/@hono/node-server/dist/types.mjs new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/@hono/node-server/dist/utils.d.mts b/node_modules/@hono/node-server/dist/utils.d.mts new file mode 100644 index 000000000..6240c5eca --- /dev/null +++ b/node_modules/@hono/node-server/dist/utils.d.mts @@ -0,0 +1,9 @@ +import { OutgoingHttpHeaders } from 'node:http'; +import { Writable } from 'node:stream'; + +declare function readWithoutBlocking(readPromise: Promise>): Promise | undefined>; +declare function writeFromReadableStreamDefaultReader(reader: ReadableStreamDefaultReader, writable: Writable, currentReadPromise?: Promise> | undefined): Promise; +declare function writeFromReadableStream(stream: ReadableStream, writable: Writable): Promise | undefined; +declare const buildOutgoingHttpHeaders: (headers: Headers | HeadersInit | null | undefined) => OutgoingHttpHeaders; + +export { buildOutgoingHttpHeaders, readWithoutBlocking, writeFromReadableStream, writeFromReadableStreamDefaultReader }; diff --git a/node_modules/@hono/node-server/dist/utils.d.ts b/node_modules/@hono/node-server/dist/utils.d.ts new file mode 100644 index 000000000..6240c5eca --- /dev/null +++ b/node_modules/@hono/node-server/dist/utils.d.ts @@ -0,0 +1,9 @@ +import { OutgoingHttpHeaders } from 'node:http'; +import { Writable } from 'node:stream'; + +declare function readWithoutBlocking(readPromise: Promise>): Promise | undefined>; +declare function writeFromReadableStreamDefaultReader(reader: ReadableStreamDefaultReader, writable: Writable, currentReadPromise?: Promise> | undefined): Promise; +declare function writeFromReadableStream(stream: ReadableStream, writable: Writable): Promise | undefined; +declare const buildOutgoingHttpHeaders: (headers: Headers | HeadersInit | null | undefined) => OutgoingHttpHeaders; + +export { buildOutgoingHttpHeaders, readWithoutBlocking, writeFromReadableStream, writeFromReadableStreamDefaultReader }; diff --git a/node_modules/@hono/node-server/dist/utils.js b/node_modules/@hono/node-server/dist/utils.js new file mode 100644 index 000000000..7d416f142 --- /dev/null +++ b/node_modules/@hono/node-server/dist/utils.js @@ -0,0 +1,99 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/utils.ts +var utils_exports = {}; +__export(utils_exports, { + buildOutgoingHttpHeaders: () => buildOutgoingHttpHeaders, + readWithoutBlocking: () => readWithoutBlocking, + writeFromReadableStream: () => writeFromReadableStream, + writeFromReadableStreamDefaultReader: () => writeFromReadableStreamDefaultReader +}); +module.exports = __toCommonJS(utils_exports); +async function readWithoutBlocking(readPromise) { + return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); +} +function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { + const cancel = (error) => { + reader.cancel(error).catch(() => { + }); + }; + writable.on("close", cancel); + writable.on("error", cancel); + (currentReadPromise ?? reader.read()).then(flow, handleStreamError); + return reader.closed.finally(() => { + writable.off("close", cancel); + writable.off("error", cancel); + }); + function handleStreamError(error) { + if (error) { + writable.destroy(error); + } + } + function onDrain() { + reader.read().then(flow, handleStreamError); + } + function flow({ done, value }) { + try { + if (done) { + writable.end(); + } else if (!writable.write(value)) { + writable.once("drain", onDrain); + } else { + return reader.read().then(flow, handleStreamError); + } + } catch (e) { + handleStreamError(e); + } + } +} +function writeFromReadableStream(stream, writable) { + if (stream.locked) { + throw new TypeError("ReadableStream is locked."); + } else if (writable.destroyed) { + return; + } + return writeFromReadableStreamDefaultReader(stream.getReader(), writable); +} +var buildOutgoingHttpHeaders = (headers) => { + const res = {}; + if (!(headers instanceof Headers)) { + headers = new Headers(headers ?? void 0); + } + const cookies = []; + for (const [k, v] of headers) { + if (k === "set-cookie") { + cookies.push(v); + } else { + res[k] = v; + } + } + if (cookies.length > 0) { + res["set-cookie"] = cookies; + } + res["content-type"] ??= "text/plain; charset=UTF-8"; + return res; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + buildOutgoingHttpHeaders, + readWithoutBlocking, + writeFromReadableStream, + writeFromReadableStreamDefaultReader +}); diff --git a/node_modules/@hono/node-server/dist/utils.mjs b/node_modules/@hono/node-server/dist/utils.mjs new file mode 100644 index 000000000..5184acbdf --- /dev/null +++ b/node_modules/@hono/node-server/dist/utils.mjs @@ -0,0 +1,71 @@ +// src/utils.ts +async function readWithoutBlocking(readPromise) { + return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); +} +function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { + const cancel = (error) => { + reader.cancel(error).catch(() => { + }); + }; + writable.on("close", cancel); + writable.on("error", cancel); + (currentReadPromise ?? reader.read()).then(flow, handleStreamError); + return reader.closed.finally(() => { + writable.off("close", cancel); + writable.off("error", cancel); + }); + function handleStreamError(error) { + if (error) { + writable.destroy(error); + } + } + function onDrain() { + reader.read().then(flow, handleStreamError); + } + function flow({ done, value }) { + try { + if (done) { + writable.end(); + } else if (!writable.write(value)) { + writable.once("drain", onDrain); + } else { + return reader.read().then(flow, handleStreamError); + } + } catch (e) { + handleStreamError(e); + } + } +} +function writeFromReadableStream(stream, writable) { + if (stream.locked) { + throw new TypeError("ReadableStream is locked."); + } else if (writable.destroyed) { + return; + } + return writeFromReadableStreamDefaultReader(stream.getReader(), writable); +} +var buildOutgoingHttpHeaders = (headers) => { + const res = {}; + if (!(headers instanceof Headers)) { + headers = new Headers(headers ?? void 0); + } + const cookies = []; + for (const [k, v] of headers) { + if (k === "set-cookie") { + cookies.push(v); + } else { + res[k] = v; + } + } + if (cookies.length > 0) { + res["set-cookie"] = cookies; + } + res["content-type"] ??= "text/plain; charset=UTF-8"; + return res; +}; +export { + buildOutgoingHttpHeaders, + readWithoutBlocking, + writeFromReadableStream, + writeFromReadableStreamDefaultReader +}; diff --git a/node_modules/@hono/node-server/dist/utils/response.d.mts b/node_modules/@hono/node-server/dist/utils/response.d.mts new file mode 100644 index 000000000..523b753e0 --- /dev/null +++ b/node_modules/@hono/node-server/dist/utils/response.d.mts @@ -0,0 +1,3 @@ +declare const RESPONSE_ALREADY_SENT: Response; + +export { RESPONSE_ALREADY_SENT }; diff --git a/node_modules/@hono/node-server/dist/utils/response.d.ts b/node_modules/@hono/node-server/dist/utils/response.d.ts new file mode 100644 index 000000000..523b753e0 --- /dev/null +++ b/node_modules/@hono/node-server/dist/utils/response.d.ts @@ -0,0 +1,3 @@ +declare const RESPONSE_ALREADY_SENT: Response; + +export { RESPONSE_ALREADY_SENT }; diff --git a/node_modules/@hono/node-server/dist/utils/response.js b/node_modules/@hono/node-server/dist/utils/response.js new file mode 100644 index 000000000..6fe007b6a --- /dev/null +++ b/node_modules/@hono/node-server/dist/utils/response.js @@ -0,0 +1,37 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/utils/response.ts +var response_exports = {}; +__export(response_exports, { + RESPONSE_ALREADY_SENT: () => RESPONSE_ALREADY_SENT +}); +module.exports = __toCommonJS(response_exports); + +// src/utils/response/constants.ts +var X_ALREADY_SENT = "x-hono-already-sent"; + +// src/utils/response.ts +var RESPONSE_ALREADY_SENT = new Response(null, { + headers: { [X_ALREADY_SENT]: "true" } +}); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + RESPONSE_ALREADY_SENT +}); diff --git a/node_modules/@hono/node-server/dist/utils/response.mjs b/node_modules/@hono/node-server/dist/utils/response.mjs new file mode 100644 index 000000000..5d42aaaec --- /dev/null +++ b/node_modules/@hono/node-server/dist/utils/response.mjs @@ -0,0 +1,10 @@ +// src/utils/response/constants.ts +var X_ALREADY_SENT = "x-hono-already-sent"; + +// src/utils/response.ts +var RESPONSE_ALREADY_SENT = new Response(null, { + headers: { [X_ALREADY_SENT]: "true" } +}); +export { + RESPONSE_ALREADY_SENT +}; diff --git a/node_modules/@hono/node-server/dist/utils/response/constants.d.mts b/node_modules/@hono/node-server/dist/utils/response/constants.d.mts new file mode 100644 index 000000000..f09b912b4 --- /dev/null +++ b/node_modules/@hono/node-server/dist/utils/response/constants.d.mts @@ -0,0 +1,3 @@ +declare const X_ALREADY_SENT = "x-hono-already-sent"; + +export { X_ALREADY_SENT }; diff --git a/node_modules/@hono/node-server/dist/utils/response/constants.d.ts b/node_modules/@hono/node-server/dist/utils/response/constants.d.ts new file mode 100644 index 000000000..f09b912b4 --- /dev/null +++ b/node_modules/@hono/node-server/dist/utils/response/constants.d.ts @@ -0,0 +1,3 @@ +declare const X_ALREADY_SENT = "x-hono-already-sent"; + +export { X_ALREADY_SENT }; diff --git a/node_modules/@hono/node-server/dist/utils/response/constants.js b/node_modules/@hono/node-server/dist/utils/response/constants.js new file mode 100644 index 000000000..615e7c521 --- /dev/null +++ b/node_modules/@hono/node-server/dist/utils/response/constants.js @@ -0,0 +1,30 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/utils/response/constants.ts +var constants_exports = {}; +__export(constants_exports, { + X_ALREADY_SENT: () => X_ALREADY_SENT +}); +module.exports = __toCommonJS(constants_exports); +var X_ALREADY_SENT = "x-hono-already-sent"; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + X_ALREADY_SENT +}); diff --git a/node_modules/@hono/node-server/dist/utils/response/constants.mjs b/node_modules/@hono/node-server/dist/utils/response/constants.mjs new file mode 100644 index 000000000..e6ed45f81 --- /dev/null +++ b/node_modules/@hono/node-server/dist/utils/response/constants.mjs @@ -0,0 +1,5 @@ +// src/utils/response/constants.ts +var X_ALREADY_SENT = "x-hono-already-sent"; +export { + X_ALREADY_SENT +}; diff --git a/node_modules/@hono/node-server/dist/vercel.d.mts b/node_modules/@hono/node-server/dist/vercel.d.mts new file mode 100644 index 000000000..d187c0582 --- /dev/null +++ b/node_modules/@hono/node-server/dist/vercel.d.mts @@ -0,0 +1,7 @@ +import * as http2 from 'http2'; +import * as http from 'http'; +import { Hono } from 'hono'; + +declare const handle: (app: Hono) => (incoming: http.IncomingMessage | http2.Http2ServerRequest, outgoing: http.ServerResponse | http2.Http2ServerResponse) => Promise; + +export { handle }; diff --git a/node_modules/@hono/node-server/dist/vercel.d.ts b/node_modules/@hono/node-server/dist/vercel.d.ts new file mode 100644 index 000000000..d187c0582 --- /dev/null +++ b/node_modules/@hono/node-server/dist/vercel.d.ts @@ -0,0 +1,7 @@ +import * as http2 from 'http2'; +import * as http from 'http'; +import { Hono } from 'hono'; + +declare const handle: (app: Hono) => (incoming: http.IncomingMessage | http2.Http2ServerRequest, outgoing: http.ServerResponse | http2.Http2ServerResponse) => Promise; + +export { handle }; diff --git a/node_modules/@hono/node-server/dist/vercel.js b/node_modules/@hono/node-server/dist/vercel.js new file mode 100644 index 000000000..63def623e --- /dev/null +++ b/node_modules/@hono/node-server/dist/vercel.js @@ -0,0 +1,588 @@ +"use strict"; +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 __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 __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 +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/vercel.ts +var vercel_exports = {}; +__export(vercel_exports, { + handle: () => handle +}); +module.exports = __toCommonJS(vercel_exports); + +// src/listener.ts +var import_node_http22 = require("http2"); + +// src/request.ts +var import_node_http2 = require("http2"); +var import_node_stream = require("stream"); +var RequestError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "RequestError"; + } +}; +var toRequestError = (e) => { + if (e instanceof RequestError) { + return e; + } + return new RequestError(e.message, { cause: e }); +}; +var GlobalRequest = global.Request; +var Request = class extends GlobalRequest { + constructor(input, options) { + if (typeof input === "object" && getRequestCache in input) { + input = input[getRequestCache](); + } + if (typeof options?.body?.getReader !== "undefined") { + ; + options.duplex ??= "half"; + } + super(input, options); + } +}; +var newHeadersFromIncoming = (incoming) => { + const headerRecord = []; + const rawHeaders = incoming.rawHeaders; + for (let i = 0; i < rawHeaders.length; i += 2) { + const { [i]: key, [i + 1]: value } = rawHeaders; + if (key.charCodeAt(0) !== /*:*/ + 58) { + headerRecord.push([key, value]); + } + } + return new Headers(headerRecord); +}; +var wrapBodyStream = Symbol("wrapBodyStream"); +var newRequestFromIncoming = (method, url, headers, incoming, abortController) => { + const init = { + method, + headers, + signal: abortController.signal + }; + if (method === "TRACE") { + init.method = "GET"; + const req = new Request(url, init); + Object.defineProperty(req, "method", { + get() { + return "TRACE"; + } + }); + return req; + } + if (!(method === "GET" || method === "HEAD")) { + if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { + init.body = new ReadableStream({ + start(controller) { + controller.enqueue(incoming.rawBody); + controller.close(); + } + }); + } else if (incoming[wrapBodyStream]) { + let reader; + init.body = new ReadableStream({ + async pull(controller) { + try { + reader ||= import_node_stream.Readable.toWeb(incoming).getReader(); + const { done, value } = await reader.read(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + } catch (error) { + controller.error(error); + } + } + }); + } else { + init.body = import_node_stream.Readable.toWeb(incoming); + } + } + return new Request(url, init); +}; +var getRequestCache = Symbol("getRequestCache"); +var requestCache = Symbol("requestCache"); +var incomingKey = Symbol("incomingKey"); +var urlKey = Symbol("urlKey"); +var headersKey = Symbol("headersKey"); +var abortControllerKey = Symbol("abortControllerKey"); +var getAbortController = Symbol("getAbortController"); +var requestPrototype = { + get method() { + return this[incomingKey].method || "GET"; + }, + get url() { + return this[urlKey]; + }, + get headers() { + return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); + }, + [getAbortController]() { + this[getRequestCache](); + return this[abortControllerKey]; + }, + [getRequestCache]() { + this[abortControllerKey] ||= new AbortController(); + return this[requestCache] ||= newRequestFromIncoming( + this.method, + this[urlKey], + this.headers, + this[incomingKey], + this[abortControllerKey] + ); + } +}; +[ + "body", + "bodyUsed", + "cache", + "credentials", + "destination", + "integrity", + "mode", + "redirect", + "referrer", + "referrerPolicy", + "signal", + "keepalive" +].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + get() { + return this[getRequestCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + value: function() { + return this[getRequestCache]()[k](); + } + }); +}); +Object.setPrototypeOf(requestPrototype, Request.prototype); +var newRequest = (incoming, defaultHostname) => { + const req = Object.create(requestPrototype); + req[incomingKey] = incoming; + const incomingUrl = incoming.url || ""; + if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. + (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { + if (incoming instanceof import_node_http2.Http2ServerRequest) { + throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); + } + try { + const url2 = new URL(incomingUrl); + req[urlKey] = url2.href; + } catch (e) { + throw new RequestError("Invalid absolute URL", { cause: e }); + } + return req; + } + const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; + if (!host) { + throw new RequestError("Missing host header"); + } + let scheme; + if (incoming instanceof import_node_http2.Http2ServerRequest) { + scheme = incoming.scheme; + if (!(scheme === "http" || scheme === "https")) { + throw new RequestError("Unsupported scheme"); + } + } else { + scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; + } + const url = new URL(`${scheme}://${host}${incomingUrl}`); + if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) { + throw new RequestError("Invalid host header"); + } + req[urlKey] = url.href; + return req; +}; + +// src/response.ts +var responseCache = Symbol("responseCache"); +var getResponseCache = Symbol("getResponseCache"); +var cacheKey = Symbol("cache"); +var GlobalResponse = global.Response; +var Response2 = class _Response { + #body; + #init; + [getResponseCache]() { + delete this[cacheKey]; + return this[responseCache] ||= new GlobalResponse(this.#body, this.#init); + } + constructor(body, init) { + let headers; + this.#body = body; + if (init instanceof _Response) { + const cachedGlobalResponse = init[responseCache]; + if (cachedGlobalResponse) { + this.#init = cachedGlobalResponse; + this[getResponseCache](); + return; + } else { + this.#init = init.#init; + headers = new Headers(init.#init.headers); + } + } else { + this.#init = init; + } + if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { + headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" }; + this[cacheKey] = [init?.status || 200, body, headers]; + } + } + get headers() { + const cache = this[cacheKey]; + if (cache) { + if (!(cache[2] instanceof Headers)) { + cache[2] = new Headers(cache[2]); + } + return cache[2]; + } + return this[getResponseCache]().headers; + } + get status() { + return this[cacheKey]?.[0] ?? this[getResponseCache]().status; + } + get ok() { + const status = this.status; + return status >= 200 && status < 300; + } +}; +["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + get() { + return this[getResponseCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + value: function() { + return this[getResponseCache]()[k](); + } + }); +}); +Object.setPrototypeOf(Response2, GlobalResponse); +Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); + +// src/utils.ts +async function readWithoutBlocking(readPromise) { + return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); +} +function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { + const cancel = (error) => { + reader.cancel(error).catch(() => { + }); + }; + writable.on("close", cancel); + writable.on("error", cancel); + (currentReadPromise ?? reader.read()).then(flow, handleStreamError); + return reader.closed.finally(() => { + writable.off("close", cancel); + writable.off("error", cancel); + }); + function handleStreamError(error) { + if (error) { + writable.destroy(error); + } + } + function onDrain() { + reader.read().then(flow, handleStreamError); + } + function flow({ done, value }) { + try { + if (done) { + writable.end(); + } else if (!writable.write(value)) { + writable.once("drain", onDrain); + } else { + return reader.read().then(flow, handleStreamError); + } + } catch (e) { + handleStreamError(e); + } + } +} +function writeFromReadableStream(stream, writable) { + if (stream.locked) { + throw new TypeError("ReadableStream is locked."); + } else if (writable.destroyed) { + return; + } + return writeFromReadableStreamDefaultReader(stream.getReader(), writable); +} +var buildOutgoingHttpHeaders = (headers) => { + const res = {}; + if (!(headers instanceof Headers)) { + headers = new Headers(headers ?? void 0); + } + const cookies = []; + for (const [k, v] of headers) { + if (k === "set-cookie") { + cookies.push(v); + } else { + res[k] = v; + } + } + if (cookies.length > 0) { + res["set-cookie"] = cookies; + } + res["content-type"] ??= "text/plain; charset=UTF-8"; + return res; +}; + +// src/utils/response/constants.ts +var X_ALREADY_SENT = "x-hono-already-sent"; + +// src/globals.ts +var import_node_crypto = __toESM(require("crypto")); +if (typeof global.crypto === "undefined") { + global.crypto = import_node_crypto.default; +} + +// src/listener.ts +var outgoingEnded = Symbol("outgoingEnded"); +var handleRequestError = () => new Response(null, { + status: 400 +}); +var handleFetchError = (e) => new Response(null, { + status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 +}); +var handleResponseError = (e, outgoing) => { + const err = e instanceof Error ? e : new Error("unknown error", { cause: e }); + if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { + console.info("The user aborted a request."); + } else { + console.error(e); + if (!outgoing.headersSent) { + outgoing.writeHead(500, { "Content-Type": "text/plain" }); + } + outgoing.end(`Error: ${err.message}`); + outgoing.destroy(err); + } +}; +var flushHeaders = (outgoing) => { + if ("flushHeaders" in outgoing && outgoing.writable) { + outgoing.flushHeaders(); + } +}; +var responseViaCache = async (res, outgoing) => { + let [status, body, header] = res[cacheKey]; + if (header instanceof Headers) { + header = buildOutgoingHttpHeaders(header); + } + if (typeof body === "string") { + header["Content-Length"] = Buffer.byteLength(body); + } else if (body instanceof Uint8Array) { + header["Content-Length"] = body.byteLength; + } else if (body instanceof Blob) { + header["Content-Length"] = body.size; + } + outgoing.writeHead(status, header); + if (typeof body === "string" || body instanceof Uint8Array) { + outgoing.end(body); + } else if (body instanceof Blob) { + outgoing.end(new Uint8Array(await body.arrayBuffer())); + } else { + flushHeaders(outgoing); + await writeFromReadableStream(body, outgoing)?.catch( + (e) => handleResponseError(e, outgoing) + ); + } + ; + outgoing[outgoingEnded]?.(); +}; +var isPromise = (res) => typeof res.then === "function"; +var responseViaResponseObject = async (res, outgoing, options = {}) => { + if (isPromise(res)) { + if (options.errorHandler) { + try { + res = await res; + } catch (err) { + const errRes = await options.errorHandler(err); + if (!errRes) { + return; + } + res = errRes; + } + } else { + res = await res.catch(handleFetchError); + } + } + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); + if (res.body) { + const reader = res.body.getReader(); + const values = []; + let done = false; + let currentReadPromise = void 0; + if (resHeaderRecord["transfer-encoding"] !== "chunked") { + let maxReadCount = 2; + for (let i = 0; i < maxReadCount; i++) { + currentReadPromise ||= reader.read(); + const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => { + console.error(e); + done = true; + }); + if (!chunk) { + if (i === 1) { + await new Promise((resolve) => setTimeout(resolve)); + maxReadCount = 3; + continue; + } + break; + } + currentReadPromise = void 0; + if (chunk.value) { + values.push(chunk.value); + } + if (chunk.done) { + done = true; + break; + } + } + if (done && !("content-length" in resHeaderRecord)) { + resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0); + } + } + outgoing.writeHead(res.status, resHeaderRecord); + values.forEach((value) => { + ; + outgoing.write(value); + }); + if (done) { + outgoing.end(); + } else { + if (values.length === 0) { + flushHeaders(outgoing); + } + await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise); + } + } else if (resHeaderRecord[X_ALREADY_SENT]) { + } else { + outgoing.writeHead(res.status, resHeaderRecord); + outgoing.end(); + } + ; + outgoing[outgoingEnded]?.(); +}; +var getRequestListener = (fetchCallback, options = {}) => { + const autoCleanupIncoming = options.autoCleanupIncoming ?? true; + if (options.overrideGlobalObjects !== false && global.Request !== Request) { + Object.defineProperty(global, "Request", { + value: Request + }); + Object.defineProperty(global, "Response", { + value: Response2 + }); + } + return async (incoming, outgoing) => { + let res, req; + try { + req = newRequest(incoming, options.hostname); + let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD"; + if (!incomingEnded) { + ; + incoming[wrapBodyStream] = true; + incoming.on("end", () => { + incomingEnded = true; + }); + if (incoming instanceof import_node_http22.Http2ServerRequest) { + ; + outgoing[outgoingEnded] = () => { + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + outgoing.destroy(); + }); + } + }); + } + }; + } + } + outgoing.on("close", () => { + const abortController = req[abortControllerKey]; + if (abortController) { + if (incoming.errored) { + req[abortControllerKey].abort(incoming.errored.toString()); + } else if (!outgoing.writableFinished) { + req[abortControllerKey].abort("Client connection prematurely closed."); + } + } + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + }); + } + }); + } + }); + res = fetchCallback(req, { incoming, outgoing }); + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + } catch (e) { + if (!res) { + if (options.errorHandler) { + res = await options.errorHandler(req ? e : toRequestError(e)); + if (!res) { + return; + } + } else if (!req) { + res = handleRequestError(); + } else { + res = handleFetchError(e); + } + } else { + return handleResponseError(e, outgoing); + } + } + try { + return await responseViaResponseObject(res, outgoing, options); + } catch (e) { + return handleResponseError(e, outgoing); + } + }; +}; + +// src/vercel.ts +var handle = (app) => { + return getRequestListener(app.fetch); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + handle +}); diff --git a/node_modules/@hono/node-server/dist/vercel.mjs b/node_modules/@hono/node-server/dist/vercel.mjs new file mode 100644 index 000000000..334c1c85a --- /dev/null +++ b/node_modules/@hono/node-server/dist/vercel.mjs @@ -0,0 +1,551 @@ +// src/listener.ts +import { Http2ServerRequest as Http2ServerRequest2 } from "http2"; + +// src/request.ts +import { Http2ServerRequest } from "http2"; +import { Readable } from "stream"; +var RequestError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "RequestError"; + } +}; +var toRequestError = (e) => { + if (e instanceof RequestError) { + return e; + } + return new RequestError(e.message, { cause: e }); +}; +var GlobalRequest = global.Request; +var Request = class extends GlobalRequest { + constructor(input, options) { + if (typeof input === "object" && getRequestCache in input) { + input = input[getRequestCache](); + } + if (typeof options?.body?.getReader !== "undefined") { + ; + options.duplex ??= "half"; + } + super(input, options); + } +}; +var newHeadersFromIncoming = (incoming) => { + const headerRecord = []; + const rawHeaders = incoming.rawHeaders; + for (let i = 0; i < rawHeaders.length; i += 2) { + const { [i]: key, [i + 1]: value } = rawHeaders; + if (key.charCodeAt(0) !== /*:*/ + 58) { + headerRecord.push([key, value]); + } + } + return new Headers(headerRecord); +}; +var wrapBodyStream = Symbol("wrapBodyStream"); +var newRequestFromIncoming = (method, url, headers, incoming, abortController) => { + const init = { + method, + headers, + signal: abortController.signal + }; + if (method === "TRACE") { + init.method = "GET"; + const req = new Request(url, init); + Object.defineProperty(req, "method", { + get() { + return "TRACE"; + } + }); + return req; + } + if (!(method === "GET" || method === "HEAD")) { + if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { + init.body = new ReadableStream({ + start(controller) { + controller.enqueue(incoming.rawBody); + controller.close(); + } + }); + } else if (incoming[wrapBodyStream]) { + let reader; + init.body = new ReadableStream({ + async pull(controller) { + try { + reader ||= Readable.toWeb(incoming).getReader(); + const { done, value } = await reader.read(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + } catch (error) { + controller.error(error); + } + } + }); + } else { + init.body = Readable.toWeb(incoming); + } + } + return new Request(url, init); +}; +var getRequestCache = Symbol("getRequestCache"); +var requestCache = Symbol("requestCache"); +var incomingKey = Symbol("incomingKey"); +var urlKey = Symbol("urlKey"); +var headersKey = Symbol("headersKey"); +var abortControllerKey = Symbol("abortControllerKey"); +var getAbortController = Symbol("getAbortController"); +var requestPrototype = { + get method() { + return this[incomingKey].method || "GET"; + }, + get url() { + return this[urlKey]; + }, + get headers() { + return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); + }, + [getAbortController]() { + this[getRequestCache](); + return this[abortControllerKey]; + }, + [getRequestCache]() { + this[abortControllerKey] ||= new AbortController(); + return this[requestCache] ||= newRequestFromIncoming( + this.method, + this[urlKey], + this.headers, + this[incomingKey], + this[abortControllerKey] + ); + } +}; +[ + "body", + "bodyUsed", + "cache", + "credentials", + "destination", + "integrity", + "mode", + "redirect", + "referrer", + "referrerPolicy", + "signal", + "keepalive" +].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + get() { + return this[getRequestCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(requestPrototype, k, { + value: function() { + return this[getRequestCache]()[k](); + } + }); +}); +Object.setPrototypeOf(requestPrototype, Request.prototype); +var newRequest = (incoming, defaultHostname) => { + const req = Object.create(requestPrototype); + req[incomingKey] = incoming; + const incomingUrl = incoming.url || ""; + if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. + (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { + if (incoming instanceof Http2ServerRequest) { + throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); + } + try { + const url2 = new URL(incomingUrl); + req[urlKey] = url2.href; + } catch (e) { + throw new RequestError("Invalid absolute URL", { cause: e }); + } + return req; + } + const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; + if (!host) { + throw new RequestError("Missing host header"); + } + let scheme; + if (incoming instanceof Http2ServerRequest) { + scheme = incoming.scheme; + if (!(scheme === "http" || scheme === "https")) { + throw new RequestError("Unsupported scheme"); + } + } else { + scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; + } + const url = new URL(`${scheme}://${host}${incomingUrl}`); + if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) { + throw new RequestError("Invalid host header"); + } + req[urlKey] = url.href; + return req; +}; + +// src/response.ts +var responseCache = Symbol("responseCache"); +var getResponseCache = Symbol("getResponseCache"); +var cacheKey = Symbol("cache"); +var GlobalResponse = global.Response; +var Response2 = class _Response { + #body; + #init; + [getResponseCache]() { + delete this[cacheKey]; + return this[responseCache] ||= new GlobalResponse(this.#body, this.#init); + } + constructor(body, init) { + let headers; + this.#body = body; + if (init instanceof _Response) { + const cachedGlobalResponse = init[responseCache]; + if (cachedGlobalResponse) { + this.#init = cachedGlobalResponse; + this[getResponseCache](); + return; + } else { + this.#init = init.#init; + headers = new Headers(init.#init.headers); + } + } else { + this.#init = init; + } + if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { + headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" }; + this[cacheKey] = [init?.status || 200, body, headers]; + } + } + get headers() { + const cache = this[cacheKey]; + if (cache) { + if (!(cache[2] instanceof Headers)) { + cache[2] = new Headers(cache[2]); + } + return cache[2]; + } + return this[getResponseCache]().headers; + } + get status() { + return this[cacheKey]?.[0] ?? this[getResponseCache]().status; + } + get ok() { + const status = this.status; + return status >= 200 && status < 300; + } +}; +["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + get() { + return this[getResponseCache]()[k]; + } + }); +}); +["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { + Object.defineProperty(Response2.prototype, k, { + value: function() { + return this[getResponseCache]()[k](); + } + }); +}); +Object.setPrototypeOf(Response2, GlobalResponse); +Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); + +// src/utils.ts +async function readWithoutBlocking(readPromise) { + return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); +} +function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { + const cancel = (error) => { + reader.cancel(error).catch(() => { + }); + }; + writable.on("close", cancel); + writable.on("error", cancel); + (currentReadPromise ?? reader.read()).then(flow, handleStreamError); + return reader.closed.finally(() => { + writable.off("close", cancel); + writable.off("error", cancel); + }); + function handleStreamError(error) { + if (error) { + writable.destroy(error); + } + } + function onDrain() { + reader.read().then(flow, handleStreamError); + } + function flow({ done, value }) { + try { + if (done) { + writable.end(); + } else if (!writable.write(value)) { + writable.once("drain", onDrain); + } else { + return reader.read().then(flow, handleStreamError); + } + } catch (e) { + handleStreamError(e); + } + } +} +function writeFromReadableStream(stream, writable) { + if (stream.locked) { + throw new TypeError("ReadableStream is locked."); + } else if (writable.destroyed) { + return; + } + return writeFromReadableStreamDefaultReader(stream.getReader(), writable); +} +var buildOutgoingHttpHeaders = (headers) => { + const res = {}; + if (!(headers instanceof Headers)) { + headers = new Headers(headers ?? void 0); + } + const cookies = []; + for (const [k, v] of headers) { + if (k === "set-cookie") { + cookies.push(v); + } else { + res[k] = v; + } + } + if (cookies.length > 0) { + res["set-cookie"] = cookies; + } + res["content-type"] ??= "text/plain; charset=UTF-8"; + return res; +}; + +// src/utils/response/constants.ts +var X_ALREADY_SENT = "x-hono-already-sent"; + +// src/globals.ts +import crypto from "crypto"; +if (typeof global.crypto === "undefined") { + global.crypto = crypto; +} + +// src/listener.ts +var outgoingEnded = Symbol("outgoingEnded"); +var handleRequestError = () => new Response(null, { + status: 400 +}); +var handleFetchError = (e) => new Response(null, { + status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 +}); +var handleResponseError = (e, outgoing) => { + const err = e instanceof Error ? e : new Error("unknown error", { cause: e }); + if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { + console.info("The user aborted a request."); + } else { + console.error(e); + if (!outgoing.headersSent) { + outgoing.writeHead(500, { "Content-Type": "text/plain" }); + } + outgoing.end(`Error: ${err.message}`); + outgoing.destroy(err); + } +}; +var flushHeaders = (outgoing) => { + if ("flushHeaders" in outgoing && outgoing.writable) { + outgoing.flushHeaders(); + } +}; +var responseViaCache = async (res, outgoing) => { + let [status, body, header] = res[cacheKey]; + if (header instanceof Headers) { + header = buildOutgoingHttpHeaders(header); + } + if (typeof body === "string") { + header["Content-Length"] = Buffer.byteLength(body); + } else if (body instanceof Uint8Array) { + header["Content-Length"] = body.byteLength; + } else if (body instanceof Blob) { + header["Content-Length"] = body.size; + } + outgoing.writeHead(status, header); + if (typeof body === "string" || body instanceof Uint8Array) { + outgoing.end(body); + } else if (body instanceof Blob) { + outgoing.end(new Uint8Array(await body.arrayBuffer())); + } else { + flushHeaders(outgoing); + await writeFromReadableStream(body, outgoing)?.catch( + (e) => handleResponseError(e, outgoing) + ); + } + ; + outgoing[outgoingEnded]?.(); +}; +var isPromise = (res) => typeof res.then === "function"; +var responseViaResponseObject = async (res, outgoing, options = {}) => { + if (isPromise(res)) { + if (options.errorHandler) { + try { + res = await res; + } catch (err) { + const errRes = await options.errorHandler(err); + if (!errRes) { + return; + } + res = errRes; + } + } else { + res = await res.catch(handleFetchError); + } + } + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); + if (res.body) { + const reader = res.body.getReader(); + const values = []; + let done = false; + let currentReadPromise = void 0; + if (resHeaderRecord["transfer-encoding"] !== "chunked") { + let maxReadCount = 2; + for (let i = 0; i < maxReadCount; i++) { + currentReadPromise ||= reader.read(); + const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => { + console.error(e); + done = true; + }); + if (!chunk) { + if (i === 1) { + await new Promise((resolve) => setTimeout(resolve)); + maxReadCount = 3; + continue; + } + break; + } + currentReadPromise = void 0; + if (chunk.value) { + values.push(chunk.value); + } + if (chunk.done) { + done = true; + break; + } + } + if (done && !("content-length" in resHeaderRecord)) { + resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0); + } + } + outgoing.writeHead(res.status, resHeaderRecord); + values.forEach((value) => { + ; + outgoing.write(value); + }); + if (done) { + outgoing.end(); + } else { + if (values.length === 0) { + flushHeaders(outgoing); + } + await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise); + } + } else if (resHeaderRecord[X_ALREADY_SENT]) { + } else { + outgoing.writeHead(res.status, resHeaderRecord); + outgoing.end(); + } + ; + outgoing[outgoingEnded]?.(); +}; +var getRequestListener = (fetchCallback, options = {}) => { + const autoCleanupIncoming = options.autoCleanupIncoming ?? true; + if (options.overrideGlobalObjects !== false && global.Request !== Request) { + Object.defineProperty(global, "Request", { + value: Request + }); + Object.defineProperty(global, "Response", { + value: Response2 + }); + } + return async (incoming, outgoing) => { + let res, req; + try { + req = newRequest(incoming, options.hostname); + let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD"; + if (!incomingEnded) { + ; + incoming[wrapBodyStream] = true; + incoming.on("end", () => { + incomingEnded = true; + }); + if (incoming instanceof Http2ServerRequest2) { + ; + outgoing[outgoingEnded] = () => { + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + outgoing.destroy(); + }); + } + }); + } + }; + } + } + outgoing.on("close", () => { + const abortController = req[abortControllerKey]; + if (abortController) { + if (incoming.errored) { + req[abortControllerKey].abort(incoming.errored.toString()); + } else if (!outgoing.writableFinished) { + req[abortControllerKey].abort("Client connection prematurely closed."); + } + } + if (!incomingEnded) { + setTimeout(() => { + if (!incomingEnded) { + setTimeout(() => { + incoming.destroy(); + }); + } + }); + } + }); + res = fetchCallback(req, { incoming, outgoing }); + if (cacheKey in res) { + return responseViaCache(res, outgoing); + } + } catch (e) { + if (!res) { + if (options.errorHandler) { + res = await options.errorHandler(req ? e : toRequestError(e)); + if (!res) { + return; + } + } else if (!req) { + res = handleRequestError(); + } else { + res = handleFetchError(e); + } + } else { + return handleResponseError(e, outgoing); + } + } + try { + return await responseViaResponseObject(res, outgoing, options); + } catch (e) { + return handleResponseError(e, outgoing); + } + }; +}; + +// src/vercel.ts +var handle = (app) => { + return getRequestListener(app.fetch); +}; +export { + handle +}; diff --git a/node_modules/@hono/node-server/package.json b/node_modules/@hono/node-server/package.json new file mode 100644 index 000000000..58fbc7979 --- /dev/null +++ b/node_modules/@hono/node-server/package.json @@ -0,0 +1,103 @@ +{ + "name": "@hono/node-server", + "version": "1.19.9", + "description": "Node.js Adapter for Hono", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "require": "./dist/index.js", + "import": "./dist/index.mjs" + }, + "./serve-static": { + "types": "./dist/serve-static.d.ts", + "require": "./dist/serve-static.js", + "import": "./dist/serve-static.mjs" + }, + "./vercel": { + "types": "./dist/vercel.d.ts", + "require": "./dist/vercel.js", + "import": "./dist/vercel.mjs" + }, + "./utils/*": { + "types": "./dist/utils/*.d.ts", + "require": "./dist/utils/*.js", + "import": "./dist/utils/*.mjs" + }, + "./conninfo": { + "types": "./dist/conninfo.d.ts", + "require": "./dist/conninfo.js", + "import": "./dist/conninfo.mjs" + } + }, + "typesVersions": { + "*": { + ".": [ + "./dist/index.d.ts" + ], + "serve-static": [ + "./dist/serve-static.d.ts" + ], + "vercel": [ + "./dist/vercel.d.ts" + ], + "utils/*": [ + "./dist/utils/*.d.ts" + ], + "conninfo": [ + "./dist/conninfo.d.ts" + ] + } + }, + "scripts": { + "test": "node --expose-gc node_modules/jest/bin/jest.js", + "build": "tsup --external hono", + "watch": "tsup --watch", + "postbuild": "publint", + "prerelease": "bun run build && bun run test", + "release": "np", + "lint": "eslint src test", + "lint:fix": "eslint src test --fix", + "format": "prettier --check \"src/**/*.{js,ts}\" \"test/**/*.{js,ts}\"", + "format:fix": "prettier --write \"src/**/*.{js,ts}\" \"test/**/*.{js,ts}\"" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/honojs/node-server.git" + }, + "homepage": "https://github.com/honojs/node-server", + "author": "Yusuke Wada (https://github.com/yusukebe)", + "publishConfig": { + "registry": "https://registry.npmjs.org", + "access": "public" + }, + "engines": { + "node": ">=18.14.1" + }, + "devDependencies": { + "@hono/eslint-config": "^1.0.1", + "@types/jest": "^29.5.3", + "@types/node": "^20.10.0", + "@types/supertest": "^2.0.12", + "@whatwg-node/fetch": "^0.9.14", + "eslint": "^9.10.0", + "hono": "^4.4.10", + "jest": "^29.6.1", + "np": "^7.7.0", + "prettier": "^3.2.4", + "publint": "^0.1.16", + "supertest": "^6.3.3", + "ts-jest": "^29.1.1", + "tsup": "^7.2.0", + "typescript": "^5.3.2" + }, + "peerDependencies": { + "hono": "^4" + }, + "packageManager": "bun@1.2.20" +} diff --git a/node_modules/@modelcontextprotocol/conformance/LICENSE b/node_modules/@modelcontextprotocol/conformance/LICENSE new file mode 100644 index 000000000..4a9398576 --- /dev/null +++ b/node_modules/@modelcontextprotocol/conformance/LICENSE @@ -0,0 +1,216 @@ +The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. + +No rights beyond those granted by the applicable original license are conveyed for such contributions. + +--- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright + owner or by an individual or Legal Entity authorized to submit on behalf + of the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +--- + +MIT License + +Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. + +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. + +--- + +Creative Commons Attribution 4.0 International (CC-BY-4.0) + +Documentation in this project (excluding specifications) is licensed under +CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for +the full license text. diff --git a/node_modules/@modelcontextprotocol/conformance/README.md b/node_modules/@modelcontextprotocol/conformance/README.md new file mode 100644 index 000000000..da649d5e9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/conformance/README.md @@ -0,0 +1,237 @@ +# MCP Conformance Test Framework + +A framework for testing MCP (Model Context Protocol) client and server implementations against the specification. + +> [!WARNING] +> This repository is a work in progress and is unstable. Join the conversation in the #conformance-testing-wg in the MCP Contributors discord. + +**For SDK maintainers:** See [SDK Integration Guide](./SDK_INTEGRATION.md) for a streamlined guide on integrating conformance tests into your SDK repository. + +## Quick Start + +### Testing Clients + +```bash +# Using the everything-client (recommended) +npx @modelcontextprotocol/conformance client --command "tsx examples/clients/typescript/everything-client.ts" --scenario initialize + +# Run an entire suite of tests +npx @modelcontextprotocol/conformance client --command "tsx examples/clients/typescript/everything-client.ts" --suite auth +``` + +### Testing Servers + +```bash +# Run all server scenarios (default) +npx @modelcontextprotocol/conformance server --url http://localhost:3000/mcp + +# Run a single scenario +npx @modelcontextprotocol/conformance server --url http://localhost:3000/mcp --scenario server-initialize +``` + +### List Available Scenarios + +```bash +npx @modelcontextprotocol/conformance list +``` + +## Overview + +The conformance test framework validates MCP implementations by: + +**For Clients:** + +1. Starting a test server for the specified scenario +2. Running the client implementation with the test server URL +3. Capturing MCP protocol interactions +4. Running conformance checks against the specification +5. Generating detailed test results + +**For Servers:** + +1. Connecting to the running server as an MCP client +2. Sending test requests and capturing responses +3. Running conformance checks against server behavior +4. Generating detailed test results + +## Usage + +### Client Testing + +```bash +npx @modelcontextprotocol/conformance client --command "" --scenario [options] +``` + +**Options:** + +- `--command` - The command to run your MCP client (can include flags) +- `--scenario` - The test scenario to run (e.g., "initialize") +- `--suite` - Run a suite of tests in parallel (e.g., "auth") +- `--expected-failures ` - Path to YAML baseline file of known failures (see [Expected Failures](#expected-failures)) +- `--timeout` - Timeout in milliseconds (default: 30000) +- `--verbose` - Show verbose output + +The framework appends `` as an argument to your command and sets the `MCP_CONFORMANCE_SCENARIO` environment variable to the scenario name. For scenarios that require additional context (e.g., client credentials), the `MCP_CONFORMANCE_CONTEXT` environment variable contains a JSON object with scenario-specific data. + +### Server Testing + +```bash +npx @modelcontextprotocol/conformance server --url [--scenario ] +``` + +**Options:** + +- `--url` - URL of the server to test +- `--scenario ` - Test scenario to run (e.g., "server-initialize"). Runs all available scenarios by default +- `--suite ` - Suite to run: "active" (default), "all", or "pending" +- `--expected-failures ` - Path to YAML baseline file of known failures (see [Expected Failures](#expected-failures)) +- `--verbose` - Show verbose output + +## Test Results + +**Client Testing** - Results are saved to `results/-/`: + +- `checks.json` - Array of conformance check results with pass/fail status +- `stdout.txt` - Client stdout output +- `stderr.txt` - Client stderr output + +**Server Testing** - Results are saved to `results/server--/`: + +- `checks.json` - Array of conformance check results with pass/fail status + +## Expected Failures + +SDKs that don't yet pass all conformance tests can specify a baseline of known failures. This allows running conformance tests in CI without failing, while still catching regressions. + +Create a YAML file listing expected failures by mode: + +```yaml +# conformance-baseline.yml +server: + - tools-call-with-progress + - resources-subscribe +client: + - sse-retry +``` + +Then pass it to the CLI: + +```bash +npx @modelcontextprotocol/conformance server --url http://localhost:3000/mcp --expected-failures ./conformance-baseline.yml +``` + +**Exit code behavior:** + +| Scenario Result | In Baseline? | Outcome | +| --------------- | ------------ | ----------------------------------------- | +| Fails | Yes | Exit 0 — expected failure | +| Fails | No | Exit 1 — unexpected regression | +| Passes | Yes | Exit 1 — stale baseline, remove the entry | +| Passes | No | Exit 0 — normal pass | + +This ensures: + +- CI passes when only known failures occur +- CI fails on new regressions (unexpected failures) +- CI fails when a fix lands but the baseline isn't updated (stale entries) + +## GitHub Action + +This repo provides a composite GitHub Action so SDK repos don't need to write their own conformance scripts. + +### Server Testing + +```yaml +steps: + - uses: actions/checkout@v4 + + # Start your server (SDK-specific) + - run: | + my-server --port 3001 & + timeout 15 bash -c 'until curl -s http://localhost:3001/mcp; do sleep 0.5; done' + + - uses: modelcontextprotocol/conformance@v0.1.11 + with: + mode: server + url: http://localhost:3001/mcp + expected-failures: ./conformance-baseline.yml # optional +``` + +### Client Testing + +```yaml +steps: + - uses: actions/checkout@v4 + + - uses: modelcontextprotocol/conformance@v0.1.11 + with: + mode: client + command: 'python tests/conformance/client.py' + expected-failures: ./conformance-baseline.yml # optional +``` + +### Action Inputs + +| Input | Required | Description | +| ------------------- | ----------- | ----------------------------------------------- | +| `mode` | Yes | `server` or `client` | +| `url` | Server mode | URL of the server to test | +| `command` | Client mode | Command to run the client under test | +| `expected-failures` | No | Path to YAML baseline file | +| `suite` | No | Test suite to run | +| `scenario` | No | Run a single scenario by name | +| `timeout` | No | Timeout in ms for client tests (default: 30000) | +| `verbose` | No | Show verbose output (default: false) | +| `node-version` | No | Node.js version (default: 20) | + +## Example Clients + +- `examples/clients/typescript/everything-client.ts` - Single client that handles all scenarios based on scenario name (recommended) +- `examples/clients/typescript/test1.ts` - Simple MCP client (for reference) +- `examples/clients/typescript/auth-test.ts` - Well-behaved OAuth client (for reference) + +## Available Scenarios + +### Client Scenarios + +- **initialize** - Tests MCP client initialization handshake + - Validates protocol version + - Validates clientInfo (name and version) + - Validates server response handling +- **tools-call** - Tests tool invocation +- **auth/basic-dcr** - Tests OAuth Dynamic Client Registration flow +- **auth/basic-metadata-var1** - Tests OAuth with authorization metadata + +### Server Scenarios + +Run `npx @modelcontextprotocol/conformance list --server` to see all available server scenarios, including: + +- **server-initialize** - Tests server initialization and capabilities +- **tools-list** - Tests tool listing endpoint +- **tools-call-\*** - Various tool invocation scenarios +- **resources-\*** - Resource management scenarios +- **prompts-\*** - Prompt management scenarios + +## Architecture + +See `src/runner/DESIGN.md` for detailed architecture documentation. + +### Key Components + +- **Runner** (`src/runner/`) - Orchestrates test execution and result generation + - `client.ts` - Client testing implementation + - `server.ts` - Server testing implementation + - `utils.ts` - Shared utilities + - `index.ts` - Public API exports +- **CLI** (`src/index.ts`) - Command-line interface using Commander.js +- **Scenarios** (`src/scenarios/`) - Test scenarios with expected behaviors +- **Checks** (`src/checks/`) - Conformance validation functions +- **Types** (`src/types.ts`) - Shared type definitions + +## Adding New Scenarios + +1. Create a new directory in `src/scenarios//` +2. Implement the `Scenario` interface with `start()`, `stop()`, and `getChecks()` +3. Register the scenario in `src/scenarios/index.ts` + +See `src/scenarios/initialize/` for a reference implementation. diff --git a/node_modules/@modelcontextprotocol/conformance/dist/index.js b/node_modules/@modelcontextprotocol/conformance/dist/index.js new file mode 100755 index 000000000..f516757dd --- /dev/null +++ b/node_modules/@modelcontextprotocol/conformance/dist/index.js @@ -0,0 +1,666 @@ +#!/usr/bin/env node +import{Command as e}from"commander";import{ZodError as t,z as n}from"zod";import{spawn as r}from"child_process";import{promises as i}from"fs";import a from"path";import o from"http";import{Server as s}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as c}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as l,CallToolResultSchema as u,CreateMessageRequestSchema as d,ElicitRequestSchema as f,ElicitResultSchema as p,ErrorCode as m,ListToolsRequestSchema as h,LoggingMessageNotificationSchema as g,McpError as _,ProgressNotificationSchema as v}from"@modelcontextprotocol/sdk/types.js";import y from"express";import{createHash as b,randomUUID as x}from"crypto";import{Client as S}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as C}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{EventSourceParserStream as w}from"eventsource-parser/stream";import{request as ee}from"undici";import{requireBearerAuth as te}from"@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";import*as T from"jose";import{parse as ne}from"yaml";var re=Object.defineProperty,ie=(e=>{let t={};for(var n in e)re(t,n,{get:e[n],enumerable:!0});return t})({createClientInitializationCheck:()=>oe,createServerInfoCheck:()=>ae});function ae(e){return{id:`server-info`,name:`ServerInfo`,description:`Test server info returned to client`,status:`INFO`,timestamp:new Date().toISOString(),specReferences:[{id:`MCP-Lifecycle`,url:`https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle`}],details:{serverName:e.name,serverVersion:e.version}}}const E=[`2025-06-18`,`2025-11-25`];function oe(e,t=`2025-11-25`){let n=e?.protocolVersion,r=(E.includes(t)?E:[...E,t]).includes(n),i=[];return n||i.push(`Protocol version not provided`),r||i.push(`Version mismatch: expected ${t}, got ${n}`),e?.clientInfo?.name||i.push(`Client name missing`),e?.clientInfo?.version||i.push(`Client version missing`),{id:`mcp-client-initialization`,name:`MCPClientInitialization`,description:`Validates that MCP client properly initializes with server`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[{id:`MCP-Lifecycle`,url:`https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle`}],details:{protocolVersionSent:n,expectedSpecVersion:t,versionMatch:r,clientName:e?.clientInfo?.name,clientVersion:e?.clientInfo?.version},errorMessage:i.length>0?i.join(`; `):void 0,logs:i.length>0?i:void 0}}const D=ie;var se=class{constructor(){this.name=`initialize`,this.description=`Tests MCP client initialization handshake`,this.server=null,this.checks=[],this.port=0}async start(){return new Promise((e,t)=>{this.server=o.createServer((e,t)=>{this.handleRequest(e,t)}),this.server.on(`error`,t),this.server.listen(0,()=>{let n=this.server.address();n&&typeof n==`object`?(this.port=n.port,e({serverUrl:`http://localhost:${this.port}`})):t(Error(`Failed to get server address`))})})}async stop(){return new Promise((e,t)=>{this.server?this.server.close(n=>{n?t(n):(this.server=null,e())}):e()})}getChecks(){return this.checks}handleRequest(e,t){let n=``;e.on(`data`,e=>{n+=e.toString()}),e.on(`end`,()=>{try{let e=JSON.parse(n);e.method===`initialize`?this.handleInitialize(e,t):e.method===`tools/list`?this.handleToolsList(e,t):(t.writeHead(200,{"Content-Type":`application/json`}),t.end(JSON.stringify({jsonrpc:`2.0`,id:e.id,result:{}})))}catch(e){t.writeHead(400,{"Content-Type":`application/json`}),t.end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32700,message:`Parse error ${e}`}}))}})}handleInitialize(e,t){let n=e.params,r=D.createClientInitializationCheck(n);this.checks.push(r);let i={name:`test-server`,version:`1.0.0`};this.checks.push(D.createServerInfoCheck(i));let a=[`2025-06-18`,`2025-11-25`],o=n?.protocolVersion,s=a.includes(o)?o:`2025-11-25`,c={jsonrpc:`2.0`,id:e.id,result:{protocolVersion:s,serverInfo:i,capabilities:{}}};t.writeHead(200,{"Content-Type":`application/json`}),t.end(JSON.stringify(c))}handleToolsList(e,t){let n={jsonrpc:`2.0`,id:e.id,result:{tools:[]}};t.writeHead(200,{"Content-Type":`application/json`}),t.end(JSON.stringify(n))}};function O(e,t){return(n,r,i)=>{let a=`Received ${n.method} request for ${n.path}`,o={method:n.method,path:n.path,body:n.body};if(Object.keys(n.query).length>0&&(o.query=n.query),t.mcpRoute&&n.path===t.mcpRoute&&n.get(`content-type`)?.includes(`application/json`)&&n.body&&typeof n.body==`object`&&n.body.method){let e=n.body.method;a+=` (method: ${e})`,o.mcpMethod=e}e.push({id:t.incomingId,name:t.incomingId.charAt(0).toUpperCase()+t.incomingId.slice(1),description:a,status:`INFO`,timestamp:new Date().toISOString(),details:o});let s=r.write.bind(r),c=r.end.bind(r),l=[];r.write=function(e,...t){return l.push(e),s(e,...t)},r.end=function(i,...a){i&&l.push(i);let s=l.map(e=>typeof e==`string`?Buffer.from(e):e),u=Buffer.concat(s).toString(`utf8`),d=`Sent ${r.statusCode} response for ${n.method} ${n.path}`,f={method:n.method,path:n.path,statusCode:r.statusCode};o.mcpMethod&&(d+=` (method: ${o.mcpMethod})`,f.mcpMethod=o.mcpMethod);let p=r.getHeaders();if(Object.keys(p).length>0&&(f.headers=p),u)try{f.body=JSON.parse(u)}catch{f.body=u}return e.push({id:t.outgoingId,name:t.outgoingId.charAt(0).toUpperCase()+t.outgoingId.slice(1),description:d,status:`INFO`,timestamp:new Date().toISOString(),details:f}),c(i,...a)},i()}}function ce(e){let t=new s({name:`add-numbers-server`,version:`1.0.0`},{capabilities:{tools:{}}});t.setRequestHandler(h,async()=>({tools:[{name:`add_numbers`,description:`Add two numbers together`,inputSchema:{type:`object`,properties:{a:{type:`number`,description:`First number`},b:{type:`number`,description:`Second number`}},required:[`a`,`b`]}}]})),t.setRequestHandler(l,async t=>{if(t.params.name===`add_numbers`){let{a:n,b:r}=t.params.arguments,i=n+r;return e.push({id:`tool-add-numbers`,name:`ToolAddNumbers`,description:`Validates that the add_numbers tool works correctly`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[{id:`MCP-Tools`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools`}],details:{a:n,b:r,result:i}}),{content:[{type:`text`,text:`The sum of ${n} and ${r} is ${i}`}]}}throw Error(`Unknown tool: ${t.params.name}`)});let n=y();return n.use(y.json()),n.use(O(e,{incomingId:`incoming-request`,outgoingId:`outgoing-response`,mcpRoute:`/mcp`})),n.post(`/mcp`,async(e,n)=>{let r=new c({sessionIdGenerator:void 0});await t.connect(r),await r.handleRequest(e,n,e.body)}),n}var le=class{constructor(){this.name=`tools_call`,this.description=`Tests calling tools with various parameter types`,this.app=null,this.httpServer=null,this.checks=[]}async start(){return this.checks=[],this.app=ce(this.checks),this.httpServer=this.app.listen(0),{serverUrl:`http://localhost:${this.httpServer.address().port}/mcp`}}async stop(){this.httpServer&&=(await new Promise(e=>this.httpServer.close(e)),null),this.app=null}getChecks(){for(let e of[`tool-add-numbers`])this.checks.find(t=>t.id===e)||this.checks.push({id:e,name:`ToolAddNumbers`,description:`Validates that the add_numbers tool works correctly`,status:`FAILURE`,timestamp:new Date().toISOString(),details:{message:`Tool was not called by client`},specReferences:[{id:`MCP-Tools`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools`}]});return this.checks}};function ue(e){return!!(typeof e==`object`&&e&&`method`in e&&e.method===`initialize`)}function de(e){let t={},n={},r=()=>{let t=new s({name:`elicitation-defaults-test-server`,version:`1.0.0`},{capabilities:{tools:{}}});return t.setRequestHandler(h,async()=>({tools:[{name:`test_client_elicitation_defaults`,description:`Tests that client applies defaults for omitted elicitation fields`,inputSchema:{type:`object`,properties:{},required:[]}}]})),t.setRequestHandler(l,async n=>{if(n.params.name===`test_client_elicitation_defaults`)try{let n=await t.request({method:`elicitation/create`,params:{message:`Test client default value handling - please accept with defaults`,requestedSchema:{type:`object`,properties:{name:{type:`string`,description:`User name`,default:`John Doe`},age:{type:`integer`,description:`User age`,default:30},score:{type:`number`,description:`User score`,default:95.5},status:{type:`string`,description:`User status`,enum:[`active`,`inactive`,`pending`],default:`active`},verified:{type:`boolean`,description:`Verification status`,default:!0}},required:[]}}},p);if(n.action!==`accept`)return e.push({id:`client-elicitation-sep1034-general`,name:`ClientElicitationSEP1034General`,description:`Client accepts elicitation request`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Expected action 'accept', got '${n.action}'`,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}]}),{content:[{type:`text`,text:`Elicitation was not accepted`}]};let r=n.content||{},i=[];`name`in r?typeof r.name!=`string`&&i.push(`Expected string for "name", got ${typeof r.name}`):i.push(`Field "name" missing - should have default "John Doe"`),e.push({id:`client-elicitation-sep1034-string-default`,name:`ClientElicitationSEP1034StringDefault`,description:`Client applies string default value for elicitation`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}],details:{field:`name`,expectedDefault:`John Doe`,receivedValue:r.name}});let a=[];`age`in r?typeof r.age!=`number`&&a.push(`Expected number for "age", got ${typeof r.age}`):a.push(`Field "age" missing - should have default 30`),e.push({id:`client-elicitation-sep1034-integer-default`,name:`ClientElicitationSEP1034IntegerDefault`,description:`Client applies integer default value for elicitation`,status:a.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:a.length>0?a.join(`; `):void 0,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}],details:{field:`age`,expectedDefault:30,receivedValue:r.age}});let o=[];`score`in r?typeof r.score!=`number`&&o.push(`Expected number for "score", got ${typeof r.score}`):o.push(`Field "score" missing - should have default 95.5`),e.push({id:`client-elicitation-sep1034-number-default`,name:`ClientElicitationSEP1034NumberDefault`,description:`Client applies number default value for elicitation`,status:o.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:o.length>0?o.join(`; `):void 0,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}],details:{field:`score`,expectedDefault:95.5,receivedValue:r.score}});let s=[];`status`in r?typeof r.status==`string`?[`active`,`inactive`,`pending`].includes(r.status)||s.push(`Value "${r.status}" is not a valid enum member`):s.push(`Expected string for "status", got ${typeof r.status}`):s.push(`Field "status" missing - should have default "active"`),e.push({id:`client-elicitation-sep1034-enum-default`,name:`ClientElicitationSEP1034EnumDefault`,description:`Client applies enum default value for elicitation`,status:s.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:s.length>0?s.join(`; `):void 0,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}],details:{field:`status`,expectedDefault:`active`,receivedValue:r.status}});let c=[];return`verified`in r?typeof r.verified!=`boolean`&&c.push(`Expected boolean for "verified", got ${typeof r.verified}`):c.push(`Field "verified" missing - should have default true`),e.push({id:`client-elicitation-sep1034-boolean-default`,name:`ClientElicitationSEP1034BooleanDefault`,description:`Client applies boolean default value for elicitation`,status:c.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:c.length>0?c.join(`; `):void 0,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}],details:{field:`verified`,expectedDefault:!0,receivedValue:r.verified}}),{content:[{type:`text`,text:`Elicitation completed: ${JSON.stringify(r)}`}]}}catch(t){return e.push({id:`client-elicitation-sep1034-general`,name:`ClientElicitationSEP1034General`,description:`Client handles elicitation with defaults`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Elicitation failed: ${t.message}`,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}]}),{content:[{type:`text`,text:`Elicitation error: ${t.message}`}]}}throw Error(`Unknown tool: ${n.params.name}`)}),t},i=y();return i.use(y.json()),i.use(O(e,{incomingId:`incoming-request`,outgoingId:`outgoing-response`,mcpRoute:`/mcp`})),i.post(`/mcp`,async(e,i)=>{let a=e.headers[`mcp-session-id`];try{let o;if(a&&t[a])o=t[a];else if(!a&&ue(e.body)){let a=r();o=new c({sessionIdGenerator:()=>x(),onsessioninitialized:e=>{t[e]=o,n[e]=a}}),o.onclose=()=>{let e=o.sessionId;e&&t[e]&&(delete t[e],n[e]&&(n[e].close(),delete n[e]))},await a.connect(o),await o.handleRequest(e,i,e.body);return}else{i.status(400).json({jsonrpc:`2.0`,error:{code:-32e3,message:`Invalid or missing session ID`},id:null});return}await o.handleRequest(e,i,e.body)}catch{i.headersSent||i.status(500).json({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`},id:null})}}),i.get(`/mcp`,async(e,n)=>{let r=e.headers[`mcp-session-id`];if(!r||!t[r]){n.status(400).send(`Invalid or missing session ID`);return}try{await t[r].handleRequest(e,n)}catch{n.headersSent||n.status(500).send(`Error establishing SSE stream`)}}),i.delete(`/mcp`,async(e,n)=>{let r=e.headers[`mcp-session-id`];if(!r||!t[r]){n.status(400).send(`Invalid or missing session ID`);return}try{await t[r].handleRequest(e,n)}catch{n.headersSent||n.status(500).send(`Error handling termination`)}}),{app:i,cleanup:()=>{for(let e of Object.keys(t))n[e]&&n[e].close()}}}var fe=class{constructor(){this.name=`elicitation-sep1034-client-defaults`,this.description=`Tests client applies default values for omitted elicitation fields (SEP-1034)`,this.app=null,this.httpServer=null,this.checks=[],this.cleanup=null}async start(){this.checks=[];let{app:e,cleanup:t}=de(this.checks);return this.app=e,this.cleanup=t,this.httpServer=this.app.listen(0),{serverUrl:`http://localhost:${this.httpServer.address().port}/mcp`}}async stop(){this.cleanup&&=(this.cleanup(),null),this.httpServer&&=(await new Promise(e=>this.httpServer.close(e)),null),this.app=null}getChecks(){for(let e of[`client-elicitation-sep1034-string-default`,`client-elicitation-sep1034-integer-default`,`client-elicitation-sep1034-number-default`,`client-elicitation-sep1034-enum-default`,`client-elicitation-sep1034-boolean-default`])this.checks.find(t=>t.id===e)||this.checks.push({id:e,name:e.replace(/-/g,``),description:`Server applies ${e.split(`-`)[4]} default for elicitation`,status:`FAILURE`,timestamp:new Date().toISOString(),details:{message:`Tool was not called by client`},specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}]});return this.checks}},pe=class{constructor(){this.name=`sse-retry`,this.description=`Tests that client respects SSE retry field timing and reconnects properly (SEP-1699)`,this.server=null,this.checks=[],this.port=0,this.toolStreamCloseTime=null,this.getReconnectionTime=null,this.getConnectionCount=0,this.lastEventIds=[],this.retryValue=500,this.eventIdCounter=0,this.sessionId=`session-${Date.now()}`,this.pendingToolCallId=null,this.getResponseStream=null,this.EARLY_TOLERANCE=50,this.LATE_TOLERANCE=200,this.VERY_LATE_MULTIPLIER=2}async start(){return new Promise((e,t)=>{this.server=o.createServer((e,t)=>{this.handleRequest(e,t)}),this.server.on(`error`,t),this.server.listen(0,()=>{let n=this.server.address();n&&typeof n==`object`?(this.port=n.port,e({serverUrl:`http://localhost:${this.port}`})):t(Error(`Failed to get server address`))})})}async stop(){return new Promise((e,t)=>{this.server?this.server.close(n=>{n?t(n):(this.server=null,e())}):e()})}getChecks(){return this.generateChecks(),this.checks}handleRequest(e,t){if(e.method===`GET`){this.getConnectionCount++,this.getReconnectionTime=performance.now();let n=e.headers[`last-event-id`],r=n?`Received GET request for ${e.url} (Last-Event-ID: ${n})`:`Received GET request for ${e.url}`;this.checks.push({id:`incoming-request`,name:`IncomingRequest`,description:r,status:`INFO`,timestamp:new Date().toISOString(),details:{method:`GET`,url:e.url,headers:e.headers,connectionCount:this.getConnectionCount}}),n&&this.lastEventIds.push(n),this.handleGetSSEStream(e,t)}else e.method===`POST`?this.handlePostRequest(e,t):(t.writeHead(405),t.end(`Method Not Allowed`))}handleGetSSEStream(e,t){t.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`,"mcp-session-id":this.sessionId}),this.eventIdCounter++;let n=`event-${this.eventIdCounter}`,r=`id: ${n}\nretry: ${this.retryValue}\ndata: \n\n`;if(t.write(r),this.checks.push({id:`outgoing-sse-event`,name:`OutgoingSseEvent`,description:`Sent SSE priming event on GET stream (id: ${n}, retry: ${this.retryValue}ms)`,status:`INFO`,timestamp:new Date().toISOString(),details:{eventId:n,retryMs:this.retryValue,eventType:`priming`,raw:r}}),this.getResponseStream=t,this.pendingToolCallId!==null){let e={jsonrpc:`2.0`,id:this.pendingToolCallId,result:{content:[{type:`text`,text:`Reconnection test completed successfully`}]}},n=`event-${++this.eventIdCounter}`,r=`event: message\nid: ${n}\ndata: ${JSON.stringify(e)}\n\n`;t.write(r),this.checks.push({id:`outgoing-sse-event`,name:`OutgoingSseEvent`,description:`Sent tool response on GET stream after reconnection (id: ${n})`,status:`INFO`,timestamp:new Date().toISOString(),details:{eventId:n,eventType:`message`,jsonrpcId:this.pendingToolCallId,body:e,raw:r}}),this.pendingToolCallId=null}}handlePostRequest(e,t){let n=``;e.on(`data`,e=>{n+=e.toString()}),e.on(`end`,()=>{try{let r=JSON.parse(n);this.checks.push({id:`incoming-request`,name:`IncomingRequest`,description:`Received POST request for ${e.url} (method: ${r.method})`,status:`INFO`,timestamp:new Date().toISOString(),details:{method:`POST`,url:e.url,jsonrpcMethod:r.method,jsonrpcId:r.id}}),r.method===`initialize`?this.handleInitialize(e,t,r):r.method===`tools/list`?this.handleToolsList(t,r):r.method===`tools/call`?this.handleToolsCall(t,r):r.id===void 0?(t.writeHead(202),t.end()):(t.writeHead(200,{"Content-Type":`application/json`,"mcp-session-id":this.sessionId}),t.end(JSON.stringify({jsonrpc:`2.0`,id:r.id,result:{}})))}catch(e){t.writeHead(400,{"Content-Type":`application/json`}),t.end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32700,message:`Parse error: ${e}`}}))}})}handleInitialize(e,t,n){t.writeHead(200,{"Content-Type":`application/json`,"mcp-session-id":this.sessionId});let r={jsonrpc:`2.0`,id:n.id,result:{protocolVersion:`2025-03-26`,serverInfo:{name:`sse-retry-test-server`,version:`1.0.0`},capabilities:{tools:{}}}};t.end(JSON.stringify(r)),this.checks.push({id:`outgoing-response`,name:`OutgoingResponse`,description:`Sent initialize response`,status:`INFO`,timestamp:new Date().toISOString(),details:{jsonrpcId:n.id,body:r}})}handleToolsList(e,t){e.writeHead(200,{"Content-Type":`application/json`,"mcp-session-id":this.sessionId});let n={jsonrpc:`2.0`,id:t.id,result:{tools:[{name:`test_reconnection`,description:`A tool that triggers SSE stream closure to test client reconnection behavior`,inputSchema:{type:`object`,properties:{},required:[]}}]}};e.end(JSON.stringify(n)),this.checks.push({id:`outgoing-response`,name:`OutgoingResponse`,description:`Sent tools/list response`,status:`INFO`,timestamp:new Date().toISOString(),details:{jsonrpcId:t.id,body:n}})}handleToolsCall(e,t){this.pendingToolCallId=t.id,e.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`,"mcp-session-id":this.sessionId}),this.eventIdCounter++;let n=`event-${this.eventIdCounter}`,r=`id: ${n}\nretry: ${this.retryValue}\ndata: \n\n`;e.write(r),this.checks.push({id:`outgoing-sse-event`,name:`OutgoingSseEvent`,description:`Sent SSE priming event for tools/call (id: ${n}, retry: ${this.retryValue}ms)`,status:`INFO`,timestamp:new Date().toISOString(),details:{eventId:n,retryMs:this.retryValue,eventType:`priming`,raw:r}}),setTimeout(()=>{this.toolStreamCloseTime=performance.now(),this.checks.push({id:`outgoing-stream-close`,name:`OutgoingStreamClose`,description:`Closed tools/call SSE stream to trigger client reconnection`,status:`INFO`,timestamp:new Date().toISOString(),details:{retryMs:this.retryValue,pendingToolCallId:this.pendingToolCallId}}),e.end()},50)}generateChecks(){if(this.getConnectionCount<1){this.checks.push({id:`client-sse-graceful-reconnect`,name:`ClientGracefulReconnect`,description:`Client reconnects via GET after SSE stream is closed gracefully`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Client did not attempt GET reconnection after stream closure. Client should treat graceful stream close as reconnectable.`,specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{getConnectionCount:this.getConnectionCount,toolStreamCloseTime:this.toolStreamCloseTime,retryValue:this.retryValue}});return}if(this.checks.push({id:`client-sse-graceful-reconnect`,name:`ClientGracefulReconnect`,description:`Client reconnects via GET after SSE stream is closed gracefully`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{getConnectionCount:this.getConnectionCount}}),this.toolStreamCloseTime!==null&&this.getReconnectionTime!==null){let e=this.getReconnectionTime-this.toolStreamCloseTime,t=this.retryValue-this.EARLY_TOLERANCE,n=this.retryValue+this.LATE_TOLERANCE,r=en,a=e>this.retryValue*this.VERY_LATE_MULTIPLIER,o=!r&&!i,s=`SUCCESS`,c;r?(s=`FAILURE`,c=`Client reconnected too early (${e.toFixed(0)}ms instead of ${this.retryValue}ms). Client MUST respect the retry field and wait the specified time.`):a?(s=`FAILURE`,c=`Client reconnected very late (${e.toFixed(0)}ms instead of ${this.retryValue}ms). Client appears to be ignoring the retry field and using its own backoff strategy.`):i&&(s=`WARNING`,c=`Client reconnected slightly late (${e.toFixed(0)}ms instead of ${this.retryValue}ms). This is acceptable but may indicate network delays.`),this.checks.push({id:`client-sse-retry-timing`,name:`ClientRespectsRetryField`,description:`Client MUST respect the retry field, waiting the given number of milliseconds before attempting to reconnect`,status:s,timestamp:new Date().toISOString(),errorMessage:c,specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{expectedRetryMs:this.retryValue,actualDelayMs:Math.round(e),minAcceptableMs:t,maxAcceptableMs:n,veryLateThresholdMs:this.retryValue*this.VERY_LATE_MULTIPLIER,earlyToleranceMs:this.EARLY_TOLERANCE,lateToleranceMs:this.LATE_TOLERANCE,withinTolerance:o,tooEarly:r,slightlyLate:i,veryLate:a,getConnectionCount:this.getConnectionCount}})}else this.checks.push({id:`client-sse-retry-timing`,name:`ClientRespectsRetryField`,description:`Client MUST respect the retry field timing`,status:`WARNING`,timestamp:new Date().toISOString(),errorMessage:`Could not measure timing - tool stream close time or GET reconnection time not recorded`,specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{toolStreamCloseTime:this.toolStreamCloseTime,getReconnectionTime:this.getReconnectionTime}});let e=this.lastEventIds.length>0&&this.lastEventIds[0]!==void 0;this.checks.push({id:`client-sse-last-event-id`,name:`ClientSendsLastEventId`,description:`Client SHOULD send Last-Event-ID header on reconnection for resumability`,status:e?`SUCCESS`:`WARNING`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{hasLastEventId:e,lastEventIds:this.lastEventIds,getConnectionCount:this.getConnectionCount},errorMessage:e?void 0:`Client did not send Last-Event-ID header on reconnection. This is a SHOULD requirement for resumability.`})}};async function k(e){let t=new S({name:`conformance-test-client`,version:`1.0.0`},{capabilities:{sampling:{},elicitation:{}}}),n=new C(new URL(e));return await t.connect(n),{client:t,close:async()=>{await t.close()}}}var me=class{constructor(e){this.loggingNotifications=[],this.progressNotifications=[],e.setNotificationHandler(g,e=>{this.loggingNotifications.push(e)}),e.setNotificationHandler(v,e=>{this.progressNotifications.push(e)})}getLoggingNotifications(){return this.loggingNotifications}getProgressNotifications(){return this.progressNotifications}getNotifications(){return this.loggingNotifications}},he=class{constructor(){this.name=`server-initialize`,this.description=`Test basic server initialization handshake. + +**Server Implementation Requirements:** + +**Endpoint**: \`initialize\` + +**Requirements**: +- Accept \`initialize\` request with client info and capabilities +- Return valid initialize response with server info, protocol version, and capabilities +- Accept \`initialized\` notification from client after handshake + +This test verifies the server can complete the two-phase initialization handshake successfully.`}async run(e){let t=[];try{let n=await k(e);t.push({id:`server-initialize`,name:`ServerInitialize`,description:`Server responds to initialize request with valid structure`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[{id:`MCP-Initialize`,url:`https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle#initialization`}],details:{serverUrl:e,connected:!0}}),await n.close()}catch(e){t.push({id:`server-initialize`,name:`ServerInitialize`,description:`Server responds to initialize request with valid structure`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed to initialize: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Initialize`,url:`https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle#initialization`}]})}return t}},ge=class{constructor(){this.name=`logging-set-level`,this.description="Test setting logging level.\n\n**Server Implementation Requirements:**\n\n**Endpoint**: `logging/setLevel`\n\n**Requirements**:\n- Accept log level setting\n- Filter subsequent log notifications based on level\n- Return empty object `{}`\n\n**Log Levels** (in order of severity):\n- `debug`\n- `info`\n- `notice`\n- `warning`\n- `error`\n- `critical`\n- `alert`\n- `emergency`"}async run(e){let t=[];try{let n=await k(e),r=await n.client.setLoggingLevel(`info`),i=[];r&&Object.keys(r).length>0&&i.push(`Expected empty object {} response`),t.push({id:`logging-set-level`,name:`LoggingSetLevel`,description:`Server accepts logging level setting`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Logging`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/logging`}],details:{result:r}}),await n.close()}catch(e){t.push({id:`logging-set-level`,name:`LoggingSetLevel`,description:`Server accepts logging level setting`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Logging`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/logging`}]})}return t}},_e=class{constructor(){this.name=`ping`,this.description=`Test ping utility for connection health check. + +**Server Implementation Requirements:** + +**Endpoint**: \`ping\` + +**Requirements**: +- Accept ping request with no parameters +- Respond promptly with empty object \`{}\` + +**Request Format**: + +\`\`\`json +{ + "jsonrpc": "2.0", + "id": "123", + "method": "ping" +} +\`\`\` + +**Response Format**: + +\`\`\`json +{ + "jsonrpc": "2.0", + "id": "123", + "result": {} +} +\`\`\` + +**Implementation Note**: The ping utility allows either party to verify that their counterpart is still responsive and the connection is alive.`}async run(e){let t=[];try{let n=await k(e),r=await n.client.ping(),i=[];r&&Object.keys(r).length>0&&i.push(`Expected empty object {} response`),t.push({id:`ping`,name:`Ping`,description:`Server responds to ping requests`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Ping`,url:`https://modelcontextprotocol.io/specification/2025-06-18/basic/utilities/ping`}],details:{result:r}}),await n.close()}catch(e){t.push({id:`ping`,name:`Ping`,description:`Server responds to ping requests`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Ping`,url:`https://modelcontextprotocol.io/specification/2025-06-18/basic/utilities/ping`}]})}return t}},ve=class{constructor(){this.name=`completion-complete`,this.description=`Test completion endpoint. + +**Server Implementation Requirements:** + +**Endpoint**: \`completion/complete\` + +**Requirements**: +- Accept completion requests for prompt or resource template arguments +- Provide contextual suggestions based on partial input +- Return array of completion values ranked by relevance + +**Request Format**: + +\`\`\`json +{ + "method": "completion/complete", + "params": { + "ref": { + "type": "ref/prompt", + "name": "test_prompt_with_arguments" + }, + "argument": { + "name": "arg1", + "value": "par" + } + } +} +\`\`\` + +**Response Format**: + +\`\`\`json +{ + "completion": { + "values": ["paris", "park", "party"], + "total": 150, + "hasMore": false + } +} +\`\`\` + +**Implementation Note**: For conformance testing, completion support can be minimal or return empty arrays. The capability just needs to be declared and the endpoint must respond correctly.`}async run(e){let t=[];try{let n=await k(e),r=await n.client.complete({ref:{type:`ref/prompt`,name:`test_prompt_with_arguments`},argument:{name:`arg1`,value:`test`}}),i=[];r.completion?(r.completion.values||i.push(`Missing values array in completion`),Array.isArray(r.completion.values)||i.push(`completion.values is not an array`)):i.push(`Missing completion field`),t.push({id:`completion-complete`,name:`CompletionComplete`,description:`Server responds to completion requests`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Completion`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/completion`}],details:{result:r}}),await n.close()}catch(e){t.push({id:`completion-complete`,name:`CompletionComplete`,description:`Server responds to completion requests`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Completion`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/completion`}]})}return t}},ye=class{constructor(){this.name=`tools-list`,this.description=`Test listing available tools. + +**Server Implementation Requirements:** + +**Endpoint**: \`tools/list\` + +**Requirements**: +- Return array of all available tools +- Each tool MUST have: + - \`name\` (string) + - \`description\` (string) + - \`inputSchema\` (valid JSON Schema object)`}async run(e){let t=[];try{let n=await k(e),r=await n.client.listTools(),i=[];r.tools?(Array.isArray(r.tools)||i.push(`tools is not an array`),r.tools.forEach((e,t)=>{e.name||i.push(`Tool ${t}: missing name`),e.description||i.push(`Tool ${t}: missing description`),e.inputSchema||i.push(`Tool ${t}: missing inputSchema`)})):i.push(`Missing tools array`),t.push({id:`tools-list`,name:`ToolsList`,description:`Server lists available tools with valid structure`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Tools-List`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#listing-tools`}],details:{toolCount:r.tools?.length||0,tools:r.tools?.map(e=>e.name)}}),await n.close()}catch(e){t.push({id:`tools-list`,name:`ToolsList`,description:`Server lists available tools with valid structure`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Tools-List`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#listing-tools`}]})}return t}},be=class{constructor(){this.name=`tools-call-simple-text`,this.description=`Test calling a tool that returns simple text. + +**Server Implementation Requirements:** + +Implement tool \`test_simple_text\` with no arguments that returns: + +\`\`\`json +{ + "content": [ + { + "type": "text", + "text": "This is a simple text response for testing." + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=await n.client.callTool({name:`test_simple_text`}),i=[],a=r.content;a||i.push(`Missing content array`),Array.isArray(a)||i.push(`content is not an array`),a&&a.length===0&&i.push(`content array is empty`);let o=a&&a.find(e=>e.type===`text`);o||i.push(`No text content found`),o&&!o.text&&i.push(`Text content missing text field`),t.push({id:`tools-call-simple-text`,name:`ToolsCallSimpleText`,description:`Tool returns simple text content`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Tools-Call`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools`}],details:{result:r}}),await n.close()}catch(e){t.push({id:`tools-call-simple-text`,name:`ToolsCallSimpleText`,description:`Tool returns simple text content`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Tools-Call`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools`}]})}return t}},xe=class{constructor(){this.name=`tools-call-image`,this.description=`Test calling a tool that returns image content. + +**Server Implementation Requirements:** + +Implement tool \`test_image_content\` with no arguments that returns: + +\`\`\`json +{ + "content": [ + { + "type": "image", + "data": "", + "mimeType": "image/png" + } + ] +} +\`\`\` + +**Implementation Note**: Use a minimal test image (e.g., 1x1 red pixel PNG)`}async run(e){let t=[];try{let n=await k(e),r=await n.client.callTool({name:`test_image_content`,arguments:{}}),i=[],a=r.content;a||i.push(`Missing content array`);let o=a&&a.find(e=>e.type===`image`);o||i.push(`No image content found`),o&&!o.data&&i.push(`Image content missing data field`),o&&!o.mimeType&&i.push(`Image content missing mimeType`),t.push({id:`tools-call-image`,name:`ToolsCallImage`,description:`Tool returns image content`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Tools-Call`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools`}],details:{mimeType:o?.mimeType,hasData:!!o?.data}}),await n.close()}catch(e){t.push({id:`tools-call-image`,name:`ToolsCallImage`,description:`Tool returns image content`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Tools-Call`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools`}]})}return t}},Se=class{constructor(){this.name=`tools-call-mixed-content`,this.description=`Test tool returning multiple content types. + +**Server Implementation Requirements:** + +Implement tool \`test_multiple_content_types\` with no arguments that returns: + +\`\`\`json +{ + "content": [ + { + "type": "text", + "text": "Multiple content types test:" + }, + { + "type": "image", + "data": "", + "mimeType": "image/png" + }, + { + "type": "resource", + "resource": { + "uri": "test://mixed-content-resource", + "mimeType": "application/json", + "text": "{"test":"data","value":123}" + } + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=await n.client.callTool({name:`test_multiple_content_types`,arguments:{}}),i=[],a=r.content;a||i.push(`Missing content array`),a&&a.length<2&&i.push(`Expected multiple content items`);let o=a&&a.some(e=>e.type===`text`),s=a&&a.some(e=>e.type===`image`),c=a&&a.some(e=>e.type===`resource`);o||i.push(`Missing text content`),s||i.push(`Missing image content`),c||i.push(`Missing resource content`),t.push({id:`tools-call-mixed-content`,name:`ToolsCallMixedContent`,description:`Tool returns multiple content types`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Tools-Call`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools`}],details:{contentCount:a?a.length:0,contentTypes:a?a.map(e=>e.type):[]}}),await n.close()}catch(e){t.push({id:`tools-call-mixed-content`,name:`ToolsCallMixedContent`,description:`Tool returns multiple content types`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Tools-Call`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools`}]})}return t}},Ce=class{constructor(){this.name=`tools-call-with-logging`,this.description=`Test tool that sends log messages during execution. + +**Server Implementation Requirements:** + +Implement tool \`test_tool_with_logging\` with no arguments. + +**Behavior**: During execution, send 3 log notifications at info level: +1. "Tool execution started" +2. "Tool processing data" (after ~50ms delay) +3. "Tool execution completed" (after another ~50ms delay) + +**Returns**: Text content confirming execution + +**Implementation Note**: The delays are important to test that clients can receive multiple log notifications during tool execution`}async run(e){let t=[];try{let n=await k(e),r=new me(n.client);await n.client.setLoggingLevel(`debug`),await n.client.callTool({name:`test_tool_with_logging`,arguments:{}}),await new Promise(e=>setTimeout(e,200));let i=r.getNotifications(),a=[];i.length===0?a.push(`No log notifications received`):i.length<3&&a.push(`Expected at least 3 log messages, got ${i.length}`),t.push({id:`tools-call-with-logging`,name:`ToolsCallWithLogging`,description:`Tool sends log messages during execution`,status:a.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:a.length>0?a.join(`; `):void 0,specReferences:[{id:`MCP-Logging`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/logging`}],details:{logCount:i.length,logs:i.map(e=>e.params)}}),await n.close()}catch(e){t.push({id:`tools-call-with-logging`,name:`ToolsCallWithLogging`,description:`Tool sends log messages during execution`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Logging`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/logging`}]})}return t}},we=class{constructor(){this.name=`tools-call-error`,this.description=`Test tool error reporting. + +**Server Implementation Requirements:** + +Implement tool \`test_error_handling\` with no arguments. + +**Behavior**: Always throw an error + +**Returns**: JSON-RPC response with \`isError: true\` + +\`\`\`json +{ + "isError": true, + "content": [ + { + "type": "text", + "text": "This tool intentionally returns an error for testing" + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=await n.client.callTool({name:`test_error_handling`,arguments:{}}),i=r.isError===!0,a=r.content&&r.content.length>0&&r.content[0].text;t.push({id:`tools-call-error`,name:`ToolsCallError`,description:`Tool returns error correctly`,status:i&&a?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i?a?void 0:`Error result missing error message`:`Tool did not return isError: true`,specReferences:[{id:`MCP-Error-Handling`,url:`https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle`}],details:{result:r}}),await n.close()}catch(e){t.push({id:`tools-call-error`,name:`ToolsCallError`,description:`Tool returns error correctly`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Error-Handling`,url:`https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle`}]})}return t}},Te=class{constructor(){this.name=`tools-call-with-progress`,this.description=`Test tool that reports progress notifications. + +**Server Implementation Requirements:** + +Implement tool \`test_tool_with_progress\` with no arguments. + +**Behavior**: If \`_meta.progressToken\` is provided in request: +- Send progress notification: \`0/100\` +- Wait ~50ms +- Send progress notification: \`50/100\` +- Wait ~50ms +- Send progress notification: \`100/100\` + +If no progress token provided, just execute with delays. + +**Returns**: Text content confirming execution + +**Progress Notification Format**: + +\`\`\`json +{ + "method": "notifications/progress", + "params": { + "progressToken": "", + "progress": 50, + "total": 100 + } +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=[],i=await n.client.request({method:`tools/call`,params:{name:`test_tool_with_progress`,arguments:{},_meta:{progressToken:`progress-test-1`}}},u,{onprogress:e=>{r.push(e)}}),a=[];if(r.length===0?a.push(`No progress notifications received`):r.length<3&&a.push(`Expected at least 3 progress notifications, got ${r.length}`),r.length>=3){let e=r[0].progress,t=r[1].progress,n=r[2].progress;e<=t&&t<=n||a.push(`Progress values should be increasing`)}t.push({id:`tools-call-with-progress`,name:`ToolsCallWithProgress`,description:`Tool reports progress notifications`,status:a.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:a.length>0?a.join(`; `):void 0,specReferences:[{id:`MCP-Progress`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/progress`}],details:{progressCount:r.length,progressNotifications:r.map(e=>e),result:i}}),await n.close()}catch(e){t.push({id:`tools-call-with-progress`,name:`ToolsCallWithProgress`,description:`Tool reports progress notifications`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Progress`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/progress`}]})}return t}},Ee=class{constructor(){this.name=`tools-call-sampling`,this.description=`Test tool that requests LLM sampling from client. + +**Server Implementation Requirements:** + +Implement tool \`test_sampling\` with argument: +- \`prompt\` (string, required) - The prompt to send to the LLM + +**Behavior**: Request LLM sampling from the client using \`sampling/createMessage\` + +**Sampling Request**: + +\`\`\`json +{ + "method": "sampling/createMessage", + "params": { + "messages": [ + { + "role": "user", + "content": { + "type": "text", + "text": "" + } + } + ], + "maxTokens": 100 + } +} +\`\`\` + +**Returns**: Text content with the LLM's response + +\`\`\`json +{ + "content": [ + { + "type": "text", + "text": "LLM response: " + } + ] +} +\`\`\` + +**Implementation Note**: If the client doesn't support sampling (no \`sampling\` capability), return an error.`}async run(e){let t=[];try{let n=await k(e),r=!1;n.client.setRequestHandler(d,async e=>(r=!0,{role:`assistant`,content:{type:`text`,text:`This is a test response from the client`},model:`test-model`,stopReason:`endTurn`}));let i=await n.client.callTool({name:`test_sampling`,arguments:{prompt:`Test prompt for sampling`}}),a=[];r||a.push(`Server did not request sampling from client`);let o=i.content;(!o||o.length===0)&&a.push(`Tool did not return content`),t.push({id:`tools-call-sampling`,name:`ToolsCallSampling`,description:`Tool requests LLM sampling from client`,status:a.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:a.length>0?a.join(`; `):void 0,specReferences:[{id:`MCP-Sampling`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/sampling`}],details:{samplingRequested:r,result:i}}),await n.close()}catch(e){t.push({id:`tools-call-sampling`,name:`ToolsCallSampling`,description:`Tool requests LLM sampling from client`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Sampling`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/sampling`}]})}return t}},De=class{constructor(){this.name=`tools-call-elicitation`,this.description=`Test tool that requests user input (elicitation) from client. + +**Server Implementation Requirements:** + +Implement tool \`test_elicitation\` with argument: +- \`message\` (string, required) - The message to show the user + +**Behavior**: Request user input from the client using \`elicitation/create\` + +**Elicitation Request**: + +\`\`\`json +{ + "method": "elicitation/create", + "params": { + "message": "", + "requestedSchema": { + "type": "object", + "properties": { + "username": { + "type": "string", + "description": "User's response" + }, + "email": { + "type": "string", + "description": "User's email address" + } + }, + "required": ["username", "email"] + } + } +} +\`\`\` + +**Returns**: Text content with the user's response + +\`\`\`json +{ + "content": [ + { + "type": "text", + "text": "User response: " + } + ] +} +\`\`\` + +**Implementation Note**: If the client doesn't support elicitation (no \`elicitation\` capability), return an error.`}async run(e){let t=[];try{let n=await k(e),r=!1;n.client.setRequestHandler(f,async e=>(r=!0,{action:`accept`,content:{username:`testuser`,email:`test@example.com`}}));let i=await n.client.callTool({name:`test_elicitation`,arguments:{message:`Please provide your information`}}),a=[];r||a.push(`Server did not request elicitation from client`);let o=i.content;(!o||o.length===0)&&a.push(`Tool did not return content`),t.push({id:`tools-call-elicitation`,name:`ToolsCallElicitation`,description:`Tool requests user input from client`,status:a.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:a.length>0?a.join(`; `):void 0,specReferences:[{id:`MCP-Elicitation`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/elicitation`}],details:{elicitationRequested:r,result:i}}),await n.close()}catch(e){t.push({id:`tools-call-elicitation`,name:`ToolsCallElicitation`,description:`Tool requests user input from client`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Elicitation`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/elicitation`}]})}return t}},Oe=class{constructor(){this.name=`tools-call-audio`,this.description=`Test calling a tool that returns audio content. + +**Server Implementation Requirements:** + +Implement tool \`test_audio_content\` with no arguments that returns: + +\`\`\`json +{ + "content": [ + { + "type": "audio", + "data": "", + "mimeType": "audio/wav" + } + ] +} +\`\`\` + +**Implementation Note**: Use a minimal test audio file`}async run(e){let t=[];try{let n=await k(e),r=await n.client.callTool({name:`test_audio_content`,arguments:{}}),i=[],a=r.content;a||i.push(`Missing content array`),Array.isArray(a)||i.push(`content is not an array`),a&&a.length===0&&i.push(`content array is empty`);let o=a&&a.find(e=>e.type===`audio`);o||i.push(`No audio content found`),o&&!o.data&&i.push(`Audio content missing data field`),o&&!o.mimeType&&i.push(`Audio content missing mimeType field`),o&&o.mimeType!==`audio/wav`&&i.push(`Expected mimeType 'audio/wav', got '${o.mimeType}'`),t.push({id:`tools-call-audio`,name:`ToolsCallAudio`,description:`Tool returns audio content`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Tools-Call`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools`}],details:{hasAudioContent:!!o,audioDataLength:o?.data?.length||0}}),await n.close()}catch(e){t.push({id:`tools-call-audio`,name:`ToolsCallAudio`,description:`Tool returns audio content`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Tools-Call`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools`}]})}return t}},ke=class{constructor(){this.name=`tools-call-embedded-resource`,this.description=`Test calling a tool that returns embedded resource content. + +**Server Implementation Requirements:** + +Implement tool \`test_embedded_resource\` with no arguments that returns: + +\`\`\`json +{ + "content": [ + { + "type": "resource", + "resource": { + "uri": "test://embedded-resource", + "mimeType": "text/plain", + "text": "This is an embedded resource content." + } + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=await n.client.callTool({name:`test_embedded_resource`,arguments:{}}),i=[],a=r.content;a||i.push(`Missing content array`),Array.isArray(a)||i.push(`content is not an array`),a&&a.length===0&&i.push(`content array is empty`);let o=a&&a.find(e=>e.type===`resource`);o||i.push(`No resource content found`),o&&!o.resource&&i.push(`Resource content missing resource field`),o?.resource&&(o.resource.uri||i.push(`Resource missing uri field`),o.resource.mimeType||i.push(`Resource missing mimeType field`),!o.resource.text&&!o.resource.blob&&i.push(`Resource missing both text and blob fields`)),t.push({id:`tools-call-embedded-resource`,name:`ToolsCallEmbeddedResource`,description:`Tool returns embedded resource content`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Tools-Call`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools`}],details:{hasResourceContent:!!o,resourceUri:o?.resource?.uri}}),await n.close()}catch(e){t.push({id:`tools-call-embedded-resource`,name:`ToolsCallEmbeddedResource`,description:`Tool returns embedded resource content`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Tools-Call`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/tools#calling-tools`}]})}return t}};const A=`json_schema_2020_12_tool`,j=`https://json-schema.org/draft/2020-12/schema`;var Ae=class{constructor(){this.name=`json-schema-2020-12`,this.description=`Validates JSON Schema 2020-12 keyword preservation (SEP-1613). + +**Server Implementation Requirements:** + +Implement tool \`${A}\` with inputSchema containing JSON Schema 2020-12 features: + +\`\`\`json +{ + "name": "${A}", + "description": "Tool with JSON Schema 2020-12 features", + "inputSchema": { + "$schema": "${j}", + "type": "object", + "$defs": { + "address": { + "type": "object", + "properties": { + "street": { "type": "string" }, + "city": { "type": "string" } + } + } + }, + "properties": { + "name": { "type": "string" }, + "address": { "$ref": "#/$defs/address" } + }, + "additionalProperties": false + } +} +\`\`\` + +**Verification**: The test verifies that \`$schema\`, \`$defs\`, and \`additionalProperties\` are preserved in the tool listing response.`}async run(e){let t=[],n=[{id:`SEP-1613`,url:`https://github.com/modelcontextprotocol/specification/pull/655`}];try{let r=await k(e),i=await r.client.listTools(),a=i.tools?.find(e=>e.name===A);if(t.push({id:`json-schema-2020-12-tool-found`,name:`JsonSchema2020_12ToolFound`,description:`Server advertises tool '${A}'`,status:a?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:a?void 0:`Tool '${A}' not found. Available tools: ${i.tools?.map(e=>e.name).join(`, `)||`none`}`,specReferences:n,details:{toolFound:!!a,availableTools:i.tools?.map(e=>e.name)||[]}}),!a)return await r.close(),t;let o=a.inputSchema,s=`$schema`in o,c=o.$schema,l=c===j;t.push({id:`json-schema-2020-12-$schema`,name:`JsonSchema2020_12$Schema`,description:`inputSchema.$schema field preserved with value '${j}'`,status:s&&l?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:s?l?void 0:`$schema has unexpected value: ${JSON.stringify(c)}`:`$schema field missing from inputSchema - field was likely stripped`,specReferences:n,details:{hasSchema:s,schemaValue:c,expected:j}});let u=`$defs`in o,d=o.$defs,f=d&&`address`in d;t.push({id:`json-schema-2020-12-$defs`,name:`JsonSchema2020_12$Defs`,description:`inputSchema.$defs field preserved with expected structure`,status:u&&f?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:u?f?void 0:`$defs exists but missing expected "address" definition`:`$defs field missing from inputSchema - field was likely stripped`,specReferences:n,details:{hasDefs:u,defsKeys:d?Object.keys(d):[],defsValue:d}});let p=`additionalProperties`in o,m=o.additionalProperties,h=m===!1;t.push({id:`json-schema-2020-12-additionalProperties`,name:`JsonSchema2020_12AdditionalProperties`,description:`inputSchema.additionalProperties field preserved`,status:p&&h?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:p?h?void 0:`additionalProperties has unexpected value: ${JSON.stringify(m)}, expected: false`:`additionalProperties field missing from inputSchema - field was likely stripped`,specReferences:n,details:{hasAdditionalProps:p,additionalPropsValue:m,expected:!1}}),await r.close()}catch(e){t.push({id:`json-schema-2020-12-error`,name:`JsonSchema2020_12Error`,description:`JSON Schema 2020-12 conformance test`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:n})}return t}},je=class{constructor(){this.name=`elicitation-sep1034-defaults`,this.description=`Test elicitation with default values for all primitive types (SEP-1034). + +**Server Implementation Requirements:** + +Implement a tool named \`test_elicitation_sep1034_defaults\` (no arguments) that requests \`elicitation/create\` from the client with a schema containing default values for all primitive types: +- \`name\` (string): default "John Doe" +- \`age\` (integer): default 30 +- \`score\` (number): default 95.5 +- \`status\` (string enum: ["active", "inactive", "pending"]): default "active" +- \`verified\` (boolean): default true + +**Returns**: Text content with the elicitation result + +\`\`\`json +{ + "content": [ + { + "type": "text", + "text": "Elicitation completed: action=, content={...}" + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=null;if(n.client.setRequestHandler(f,async e=>(r=e,{action:`accept`,content:{name:`Jane Smith`,age:25,score:88,status:`inactive`,verified:!1}})),await n.client.callTool({name:`test_elicitation_sep1034_defaults`,arguments:{}}),!r)return t.push({id:`elicitation-sep1034-general`,name:`ElicitationSEP1034General`,description:`Server requests elicitation with default values`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Server did not request elicitation from client`,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}]}),await n.close(),t;let i=r.params?.requestedSchema?.properties,a=[];i?.name?(i.name.type!==`string`&&a.push(`Expected type "string", got "${i.name.type}"`),`default`in i.name?i.name.default!==`John Doe`&&a.push(`Expected default "John Doe", got "${i.name.default}"`):a.push(`Missing default field`)):a.push(`Missing string field "name"`),t.push({id:`elicitation-sep1034-string-default`,name:`ElicitationSEP1034StringDefault`,description:`String schema includes default value`,status:a.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:a.length>0?a.join(`; `):void 0,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}],details:{field:`name`,schema:i?.name}});let o=[];i?.age?(i.age.type!==`integer`&&o.push(`Expected type "integer", got "${i.age.type}"`),`default`in i.age?i.age.default!==30&&o.push(`Expected default 30, got ${i.age.default}`):o.push(`Missing default field`)):o.push(`Missing integer field "age"`),t.push({id:`elicitation-sep1034-integer-default`,name:`ElicitationSEP1034IntegerDefault`,description:`Integer schema includes default value`,status:o.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:o.length>0?o.join(`; `):void 0,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}],details:{field:`age`,schema:i?.age}});let s=[];i?.score?(i.score.type!==`number`&&s.push(`Expected type "number", got "${i.score.type}"`),`default`in i.score?i.score.default!==95.5&&s.push(`Expected default 95.5, got ${i.score.default}`):s.push(`Missing default field`)):s.push(`Missing number field "score"`),t.push({id:`elicitation-sep1034-number-default`,name:`ElicitationSEP1034NumberDefault`,description:`Number schema includes default value`,status:s.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:s.length>0?s.join(`; `):void 0,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}],details:{field:`score`,schema:i?.score}});let c=[];i?.status?(i.status.type!==`string`&&c.push(`Expected type "string", got "${i.status.type}"`),(!i.status.enum||!Array.isArray(i.status.enum))&&c.push(`Missing or invalid enum array`),`default`in i.status?(i.status.default!==`active`&&c.push(`Expected default "active", got "${i.status.default}"`),i.status.enum&&!i.status.enum.includes(i.status.default)&&c.push(`Default value "${i.status.default}" is not a valid enum member`)):c.push(`Missing default field`)):c.push(`Missing enum field "status"`),t.push({id:`elicitation-sep1034-enum-default`,name:`ElicitationSEP1034EnumDefault`,description:`Enum schema includes valid default value`,status:c.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:c.length>0?c.join(`; `):void 0,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}],details:{field:`status`,schema:i?.status}});let l=[];i?.verified?(i.verified.type!==`boolean`&&l.push(`Expected type "boolean", got "${i.verified.type}"`),`default`in i.verified?i.verified.default!==!0&&l.push(`Expected default true, got ${i.verified.default}`):l.push(`Missing default field`)):l.push(`Missing boolean field "verified"`),t.push({id:`elicitation-sep1034-boolean-default`,name:`ElicitationSEP1034BooleanDefault`,description:`Boolean schema includes default value`,status:l.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:l.length>0?l.join(`; `):void 0,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}],details:{field:`verified`,schema:i?.verified}}),await n.close()}catch(e){t.push({id:`elicitation-sep1034-general`,name:`ElicitationSEP1034General`,description:`Server requests elicitation with default values`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`SEP-1034`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034`}]})}return t}},Me=class{constructor(){this.name=`elicitation-sep1330-enums`,this.description=`Test elicitation with enum schema improvements (SEP-1330). + +**Server Implementation Requirements:** + +Implement a tool named \`test_elicitation_sep1330_enums\` (no arguments) that requests \`elicitation/create\` from the client with a schema containing all 5 enum variants: + +1. **Untitled single-select**: \`{ type: "string", enum: ["option1", "option2", "option3"] }\` +2. **Titled single-select**: \`{ type: "string", oneOf: [{ const: "value1", title: "First Option" }, ...] }\` +3. **Legacy titled (deprecated)**: \`{ type: "string", enum: ["opt1", "opt2", "opt3"], enumNames: ["Option One", "Option Two", "Option Three"] }\` +4. **Untitled multi-select**: \`{ type: "array", items: { type: "string", enum: ["option1", "option2", "option3"] } }\` +5. **Titled multi-select**: \`{ type: "array", items: { anyOf: [{ const: "value1", title: "First Choice" }, ...] } }\` + +**Returns**: Text content with the elicitation result + +\`\`\`json +{ + "content": [ + { + "type": "text", + "text": "Elicitation completed: action=, content={...}" + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=null;if(n.client.setRequestHandler(f,async e=>(r=e,{action:`accept`,content:{untitledSingle:`option1`,titledSingle:`value1`,legacyEnum:`opt1`,untitledMulti:[`option1`,`option2`],titledMulti:[`value1`,`value2`]}})),await n.client.callTool({name:`test_elicitation_sep1330_enums`,arguments:{}}),!r)return t.push({id:`elicitation-sep1330-general`,name:`ElicitationSEP1330General`,description:`Server requests elicitation with enum schemas`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Server did not request elicitation from client`,specReferences:[{id:`SEP-1330`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1330`}]}),await n.close(),t;let i=r.params?.requestedSchema?.properties,a=[];i?.untitledSingle?(i.untitledSingle.type!==`string`&&a.push(`Expected type "string", got "${i.untitledSingle.type}"`),(!i.untitledSingle.enum||!Array.isArray(i.untitledSingle.enum))&&a.push(`Missing or invalid enum array`),i.untitledSingle.oneOf&&a.push(`Untitled enum should not have oneOf property`),i.untitledSingle.enumNames&&a.push(`Untitled enum should not have enumNames property`)):a.push(`Missing untitled single-select enum field "untitledSingle"`),t.push({id:`elicitation-sep1330-untitled-single`,name:`ElicitationSEP1330UntitledSingle`,description:`Untitled single-select enum schema uses enum array`,status:a.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:a.length>0?a.join(`; `):void 0,specReferences:[{id:`SEP-1330`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1330`}],details:{field:`untitledSingle`,schema:i?.untitledSingle}});let o=[];i?.titledSingle?(i.titledSingle.type!==`string`&&o.push(`Expected type "string", got "${i.titledSingle.type}"`),!i.titledSingle.oneOf||!Array.isArray(i.titledSingle.oneOf)?o.push(`Missing or invalid oneOf array for titled enum`):i.titledSingle.oneOf.filter(e=>typeof e.const!=`string`||typeof e.title!=`string`).length>0&&o.push(`oneOf items must have "const" (string) and "title" (string) properties`),i.titledSingle.enum&&o.push(`Titled enum should use oneOf instead of enum array`)):o.push(`Missing titled single-select enum field "titledSingle"`),t.push({id:`elicitation-sep1330-titled-single`,name:`ElicitationSEP1330TitledSingle`,description:`Titled single-select enum schema uses oneOf with const/title`,status:o.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:o.length>0?o.join(`; `):void 0,specReferences:[{id:`SEP-1330`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1330`}],details:{field:`titledSingle`,schema:i?.titledSingle}});let s=[];i?.legacyEnum?(i.legacyEnum.type!==`string`&&s.push(`Expected type "string", got "${i.legacyEnum.type}"`),(!i.legacyEnum.enum||!Array.isArray(i.legacyEnum.enum))&&s.push(`Missing or invalid enum array`),!i.legacyEnum.enumNames||!Array.isArray(i.legacyEnum.enumNames)?s.push(`Missing or invalid enumNames array for legacy titled enum`):i.legacyEnum.enum&&i.legacyEnum.enumNames.length!==i.legacyEnum.enum.length&&s.push(`enumNames length (${i.legacyEnum.enumNames.length}) must match enum length (${i.legacyEnum.enum.length})`)):s.push(`Missing legacy titled enum field "legacyEnum"`),t.push({id:`elicitation-sep1330-legacy-enumnames`,name:`ElicitationSEP1330LegacyEnumNames`,description:`Legacy titled enum schema uses enumNames (deprecated)`,status:s.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:s.length>0?s.join(`; `):void 0,specReferences:[{id:`SEP-1330`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1330`}],details:{field:`legacyEnum`,schema:i?.legacyEnum}});let c=[];i?.untitledMulti?(i.untitledMulti.type!==`array`&&c.push(`Expected type "array", got "${i.untitledMulti.type}"`),i.untitledMulti.items?(i.untitledMulti.items.type!==`string`&&c.push(`Expected items.type "string", got "${i.untitledMulti.items.type}"`),(!i.untitledMulti.items.enum||!Array.isArray(i.untitledMulti.items.enum))&&c.push(`Missing or invalid items.enum array`),i.untitledMulti.items.anyOf&&c.push(`Untitled multi-select should use items.enum, not items.anyOf`)):c.push(`Missing items property for array type`)):c.push(`Missing untitled multi-select enum field "untitledMulti"`),t.push({id:`elicitation-sep1330-untitled-multi`,name:`ElicitationSEP1330UntitledMulti`,description:`Untitled multi-select enum schema uses array with items.enum`,status:c.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:c.length>0?c.join(`; `):void 0,specReferences:[{id:`SEP-1330`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1330`}],details:{field:`untitledMulti`,schema:i?.untitledMulti}});let l=[];i?.titledMulti?(i.titledMulti.type!==`array`&&l.push(`Expected type "array", got "${i.titledMulti.type}"`),i.titledMulti.items?(!i.titledMulti.items.anyOf||!Array.isArray(i.titledMulti.items.anyOf)?l.push(`Missing or invalid items.anyOf array for titled multi-select`):i.titledMulti.items.anyOf.filter(e=>typeof e.const!=`string`||typeof e.title!=`string`).length>0&&l.push(`items.anyOf entries must have "const" (string) and "title" (string) properties`),i.titledMulti.items.enum&&l.push(`Titled multi-select should use items.anyOf, not items.enum`)):l.push(`Missing items property for array type`)):l.push(`Missing titled multi-select enum field "titledMulti"`),t.push({id:`elicitation-sep1330-titled-multi`,name:`ElicitationSEP1330TitledMulti`,description:`Titled multi-select enum schema uses array with items.anyOf`,status:l.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:l.length>0?l.join(`; `):void 0,specReferences:[{id:`SEP-1330`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1330`}],details:{field:`titledMulti`,schema:i?.titledMulti}}),await n.close()}catch(e){t.push({id:`elicitation-sep1330-general`,name:`ElicitationSEP1330General`,description:`Server requests elicitation with enum schemas`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`SEP-1330`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1330`}]})}return t}};function Ne(e){return async(t,n)=>{let r=n.method||`GET`,i=`Sending ${r} request`;if(n.body)try{let e=JSON.parse(n.body);e.method&&(i=`Sending ${r} ${e.method}`)}catch{}e.push({id:`outgoing-request`,name:`OutgoingRequest`,description:i,status:`INFO`,timestamp:new Date().toISOString(),details:{method:r,url:t,headers:n.headers,body:n.body?JSON.parse(n.body):void 0}});let a=await fetch(t,n),o={};return a.headers.forEach((e,t)=>{o[t]=e}),e.push({id:`incoming-response`,name:`IncomingResponse`,description:`Received ${a.status} response for ${r}`,status:`INFO`,timestamp:new Date().toISOString(),details:{statusCode:a.status,headers:o}}),a}}var Pe=class{constructor(){this.name=`server-sse-polling`,this.description=`Test server SSE polling via test_reconnection tool that closes stream mid-call (SEP-1699)`}async run(e){let t=[],n,r,i;try{r=new S({name:`conformance-test-client`,version:`1.0.0`},{capabilities:{sampling:{},elicitation:{}}}),i=new C(new URL(e)),await r.connect(i),n=i.sessionId,n||t.push({id:`server-sse-polling-session`,name:`ServerSSEPollingSession`,description:`Server provides session ID for SSE polling tests`,status:`WARNING`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{message:`Server did not provide session ID - SSE polling tests may not work correctly`}});let a=Ne(t),o=await a(e,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream, application/json`,...n&&{"mcp-session-id":n},"mcp-protocol-version":`2025-03-26`},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:`tools/call`,params:{name:`test_reconnection`,arguments:{}}})});if(!o.ok)return o.status===400||o.status===404?(t.push({id:`server-sse-test-reconnection-tool`,name:`ServerTestReconnectionTool`,description:`Server implements test_reconnection tool for SSE polling tests`,status:`WARNING`,timestamp:new Date().toISOString(),errorMessage:`Server does not implement test_reconnection tool (HTTP ${o.status}). This tool is recommended for testing SSE polling behavior.`,specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}]}),t):(t.push({id:`server-sse-post-request`,name:`ServerSSEPostRequest`,description:`Server accepts POST request with SSE stream response`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Server returned HTTP ${o.status}`,specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}]}),t);let s=o.headers.get(`content-type`);if(!s?.includes(`text/event-stream`))return t.push({id:`server-sse-content-type`,name:`ServerSSEContentType`,description:`Server returns text/event-stream for POST request`,status:`INFO`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{contentType:s,message:`Server returned JSON instead of SSE stream - priming event tests not applicable`}}),t;let c=!1,l=!1,u=!1,d=!1,f,p,m=0,h=!1;if(!o.body)return t.push({id:`server-sse-polling-stream`,name:`ServerSSEPollingStream`,description:`Server provides SSE response body`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Response body is null`,specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}]}),t;let g=o.body.pipeThrough(new TextDecoderStream).pipeThrough(new w({onRetry:e=>{d=!0,f=e}})).getReader(),_=setTimeout(()=>{g.cancel()},1e4);try{for(;;){let{value:e,done:n}=await g.read();if(n)break;if(m++,e.id){c=!0,p=e.id;let n=e.data===``||e.data===`{}`||e.data.trim()===``;n&&(l=!0,m===1&&(u=!0)),t.push({id:`incoming-sse-event`,name:`IncomingSseEvent`,description:n?`Received SSE priming event (id: ${e.id})`:`Received SSE event (id: ${e.id})`,status:`INFO`,timestamp:new Date().toISOString(),details:{eventId:e.id,eventType:e.event||`message`,isPriming:n,hasRetryField:d,retryValue:f,data:e.data}})}if(e.data)try{let n=JSON.parse(e.data);if(n.id===1&&n.result){h=!0;let r=n.result?.isError===!0;t.push({id:`incoming-sse-event`,name:`IncomingSseEvent`,description:`Received tool response on POST stream`,status:r?`FAILURE`:`INFO`,timestamp:new Date().toISOString(),details:{eventId:e.id,body:n},...r&&{errorMessage:`Tool call failed`}})}}catch{}}}finally{clearTimeout(_)}t.push({id:`stream-closed`,name:`StreamClosed`,description:`POST SSE stream closed after ${m} event(s)`,status:`INFO`,timestamp:new Date().toISOString(),details:{eventCount:m,lastEventId:p,receivedToolResponse:h}});let v=`SUCCESS`,y;if(l?u||(v=`WARNING`,y=`Priming event was not sent first. It should be sent immediately when the SSE stream is established.`):(v=`WARNING`,y=`Server did not send priming event with id and empty data on POST SSE stream. This is recommended for resumability.`),t.push({id:`server-sse-priming-event`,name:`ServerSendsPrimingEvent`,description:`Server SHOULD send priming event with id and empty data on POST SSE streams`,status:v,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{hasPrimingEvent:l,primingEventIsFirst:u,hasEventId:c,lastEventId:p,eventCount:m},errorMessage:y}),t.push({id:`server-sse-retry-field`,name:`ServerSendsRetryField`,description:`Server SHOULD send retry field to control client reconnection timing`,status:d?`SUCCESS`:`WARNING`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{hasRetryField:d,retryValue:f},errorMessage:d?void 0:`Server did not send retry field. This is recommended for controlling client reconnection timing.`}),!h&&p&&n){let r=await a(e,{method:`GET`,headers:{Accept:`text/event-stream`,"mcp-session-id":n,"mcp-protocol-version":`2025-03-26`,"last-event-id":p}});if(r.ok&&r.body){let e=r.body.pipeThrough(new TextDecoderStream).pipeThrough(new w).getReader(),n=setTimeout(()=>{e.cancel()},5e3);try{for(;;){let{value:n,done:r}=await e.read();if(r)break;if(t.push({id:`incoming-sse-event`,name:`IncomingSseEvent`,description:`Received SSE event on GET reconnection stream (id: ${n.id||`none`})`,status:`INFO`,timestamp:new Date().toISOString(),details:{eventId:n.id,eventType:n.event||`message`,data:n.data}}),n.data)try{let e=JSON.parse(n.data);if(e.id===1&&e.result){h=!0;break}}catch{}}}finally{clearTimeout(n)}t.push({id:`server-sse-disconnect-resume`,name:`ServerDisconnectResume`,description:`Server closes SSE stream mid-call and resumes after client reconnects with Last-Event-ID`,status:h?`SUCCESS`:`WARNING`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{lastEventIdUsed:p,receivedToolResponse:h,message:h?`Successfully received tool response after reconnection`:`Tool response not received after reconnection`},errorMessage:h?void 0:`Server did not send tool response after client reconnected with Last-Event-ID`})}else r.status===405?t.push({id:`server-sse-disconnect-resume`,name:`ServerDisconnectResume`,description:`Server supports GET reconnection with Last-Event-ID`,status:`INFO`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{statusCode:r.status,message:`Server does not support standalone GET SSE endpoint (405 Method Not Allowed)`}}):t.push({id:`server-sse-disconnect-resume`,name:`ServerDisconnectResume`,description:`Server supports GET reconnection with Last-Event-ID`,status:`WARNING`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{statusCode:r.status,lastEventIdUsed:p,message:`Server returned ${r.status} for GET request with Last-Event-ID`},errorMessage:`Server did not accept reconnection with Last-Event-ID (HTTP ${r.status})`})}else h?t.push({id:`server-sse-disconnect-resume`,name:`ServerDisconnectResume`,description:`Server closes SSE stream mid-call and resumes after reconnection`,status:`INFO`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{receivedToolResponse:!0,message:`Tool response received on initial POST stream - server did not disconnect mid-call. The test_reconnection tool should close the stream before sending the result.`}}):t.push({id:`server-sse-disconnect-resume`,name:`ServerDisconnectResume`,description:`Server closes SSE stream mid-call and resumes after reconnection`,status:`INFO`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{lastEventId:p,sessionId:n,message:`Could not test disconnect/resume - no last event ID or session ID available`}})}catch(e){t.push({id:`server-sse-polling-error`,name:`ServerSSEPollingTest`,description:`Test server SSE polling behavior`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Error: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}]})}finally{if(r)try{await r.close()}catch{}}return t}},Fe=class{constructor(){this.name=`server-sse-multiple-streams`,this.description=`Test server supports multiple concurrent POST SSE streams (SEP-1699)`}async run(e){let t=[],n,r,i;try{if(r=new S({name:`conformance-test-client`,version:`1.0.0`},{capabilities:{sampling:{},elicitation:{}}}),i=new C(new URL(e)),await r.connect(i),n=i.sessionId,!n)return t.push({id:`server-sse-multiple-streams-session`,name:`ServerSSEMultipleStreamsSession`,description:`Server provides session ID for multiple streams test`,status:`WARNING`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{message:`Server did not provide session ID - multiple streams test may not work correctly`}}),t;let a=[],o=[];for(let t=0;t<3;t++){let r=fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream, application/json`,"mcp-session-id":n,"mcp-protocol-version":`2025-03-26`},body:JSON.stringify({jsonrpc:`2.0`,id:1e3+t,method:`tools/list`,params:{}})});o.push(r)}let s=await Promise.all(o);a.push(...s);let c=a.every(e=>e.ok),l=a.map(e=>e.status),u=a.map(e=>e.headers.get(`content-type`)),d=u.filter(e=>e?.includes(`text/event-stream`)).length;t.push({id:`server-accepts-multiple-post-streams`,name:`ServerAcceptsMultiplePostStreams`,description:`Server allows multiple concurrent POST requests (each may return SSE or JSON)`,status:c?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{numStreamsAttempted:3,numStreamsAccepted:l.filter(e=>e===200).length,numSseStreams:d,statuses:l,contentTypes:u},errorMessage:c?void 0:`Server rejected some requests. Statuses: ${l.join(`, `)}`});let f=await Promise.all(a.map(async(e,t)=>{if(!e.headers.get(`content-type`)?.includes(`text/event-stream`))return{index:t,type:`json`,skipped:!0};if(!e.ok||!e.body)return{index:t,type:`sse`,error:`Stream not available`};try{let n=e.body.pipeThrough(new TextDecoderStream).pipeThrough(new w).getReader(),r=new Promise(e=>setTimeout(()=>e(null),2e3)),i=n.read().then(({value:e})=>e),a=await Promise.race([i,r]);return await n.cancel(),{index:t,type:`sse`,event:a}}catch(e){return{index:t,type:`sse`,error:e instanceof Error?e.message:String(e)}}})),p=f.filter(e=>e.type===`sse`).filter(e=>!(`error`in e)).length;d>0?t.push({id:`server-sse-streams-functional`,name:`ServerSSEStreamsFunctional`,description:`Multiple POST SSE streams should be functional`,status:p===d?`SUCCESS`:p>0?`WARNING`:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[{id:`SEP-1699`,url:`https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699`}],details:{numSseStreams:d,functionalSseStreams:p,results:f},errorMessage:p{e.uri||i.push(`Resource ${t}: missing uri`),e.name||i.push(`Resource ${t}: missing name`)})):i.push(`Missing resources array`),t.push({id:`resources-list`,name:`ResourcesList`,description:`Server lists available resources with valid structure`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Resources-List`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/resources#listing-resources`}],details:{resourceCount:r.resources?.length||0,resources:r.resources?.map(e=>e.uri)}}),await n.close()}catch(e){t.push({id:`resources-list`,name:`ResourcesList`,description:`Server lists available resources with valid structure`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Resources-List`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/resources#listing-resources`}]})}return t}},Le=class{constructor(){this.name=`resources-read-text`,this.description=`Test reading text resource. + +**Server Implementation Requirements:** + +Implement resource \`test://static-text\` that returns: + +\`\`\`json +{ + "contents": [ + { + "uri": "test://static-text", + "mimeType": "text/plain", + "text": "This is the content of the static text resource." + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=await n.client.readResource({uri:`test://static-text`}),i=[];r.contents||i.push(`Missing contents array`),Array.isArray(r.contents)||i.push(`contents is not an array`),r.contents.length===0&&i.push(`contents array is empty`);let a=r.contents[0];a&&(a.uri||i.push(`Content missing uri`),a.mimeType||i.push(`Content missing mimeType`),a.text||i.push(`Content missing text field`)),t.push({id:`resources-read-text`,name:`ResourcesReadText`,description:`Read text resource successfully`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Resources-Read`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/resources#reading-resources`}],details:{uri:a?.uri,mimeType:a?.mimeType,hasText:!!a?.text}}),await n.close()}catch(e){t.push({id:`resources-read-text`,name:`ResourcesReadText`,description:`Read text resource successfully`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Resources-Read`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/resources#reading-resources`}]})}return t}},Re=class{constructor(){this.name=`resources-read-binary`,this.description=`Test reading binary resource. + +**Server Implementation Requirements:** + +Implement resource \`test://static-binary\` that returns: + +\`\`\`json +{ + "contents": [ + { + "uri": "test://static-binary", + "mimeType": "image/png", + "blob": "" + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=await n.client.readResource({uri:`test://static-binary`}),i=[];r.contents||i.push(`Missing contents array`),r.contents.length===0&&i.push(`contents array is empty`);let a=r.contents[0];a&&(a.uri||i.push(`Content missing uri`),a.mimeType||i.push(`Content missing mimeType`),a.blob||i.push(`Content missing blob field`)),t.push({id:`resources-read-binary`,name:`ResourcesReadBinary`,description:`Read binary resource successfully`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Resources-Read`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/resources#reading-resources`}],details:{uri:a?.uri,mimeType:a?.mimeType,hasBlob:!!a?.blob}}),await n.close()}catch(e){t.push({id:`resources-read-binary`,name:`ResourcesReadBinary`,description:`Read binary resource successfully`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Resources-Read`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/resources#reading-resources`}]})}return t}},ze=class{constructor(){this.name=`resources-templates-read`,this.description=`Test reading resource from template. + +**Server Implementation Requirements:** + +Implement resource template \`test://template/{id}/data\` that substitutes parameters. + +**Behavior**: When client requests \`test://template/123/data\`, substitute \`{id}\` with \`123\` + +Returns (for \`uri: "test://template/123/data"\`): + +\`\`\`json +{ + "contents": [ + { + "uri": "test://template/123/data", + "mimeType": "application/json", + "text": "{"id":"123","templateTest":true,"data":"Data for ID: 123"}" + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=await n.client.readResource({uri:`test://template/123/data`}),i=[];r.contents||i.push(`Missing contents array`),r.contents.length===0&&i.push(`contents array is empty`);let a=r.contents[0];if(a){a.uri||i.push(`Content missing uri`);let e=`text`in a,t=`blob`in a;!e&&!t&&i.push(`Content missing text or blob`);let n=e?a.text:t?`[binary]`:``;typeof n==`string`&&!n.includes(`123`)&&i.push(`Parameter substitution not reflected in content`)}t.push({id:`resources-templates-read`,name:`ResourcesTemplateRead`,description:`Read resource from template with parameter substitution`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Resources-Templates`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/resources#resource-templates`}],details:{uri:a?.uri,content:a?`text`in a?a.text:a.blob:void 0}}),await n.close()}catch(e){t.push({id:`resources-templates-read`,name:`ResourcesTemplateRead`,description:`Read resource from template with parameter substitution`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Resources-Templates`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/resources#resource-templates`}]})}return t}},Be=class{constructor(){this.name=`resources-subscribe`,this.description=`Test subscribing to resource updates. + +**Server Implementation Requirements:** + +**Endpoint**: \`resources/subscribe\` + +**Requirements**: +- Accept subscription request with URI +- Track subscribed URIs +- Return empty object \`{}\` + +Example request: + +\`\`\`json +{ + "method": "resources/subscribe", + "params": { + "uri": "test://watched-resource" + } +} +\`\`\``}async run(e){let t=[];try{let n=await k(e);await n.client.subscribeResource({uri:`test://watched-resource`}),t.push({id:`resources-subscribe`,name:`ResourcesSubscribe`,description:`Subscribe to resource successfully`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[{id:`MCP-Resources-Subscribe`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/resources#resource-subscriptions`}]}),await n.close()}catch(e){t.push({id:`resources-subscribe`,name:`ResourcesSubscribe`,description:`Subscribe to resource successfully`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Resources-Subscribe`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/resources#resource-subscriptions`}]})}return t}},Ve=class{constructor(){this.name=`resources-unsubscribe`,this.description=`Test unsubscribing from resource. + +**Server Implementation Requirements:** + +**Endpoint**: \`resources/unsubscribe\` + +**Requirements**: +- Accept unsubscribe request with URI +- Remove URI from subscriptions +- Stop sending update notifications for that URI +- Return empty object \`{}\``}async run(e){let t=[];try{let n=await k(e);await n.client.subscribeResource({uri:`test://watched-resource`}),await n.client.unsubscribeResource({uri:`test://watched-resource`}),t.push({id:`resources-unsubscribe`,name:`ResourcesUnsubscribe`,description:`Unsubscribe from resource successfully`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[{id:`MCP-Resources-Subscribe`,url:`https://modelcontextprotocol.io/specification/2025-06-18/schema#unsubscriberequest`}]}),await n.close()}catch(e){t.push({id:`resources-unsubscribe`,name:`ResourcesUnsubscribe`,description:`Unsubscribe from resource successfully`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Resources-Subscribe`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/resources#resource-subscriptions`}]})}return t}},He=class{constructor(){this.name=`prompts-list`,this.description=`Test listing available prompts. + +**Server Implementation Requirements:** + +**Endpoint**: \`prompts/list\` + +**Requirements**: +- Return array of all available prompts +- Each prompt MUST have: + - \`name\` (string) + - \`description\` (string) + - \`arguments\` (array, optional) - list of required arguments`}async run(e){let t=[];try{let n=await k(e),r=await n.client.listPrompts(),i=[];r.prompts?(Array.isArray(r.prompts)||i.push(`prompts is not an array`),r.prompts.forEach((e,t)=>{e.name||i.push(`Prompt ${t}: missing name`),e.description||i.push(`Prompt ${t}: missing description`)})):i.push(`Missing prompts array`),t.push({id:`prompts-list`,name:`PromptsList`,description:`Server lists available prompts with valid structure`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Prompts-List`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/prompts#listing-prompts`}],details:{promptCount:r.prompts?.length||0,prompts:r.prompts?.map(e=>e.name)}}),await n.close()}catch(e){t.push({id:`prompts-list`,name:`PromptsList`,description:`Server lists available prompts with valid structure`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Prompts-List`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/prompts#listing-prompts`}]})}return t}},Ue=class{constructor(){this.name=`prompts-get-simple`,this.description=`Test getting a simple prompt without arguments. + +**Server Implementation Requirements:** + +Implement a prompt named \`test_simple_prompt\` with no arguments that returns: + +\`\`\`json +{ + "messages": [ + { + "role": "user", + "content": { + "type": "text", + "text": "This is a simple prompt for testing." + } + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=await n.client.getPrompt({name:`test_simple_prompt`}),i=[];r.messages||i.push(`Missing messages array`),Array.isArray(r.messages)||i.push(`messages is not an array`),r.messages.length===0&&i.push(`messages array is empty`),r.messages.forEach((e,t)=>{e.role||i.push(`Message ${t}: missing role`),e.content||i.push(`Message ${t}: missing content`)}),t.push({id:`prompts-get-simple`,name:`PromptsGetSimple`,description:`Get simple prompt successfully`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Prompts-Get`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/prompts#getting-prompts`}],details:{messageCount:r.messages?.length||0}}),await n.close()}catch(e){t.push({id:`prompts-get-simple`,name:`PromptsGetSimple`,description:`Get simple prompt successfully`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Prompts-Get`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/prompts#getting-prompts`}]})}return t}},We=class{constructor(){this.name=`prompts-get-with-args`,this.description=`Test parameterized prompt. + +**Server Implementation Requirements:** + +Implement a prompt named \`test_prompt_with_arguments\` with arguments: +- \`arg1\` (string, required) - First test argument +- \`arg2\` (string, required) - Second test argument + +Returns (with args \`{arg1: "hello", arg2: "world"}\`): + +\`\`\`json +{ + "messages": [ + { + "role": "user", + "content": { + "type": "text", + "text": "Prompt with arguments: arg1='hello', arg2='world'" + } + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=await n.client.getPrompt({name:`test_prompt_with_arguments`,arguments:{arg1:`testValue1`,arg2:`testValue2`}}),i=[];r.messages||i.push(`Missing messages array`),r.messages.length===0&&i.push(`messages array is empty`);let a=JSON.stringify(r.messages);a.includes(`testValue1`)||i.push(`arg1 not substituted in prompt`),a.includes(`testValue2`)||i.push(`arg2 not substituted in prompt`),t.push({id:`prompts-get-with-args`,name:`PromptsGetWithArgs`,description:`Get parameterized prompt with argument substitution`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Prompts-Get`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/prompts#getting-prompts`}],details:{messageCount:r.messages?.length||0,messages:r.messages}}),await n.close()}catch(e){t.push({id:`prompts-get-with-args`,name:`PromptsGetWithArgs`,description:`Get parameterized prompt with argument substitution`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Prompts-Get`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/prompts#getting-prompts`}]})}return t}},Ge=class{constructor(){this.name=`prompts-get-embedded-resource`,this.description=`Test prompt with embedded resource content. + +**Server Implementation Requirements:** + +Implement a prompt named \`test_prompt_with_embedded_resource\` with argument: +- \`resourceUri\` (string, required) - URI of the resource to embed + +Returns: + +\`\`\`json +{ + "messages": [ + { + "role": "user", + "content": { + "type": "resource", + "resource": { + "uri": "", + "mimeType": "text/plain", + "text": "Embedded resource content for testing." + } + } + }, + { + "role": "user", + "content": { + "type": "text", + "text": "Please process the embedded resource above." + } + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=await n.client.getPrompt({name:`test_prompt_with_embedded_resource`,arguments:{resourceUri:`test://example-resource`}}),i=[];r.messages||i.push(`Missing messages array`),r.messages.some(e=>e.content?.type===`resource`||e.content?.resource!==void 0)||i.push(`No embedded resource found in prompt`),t.push({id:`prompts-get-embedded-resource`,name:`PromptsGetEmbeddedResource`,description:`Get prompt with embedded resource`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Prompts-Embedded-Resources`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/prompts#embedded-resources`}],details:{messageCount:r.messages?.length||0,messages:r.messages}}),await n.close()}catch(e){t.push({id:`prompts-get-embedded-resource`,name:`PromptsGetEmbeddedResource`,description:`Get prompt with embedded resource`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Prompts-Embedded-Resources`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/prompts#embedded-resources`}]})}return t}},Ke=class{constructor(){this.name=`prompts-get-with-image`,this.description=`Test prompt with image content. + +**Server Implementation Requirements:** + +Implement a prompt named \`test_prompt_with_image\` with no arguments that returns: + +\`\`\`json +{ + "messages": [ + { + "role": "user", + "content": { + "type": "image", + "data": "", + "mimeType": "image/png" + } + }, + { + "role": "user", + "content": { + "type": "text", + "text": "Please analyze the image above." + } + } + ] +} +\`\`\``}async run(e){let t=[];try{let n=await k(e),r=await n.client.getPrompt({name:`test_prompt_with_image`}),i=[];r.messages||i.push(`Missing messages array`),r.messages.some(e=>e.content?.type===`image`&&e.content?.data&&e.content?.mimeType)||i.push(`No image content found in prompt`),t.push({id:`prompts-get-with-image`,name:`PromptsGetWithImage`,description:`Get prompt with image content`,status:i.length===0?`SUCCESS`:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:i.length>0?i.join(`; `):void 0,specReferences:[{id:`MCP-Prompts-Image`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/prompts#image-content`}],details:{messageCount:r.messages?.length||0}}),await n.close()}catch(e){t.push({id:`prompts-get-with-image`,name:`PromptsGetWithImage`,description:`Get prompt with image content`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:`Failed: ${e instanceof Error?e.message:String(e)}`,specReferences:[{id:`MCP-Prompts-Image`,url:`https://modelcontextprotocol.io/specification/2025-06-18/server/prompts#image-content`}]})}return t}};const qe=[{id:`MCP-DNS-Rebinding-Protection`,url:`https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise`},{id:`MCP-Transport-Security`,url:`https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#security-warning`}];function Je(e){let t=new URL(e).hostname.toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`[::1]`||t===`::1`}function Ye(e){return new URL(e).host}async function Xe(e,t){let n=await ee(e,{method:`POST`,headers:{"Content-Type":`application/json`,Host:t,Origin:`http://${t}`,Accept:`application/json, text/event-stream`},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:`initialize`,params:{protocolVersion:`2025-11-25`,capabilities:{},clientInfo:{name:`conformance-dns-rebinding-test`,version:`1.0.0`}}})}),r;try{r=await n.body.json()}catch{r=null}return{statusCode:n.statusCode,body:r}}var Ze=class{constructor(){this.name=`dns-rebinding-protection`,this.description=`Test DNS rebinding protection for localhost servers. + +**Scope:** This test applies to localhost MCP servers running without HTTPS and without +authentication. These servers are vulnerable to DNS rebinding attacks where a malicious +website tricks a user's browser into making requests to the local server. + +**Attack scenario:** +1. User visits malicious website (e.g., evil.com) +2. evil.com's DNS is configured to resolve to 127.0.0.1 +3. Browser makes request to evil.com which actually goes to localhost +4. Without Host/Origin header validation, the local MCP server processes the request + +**Requirements:** +- Server **MUST** validate the Host or Origin header on incoming requests +- Server **MUST** reject requests with non-localhost Host/Origin headers (HTTP 4xx) +- Server **MUST** accept requests with valid localhost Host/Origin headers + +**Valid localhost values:** \`localhost\`, \`127.0.0.1\`, \`[::1]\` (with optional port) + +**Note:** This test requires a localhost server URL. Non-localhost URLs will fail. + +See: https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/GHSA-w48q-cv73-mx4w`}async run(e){let t=[],n=new Date().toISOString(),r={id:`localhost-host-rebinding-rejected`,name:`DNSRebindingRejected`,description:`Server rejects requests with non-localhost Host/Origin headers`,timestamp:n,specReferences:qe},i={id:`localhost-host-valid-accepted`,name:`LocalhostHostAccepted`,description:`Server accepts requests with valid localhost Host/Origin headers`,timestamp:n,specReferences:qe};if(!Je(e)){let n=`DNS rebinding tests require a localhost server URL (localhost, 127.0.0.1, or [::1])`,a={serverUrl:e,reason:`non-localhost-url`};return t.push({...r,status:`FAILURE`,errorMessage:n,details:a}),t.push({...i,status:`FAILURE`,errorMessage:n,details:a}),t}let a=Ye(e),o=`evil.example.com`;try{let n=await Xe(e,o),i=n.statusCode>=400&&n.statusCode<500,a={hostHeader:o,originHeader:`http://${o}`,statusCode:n.statusCode,body:n.body};i?t.push({...r,status:`SUCCESS`,details:a}):t.push({...r,status:`FAILURE`,errorMessage:`Expected HTTP 4xx for invalid Host/Origin headers, got ${n.statusCode}`,details:a})}catch(e){t.push({...r,status:`FAILURE`,errorMessage:`Request failed: ${e instanceof Error?e.message:String(e)}`,details:{hostHeader:o,originHeader:`http://${o}`}})}try{let n=await Xe(e,a),r=n.statusCode>=200&&n.statusCode<300,o={hostHeader:a,originHeader:`http://${a}`,statusCode:n.statusCode,body:n.body};r?t.push({...i,status:`SUCCESS`,details:o}):t.push({...i,status:`FAILURE`,errorMessage:`Expected HTTP 2xx for valid localhost Host/Origin headers, got ${n.statusCode}`,details:o})}catch(e){t.push({...i,status:`FAILURE`,errorMessage:`Request failed: ${e instanceof Error?e.message:String(e)}`,details:{hostHeader:a,originHeader:`http://${a}`}})}return t}};const M={RFC_PRM_DISCOVERY:{id:`RFC-9728`,url:`https://www.rfc-editor.org/rfc/rfc9728.html#section-3.1`},RFC_AUTH_SERVER_METADATA_REQUEST:{id:`RFC-8414-metadata-request`,url:`https://www.rfc-editor.org/rfc/rfc8414.html#section-3.1`},LEGACY_2025_03_26_AUTH_DISCOVERY:{id:`MCP-2025-03-26-Authorization-metadata-discovery`,url:`https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization#server-metadata-discovery`},LEGACY_2025_03_26_AUTH_URL_FALLBACK:{id:`MCP-2025-03-26-Authorization-metadata-url-fallback`,url:`https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization#fallbacks-for-servers-without-metadata-discovery`},MCP_PRM_DISCOVERY:{id:`MCP-2025-06-18-PRM-discovery`,url:`https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#protected-resource-metadata-discovery-requirements`},MCP_AUTH_DISCOVERY:{id:`MCP-Authorization-metadata-discovery`,url:`https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#authorization-server-metadata-discovery`},MCP_DCR:{id:`MCP-Dynamic-client-registration`,url:`https://modelcontextprotocol.io/specification/2025-11-25/basic/client#dynamic-client-registration`},OAUTH_2_1_AUTHORIZATION_ENDPOINT:{id:`OAUTH-2.1-authorization-endpoint`,url:`https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-13.html#name-authorization-endpoint`},OAUTH_2_1_TOKEN:{id:`OAUTH-2.1-token-request`,url:`https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-13.html#name-token-request`},MCP_ACCESS_TOKEN_USAGE:{id:`MCP-Access-token-usage`,url:`https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#access-token-usage`},MCP_SCOPE_SELECTION_STRATEGY:{id:`MCP-Scope-selection-strategy`,url:`https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#scope-selection-strategy`},MCP_SCOPE_CHALLENGE_HANDLING:{id:`MCP-Scope-challenge-handling`,url:`https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#scope-challenge-handling`},MCP_AUTH_ERROR_HANDLING:{id:`MCP-Auth-error-handling`,url:`https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#error-handling`},MCP_CLIENT_ID_METADATA_DOCUMENTS:{id:`MCP-Client-ID-Metadata-Documents`,url:`https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#client-id-metadata-documents`},IETF_CIMD:{id:`IETF-OAuth-Client-ID-Metadata-Document`,url:`https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00`},RFC_JWT_CLIENT_AUTH:{id:`RFC-7523-JWT-Client-Auth`,url:`https://datatracker.ietf.org/doc/html/rfc7523#section-2.2`},OAUTH_2_1_CLIENT_CREDENTIALS:{id:`OAUTH-2.1-client-credentials-grant`,url:`https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-13.html#section-4.2`},SEP_1046_CLIENT_CREDENTIALS:{id:`SEP-1046-Client-Credentials`,url:`https://github.com/modelcontextprotocol/ext-auth/blob/main/specification/draft/oauth-client-credentials.mdx`},RFC_8707_RESOURCE_INDICATORS:{id:`RFC-8707-Resource-Indicators`,url:`https://www.rfc-editor.org/rfc/rfc8707.html`},MCP_RESOURCE_PARAMETER:{id:`MCP-Resource-Parameter-Implementation`,url:`https://modelcontextprotocol.io/specification/draft/basic/authorization#resource-parameter-implementation`},MCP_PREREGISTRATION:{id:`MCP-Preregistration`,url:`https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#preregistration`},MCP_PKCE:{id:`MCP-PKCE-requirement`,url:`https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#authorization-code-protection`}};function Qe(e){return b(`sha256`).update(e).digest().toString(`base64`).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function N(e,t,n={}){let{metadataPath:r=`/.well-known/oauth-authorization-server`,isOpenIdConfiguration:i=!1,loggingEnabled:a=!0,routePrefix:o=``,scopesSupported:s,grantTypesSupported:c=[`authorization_code`,`refresh_token`],tokenEndpointAuthMethodsSupported:l=[`none`],tokenEndpointAuthSigningAlgValuesSupported:u,clientIdMetadataDocumentSupported:d,disableDynamicRegistration:f=!1,codeChallengeMethodsSupported:p=[`S256`],tokenVerifier:m,onTokenRequest:h,onAuthorizationRequest:g,onRegistrationRequest:_}=n,v=[],b,x={authorization_endpoint:`${o}/authorize`,token_endpoint:`${o}/token`,registration_endpoint:`${o}/register`},S=y();return S.use(y.json()),S.use(y.urlencoded({extended:!0})),a&&S.use(O(e,{incomingId:`incoming-auth-request`,outgoingId:`outgoing-auth-response`})),S.get(r,(n,r)=>{e.push({id:`authorization-server-metadata`,name:`AuthorizationServerMetadata`,description:`Client requested authorization server metadata`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[M.RFC_AUTH_SERVER_METADATA_REQUEST,M.MCP_AUTH_DISCOVERY],details:{url:n.url,path:n.path}});let a={issuer:t(),authorization_endpoint:`${t()}${x.authorization_endpoint}`,token_endpoint:`${t()}${x.token_endpoint}`,...!f&&{registration_endpoint:`${t()}${x.registration_endpoint}`},response_types_supported:[`code`],grant_types_supported:c,...p!==null&&{code_challenge_methods_supported:p},token_endpoint_auth_methods_supported:l,...u&&{token_endpoint_auth_signing_alg_values_supported:u}};s!==void 0&&(a.scopes_supported=s),d!==void 0&&(a.client_id_metadata_document_supported=d),i&&(a.jwks_uri=`${t()}/.well-known/jwks.json`,a.subject_types_supported=[`public`],a.id_token_signing_alg_values_supported=[`RS256`]),r.json(a)}),S.get(x.authorization_endpoint,(t,n)=>{let r=new Date().toISOString();e.push({id:`authorization-request`,name:`AuthorizationRequest`,description:`Client made authorization request`,status:`SUCCESS`,timestamp:r,specReferences:[M.OAUTH_2_1_AUTHORIZATION_ENDPOINT],details:{query:t.query}});let i=t.query.code_challenge,a=t.query.code_challenge_method;b=i,e.push({id:`pkce-code-challenge-sent`,name:`PKCE Code Challenge`,description:i?`Client sent code_challenge in authorization request`:`Client MUST send code_challenge in authorization request`,status:i?`SUCCESS`:`FAILURE`,timestamp:r,specReferences:[M.MCP_PKCE]}),e.push({id:`pkce-s256-method-used`,name:`PKCE S256 Method`,description:a===`S256`?`Client used S256 code challenge method`:`Client MUST use S256 code challenge method when technically capable`,status:a===`S256`?`SUCCESS`:`FAILURE`,timestamp:r,specReferences:[M.MCP_PKCE],details:{method:a||`not specified`}});let o=t.query.scope;v=o?o.split(` `):[],g&&g({clientId:t.query.client_id,scope:o,resource:t.query.resource,timestamp:r});let s=t.query.redirect_uri,c=t.query.state,l=new URL(s);l.searchParams.set(`code`,`test-auth-code`),c&&l.searchParams.set(`state`,c),n.redirect(l.toString())}),S.post(x.token_endpoint,async(n,r)=>{let i=new Date().toISOString(),a=n.body.scope,o=n.body.grant_type;e.push({id:`token-request`,name:`TokenRequest`,description:`Client requested access token`,status:`SUCCESS`,timestamp:i,specReferences:[M.OAUTH_2_1_TOKEN],details:{endpoint:`/token`,grantType:o}});let s=n.body.code_verifier;if(o===`authorization_code`){e.push({id:`pkce-code-verifier-sent`,name:`PKCE Code Verifier`,description:s?`Client sent code_verifier in token request`:`Client MUST send code_verifier in token request`,status:s?`SUCCESS`:`FAILURE`,timestamp:i,specReferences:[M.MCP_PKCE]});let t=s&&b?Qe(s):void 0,n=t!==void 0&&t===b,r;r=!b&&!s?`Neither code_challenge nor code_verifier were sent - PKCE is required`:b?s?n?`code_verifier correctly matches code_challenge (S256)`:`code_verifier does not match code_challenge`:`code_verifier was not sent in token request - PKCE is required`:`code_challenge was not sent in authorization request - PKCE is required`,e.push({id:`pkce-verifier-matches-challenge`,name:`PKCE Verifier Validation`,description:r,status:n?`SUCCESS`:`FAILURE`,timestamp:i,specReferences:[M.MCP_PKCE],details:{matches:n,storedChallenge:b||`not sent`,computedChallenge:t||`not computed`}})}let c=`test-token-${Date.now()}`,l=v;if(h){let e=await h({scope:a,grantType:o,timestamp:i,body:n.body,authBaseUrl:t(),tokenEndpoint:`${t()}${x.token_endpoint}`,authorizationHeader:n.headers.authorization});if(`error`in e){r.status(e.statusCode||400).json({error:e.error,error_description:e.errorDescription});return}c=e.token,l=e.scopes}m&&m.registerToken(c,l),r.json({access_token:c,token_type:`Bearer`,expires_in:3600,...l.length>0&&{scope:l.join(` `)}})}),S.post(x.registration_endpoint,(t,n)=>{let r=`test-client-id`,i=`test-client-secret`,a;if(_){let e=_(t);r=e.clientId,i=e.clientSecret,a=e.tokenEndpointAuthMethod}e.push({id:`client-registration`,name:`ClientRegistration`,description:`Client registered with authorization server`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[M.MCP_DCR],details:{endpoint:`/register`,clientName:t.body.client_name,...a&&{tokenEndpointAuthMethod:a}}}),n.status(201).json({client_id:r,...i&&{client_secret:i},client_name:t.body.client_name||`test-client`,redirect_uris:t.body.redirect_uris||[],...a&&{token_endpoint_auth_method:a}})}),S}var P=class{constructor(e,t=[]){this.checks=e,this.expectedScopes=t,this.tokenScopes=new Map}registerToken(e,t){this.tokenScopes.set(e,t)}async verifyAccessToken(e){if(e.startsWith(`test-token`)||e.startsWith(`cc-token`)){let t=this.tokenScopes.get(e)||[];return this.checks.push({id:`valid-bearer-token`,name:`ValidBearerToken`,description:`Client provided valid bearer token`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[M.MCP_ACCESS_TOKEN_USAGE],details:{token:e.substring(0,15)+`...`,scopes:t}}),{token:e,clientId:`test-client`,scopes:t,expiresAt:Math.floor(Date.now()/1e3)+3600}}throw this.checks.push({id:`invalid-bearer-token`,name:`InvalidBearerToken`,description:`Client provided invalid bearer token`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.MCP_ACCESS_TOKEN_USAGE],details:{message:`Token verification failed`,token:e?e.substring(0,10)+`...`:`missing`}}),Error(`Invalid token`)}};function F(e,t,n,r={}){let{prmPath:i=`/.well-known/oauth-protected-resource/mcp`,requiredScopes:a=[],scopesSupported:o,includePrmInWwwAuth:u=!0,includeScopeInWwwAuth:d=!1,tokenVerifier:f,prmResourceOverride:p}=r,g=new s({name:`auth-prm-pathbased-server`,version:`1.0.0`},{capabilities:{tools:{}}});g.setRequestHandler(h,async()=>({tools:[{name:`test-tool`,inputSchema:{type:`object`}}]})),g.setRequestHandler(l,async e=>{if(e.params.name===`test-tool`)return{content:[{type:`text`,text:`test`}]};throw new _(m.InvalidParams,`Tool ${e.params.name} not found`)});let v=y();return v.use(y.json()),v.use(O(e,{incomingId:`incoming-request`,outgoingId:`outgoing-response`,mcpRoute:`/mcp`})),i!==null&&v.get(i,(r,a)=>{e.push({id:`prm-pathbased-requested`,name:`PRMPathBasedRequested`,description:`Client requested PRM metadata at path-based location`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[M.RFC_PRM_DISCOVERY,M.MCP_PRM_DISCOVERY],details:{url:r.url,path:r.path}});let s={resource:p??(i===`/.well-known/oauth-protected-resource`?t():`${t()}/mcp`),authorization_servers:[n()]};o!==void 0&&(s.scopes_supported=o),a.json(s)}),v.post(`/mcp`,async(n,o,s)=>{let l=f||new P(e,a);(r.authMiddleware??te({verifier:l,requiredScopes:d?a:[],...u&&i!==null&&{resourceMetadataUrl:`${t()}${i}`}}))(n,o,async e=>{if(e)return s(e);let t=new c({sessionIdGenerator:void 0});try{await g.connect(t),await t.handleRequest(n,o,n.body),o.on(`close`,()=>{t.close(),g.close()})}catch(e){console.error(`Error handling MCP request:`,e),o.headersSent||o.status(500).json({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`},id:null})}})}),v}var I=class{constructor(){this.app=null,this.httpServer=null,this.baseUrl=``,this.getUrl=()=>this.baseUrl}async start(e){return this.app=e,this.httpServer=this.app.listen(0),this.baseUrl=`http://localhost:${this.httpServer.address().port}`,this.baseUrl}async stop(){this.httpServer&&=(await new Promise(e=>{this.httpServer.closeAllConnections?.(),this.httpServer.close(()=>e())}),null),this.app=null}};const L=[{name:`metadata-default`,prmLocation:`/.well-known/oauth-protected-resource/mcp`,inWwwAuth:!0,oauthMetadataLocation:`/.well-known/oauth-authorization-server`,trapRootPrm:!0},{name:`metadata-var1`,prmLocation:`/.well-known/oauth-protected-resource/mcp`,inWwwAuth:!1,oauthMetadataLocation:`/.well-known/openid-configuration`},{name:`metadata-var2`,prmLocation:`/.well-known/oauth-protected-resource`,inWwwAuth:!1,oauthMetadataLocation:`/.well-known/oauth-authorization-server/tenant1`,authRoutePrefix:`/tenant1`},{name:`metadata-var3`,prmLocation:`/custom/metadata/location.json`,inWwwAuth:!0,oauthMetadataLocation:`/tenant1/.well-known/openid-configuration`,authRoutePrefix:`/tenant1`}];function R(e){let t=new I,n=new I,r=[],i=e.authRoutePrefix||``,a=e.oauthMetadataLocation.includes(`openid-configuration`),o=e.prmLocation===`/.well-known/oauth-protected-resource/mcp`;return{name:`auth/${e.name}`,description:`Tests Basic OAuth metadata discovery flow. + +**PRM:** ${e.prmLocation}${e.inWwwAuth?``:` (not in WWW-Authenticate)`} +**OAuth metadata:** ${e.oauthMetadataLocation} +`,async start(){r=[];let o=N(r,t.getUrl,{metadataPath:e.oauthMetadataLocation,isOpenIdConfiguration:a,...i&&{routePrefix:i}});i&&o.get(`/.well-known/oauth-authorization-server`,(e,t)=>{r.push({id:`authorization-server-metadata-wrong-path`,name:`AuthorizationServerMetadataWrongPath`,description:`Client requested authorization server at the root path when the AS URL has a path-based location`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.RFC_AUTH_SERVER_METADATA_REQUEST,M.MCP_AUTH_DISCOVERY],details:{url:e.url}}),t.status(404).send(`Not Found`)}),await t.start(o);let s=i?()=>`${t.getUrl()}${i}`:t.getUrl,c=F(r,n.getUrl,s,{prmPath:e.prmLocation,includePrmInWwwAuth:e.inWwwAuth});return e.trapRootPrm&&c.get(`/.well-known/oauth-protected-resource`,(e,t)=>{r.push({id:`prm-priority-order`,name:`PRM Priority Order`,description:`Client requested PRM metadata at root location on a server with path-based PRM`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.RFC_PRM_DISCOVERY,M.MCP_PRM_DISCOVERY],details:{url:e.url,path:e.path}}),t.status(404).json({error:`not_found`,error_description:`PRM metadata not available at root location`})}),await n.start(c),{serverUrl:`${n.getUrl()}/mcp`}},async stop(){await t.stop(),await n.stop()},getChecks(){let e=[...o?[`prm-pathbased-requested`]:[],`authorization-server-metadata`,`client-registration`,`authorization-request`,`token-request`];for(let t of e)r.find(e=>e.id===t)||r.push({id:t,name:`Expected Check Missing: ${t}`,description:`Expected Check Missing: ${t}`,status:`FAILURE`,timestamp:new Date().toISOString()});return r}}}R(L[0]),R(L[1]),R(L[2]),R(L[3]);const $e=L.map(R);function et(){return $e.map(e=>e.name)}const tt=`https://conformance-test.local/client-metadata.json`;var nt=class{constructor(){this.name=`auth/basic-cimd`,this.description=`Tests OAuth flow with Client ID Metadata Documents (SEP-991/URL-based client IDs). Server advertises client_id_metadata_document_supported=true and client should use URL as client_id instead of DCR.`,this.authServer=new I,this.server=new I,this.checks=[]}async start(){this.checks=[];let e=N(this.checks,this.authServer.getUrl,{clientIdMetadataDocumentSupported:!0,onAuthorizationRequest:e=>{let t=e.clientId===tt;this.checks.push({id:`cimd-client-id-used`,name:`Client ID Metadata Document Usage`,description:t?`Client correctly used URL-based client ID when server supports client_id_metadata_document_supported`:`Client SHOULD use URL-based client ID when server advertises client_id_metadata_document_supported=true`,status:t?`SUCCESS`:`WARNING`,timestamp:e.timestamp,specReferences:[M.MCP_CLIENT_ID_METADATA_DOCUMENTS,M.IETF_CIMD],details:{expectedClientId:tt,actualClientId:e.clientId||`none`}})}});await this.authServer.start(e);let t=F(this.checks,this.server.getUrl,this.authServer.getUrl);return await this.server.start(t),{serverUrl:`${this.server.getUrl()}/mcp`}}async stop(){await this.authServer.stop(),await this.server.stop()}getChecks(){return this.checks.some(e=>e.id===`cimd-client-id-used`)||this.checks.push({id:`cimd-client-id-used`,name:`Client ID Metadata Document Usage`,description:`Client did not make an authorization request to test CIMD support`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.MCP_CLIENT_ID_METADATA_DOCUMENTS,M.IETF_CIMD]}),this.checks}},rt=class{constructor(){this.name=`auth/2025-03-26-oauth-metadata-backcompat`,this.description=`Tests 2025-03-26 spec OAuth flow: no PRM (Protected Resource Metadata), OAuth metadata at root location`,this.server=new I,this.checks=[]}async start(){this.checks=[];let e=N(this.checks,this.server.getUrl,{loggingEnabled:!1,routePrefix:`/oauth`}),t=F(this.checks,this.server.getUrl,this.server.getUrl,{prmPath:null});return t.use(e),await this.server.start(t),{serverUrl:`${this.server.getUrl()}/mcp`}}async stop(){await this.server.stop()}getChecks(){for(let e of[`authorization-server-metadata`,`client-registration`,`authorization-request`,`token-request`])this.checks.find(t=>t.id===e)||this.checks.push({id:e,name:`Expected Check Missing: ${e}`,description:`Expected Check Missing: ${e}`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.LEGACY_2025_03_26_AUTH_DISCOVERY]});return this.checks}},it=class{constructor(){this.name=`auth/2025-03-26-oauth-endpoint-fallback`,this.description=`Tests OAuth flow with no metadata endpoints, relying on fallback to standard OAuth endpoints at server root (2025-03-26 spec behavior)`,this.server=new I,this.checks=[]}async start(){this.checks=[];let e=F(this.checks,this.server.getUrl,this.server.getUrl,{prmPath:null});return e.use(y.urlencoded({extended:!0})),e.get(`/authorize`,(e,t)=>{this.checks.push({id:`authorization-request`,name:`AuthorizationRequest`,description:`Client made authorization request to fallback endpoint`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[M.LEGACY_2025_03_26_AUTH_URL_FALLBACK],details:{response_type:e.query.response_type,client_id:e.query.client_id,redirect_uri:e.query.redirect_uri,state:e.query.state,code_challenge:e.query.code_challenge?`present`:`missing`,code_challenge_method:e.query.code_challenge_method}});let n=e.query.redirect_uri,r=e.query.state,i=new URL(n);i.searchParams.set(`code`,`test-auth-code`),r&&i.searchParams.set(`state`,r),t.redirect(i.toString())}),e.post(`/token`,(e,t)=>{this.checks.push({id:`token-request`,name:`TokenRequest`,description:`Client requested access token from fallback endpoint`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[M.LEGACY_2025_03_26_AUTH_URL_FALLBACK],details:{endpoint:`/token`,grantType:e.body.grant_type}}),t.json({access_token:`test-token`,token_type:`Bearer`,expires_in:3600})}),e.post(`/register`,(e,t)=>{this.checks.push({id:`client-registration`,name:`ClientRegistration`,description:`Client registered with authorization server at fallback endpoint`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[M.LEGACY_2025_03_26_AUTH_URL_FALLBACK],details:{endpoint:`/register`,clientName:e.body.client_name}}),t.status(201).json({client_id:`test-client-id`,client_secret:`test-client-secret`,client_name:e.body.client_name||`test-client`,redirect_uris:e.body.redirect_uris||[]})}),await this.server.start(e),{serverUrl:`${this.server.getUrl()}/mcp`}}async stop(){await this.server.stop()}getChecks(){for(let e of[`client-registration`,`authorization-request`,`token-request`])this.checks.find(t=>t.id===e)||this.checks.push({id:e,name:`Expected Check Missing: ${e}`,description:`Expected Check Missing: ${e}`,status:`FAILURE`,timestamp:new Date().toISOString()});return this.checks}},at=class{constructor(){this.name=`auth/scope-from-www-authenticate`,this.description=`Tests that client uses scope parameter from WWW-Authenticate header when provided`,this.authServer=new I,this.server=new I,this.checks=[]}async start(){this.checks=[];let e=`mcp:basic`,t=new P(this.checks,[e]),n=N(this.checks,this.authServer.getUrl,{tokenVerifier:t,onAuthorizationRequest:t=>{let n=(t.scope?t.scope.split(` `):[]).includes(e);this.checks.push({id:`scope-from-www-authenticate`,name:`Client scope selection from WWW-Authenticate header`,description:n?`Client correctly used the scope parameter from the WWW-Authenticate header`:`Client SHOULD use the scope parameter from the WWW-Authenticate header when provided`,status:n?`SUCCESS`:`WARNING`,timestamp:t.timestamp,specReferences:[M.MCP_SCOPE_SELECTION_STRATEGY],details:{expectedScope:e,requestedScope:t.scope||`none`}})}});await this.authServer.start(n);let r=F(this.checks,this.server.getUrl,this.authServer.getUrl,{prmPath:`/.well-known/oauth-protected-resource/mcp`,requiredScopes:[e],includeScopeInWwwAuth:!0,tokenVerifier:t});return await this.server.start(r),{serverUrl:`${this.server.getUrl()}/mcp`}}async stop(){await this.authServer.stop(),await this.server.stop()}getChecks(){return this.checks.some(e=>e.id===`scope-from-www-authenticate`)||this.checks.push({id:`scope-from-www-authenticate`,name:`Client scope selection from WWW-Authenticate header`,description:`Client did not complete authorization flow - scope check could not be performed`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.MCP_SCOPE_SELECTION_STRATEGY]}),this.checks}},ot=class{constructor(){this.name=`auth/scope-from-scopes-supported`,this.description=`Tests that client uses all scopes from scopes_supported when scope not in WWW-Authenticate header`,this.authServer=new I,this.server=new I,this.checks=[]}async start(){this.checks=[];let e=[`mcp:basic`,`mcp:read`,`mcp:write`],t=new P(this.checks,e),n=N(this.checks,this.authServer.getUrl,{tokenVerifier:t,onAuthorizationRequest:t=>{let n=t.scope?t.scope.split(` `):[],r=e.every(e=>n.includes(e));this.checks.push({id:`scope-from-scopes-supported`,name:`Client scope selection from scopes_supported`,description:r?`Client correctly used all scopes from scopes_supported in PRM when scope not in WWW-Authenticate`:`Client SHOULD use all scopes from scopes_supported when scope not available in WWW-Authenticate header`,status:r?`SUCCESS`:`WARNING`,timestamp:t.timestamp,specReferences:[M.MCP_SCOPE_SELECTION_STRATEGY],details:{scopesSupported:e.join(` `),requestedScope:t.scope||`none`,...r?{}:{missingScopes:e.filter(e=>!n.includes(e)).join(` `)}}})}});await this.authServer.start(n);let r=F(this.checks,this.server.getUrl,this.authServer.getUrl,{prmPath:`/.well-known/oauth-protected-resource/mcp`,requiredScopes:e,scopesSupported:e,includeScopeInWwwAuth:!1,tokenVerifier:t});return await this.server.start(r),{serverUrl:`${this.server.getUrl()}/mcp`}}async stop(){await this.authServer.stop(),await this.server.stop()}getChecks(){return this.checks.some(e=>e.id===`scope-from-scopes-supported`)||this.checks.push({id:`scope-from-scopes-supported`,name:`Client scope selection from scopes_supported`,description:`Client did not complete authorization flow - scope check could not be performed`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.MCP_SCOPE_SELECTION_STRATEGY]}),this.checks}},st=class{constructor(){this.name=`auth/scope-omitted-when-undefined`,this.description=`Tests that client omits scope parameter when scopes_supported is undefined`,this.authServer=new I,this.server=new I,this.checks=[]}async start(){this.checks=[];let e=new P(this.checks,[]),t=N(this.checks,this.authServer.getUrl,{tokenVerifier:e,onAuthorizationRequest:e=>{let t=!e.scope||e.scope.trim()===``;this.checks.push({id:`scope-omitted-when-undefined`,name:`Client scope omission when scopes_supported undefined`,description:t?`Client correctly omitted scope parameter when scopes_supported is undefined`:`Client SHOULD omit scope parameter when scopes_supported is undefined and scope not in WWW-Authenticate`,status:t?`SUCCESS`:`WARNING`,timestamp:e.timestamp,specReferences:[M.MCP_SCOPE_SELECTION_STRATEGY],details:{scopeParameter:t?`omitted`:e.scope}})}});await this.authServer.start(t);let n=F(this.checks,this.server.getUrl,this.authServer.getUrl,{prmPath:`/.well-known/oauth-protected-resource/mcp`,requiredScopes:[],scopesSupported:void 0,includeScopeInWwwAuth:!1,tokenVerifier:e});return await this.server.start(n),{serverUrl:`${this.server.getUrl()}/mcp`}}async stop(){await this.authServer.stop(),await this.server.stop()}getChecks(){return this.checks.some(e=>e.id===`scope-omitted-when-undefined`)||this.checks.push({id:`scope-omitted-when-undefined`,name:`Client scope omission when scopes_supported undefined`,description:`Client did not complete authorization flow - scope check could not be performed`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.MCP_SCOPE_SELECTION_STRATEGY]}),this.checks}},ct=class{constructor(){this.name=`auth/scope-step-up`,this.description=`Tests that client handles step-up authentication with different scope requirements per operation`,this.authServer=new I,this.server=new I,this.checks=[]}async start(){this.checks=[];let e=`mcp:basic`,t=[`mcp:basic`,`mcp:write`],n=new P(this.checks,t),r=0,i=N(this.checks,this.authServer.getUrl,{tokenVerifier:n,onAuthorizationRequest:n=>{r++;let i=n.scope?n.scope.split(` `):[];if(r===1){let t=i.includes(e);this.checks.push({id:`scope-step-up-initial`,name:`Client initial scope selection for step-up auth`,description:t?`Client correctly used scope from WWW-Authenticate header for initial auth`:`Client SHOULD use the scope parameter from the WWW-Authenticate header`,status:t?`SUCCESS`:`WARNING`,timestamp:n.timestamp,specReferences:[M.MCP_SCOPE_SELECTION_STRATEGY],details:{expectedScope:e,requestedScope:n.scope||`none`}})}else if(r===2){let e=t.every(e=>i.includes(e));this.checks.push({id:`scope-step-up-escalation`,name:`Client scope escalation for step-up auth`,description:e?`Client correctly escalated scopes for step-up authentication`:`Client SHOULD request additional scopes when receiving 403 with new scope requirements`,status:e?`SUCCESS`:`WARNING`,timestamp:n.timestamp,specReferences:[M.MCP_SCOPE_SELECTION_STRATEGY],details:{expectedScopes:t.join(` `),requestedScope:n.scope||`none`}})}}});await this.authServer.start(i);let a=()=>`${this.server.getUrl()}/.well-known/oauth-protected-resource/mcp`,o=F(this.checks,this.server.getUrl,this.authServer.getUrl,{prmPath:`/.well-known/oauth-protected-resource/mcp`,requiredScopes:t,scopesSupported:t,includeScopeInWwwAuth:!0,authMiddleware:async(r,i,o)=>{let s=r.body;typeof s==`string`&&(s=JSON.parse(s));let c=s?.method;if(c===`initialize`||c?.startsWith(`notifications/`))return o();let l=r.headers.authorization;if(!l||!l.startsWith(`Bearer `))return i.status(401).set(`WWW-Authenticate`,`Bearer scope="${e}", resource_metadata="${a()}"`).json({error:`invalid_token`,error_description:`Missing Authorization header`});let u=l.substring(7),d=(await n.verifyAccessToken(u)).scopes||[],f=c===`tools/call`?t:[e];if(!f.every(e=>d.includes(e)))return i.status(403).set(`WWW-Authenticate`,`Bearer scope="${f.join(` `)}", resource_metadata="${a()}", error="insufficient_scope"`).json({error:`insufficient_scope`,error_description:`Token has insufficient scope`});o()},tokenVerifier:n});return await this.server.start(o),{serverUrl:`${this.server.getUrl()}/mcp`}}async stop(){await this.authServer.stop(),await this.server.stop()}getChecks(){let e=this.checks.some(e=>e.id===`scope-step-up-initial`),t=this.checks.some(e=>e.id===`scope-step-up-escalation`);return e||this.checks.push({id:`scope-step-up-initial`,name:`Client initial scope selection for step-up auth`,description:`Client did not make an initial authorization request`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.MCP_SCOPE_SELECTION_STRATEGY]}),t||this.checks.push({id:`scope-step-up-escalation`,name:`Client scope escalation for step-up auth`,description:`Client did not make a second authorization request for scope escalation`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.MCP_SCOPE_SELECTION_STRATEGY]}),this.checks}},lt=class{constructor(){this.name=`auth/scope-retry-limit`,this.description=`Tests that client implements retry limits to prevent infinite authorization loops on repeated 403 responses`,this.authServer=new I,this.server=new I,this.checks=[]}async start(){this.checks=[];let e=`mcp:admin`,t=new P(this.checks,[]),n=0,r=N(this.checks,this.authServer.getUrl,{tokenVerifier:t,onAuthorizationRequest:e=>{n++,this.checks.push({id:`scope-retry-auth-attempt`,name:`Authorization attempt ${n}`,description:`Client made authorization request attempt ${n}`,status:`INFO`,timestamp:e.timestamp,specReferences:[M.MCP_SCOPE_CHALLENGE_HANDLING],details:{attemptNumber:n,requestedScope:e.scope||`none`}})}});await this.authServer.start(r);let i=()=>`${this.server.getUrl()}/.well-known/oauth-protected-resource/mcp`,a=0,o=F(this.checks,this.server.getUrl,this.authServer.getUrl,{prmPath:`/.well-known/oauth-protected-resource/mcp`,requiredScopes:[e],scopesSupported:[e],includeScopeInWwwAuth:!0,authMiddleware:async(t,n,r)=>{let o=t.body;typeof o==`string`&&(o=JSON.parse(o));let s=o?.method;if(s===`initialize`||s?.startsWith(`notifications/`))return r();let c=t.headers.authorization;return!c||!c.startsWith(`Bearer `)?n.status(401).set(`WWW-Authenticate`,`Bearer scope="${e}", resource_metadata="${i()}"`).json({error:`invalid_token`,error_description:`Missing Authorization header`}):(a++,a>3?n.status(410).json({error:`test_complete`,error_description:`Test is over - client exceeded maximum retry attempts`}):n.status(403).set(`WWW-Authenticate`,`Bearer error="insufficient_scope", scope="${e}", resource_metadata="${i()}", error_description="Scope upgrade will never succeed"`).json({error:`insufficient_scope`,error_description:`Scope upgrade will never succeed`}))},tokenVerifier:t});return await this.server.start(o),{serverUrl:`${this.server.getUrl()}/mcp`}}async stop(){await this.authServer.stop(),await this.server.stop()}getChecks(){let e=this.checks.filter(e=>e.id===`scope-retry-auth-attempt`).length;return e===0?this.checks.push({id:`scope-retry-limit`,name:`Client retry limit for scope escalation`,description:`Client did not make any authorization requests`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.MCP_SCOPE_CHALLENGE_HANDLING]}):e<=3?this.checks.push({id:`scope-retry-limit`,name:`Client retry limit for scope escalation`,description:`Client correctly limited retry attempts to ${e} (3 or fewer)`,status:`SUCCESS`,timestamp:new Date().toISOString(),specReferences:[M.MCP_SCOPE_CHALLENGE_HANDLING],details:{authorizationAttempts:e,maxAllowed:3}}):this.checks.push({id:`scope-retry-limit`,name:`Client retry limit for scope escalation`,description:`Client made ${e} authorization attempts (more than 3). Clients SHOULD implement retry limits to avoid infinite loops.`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.MCP_SCOPE_CHALLENGE_HANDLING],details:{authorizationAttempts:e,maxAllowed:3}}),this.checks}};function ut(e,t){return e?.startsWith(`Basic `)?`client_secret_basic`:t?`client_secret_post`:`none`}function dt(e){let t=e.substring(6);try{return Buffer.from(t,`base64`).toString(`utf-8`).includes(`:`)?{valid:!0}:{valid:!1,error:`missing colon separator`}}catch{return{valid:!1,error:`base64 decoding failed`}}}const ft={client_secret_basic:`HTTP Basic authentication (client_secret_basic)`,client_secret_post:`client_secret_post`,none:`no authentication (public client)`};var z=class{constructor(e){this.authServer=new I,this.server=new I,this.checks=[],this.expectedAuthMethod=e,this.name=`auth/token-endpoint-auth-${e===`client_secret_basic`?`basic`:e===`client_secret_post`?`post`:`none`}`,this.description=`Tests that client uses ${ft[e]} when server only supports ${e}`}async start(){this.checks=[],this.authorizationResource=void 0,this.tokenResource=void 0;let e=new P(this.checks,[]),t=N(this.checks,this.authServer.getUrl,{tokenVerifier:e,tokenEndpointAuthMethodsSupported:[this.expectedAuthMethod],onAuthorizationRequest:({resource:e})=>{this.authorizationResource=e},onTokenRequest:({authorizationHeader:e,body:t,timestamp:n})=>{this.tokenResource=t.resource;let r=t.client_secret,i=ut(e,r),a=i===this.expectedAuthMethod,o;if(i===`client_secret_basic`&&e){let t=dt(e);t.valid||(o=t.error)}let s=a&&!o?`SUCCESS`:`FAILURE`,c;return c=o?`Client sent Basic auth header but ${o}`:a?`Client correctly used ${ft[this.expectedAuthMethod]} for token endpoint`:`Client used ${i} but server only supports ${this.expectedAuthMethod}`,this.checks.push({id:`token-endpoint-auth-method`,name:`Token endpoint authentication method`,description:c,status:s,timestamp:n,specReferences:[M.OAUTH_2_1_TOKEN],details:{expectedAuthMethod:this.expectedAuthMethod,actualAuthMethod:i,hasAuthorizationHeader:!!e,hasBodyClientSecret:!!r,...o&&{formatError:o}}}),{token:`test-token-${Date.now()}`,scopes:[]}},onRegistrationRequest:()=>({clientId:`test-client-${Date.now()}`,clientSecret:this.expectedAuthMethod===`none`?void 0:`test-secret-${Date.now()}`,tokenEndpointAuthMethod:this.expectedAuthMethod})});await this.authServer.start(t);let n=F(this.checks,this.server.getUrl,this.authServer.getUrl,{prmPath:`/.well-known/oauth-protected-resource/mcp`,requiredScopes:[],tokenVerifier:e});return await this.server.start(n),{serverUrl:`${this.server.getUrl()}/mcp`}}async stop(){await this.authServer.stop(),await this.server.stop()}getChecks(){let e=new Date().toISOString();return this.checks.some(e=>e.id===`token-endpoint-auth-method`)||this.checks.push({id:`token-endpoint-auth-method`,name:`Token endpoint authentication method`,description:`Client did not make a token request`,status:`FAILURE`,timestamp:e,specReferences:[M.OAUTH_2_1_TOKEN]}),this.addResourceParameterChecks(e),this.checks}addResourceParameterChecks(e){let t=[M.RFC_8707_RESOURCE_INDICATORS,M.MCP_RESOURCE_PARAMETER];if(!this.checks.some(e=>e.id===`resource-parameter-in-authorization`)){let n=!!this.authorizationResource;this.checks.push({id:`resource-parameter-in-authorization`,name:`Resource parameter in authorization request`,description:n?`Client included resource parameter in authorization request`:`Client MUST include resource parameter in authorization request per RFC 8707`,status:n?`SUCCESS`:`FAILURE`,timestamp:e,specReferences:t,details:{resource:this.authorizationResource||`not provided`}})}if(!this.checks.some(e=>e.id===`resource-parameter-in-token`)){let n=!!this.tokenResource;this.checks.push({id:`resource-parameter-in-token`,name:`Resource parameter in token request`,description:n?`Client included resource parameter in token request`:`Client MUST include resource parameter in token request per RFC 8707`,status:n?`SUCCESS`:`FAILURE`,timestamp:e,specReferences:t,details:{resource:this.tokenResource||`not provided`}})}if(!this.checks.some(e=>e.id===`resource-parameter-valid-uri`)){let n=this.authorizationResource||this.tokenResource;if(n){let r=this.validateCanonicalUri(n);this.checks.push({id:`resource-parameter-valid-uri`,name:`Resource parameter is valid canonical URI`,description:r.valid?`Resource parameter is a valid canonical URI (has scheme, no fragment)`:`Resource parameter is invalid: ${r.error}`,status:r.valid?`SUCCESS`:`FAILURE`,timestamp:e,specReferences:t,details:{resource:n,...r.error&&{error:r.error}}})}}if(!this.checks.some(e=>e.id===`resource-parameter-consistency`)&&this.authorizationResource&&this.tokenResource){let n=this.authorizationResource===this.tokenResource;this.checks.push({id:`resource-parameter-consistency`,name:`Resource parameter consistency`,description:n?`Resource parameter is consistent between authorization and token requests`:`Resource parameter MUST be consistent between authorization and token requests`,status:n?`SUCCESS`:`FAILURE`,timestamp:e,specReferences:t,details:{authorizationResource:this.authorizationResource,tokenResource:this.tokenResource}})}}validateCanonicalUri(e){try{return new URL(e).hash?{valid:!1,error:`contains fragment (not allowed per RFC 8707)`}:{valid:!0}}catch{return{valid:!1,error:`invalid URI format`}}}},pt=class extends z{constructor(){super(`client_secret_basic`)}},mt=class extends z{constructor(){super(`client_secret_post`)}},ht=class extends z{constructor(){super(`none`)}};const B=`conformance-test-client`,gt=`conformance-test-secret`;async function _t(){let{publicKey:e,privateKey:t}=await T.generateKeyPair(`ES256`,{extractable:!0});return{publicKey:e,privateKeyPem:await T.exportPKCS8(t)}}var vt=class{constructor(){this.name=`auth/client-credentials-jwt`,this.description=`Tests OAuth client_credentials flow with private_key_jwt authentication (SEP-1046)`,this.authServer=new I,this.server=new I,this.checks=[]}async start(){this.checks=[];let{publicKey:e,privateKeyPem:t}=await _t(),n=N(this.checks,this.authServer.getUrl,{grantTypesSupported:[`client_credentials`],tokenEndpointAuthMethodsSupported:[`private_key_jwt`],tokenEndpointAuthSigningAlgValuesSupported:[`ES256`],onTokenRequest:async({grantType:t,body:n,timestamp:r,authBaseUrl:i})=>{if(t!==`client_credentials`)return this.checks.push({id:`client-credentials-grant-type`,name:`ClientCredentialsGrantType`,description:`Expected grant_type=client_credentials, got ${t}`,status:`FAILURE`,timestamp:r,specReferences:[M.OAUTH_2_1_CLIENT_CREDENTIALS,M.SEP_1046_CLIENT_CREDENTIALS]}),{error:`unsupported_grant_type`,errorDescription:`Only client_credentials grant is supported`};let a=n.client_assertion,o=n.client_assertion_type;if(o!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)return this.checks.push({id:`client-credentials-assertion-type`,name:`ClientCredentialsAssertionType`,description:`Invalid client_assertion_type: ${o}`,status:`FAILURE`,timestamp:r,specReferences:[M.RFC_JWT_CLIENT_AUTH]}),{error:`invalid_client`,errorDescription:`Invalid client_assertion_type`,statusCode:401};try{let t=i.replace(/\/+$/,``),o=`${t}/`,{payload:s}=await T.jwtVerify(a,e,{audience:[t,o],clockTolerance:30});if(s.iss!==B)return this.checks.push({id:`client-credentials-jwt-iss`,name:`ClientCredentialsJwtIss`,description:`JWT iss claim '${s.iss}' does not match expected client_id '${B}'`,status:`FAILURE`,timestamp:r,specReferences:[M.RFC_JWT_CLIENT_AUTH],details:{expected:B,actual:s.iss}}),{error:`invalid_client`,errorDescription:`JWT iss claim does not match expected client_id`,statusCode:401};if(s.sub!==B)return this.checks.push({id:`client-credentials-jwt-sub`,name:`ClientCredentialsJwtSub`,description:`JWT sub claim '${s.sub}' does not match expected client_id '${B}'`,status:`FAILURE`,timestamp:r,specReferences:[M.RFC_JWT_CLIENT_AUTH],details:{expected:B,actual:s.sub}}),{error:`invalid_client`,errorDescription:`JWT sub claim does not match expected client_id`,statusCode:401};this.checks.push({id:`client-credentials-jwt-verified`,name:`ClientCredentialsJwtVerified`,description:`Client successfully authenticated with signed JWT assertion`,status:`SUCCESS`,timestamp:r,specReferences:[M.OAUTH_2_1_CLIENT_CREDENTIALS,M.SEP_1046_CLIENT_CREDENTIALS,M.RFC_JWT_CLIENT_AUTH],details:{iss:s.iss,sub:s.sub,aud:s.aud}});let c=n.scope?n.scope.split(` `):[];return{token:`cc-token-${Date.now()}`,scopes:c}}catch(e){let t=e instanceof Error?e.message:String(e);return this.checks.push({id:`client-credentials-jwt-verified`,name:`ClientCredentialsJwtVerified`,description:`JWT verification failed: ${t}`,status:`FAILURE`,timestamp:r,specReferences:[M.RFC_JWT_CLIENT_AUTH],details:{error:t}}),{error:`invalid_client`,errorDescription:`JWT verification failed: ${t}`,statusCode:401}}}});await this.authServer.start(n);let r=F(this.checks,this.server.getUrl,this.authServer.getUrl);return await this.server.start(r),{serverUrl:`${this.server.getUrl()}/mcp`,context:{client_id:B,private_key_pem:t,signing_algorithm:`ES256`}}}async stop(){await this.authServer.stop(),await this.server.stop()}getChecks(){return this.checks.some(e=>e.id===`client-credentials-jwt-verified`)||this.checks.push({id:`client-credentials-jwt-verified`,name:`ClientCredentialsJwtVerified`,description:`Client did not make a client_credentials token request`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.OAUTH_2_1_CLIENT_CREDENTIALS,M.SEP_1046_CLIENT_CREDENTIALS]}),this.checks}},yt=class{constructor(){this.name=`auth/client-credentials-basic`,this.description=`Tests OAuth client_credentials flow with client_secret_basic authentication`,this.authServer=new I,this.server=new I,this.checks=[]}async start(){this.checks=[];let e=N(this.checks,this.authServer.getUrl,{grantTypesSupported:[`client_credentials`],tokenEndpointAuthMethodsSupported:[`client_secret_basic`],onTokenRequest:async({grantType:e,body:t,timestamp:n,authorizationHeader:r})=>{if(e!==`client_credentials`)return this.checks.push({id:`client-credentials-grant-type`,name:`ClientCredentialsGrantType`,description:`Expected grant_type=client_credentials, got ${e}`,status:`FAILURE`,timestamp:n,specReferences:[M.OAUTH_2_1_CLIENT_CREDENTIALS,M.SEP_1046_CLIENT_CREDENTIALS]}),{error:`unsupported_grant_type`,errorDescription:`Only client_credentials grant is supported`};let i=r;if(!i||!i.startsWith(`Basic `))return this.checks.push({id:`client-credentials-basic-auth`,name:`ClientCredentialsBasicAuth`,description:`Missing or invalid Authorization header for Basic auth`,status:`FAILURE`,timestamp:n,specReferences:[M.SEP_1046_CLIENT_CREDENTIALS]}),{error:`invalid_client`,errorDescription:`Missing or invalid Authorization header`,statusCode:401};let a=i.slice(6),[o,s]=Buffer.from(a,`base64`).toString(`utf-8`).split(`:`);if(o!==B||s!==gt)return this.checks.push({id:`client-credentials-basic-auth`,name:`ClientCredentialsBasicAuth`,description:`Invalid client credentials`,status:`FAILURE`,timestamp:n,specReferences:[M.SEP_1046_CLIENT_CREDENTIALS],details:{clientId:o}}),{error:`invalid_client`,errorDescription:`Invalid client credentials`,statusCode:401};this.checks.push({id:`client-credentials-basic-auth`,name:`ClientCredentialsBasicAuth`,description:`Client successfully authenticated with client_secret_basic`,status:`SUCCESS`,timestamp:n,specReferences:[M.OAUTH_2_1_CLIENT_CREDENTIALS,M.SEP_1046_CLIENT_CREDENTIALS],details:{clientId:o}});let c=t.scope?t.scope.split(` `):[];return{token:`cc-token-${Date.now()}`,scopes:c}}});await this.authServer.start(e);let t=F(this.checks,this.server.getUrl,this.authServer.getUrl);return await this.server.start(t),{serverUrl:`${this.server.getUrl()}/mcp`,context:{client_id:B,client_secret:gt}}}async stop(){await this.authServer.stop(),await this.server.stop()}getChecks(){return this.checks.some(e=>e.id===`client-credentials-basic-auth`)||this.checks.push({id:`client-credentials-basic-auth`,name:`ClientCredentialsBasicAuth`,description:`Client did not make a client_credentials token request`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.OAUTH_2_1_CLIENT_CREDENTIALS,M.SEP_1046_CLIENT_CREDENTIALS]}),this.checks}},bt=class{constructor(){this.name=`auth/resource-mismatch`,this.description=`Tests that client rejects when PRM resource does not match server URL`,this.authServer=new I,this.server=new I,this.checks=[],this.authorizationRequestMade=!1}async start(){this.checks=[],this.authorizationRequestMade=!1;let e=new P(this.checks,[]),t=N(this.checks,this.authServer.getUrl,{tokenVerifier:e,tokenEndpointAuthMethodsSupported:[`none`],onAuthorizationRequest:()=>{this.authorizationRequestMade=!0},onRegistrationRequest:()=>({clientId:`test-client-${Date.now()}`,clientSecret:void 0,tokenEndpointAuthMethod:`none`})});await this.authServer.start(t);let n=F(this.checks,this.server.getUrl,this.authServer.getUrl,{prmPath:`/.well-known/oauth-protected-resource/mcp`,requiredScopes:[],tokenVerifier:e,prmResourceOverride:`https://evil.example.com/mcp`});return await this.server.start(n),{serverUrl:`${this.server.getUrl()}/mcp`}}async stop(){await this.authServer.stop(),await this.server.stop()}getChecks(){let e=new Date().toISOString(),t=[M.RFC_8707_RESOURCE_INDICATORS,M.MCP_RESOURCE_PARAMETER];if(!this.checks.some(e=>e.id===`resource-mismatch-rejected`)){let n=!this.authorizationRequestMade;this.checks.push({id:`resource-mismatch-rejected`,name:`Client rejects mismatched resource`,description:n?`Client correctly rejected authorization when PRM resource does not match server URL`:`Client MUST validate that PRM resource matches the server URL before proceeding with authorization`,status:n?`SUCCESS`:`FAILURE`,timestamp:e,specReferences:t,details:{prmResource:`https://evil.example.com/mcp`,expectedBehavior:`Client should NOT proceed with authorization`,authorizationRequestMade:this.authorizationRequestMade}})}return this.checks}};const V=`pre-registered-client`,xt=`pre-registered-secret`;var St=class{constructor(){this.name=`auth/pre-registration`,this.description=`Tests OAuth flow with pre-registered client credentials. Server does not support DCR.`,this.authServer=new I,this.server=new I,this.checks=[]}async start(){this.checks=[];let e=new P(this.checks,[]),t=N(this.checks,this.authServer.getUrl,{tokenVerifier:e,disableDynamicRegistration:!0,tokenEndpointAuthMethodsSupported:[`client_secret_basic`],onTokenRequest:({authorizationHeader:e,timestamp:t})=>{if(!e?.startsWith(`Basic `))return this.checks.push({id:`pre-registration-auth`,name:`Pre-registration authentication`,description:`Client did not use Basic authentication with pre-registered credentials`,status:`FAILURE`,timestamp:t,specReferences:[M.MCP_PREREGISTRATION]}),{error:`invalid_client`,errorDescription:`Missing or invalid Authorization header`,statusCode:401};let n=e.slice(6),[r,i]=Buffer.from(n,`base64`).toString(`utf-8`).split(`:`);return r!==V||i!==xt?(this.checks.push({id:`pre-registration-auth`,name:`Pre-registration authentication`,description:`Client used incorrect pre-registered credentials. Expected client_id '${V}', got '${r}'`,status:`FAILURE`,timestamp:t,specReferences:[M.MCP_PREREGISTRATION],details:{expectedClientId:V,actualClientId:r}}),{error:`invalid_client`,errorDescription:`Invalid pre-registered credentials`,statusCode:401}):(this.checks.push({id:`pre-registration-auth`,name:`Pre-registration authentication`,description:`Client correctly used pre-registered credentials when server does not support DCR`,status:`SUCCESS`,timestamp:t,specReferences:[M.MCP_PREREGISTRATION],details:{clientId:r}}),{token:`test-token-prereg-${Date.now()}`,scopes:[]})}});await this.authServer.start(t);let n=F(this.checks,this.server.getUrl,this.authServer.getUrl,{prmPath:`/.well-known/oauth-protected-resource/mcp`,requiredScopes:[],tokenVerifier:e});return await this.server.start(n),{serverUrl:`${this.server.getUrl()}/mcp`,context:{client_id:V,client_secret:xt}}}async stop(){await this.authServer.stop(),await this.server.stop()}getChecks(){return this.checks.some(e=>e.id===`pre-registration-auth`)||this.checks.push({id:`pre-registration-auth`,name:`Pre-registration authentication`,description:`Client did not make a token request`,status:`FAILURE`,timestamp:new Date().toISOString(),specReferences:[M.MCP_PREREGISTRATION]}),this.checks}};const H=[...$e,new nt,new rt,new it,new at,new ot,new st,new ct,new lt,new pt,new mt,new ht,new bt,new St],Ct=[new vt,new yt],wt=[new Ae,new Pe],Tt=[new he,new ge,new _e,new ve,new ye,new be,new xe,new Oe,new ke,new Se,new Ce,new we,new Te,new Ee,new De,new Ae,new je,new Pe,new Fe,new Me,new Ie,new Le,new Re,new ze,new Be,new Ve,new He,new Ue,new We,new Ge,new Ke,new Ze],Et=Tt.filter(e=>!wt.some(t=>t.name===e.name)),Dt=new Map(Tt.map(e=>[e.name,e])),Ot=[new se,new le,new fe,new pe,...H,...Ct],kt=[new se,new le,new fe,new pe,...H],At=new Map(Ot.map(e=>[e.name,e]));function U(e){return At.get(e)}function jt(e){return Dt.get(e)}function W(){return Array.from(At.keys())}function G(){return Array.from(Dt.keys())}function Mt(){return Et.map(e=>e.name)}function Nt(){return wt.map(e=>e.name)}function K(){return H.map(e=>e.name)}function Pt(){return kt.map(e=>e.name)}function Ft(){return Ct.map(e=>e.name)}const q={RESET:`\x1B[0m`,GRAY:`\x1B[90m`,GREEN:`\x1B[32m`,YELLOW:`\x1B[33m`,RED:`\x1B[31m`,BLUE:`\x1B[36m`};function It(e){switch(e){case`SUCCESS`:return q.GREEN;case`FAILURE`:return q.RED;case`WARNING`:return q.YELLOW;case`INFO`:return q.BLUE;default:return q.RESET}}function J(e){let t=Math.max(...e.map(e=>e.id.length)),n=Math.max(...e.map(e=>e.status.length));return e.map(e=>`${`${q.GRAY}${e.timestamp}${q.RESET}`} [${e.id.padEnd(t)}] ${`${It(e.status)}${e.status.padEnd(n)}${q.RESET}`} ${e.description}`+(e.id.includes(`outgoing`)&&e.id.includes(`response`)?` +`:``)).join(` +`)}function Y(e,t,n=``){let r=new Date().toISOString().replace(/[:.]/g,`-`),i=n?`${n}-${t}`:t;return a.join(e,`${i}-${r}`)}async function Lt(e,t,n,i=3e4,a){let o=e.split(` `),s=o[0],c=[...o.slice(1),n],l=``,u=``,d=!1,f={...process.env};return f.MCP_CONFORMANCE_SCENARIO=t,a&&(f.MCP_CONFORMANCE_CONTEXT=JSON.stringify({name:t,...a})),new Promise(e=>{let t=r(s,c,{shell:!0,stdio:`pipe`,env:f}),n=setTimeout(()=>{d=!0,t.kill()},i);t.stdout&&t.stdout.on(`data`,e=>{l+=e.toString()}),t.stderr&&t.stderr.on(`data`,e=>{u+=e.toString()}),t.on(`close`,t=>{clearTimeout(n),e({exitCode:t||0,stdout:l,stderr:u,timedOut:d})}),t.on(`error`,t=>{clearTimeout(n),e({exitCode:-1,stdout:l,stderr:u+`\nProcess error: ${t.message}`,timedOut:d})})})}async function Rt(e,t,n=3e4,r){let o;r&&(o=Y(r,t),await i.mkdir(o,{recursive:!0}));let s=U(t);console.error(`Starting scenario: ${t}`);let c=await s.start();console.error(`Executing client: ${e} ${c.serverUrl}`),c.context&&console.error(`With context: ${JSON.stringify(c.context)}`);try{let r=await Lt(e,t,c.serverUrl,n,c.context);r.exitCode!==0&&(console.error(`\nClient exited with code ${r.exitCode}`),r.stdout&&console.error(`\nStdout:\n${r.stdout}`),r.stderr&&console.error(`\nStderr:\n${r.stderr}`)),r.timedOut&&console.error(`\nClient timed out after ${n}ms`);let l=s.getChecks();return o&&(await i.writeFile(a.join(o,`checks.json`),JSON.stringify(l,null,2)),await i.writeFile(a.join(o,`stdout.txt`),r.stdout),await i.writeFile(a.join(o,`stderr.txt`),r.stderr),console.error(`Results saved to ${o}`)),{checks:l,clientOutput:r,resultDir:o}}finally{await s.stop()}}function zt(e,t=!1,n){let r=e.filter(e=>e.status===`SUCCESS`||e.status===`FAILURE`).length,i=e.filter(e=>e.status===`SUCCESS`).length,a=e.filter(e=>e.status===`FAILURE`).length,o=e.filter(e=>e.status===`WARNING`).length,s=n?.timedOut??!1,c=n?n.exitCode!==0:!1,l=a>0||o>0||s||c;return t?console.log(JSON.stringify(e,null,2)):console.error(`Checks:\n${J(e)}`),console.error(` +Test Results:`),console.error(`Passed: ${i}/${r}, ${a} failed, ${o} warnings`),s&&console.error(` +⚠️ CLIENT TIMED OUT - Test incomplete`),c&&!s&&console.error(`\n⚠️ CLIENT EXITED WITH ERROR (code ${n?.exitCode}) - Test may be incomplete`),a>0&&(console.error(` +Failed Checks:`),e.filter(e=>e.status===`FAILURE`).forEach(e=>{console.error(` - ${e.name}: ${e.description}`),e.errorMessage&&console.error(` Error: ${e.errorMessage}`)})),o>0&&(console.error(` +Warning Checks:`),e.filter(e=>e.status===`WARNING`).forEach(e=>{console.error(` - ${e.name}: ${e.description}`),e.errorMessage&&console.error(` Warning: ${e.errorMessage}`)})),l?console.error(` +❌ OVERALL: FAILED`):console.error(` +✅ OVERALL: PASSED`),{passed:i,failed:a,denominator:r,warnings:o,overallFailure:l}}async function Bt(e,t=!1,n){let r;n&&(r=Y(n,e),await i.mkdir(r,{recursive:!0}));let o=U(e);console.log(`Starting scenario: ${e}`);let s=await o.start();console.log(`Server URL: ${s.serverUrl}`),console.log(`Press Ctrl+C to stop...`);let c=async()=>{console.log(` +Shutting down...`);let e=o.getChecks();r&&await i.writeFile(a.join(r,`checks.json`),JSON.stringify(e,null,2)),t?console.log(`\nChecks:\n${JSON.stringify(e,null,2)}`):console.log(`\nChecks:\n${J(e)}`),r&&console.log(`\nChecks saved to ${r}/checks.json`),await o.stop(),process.exit(0)};process.on(`SIGINT`,c),process.on(`SIGTERM`,c),await new Promise(()=>{})}function Vt(e){return e.replace(/\*\*([^*]+)\*\*/g,`\x1B[1m$1\x1B[0m`).replace(/`([^`]+)`/g,`\x1B[2m$1\x1B[0m`)}async function Ht(e,t,n){let r;n&&(r=Y(n,t,`server`),await i.mkdir(r,{recursive:!0}));let o=jt(t);console.log(`Running client scenario '${t}' against server: ${e}`);let s=await o.run(e);return r&&(await i.writeFile(a.join(r,`checks.json`),JSON.stringify(s,null,2)),console.log(`Results saved to ${r}`)),{checks:s,resultDir:r,scenarioDescription:o.description}}function Ut(e,t,n=!1){let r=e.filter(e=>e.status===`SUCCESS`||e.status===`FAILURE`).length,i=e.filter(e=>e.status===`SUCCESS`).length,a=e.filter(e=>e.status===`FAILURE`).length,o=e.filter(e=>e.status===`WARNING`).length;return n?console.log(JSON.stringify(e,null,2)):console.log(`Checks:\n${J(e)}`),console.log(` +Test Results:`),console.log(`Passed: ${i}/${r}, ${a} failed, ${o} warnings`),a>0&&(console.log(` +=== Failed Checks ===`),e.filter(e=>e.status===`FAILURE`).forEach(e=>{console.log(`\n - ${e.name}: ${e.description}`),e.errorMessage&&console.log(` Error: ${e.errorMessage}`),console.log(`\n${Vt(t)}`)})),{passed:i,failed:a,denominator:r,warnings:o}}function Wt(e){console.log(` + +=== SUMMARY ===`);let t=0,n=0;for(let r of e){let e=r.checks.filter(e=>e.status===`SUCCESS`).length,i=r.checks.filter(e=>e.status===`FAILURE`).length;t+=e,n+=i;let a=i===0?`✓`:`✗`;console.log(`${a} ${r.scenario}: ${e} passed, ${i} failed`)}return console.log(`\nTotal: ${t} passed, ${n} failed`),{totalPassed:t,totalFailed:n}}const Gt=n.object({command:n.string().min(1,`Command cannot be empty`).optional(),scenario:n.string().min(1,`Scenario cannot be empty`).refine(e=>U(e)!==void 0,e=>({message:`Unknown scenario '${e}'`})),timeout:n.string().transform(e=>parseInt(e,10)).pipe(n.number().positive(`Timeout must be a positive number`).int(`Timeout must be an integer`)).optional(),verbose:n.boolean().optional()}),Kt=n.object({url:n.string().url(`Invalid server URL`),scenario:n.string().refine(e=>jt(e)!==void 0,e=>({message:`Unknown scenario '${e}'`})).optional()});n.object({scenario:n.string().min(1,`Scenario cannot be empty`).refine(e=>U(e)!==void 0,e=>({message:`Unknown scenario '${e}'`}))});async function X(e){let t=ne(await i.readFile(e,`utf-8`));if(t==null)return{};if(typeof t!=`object`||Array.isArray(t))throw Error(`Invalid expected-failures file: expected an object with 'server' and/or 'client' keys`);let n={};if(t.server!==void 0){if(!Array.isArray(t.server))throw Error(`Invalid expected-failures file: 'server' must be an array of scenario names`);n.server=t.server.map(String)}if(t.client!==void 0){if(!Array.isArray(t.client))throw Error(`Invalid expected-failures file: 'client' must be an array of scenario names`);n.client=t.client.map(String)}return n}function Z(e,t){let n=new Set(t),r=[],i=[],a=[],o=new Set;for(let t of e){o.add(t.scenario);let e=t.checks.some(e=>e.status===`FAILURE`)||t.checks.some(e=>e.status===`WARNING`),s=n.has(t.scenario);e&&s?a.push(t.scenario):e&&!s?r.push(t.scenario):!e&&s&&i.push(t.scenario)}return{exitCode:r.length>0||i.length>0?1:0,unexpectedFailures:r,staleEntries:i,expectedFailures:a}}function Q(e){if(e.expectedFailures.length>0){console.log(`\n${q.YELLOW}Expected failures (in baseline):${q.RESET}`);for(let t of e.expectedFailures)console.log(` ~ ${t}`)}if(e.staleEntries.length>0){console.log(`\n${q.RED}Stale baseline entries (now passing - remove from baseline):${q.RESET}`);for(let t of e.staleEntries)console.log(` ✓ ${t}`)}if(e.unexpectedFailures.length>0){console.log(`\n${q.RED}Unexpected failures (not in baseline):${q.RESET}`);for(let t of e.unexpectedFailures)console.log(` ✗ ${t}`)}e.exitCode===0?console.log(`\n${q.GREEN}Baseline check passed: all failures are expected.${q.RESET}`):(e.staleEntries.length>0&&console.log(`\n${q.RED}Baseline is stale: update your expected-failures file to remove passing scenarios.${q.RESET}`),e.unexpectedFailures.length>0&&console.log(`\n${q.RED}Unexpected failures detected: these scenarios are not in your expected-failures baseline.${q.RESET}`))}var qt=`0.1.11`;const $=new e;$.name(`conformance`).description(`MCP Conformance Test Suite`).version(qt),$.command(`client`).description(`Run conformance tests against a client implementation or start interactive mode`).option(`--command `,`Command to run the client`).option(`--scenario `,`Scenario to test`).option(`--suite `,`Run a suite of tests in parallel (e.g., "auth")`).option(`--timeout `,`Timeout in milliseconds`,`30000`).option(`--expected-failures `,`Path to YAML file listing expected failures (baseline)`).option(`-o, --output-dir `,`Save results to this directory`).option(`--verbose`,`Show verbose output`).action(async e=>{try{let t=parseInt(e.timeout,10),n=e.verbose??!1,r=e.outputDir;if(e.suite){e.command||(console.error(`--command is required when using --suite`),process.exit(1));let i={all:W,core:Pt,extensions:Ft,auth:K,metadata:et,"sep-835":()=>K().filter(e=>e.startsWith(`auth/scope-`))},a=e.suite.toLowerCase();i[a]||(console.error(`Unknown suite: ${a}`),console.error(`Available suites: ${Object.keys(i).join(`, `)}`),process.exit(1));let o=i[a]();console.log(`Running ${a} suite (${o.length} scenarios) in parallel...\n`);let s=await Promise.all(o.map(async n=>{try{return{scenario:n,checks:(await Rt(e.command,n,t,r)).checks,error:null}}catch(e){return{scenario:n,checks:[{id:n,name:n,description:`Failed to run scenario`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:e instanceof Error?e.message:String(e)}],error:e}}}));console.log(` +=== SUITE SUMMARY === +`);let c=0,l=0,u=0;for(let e of s){let t=e.checks.filter(e=>e.status===`SUCCESS`).length,r=e.checks.filter(e=>e.status===`FAILURE`).length,i=e.checks.filter(e=>e.status===`WARNING`).length;c+=t,l+=r,u+=i;let a=r===0&&i===0?`✓`:`✗`,o=i>0?`, ${i} warnings`:``;console.log(`${a} ${e.scenario}: ${t} passed, ${r} failed${o}`),n&&r>0&&e.checks.filter(e=>e.status===`FAILURE`).forEach(e=>{console.log(` - ${e.name}: ${e.errorMessage||e.description}`)})}if(console.log(`\nTotal: ${c} passed, ${l} failed, ${u} warnings`),e.expectedFailures){let t=Z(s,(await X(e.expectedFailures)).client??[]);Q(t),process.exit(t.exitCode)}process.exit(l>0||u>0?1:0)}e.scenario||(console.error(`Either --scenario or --suite is required`),console.error(` +Available client scenarios:`),W().forEach(e=>console.error(` - ${e}`)),console.error(` +Available suites: all, core, extensions, auth, metadata, sep-835`),process.exit(1));let i=Gt.parse(e);i.command||(await Bt(i.scenario,n,r),process.exit(0));let a=await Rt(i.command,i.scenario,t,r),{overallFailure:o}=zt(a.checks,n,a.clientOutput);if(e.expectedFailures){let t=(await X(e.expectedFailures)).client??[],n=Z([{scenario:i.scenario,checks:a.checks}],t);Q(n),process.exit(n.exitCode)}process.exit(o?1:0)}catch(e){e instanceof t&&(console.error(`Validation error:`),e.errors.forEach(e=>{console.error(` ${e.path.join(`.`)}: ${e.message}`)}),console.error(` +Available client scenarios:`),W().forEach(e=>console.error(` - ${e}`)),process.exit(1)),console.error(`Client test error:`,e),process.exit(1)}}),$.command(`server`).description(`Run conformance tests against a server implementation`).requiredOption(`--url `,`URL of the server to test`).option(`--scenario `,`Scenario to test (defaults to active suite if not specified)`).option(`--suite `,`Suite to run: "active" (default, excludes pending), "all", or "pending"`,`active`).option(`--expected-failures `,`Path to YAML file listing expected failures (baseline)`).option(`-o, --output-dir `,`Save results to this directory`).option(`--verbose`,`Show verbose output (JSON instead of pretty print)`).action(async e=>{try{let t=Kt.parse(e),n=e.verbose??!1,r=e.outputDir;if(t.scenario){let i=await Ht(t.url,t.scenario,r),{failed:a}=Ut(i.checks,i.scenarioDescription,n);if(e.expectedFailures){let n=(await X(e.expectedFailures)).server??[],r=Z([{scenario:t.scenario,checks:i.checks}],n);Q(r),process.exit(r.exitCode)}process.exit(a>0?1:0)}else{let n=e.suite?.toLowerCase()||`active`,i;n===`all`?i=G():n===`active`||n===`core`?i=Mt():n===`pending`?i=Nt():(console.error(`Unknown suite: ${n}`),console.error(`Available suites: active, all, core, pending`),process.exit(1)),console.log(`Running ${n} suite (${i.length} scenarios) against ${t.url}\n`);let a=[];for(let e of i){console.log(`\n=== Running scenario: ${e} ===`);try{let n=await Ht(t.url,e,r);a.push({scenario:e,checks:n.checks})}catch(t){console.error(`Failed to run scenario ${e}:`,t),a.push({scenario:e,checks:[{id:e,name:e,description:`Failed to run scenario`,status:`FAILURE`,timestamp:new Date().toISOString(),errorMessage:t instanceof Error?t.message:String(t)}]})}}let{totalFailed:o}=Wt(a);if(e.expectedFailures){let t=Z(a,(await X(e.expectedFailures)).server??[]);Q(t),process.exit(t.exitCode)}process.exit(o>0?1:0)}}catch(e){e instanceof t&&(console.error(`Validation error:`),e.errors.forEach(e=>{console.error(` ${e.path.join(`.`)}: ${e.message}`)}),console.error(` +Available server scenarios:`),G().forEach(e=>console.error(` - ${e}`)),process.exit(1)),console.error(`Server test error:`,e),process.exit(1)}}),$.command(`list`).description(`List available test scenarios`).option(`--client`,`List client scenarios`).option(`--server`,`List server scenarios`).action(e=>{(e.server||!e.client&&!e.server)&&(console.log(`Server scenarios (test against a server):`),G().forEach(e=>console.log(` - ${e}`))),(e.client||!e.client&&!e.server)&&((e.server||!e.client&&!e.server)&&console.log(``),console.log(`Client scenarios (test against a client):`),W().forEach(e=>console.log(` - ${e}`)))}),$.parse();export{}; \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/conformance/package.json b/node_modules/@modelcontextprotocol/conformance/package.json new file mode 100644 index 000000000..36b855b4e --- /dev/null +++ b/node_modules/@modelcontextprotocol/conformance/package.json @@ -0,0 +1,57 @@ +{ + "name": "@modelcontextprotocol/conformance", + "version": "0.1.11", + "type": "module", + "license": "MIT", + "author": "Anthropic, PBC (https://anthropic.com)", + "homepage": "https://modelcontextprotocol.io", + "bugs": "https://github.com/modelcontextprotocol/conformance/issues", + "repository": { + "type": "git", + "url": "git+https://github.com/modelcontextprotocol/conformance.git" + }, + "scripts": { + "start": "tsx src/index.ts", + "test": "vitest run", + "test:watch": "vitest", + "build": "tsdown src/index.ts --minify --clean --target node20", + "lint": "eslint src/ examples/ && prettier --check .", + "lint:fix": "eslint src/ examples/ --fix && prettier --write .", + "lint:fix_check": "npm run lint:fix && git diff --exit-code --quiet", + "check": "npm run typecheck && npm run lint", + "typecheck": "tsgo --noEmit", + "prepack": "npm run build" + }, + "files": [ + "dist" + ], + "bin": { + "conformance": "dist/index.js" + }, + "devDependencies": { + "@eslint/js": "^9.39.1", + "@types/express": "^5.0.3", + "@types/node": "^22.10.2", + "@typescript/native-preview": "^7.0.0-dev.20251201.1", + "cors": "^2.8.5", + "eslint": "^9.8.0", + "eslint-config-prettier": "^10.1.8", + "lefthook": "^2.0.2", + "prettier": "3.6.2", + "tsdown": "^0.15.12", + "tsx": "^4.7.0", + "typescript": "^5.5.4", + "typescript-eslint": "8.48.0", + "vitest": "^4.0.16" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "^1.25.2", + "commander": "^14.0.2", + "eventsource-parser": "^3.0.6", + "express": "^5.1.0", + "jose": "^6.1.2", + "undici": "^7.19.0", + "yaml": "^2.8.2", + "zod": "^3.25.76" + } +} diff --git a/node_modules/@modelcontextprotocol/sdk/LICENSE b/node_modules/@modelcontextprotocol/sdk/LICENSE new file mode 100644 index 000000000..3d4843545 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Anthropic, PBC + +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/@modelcontextprotocol/sdk/README.md b/node_modules/@modelcontextprotocol/sdk/README.md new file mode 100644 index 000000000..254671c8f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/README.md @@ -0,0 +1,169 @@ +# MCP TypeScript SDK [![NPM Version](https://img.shields.io/npm/v/%40modelcontextprotocol%2Fsdk)](https://www.npmjs.com/package/@modelcontextprotocol/sdk) [![MIT licensed](https://img.shields.io/npm/l/%40modelcontextprotocol%2Fsdk)](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/LICENSE) + +
+Table of Contents + +- [Overview](#overview) +- [Installation](#installation) +- [Quick Start](#quick-start) +- [Core Concepts](#core-concepts) +- [Examples](#examples) +- [Documentation](#documentation) +- [Contributing](#contributing) +- [License](#license) + +
+ +## Overview + +The Model Context Protocol allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. This TypeScript SDK implements +[the full MCP specification](https://modelcontextprotocol.io/specification/draft), making it easy to: + +- Create MCP servers that expose resources, prompts and tools +- Build MCP clients that can connect to any MCP server +- Use standard transports like stdio and Streamable HTTP + +## Installation + +```bash +npm install @modelcontextprotocol/sdk zod +``` + +This SDK has a **required peer dependency** on `zod` for schema validation. The SDK internally imports from `zod/v4`, but maintains backwards compatibility with projects using Zod v3.25 or later. You can use either API in your code by importing from `zod/v3` or `zod/v4`: + +## Quick Start + +To see the SDK in action end-to-end, start from the runnable examples in `src/examples`: + +1. **Install dependencies** (from the SDK repo root): + + ```bash + npm install + ``` + +2. **Run the example Streamable HTTP server**: + + ```bash + npx tsx src/examples/server/simpleStreamableHttp.ts + ``` + +3. **Run the interactive client in another terminal**: + + ```bash + npx tsx src/examples/client/simpleStreamableHttp.ts + ``` + +This pair of examples demonstrates tools, resources, prompts, sampling, elicitation, tasks and logging. For a guided walkthrough and variations (stateless servers, JSON-only responses, SSE compatibility, OAuth, etc.), see [docs/server.md](docs/server.md) and +[docs/client.md](docs/client.md). + +## Core Concepts + +### Servers and transports + +An MCP server is typically created with `McpServer` and connected to a transport such as Streamable HTTP or stdio. The SDK supports: + +- **Streamable HTTP** for remote servers (recommended). +- **HTTP + SSE** for backwards compatibility only. +- **stdio** for local, process-spawned integrations. + +Runnable server examples live under `src/examples/server` and are documented in [docs/server.md](docs/server.md). + +### Tools, resources, prompts + +- **Tools** let LLMs ask your server to take actions (computation, side effects, network calls). +- **Resources** expose read-only data that clients can surface to users or models. +- **Prompts** are reusable templates that help users talk to models in a consistent way. + +The detailed APIs, including `ResourceTemplate`, completions, and display-name metadata, are covered in [docs/server.md](docs/server.md#tools-resources-and-prompts), with runnable implementations in [`simpleStreamableHttp.ts`](src/examples/server/simpleStreamableHttp.ts). + +### Capabilities: sampling, elicitation, and tasks + +The SDK includes higher-level capabilities for richer workflows: + +- **Sampling**: server-side tools can ask connected clients to run LLM completions. +- **Form elicitation**: tools can request non-sensitive input via structured forms. +- **URL elicitation**: servers can ask users to complete secure flows in a browser (e.g., API key entry, payments, OAuth). +- **Tasks (experimental)**: long-running tool calls can be turned into tasks that you poll or resume later. + +Conceptual overviews and links to runnable examples are in: + +- [docs/capabilities.md](docs/capabilities.md) + +Key example servers include: + +- [`toolWithSampleServer.ts`](src/examples/server/toolWithSampleServer.ts) +- [`elicitationFormExample.ts`](src/examples/server/elicitationFormExample.ts) +- [`elicitationUrlExample.ts`](src/examples/server/elicitationUrlExample.ts) + +### Clients + +The high-level `Client` class connects to MCP servers over different transports and exposes helpers like `listTools`, `callTool`, `listResources`, `readResource`, `listPrompts`, and `getPrompt`. + +Runnable clients live under `src/examples/client` and are described in [docs/client.md](docs/client.md), including: + +- Interactive Streamable HTTP client ([`simpleStreamableHttp.ts`](src/examples/client/simpleStreamableHttp.ts)) +- Streamable HTTP client with SSE fallback ([`streamableHttpWithSseFallbackClient.ts`](src/examples/client/streamableHttpWithSseFallbackClient.ts)) +- OAuth-enabled clients and polling/parallel examples + +### Node.js Web Crypto (globalThis.crypto) compatibility + +Some parts of the SDK (for example, JWT-based client authentication in `auth-extensions.ts` via `jose`) rely on the Web Crypto API exposed as `globalThis.crypto`. + +See [docs/faq.md](docs/faq.md) for details on supported Node.js versions and how to polyfill `globalThis.crypto` when running on older Node.js runtimes. + +## Examples + +The SDK ships runnable examples under `src/examples`. Use these tables to find the scenario you care about and jump straight to the corresponding code and docs. + +### Server examples + +| Scenario | Description | Example file(s) | Related docs | +| --------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| Streamable HTTP server (stateful) | Feature-rich server with tools, resources, prompts, logging, tasks, sampling, and optional OAuth. | [`simpleStreamableHttp.ts`](src/examples/server/simpleStreamableHttp.ts) | [`server.md`](docs/server.md), [`capabilities.md`](docs/capabilities.md) | +| Streamable HTTP server (stateless) | No session tracking; good for simple API-style servers. | [`simpleStatelessStreamableHttp.ts`](src/examples/server/simpleStatelessStreamableHttp.ts) | [`server.md`](docs/server.md) | +| JSON response mode (no SSE) | Streamable HTTP with JSON responses only and limited notifications. | [`jsonResponseStreamableHttp.ts`](src/examples/server/jsonResponseStreamableHttp.ts) | [`server.md`](docs/server.md) | +| Server notifications over Streamable HTTP | Demonstrates server-initiated notifications using SSE with Streamable HTTP. | [`standaloneSseWithGetStreamableHttp.ts`](src/examples/server/standaloneSseWithGetStreamableHttp.ts) | [`server.md`](docs/server.md) | +| Deprecated HTTP+SSE server | Legacy HTTP+SSE transport for backwards-compatibility testing. | [`simpleSseServer.ts`](src/examples/server/simpleSseServer.ts) | [`server.md`](docs/server.md) | +| Backwards-compatible server (Streamable HTTP + SSE) | Single server that supports both Streamable HTTP and legacy SSE clients. | [`sseAndStreamableHttpCompatibleServer.ts`](src/examples/server/sseAndStreamableHttpCompatibleServer.ts) | [`server.md`](docs/server.md) | +| Form elicitation server | Uses form elicitation to collect non-sensitive user input. | [`elicitationFormExample.ts`](src/examples/server/elicitationFormExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) | +| URL elicitation server | Demonstrates URL-mode elicitation in an OAuth-protected server. | [`elicitationUrlExample.ts`](src/examples/server/elicitationUrlExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) | +| Sampling and tasks server | Combines tools, logging, sampling, and experimental task-based execution. | [`toolWithSampleServer.ts`](src/examples/server/toolWithSampleServer.ts) | [`capabilities.md`](docs/capabilities.md) | +| OAuth demo authorization server | In-memory OAuth provider used with the example servers. | [`demoInMemoryOAuthProvider.ts`](src/examples/server/demoInMemoryOAuthProvider.ts) | [`server.md`](docs/server.md) | + +### Client examples + +| Scenario | Description | Example file(s) | Related docs | +| --------------------------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | +| Interactive Streamable HTTP client | CLI client that exercises tools, resources, prompts, elicitation, and tasks. | [`simpleStreamableHttp.ts`](src/examples/client/simpleStreamableHttp.ts) | [`client.md`](docs/client.md) | +| Backwards-compatible client (Streamable HTTP → SSE) | Tries Streamable HTTP first, then falls back to SSE on 4xx responses. | [`streamableHttpWithSseFallbackClient.ts`](src/examples/client/streamableHttpWithSseFallbackClient.ts) | [`client.md`](docs/client.md), [`server.md`](docs/server.md) | +| SSE polling client | Polls a legacy SSE server and demonstrates notification handling. | [`ssePollingClient.ts`](src/examples/client/ssePollingClient.ts) | [`client.md`](docs/client.md) | +| Parallel tool calls client | Shows how to run multiple tool calls in parallel. | [`parallelToolCallsClient.ts`](src/examples/client/parallelToolCallsClient.ts) | [`client.md`](docs/client.md) | +| Multiple clients in parallel | Demonstrates connecting multiple clients concurrently to the same server. | [`multipleClientsParallel.ts`](src/examples/client/multipleClientsParallel.ts) | [`client.md`](docs/client.md) | +| OAuth clients | Examples of client_credentials (basic and private_key_jwt) and reusable providers. | [`simpleOAuthClient.ts`](src/examples/client/simpleOAuthClient.ts), [`simpleOAuthClientProvider.ts`](src/examples/client/simpleOAuthClientProvider.ts), [`simpleClientCredentials.ts`](src/examples/client/simpleClientCredentials.ts) | [`client.md`](docs/client.md) | +| URL elicitation client | Works with the URL elicitation server to drive secure browser flows. | [`elicitationUrlExample.ts`](src/examples/client/elicitationUrlExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) | + +Shared utilities: + +- In-memory event store for resumability: [`inMemoryEventStore.ts`](src/examples/shared/inMemoryEventStore.ts) (see [`server.md`](docs/server.md)). + +For more details on how to run these examples (including recommended commands and deployment diagrams), see `src/examples/README.md`. + +## Documentation + +- Local SDK docs: + - [docs/server.md](docs/server.md) – building and running MCP servers, transports, tools/resources/prompts, CORS, DNS rebinding, and multi-node deployment. + - [docs/client.md](docs/client.md) – using the high-level client, transports, backwards compatibility, and OAuth helpers. + - [docs/capabilities.md](docs/capabilities.md) – sampling, elicitation (form and URL), and experimental task-based execution. + - [docs/faq.md](docs/faq.md) – environment and troubleshooting FAQs (including Node.js Web Crypto support). +- External references: + - [Model Context Protocol documentation](https://modelcontextprotocol.io) + - [MCP Specification](https://spec.modelcontextprotocol.io) + - [Example Servers](https://github.com/modelcontextprotocol/servers) + +## Contributing + +Issues and pull requests are welcome on GitHub at . + +## License + +This project is licensed under the MIT License—see the [LICENSE](LICENSE) file for details. diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.ts new file mode 100644 index 000000000..2a3f6bff6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.ts @@ -0,0 +1,178 @@ +/** + * OAuth provider extensions for specialized authentication flows. + * + * This module provides ready-to-use OAuthClientProvider implementations + * for common machine-to-machine authentication scenarios. + */ +import { OAuthClientInformation, OAuthClientMetadata, OAuthTokens } from '../shared/auth.js'; +import { AddClientAuthentication, OAuthClientProvider } from './auth.js'; +/** + * Helper to produce a private_key_jwt client authentication function. + * + * Usage: + * const addClientAuth = createPrivateKeyJwtAuth({ issuer, subject, privateKey, alg, audience? }); + * // pass addClientAuth as provider.addClientAuthentication implementation + */ +export declare function createPrivateKeyJwtAuth(options: { + issuer: string; + subject: string; + privateKey: string | Uint8Array | Record; + alg: string; + audience?: string | URL; + lifetimeSeconds?: number; + claims?: Record; +}): AddClientAuthentication; +/** + * Options for creating a ClientCredentialsProvider. + */ +export interface ClientCredentialsProviderOptions { + /** + * The client_id for this OAuth client. + */ + clientId: string; + /** + * The client_secret for client_secret_basic authentication. + */ + clientSecret: string; + /** + * Optional client name for metadata. + */ + clientName?: string; +} +/** + * OAuth provider for client_credentials grant with client_secret_basic authentication. + * + * This provider is designed for machine-to-machine authentication where + * the client authenticates using a client_id and client_secret. + * + * @example + * const provider = new ClientCredentialsProvider({ + * clientId: 'my-client', + * clientSecret: 'my-secret' + * }); + * + * const transport = new StreamableHTTPClientTransport(serverUrl, { + * authProvider: provider + * }); + */ +export declare class ClientCredentialsProvider implements OAuthClientProvider { + private _tokens?; + private _clientInfo; + private _clientMetadata; + constructor(options: ClientCredentialsProviderOptions); + get redirectUrl(): undefined; + get clientMetadata(): OAuthClientMetadata; + clientInformation(): OAuthClientInformation; + saveClientInformation(info: OAuthClientInformation): void; + tokens(): OAuthTokens | undefined; + saveTokens(tokens: OAuthTokens): void; + redirectToAuthorization(): void; + saveCodeVerifier(): void; + codeVerifier(): string; + prepareTokenRequest(scope?: string): URLSearchParams; +} +/** + * Options for creating a PrivateKeyJwtProvider. + */ +export interface PrivateKeyJwtProviderOptions { + /** + * The client_id for this OAuth client. + */ + clientId: string; + /** + * The private key for signing JWT assertions. + * Can be a PEM string, Uint8Array, or JWK object. + */ + privateKey: string | Uint8Array | Record; + /** + * The algorithm to use for signing (e.g., 'RS256', 'ES256'). + */ + algorithm: string; + /** + * Optional client name for metadata. + */ + clientName?: string; + /** + * Optional JWT lifetime in seconds (default: 300). + */ + jwtLifetimeSeconds?: number; +} +/** + * OAuth provider for client_credentials grant with private_key_jwt authentication. + * + * This provider is designed for machine-to-machine authentication where + * the client authenticates using a signed JWT assertion (RFC 7523 Section 2.2). + * + * @example + * const provider = new PrivateKeyJwtProvider({ + * clientId: 'my-client', + * privateKey: pemEncodedPrivateKey, + * algorithm: 'RS256' + * }); + * + * const transport = new StreamableHTTPClientTransport(serverUrl, { + * authProvider: provider + * }); + */ +export declare class PrivateKeyJwtProvider implements OAuthClientProvider { + private _tokens?; + private _clientInfo; + private _clientMetadata; + addClientAuthentication: AddClientAuthentication; + constructor(options: PrivateKeyJwtProviderOptions); + get redirectUrl(): undefined; + get clientMetadata(): OAuthClientMetadata; + clientInformation(): OAuthClientInformation; + saveClientInformation(info: OAuthClientInformation): void; + tokens(): OAuthTokens | undefined; + saveTokens(tokens: OAuthTokens): void; + redirectToAuthorization(): void; + saveCodeVerifier(): void; + codeVerifier(): string; + prepareTokenRequest(scope?: string): URLSearchParams; +} +/** + * Options for creating a StaticPrivateKeyJwtProvider. + */ +export interface StaticPrivateKeyJwtProviderOptions { + /** + * The client_id for this OAuth client. + */ + clientId: string; + /** + * A pre-built JWT client assertion to use for authentication. + * + * This token should already contain the appropriate claims + * (iss, sub, aud, exp, etc.) and be signed by the client's key. + */ + jwtBearerAssertion: string; + /** + * Optional client name for metadata. + */ + clientName?: string; +} +/** + * OAuth provider for client_credentials grant with a static private_key_jwt assertion. + * + * This provider mirrors {@link PrivateKeyJwtProvider} but instead of constructing and + * signing a JWT on each request, it accepts a pre-built JWT assertion string and + * uses it directly for authentication. + */ +export declare class StaticPrivateKeyJwtProvider implements OAuthClientProvider { + private _tokens?; + private _clientInfo; + private _clientMetadata; + addClientAuthentication: AddClientAuthentication; + constructor(options: StaticPrivateKeyJwtProviderOptions); + get redirectUrl(): undefined; + get clientMetadata(): OAuthClientMetadata; + clientInformation(): OAuthClientInformation; + saveClientInformation(info: OAuthClientInformation): void; + tokens(): OAuthTokens | undefined; + saveTokens(tokens: OAuthTokens): void; + redirectToAuthorization(): void; + saveCodeVerifier(): void; + codeVerifier(): string; + prepareTokenRequest(scope?: string): URLSearchParams; +} +//# sourceMappingURL=auth-extensions.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.ts.map new file mode 100644 index 000000000..863e23a83 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-extensions.d.ts","sourceRoot":"","sources":["../../../src/client/auth-extensions.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC7F,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAEzE;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE;IAC7C,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC1D,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC,GAAG,uBAAuB,CAgE1B;AAED;;GAEG;AACH,MAAM,WAAW,gCAAgC;IAC7C;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IAErB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,yBAA0B,YAAW,mBAAmB;IACjE,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,WAAW,CAAyB;IAC5C,OAAO,CAAC,eAAe,CAAsB;gBAEjC,OAAO,EAAE,gCAAgC;IAarD,IAAI,WAAW,IAAI,SAAS,CAE3B;IAED,IAAI,cAAc,IAAI,mBAAmB,CAExC;IAED,iBAAiB,IAAI,sBAAsB;IAI3C,qBAAqB,CAAC,IAAI,EAAE,sBAAsB,GAAG,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;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;;;;OAKG;IACH,kBAAkB,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;GAMG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IACnE,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,WAAW,CAAyB;IAC5C,OAAO,CAAC,eAAe,CAAsB;IAC7C,uBAAuB,EAAE,uBAAuB,CAAC;gBAErC,OAAO,EAAE,kCAAkC;IAkBvD,IAAI,WAAW,IAAI,SAAS,CAE3B;IAED,IAAI,cAAc,IAAI,mBAAmB,CAExC;IAED,iBAAiB,IAAI,sBAAsB;IAI3C,qBAAqB,CAAC,IAAI,EAAE,sBAAsB,GAAG,IAAI;IAIzD,MAAM,IAAI,WAAW,GAAG,SAAS;IAIjC,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI;IAIrC,uBAAuB,IAAI,IAAI;IAI/B,gBAAgB,IAAI,IAAI;IAIxB,YAAY,IAAI,MAAM;IAItB,mBAAmB,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,eAAe;CAKvD"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.js new file mode 100644 index 000000000..ca75167e5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.js @@ -0,0 +1,296 @@ +"use strict"; +/** + * OAuth provider extensions for specialized authentication flows. + * + * This module provides ready-to-use OAuthClientProvider implementations + * for common machine-to-machine authentication scenarios. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StaticPrivateKeyJwtProvider = exports.PrivateKeyJwtProvider = exports.ClientCredentialsProvider = void 0; +exports.createPrivateKeyJwtAuth = createPrivateKeyJwtAuth; +/** + * Helper to produce a private_key_jwt client authentication function. + * + * Usage: + * const addClientAuth = createPrivateKeyJwtAuth({ issuer, subject, privateKey, alg, audience? }); + * // pass addClientAuth as provider.addClientAuthentication implementation + */ +function createPrivateKeyJwtAuth(options) { + return async (_headers, params, url, metadata) => { + // Lazy import to avoid heavy dependency unless used + if (typeof globalThis.crypto === 'undefined') { + throw new TypeError('crypto is not available, please ensure you add have Web Crypto API support for older Node.js versions (see https://github.com/modelcontextprotocol/typescript-sdk#nodejs-web-crypto-globalthiscrypto-compatibility)'); + } + const jose = await Promise.resolve().then(() => __importStar(require('jose'))); + const audience = String(options.audience ?? metadata?.issuer ?? url); + const lifetimeSeconds = options.lifetimeSeconds ?? 300; + const now = Math.floor(Date.now() / 1000); + const jti = `${Date.now()}-${Math.random().toString(36).slice(2)}`; + const baseClaims = { + iss: options.issuer, + sub: options.subject, + aud: audience, + exp: now + lifetimeSeconds, + iat: now, + jti + }; + const claims = options.claims ? { ...baseClaims, ...options.claims } : baseClaims; + // Import key for the requested algorithm + const alg = options.alg; + let key; + if (typeof options.privateKey === 'string') { + if (alg.startsWith('RS') || alg.startsWith('ES') || alg.startsWith('PS')) { + key = await jose.importPKCS8(options.privateKey, alg); + } + else if (alg.startsWith('HS')) { + key = new TextEncoder().encode(options.privateKey); + } + else { + throw new Error(`Unsupported algorithm ${alg}`); + } + } + else if (options.privateKey instanceof Uint8Array) { + if (alg.startsWith('HS')) { + key = options.privateKey; + } + else { + // Assume PKCS#8 DER in Uint8Array for asymmetric algorithms + key = await jose.importPKCS8(new TextDecoder().decode(options.privateKey), alg); + } + } + else { + // Treat as JWK + key = await jose.importJWK(options.privateKey, alg); + } + // Sign JWT + const assertion = await new jose.SignJWT(claims) + .setProtectedHeader({ alg, typ: 'JWT' }) + .setIssuer(options.issuer) + .setSubject(options.subject) + .setAudience(audience) + .setIssuedAt(now) + .setExpirationTime(now + lifetimeSeconds) + .setJti(jti) + .sign(key); + params.set('client_assertion', assertion); + params.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'); + }; +} +/** + * OAuth provider for client_credentials grant with client_secret_basic authentication. + * + * This provider is designed for machine-to-machine authentication where + * the client authenticates using a client_id and client_secret. + * + * @example + * const provider = new ClientCredentialsProvider({ + * clientId: 'my-client', + * clientSecret: 'my-secret' + * }); + * + * const transport = new StreamableHTTPClientTransport(serverUrl, { + * authProvider: provider + * }); + */ +class ClientCredentialsProvider { + constructor(options) { + this._clientInfo = { + client_id: options.clientId, + client_secret: options.clientSecret + }; + this._clientMetadata = { + client_name: options.clientName ?? 'client-credentials-client', + redirect_uris: [], + grant_types: ['client_credentials'], + token_endpoint_auth_method: 'client_secret_basic' + }; + } + get redirectUrl() { + return undefined; + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInfo; + } + saveClientInformation(info) { + this._clientInfo = info; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization() { + throw new Error('redirectToAuthorization is not used for client_credentials flow'); + } + saveCodeVerifier() { + // Not used for client_credentials + } + codeVerifier() { + throw new Error('codeVerifier is not used for client_credentials flow'); + } + prepareTokenRequest(scope) { + const params = new URLSearchParams({ grant_type: 'client_credentials' }); + if (scope) + params.set('scope', scope); + return params; + } +} +exports.ClientCredentialsProvider = ClientCredentialsProvider; +/** + * OAuth provider for client_credentials grant with private_key_jwt authentication. + * + * This provider is designed for machine-to-machine authentication where + * the client authenticates using a signed JWT assertion (RFC 7523 Section 2.2). + * + * @example + * const provider = new PrivateKeyJwtProvider({ + * clientId: 'my-client', + * privateKey: pemEncodedPrivateKey, + * algorithm: 'RS256' + * }); + * + * const transport = new StreamableHTTPClientTransport(serverUrl, { + * authProvider: provider + * }); + */ +class PrivateKeyJwtProvider { + constructor(options) { + this._clientInfo = { + client_id: options.clientId + }; + this._clientMetadata = { + client_name: options.clientName ?? 'private-key-jwt-client', + redirect_uris: [], + grant_types: ['client_credentials'], + token_endpoint_auth_method: 'private_key_jwt' + }; + this.addClientAuthentication = createPrivateKeyJwtAuth({ + issuer: options.clientId, + subject: options.clientId, + privateKey: options.privateKey, + alg: options.algorithm, + lifetimeSeconds: options.jwtLifetimeSeconds + }); + } + get redirectUrl() { + return undefined; + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInfo; + } + saveClientInformation(info) { + this._clientInfo = info; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization() { + throw new Error('redirectToAuthorization is not used for client_credentials flow'); + } + saveCodeVerifier() { + // Not used for client_credentials + } + codeVerifier() { + throw new Error('codeVerifier is not used for client_credentials flow'); + } + prepareTokenRequest(scope) { + const params = new URLSearchParams({ grant_type: 'client_credentials' }); + if (scope) + params.set('scope', scope); + return params; + } +} +exports.PrivateKeyJwtProvider = PrivateKeyJwtProvider; +/** + * OAuth provider for client_credentials grant with a static private_key_jwt assertion. + * + * This provider mirrors {@link PrivateKeyJwtProvider} but instead of constructing and + * signing a JWT on each request, it accepts a pre-built JWT assertion string and + * uses it directly for authentication. + */ +class StaticPrivateKeyJwtProvider { + constructor(options) { + this._clientInfo = { + client_id: options.clientId + }; + this._clientMetadata = { + client_name: options.clientName ?? 'static-private-key-jwt-client', + redirect_uris: [], + grant_types: ['client_credentials'], + token_endpoint_auth_method: 'private_key_jwt' + }; + const assertion = options.jwtBearerAssertion; + this.addClientAuthentication = async (_headers, params) => { + params.set('client_assertion', assertion); + params.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'); + }; + } + get redirectUrl() { + return undefined; + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInfo; + } + saveClientInformation(info) { + this._clientInfo = info; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization() { + throw new Error('redirectToAuthorization is not used for client_credentials flow'); + } + saveCodeVerifier() { + // Not used for client_credentials + } + codeVerifier() { + throw new Error('codeVerifier is not used for client_credentials flow'); + } + prepareTokenRequest(scope) { + const params = new URLSearchParams({ grant_type: 'client_credentials' }); + if (scope) + params.set('scope', scope); + return params; + } +} +exports.StaticPrivateKeyJwtProvider = StaticPrivateKeyJwtProvider; +//# sourceMappingURL=auth-extensions.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.js.map new file mode 100644 index 000000000..fc5bc6e3d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-extensions.js","sourceRoot":"","sources":["../../../src/client/auth-extensions.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;;;;;;;;;;;;;;;;;;;;;;;AAaH,0DAwEC;AA/ED;;;;;;GAMG;AACH,SAAgB,uBAAuB,CAAC,OAQvC;IACG,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,EAAE;QAC7C,oDAAoD;QACpD,IAAI,OAAO,UAAU,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC;YA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IAED,UAAU,CAAC,MAAmB;QAC1B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAED,uBAAuB;QACnB,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAC;IACvF,CAAC;IAED,gBAAgB;QACZ,kCAAkC;IACtC,CAAC;IAED,YAAY;QACR,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC5E,CAAC;IAED,mBAAmB,CAAC,KAAc;QAC9B,MAAM,MAAM,GAAG,IAAI,eAAe,CAAC,EAAE,UAAU,EAAE,oBAAoB,EAAE,CAAC,CAAC;QACzE,IAAI,KAAK;YAAE,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACtC,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AAjED,kEAiEC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.ts new file mode 100644 index 000000000..c1405d6c0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.ts @@ -0,0 +1,368 @@ +import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens, OAuthMetadata, OAuthClientInformationFull, OAuthProtectedResourceMetadata, AuthorizationServerMetadata } from '../shared/auth.js'; +import { OAuthError } from '../server/auth/errors.js'; +import { FetchLike } from '../shared/transport.js'; +/** + * Function type for adding client authentication to token requests. + */ +export type AddClientAuthentication = (headers: Headers, params: URLSearchParams, url: string | URL, metadata?: AuthorizationServerMetadata) => void | Promise; +/** + * Implements an end-to-end OAuth client to be used with one MCP server. + * + * This client relies upon a concept of an authorized "session," the exact + * meaning of which is application-defined. Tokens, authorization codes, and + * code verifiers should not cross different sessions. + */ +export interface OAuthClientProvider { + /** + * The URL to redirect the user agent to after authorization. + * Return undefined for non-interactive flows that don't require user interaction + * (e.g., client_credentials, jwt-bearer). + */ + get redirectUrl(): string | URL | undefined; + /** + * External URL the server should use to fetch client metadata document + */ + clientMetadataUrl?: string; + /** + * Metadata about this OAuth client. + */ + get clientMetadata(): OAuthClientMetadata; + /** + * Returns a OAuth2 state parameter. + */ + state?(): string | Promise; + /** + * Loads information about this OAuth client, as registered already with the + * server, or returns `undefined` if the client is not registered with the + * server. + */ + clientInformation(): OAuthClientInformationMixed | undefined | Promise; + /** + * If implemented, this permits the OAuth client to dynamically register with + * the server. Client information saved this way should later be read via + * `clientInformation()`. + * + * This method is not required to be implemented if client information is + * statically known (e.g., pre-registered). + */ + saveClientInformation?(clientInformation: OAuthClientInformationMixed): void | Promise; + /** + * Loads any existing OAuth tokens for the current session, or returns + * `undefined` if there are no saved tokens. + */ + tokens(): OAuthTokens | undefined | Promise; + /** + * Stores new OAuth tokens for the current session, after a successful + * authorization. + */ + saveTokens(tokens: OAuthTokens): void | Promise; + /** + * Invoked to redirect the user agent to the given URL to begin the authorization flow. + */ + redirectToAuthorization(authorizationUrl: URL): void | Promise; + /** + * Saves a PKCE code verifier for the current session, before redirecting to + * the authorization flow. + */ + saveCodeVerifier(codeVerifier: string): void | Promise; + /** + * Loads the PKCE code verifier for the current session, necessary to validate + * the authorization result. + */ + codeVerifier(): string | Promise; + /** + * Adds custom client authentication to OAuth token requests. + * + * This optional method allows implementations to customize how client credentials + * are included in token exchange and refresh requests. When provided, this method + * is called instead of the default authentication logic, giving full control over + * the authentication mechanism. + * + * Common use cases include: + * - Supporting authentication methods beyond the standard OAuth 2.0 methods + * - Adding custom headers for proprietary authentication schemes + * - Implementing client assertion-based authentication (e.g., JWT bearer tokens) + * + * @param headers - The request headers (can be modified to add authentication) + * @param params - The request body parameters (can be modified to add credentials) + * @param url - The token endpoint URL being called + * @param metadata - Optional OAuth metadata for the server, which may include supported authentication methods + */ + addClientAuthentication?: AddClientAuthentication; + /** + * If defined, overrides the selection and validation of the + * RFC 8707 Resource Indicator. If left undefined, default + * validation behavior will be used. + * + * Implementations must verify the returned resource matches the MCP server. + */ + validateResourceURL?(serverUrl: string | URL, resource?: string): Promise; + /** + * If implemented, provides a way for the client to invalidate (e.g. delete) the specified + * credentials, in the case where the server has indicated that they are no longer valid. + * This avoids requiring the user to intervene manually. + */ + invalidateCredentials?(scope: 'all' | 'client' | 'tokens' | 'verifier'): void | Promise; + /** + * Prepares grant-specific parameters for a token request. + * + * This optional method allows providers to customize the token request based on + * the grant type they support. When implemented, it returns the grant type and + * any grant-specific parameters needed for the token exchange. + * + * If not implemented, the default behavior depends on the flow: + * - For authorization code flow: uses code, code_verifier, and redirect_uri + * - For client_credentials: detected via grant_types in clientMetadata + * + * @param scope - Optional scope to request + * @returns Grant type and parameters, or undefined to use default behavior + * + * @example + * // For client_credentials grant: + * prepareTokenRequest(scope) { + * return { + * grantType: 'client_credentials', + * params: scope ? { scope } : {} + * }; + * } + * + * @example + * // For authorization_code grant (default behavior): + * async prepareTokenRequest() { + * return { + * grantType: 'authorization_code', + * params: { + * code: this.authorizationCode, + * code_verifier: await this.codeVerifier(), + * redirect_uri: String(this.redirectUrl) + * } + * }; + * } + */ + prepareTokenRequest?(scope?: string): URLSearchParams | Promise | undefined; +} +export type AuthResult = 'AUTHORIZED' | 'REDIRECT'; +export declare class UnauthorizedError extends Error { + constructor(message?: string); +} +type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none'; +/** + * Determines the best client authentication method to use based on server support and client configuration. + * + * Priority order (highest to lowest): + * 1. client_secret_basic (if client secret is available) + * 2. client_secret_post (if client secret is available) + * 3. none (for public clients) + * + * @param clientInformation - OAuth client information containing credentials + * @param supportedMethods - Authentication methods supported by the authorization server + * @returns The selected authentication method + */ +export declare function selectClientAuthMethod(clientInformation: OAuthClientInformationMixed, supportedMethods: string[]): ClientAuthMethod; +/** + * Parses an OAuth error response from a string or Response object. + * + * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec + * and an instance of the appropriate OAuthError subclass will be returned. + * If parsing fails, it falls back to a generic ServerError that includes + * the response status (if available) and original content. + * + * @param input - A Response object or string containing the error response + * @returns A Promise that resolves to an OAuthError instance + */ +export declare function parseErrorResponse(input: Response | string): Promise; +/** + * Orchestrates the full auth flow with a server. + * + * This can be used as a single entry point for all authorization functionality, + * instead of linking together the other lower-level functions in this module. + */ +export declare function auth(provider: OAuthClientProvider, options: { + serverUrl: string | URL; + authorizationCode?: string; + scope?: string; + resourceMetadataUrl?: URL; + fetchFn?: FetchLike; +}): Promise; +/** + * SEP-991: URL-based Client IDs + * Validate that the client_id is a valid URL with https scheme + */ +export declare function isHttpsUrl(value?: string): boolean; +export declare function selectResourceURL(serverUrl: string | URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise; +/** + * Extract resource_metadata, scope, and error from WWW-Authenticate header. + */ +export declare function extractWWWAuthenticateParams(res: Response): { + resourceMetadataUrl?: URL; + scope?: string; + error?: string; +}; +/** + * Extract resource_metadata from response header. + * @deprecated Use `extractWWWAuthenticateParams` instead. + */ +export declare function extractResourceMetadataUrl(res: Response): URL | undefined; +/** + * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + */ +export declare function discoverOAuthProtectedResourceMetadata(serverUrl: string | URL, opts?: { + protocolVersion?: string; + resourceMetadataUrl?: string | URL; +}, fetchFn?: FetchLike): Promise; +/** + * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + * + * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. + */ +export declare function discoverOAuthMetadata(issuer: string | URL, { authorizationServerUrl, protocolVersion }?: { + authorizationServerUrl?: string | URL; + protocolVersion?: string; +}, fetchFn?: FetchLike): Promise; +/** + * Builds a list of discovery URLs to try for authorization server metadata. + * URLs are returned in priority order: + * 1. OAuth metadata at the given URL + * 2. OIDC metadata endpoints at the given URL + */ +export declare function buildDiscoveryUrls(authorizationServerUrl: string | URL): { + url: URL; + type: 'oauth' | 'oidc'; +}[]; +/** + * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata + * and OpenID Connect Discovery 1.0 specifications. + * + * This function implements a fallback strategy for authorization server discovery: + * 1. Attempts RFC 8414 OAuth metadata discovery first + * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery + * + * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's + * protected resource metadata, or the MCP server's URL if the + * metadata was not found. + * @param options - Configuration options + * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch + * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION + * @returns Promise resolving to authorization server metadata, or undefined if discovery fails + */ +export declare function discoverAuthorizationServerMetadata(authorizationServerUrl: string | URL, { fetchFn, protocolVersion }?: { + fetchFn?: FetchLike; + protocolVersion?: string; +}): Promise; +/** + * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. + */ +export declare function startAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, redirectUrl, scope, state, resource }: { + metadata?: AuthorizationServerMetadata; + clientInformation: OAuthClientInformationMixed; + redirectUrl: string | URL; + scope?: string; + state?: string; + resource?: URL; +}): Promise<{ + authorizationUrl: URL; + codeVerifier: string; +}>; +/** + * Prepares token request parameters for an authorization code exchange. + * + * This is the default implementation used by fetchToken when the provider + * doesn't implement prepareTokenRequest. + * + * @param authorizationCode - The authorization code received from the authorization endpoint + * @param codeVerifier - The PKCE code verifier + * @param redirectUri - The redirect URI used in the authorization request + * @returns URLSearchParams for the authorization_code grant + */ +export declare function prepareAuthorizationCodeRequest(authorizationCode: string, codeVerifier: string, redirectUri: string | URL): URLSearchParams; +/** + * Exchanges an authorization code for an access token with the given server. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Falls back to appropriate defaults when server metadata is unavailable + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, auth code, etc. + * @returns Promise resolving to OAuth tokens + * @throws {Error} When token exchange fails or authentication is invalid + */ +export declare function exchangeAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }: { + metadata?: AuthorizationServerMetadata; + clientInformation: OAuthClientInformationMixed; + authorizationCode: string; + codeVerifier: string; + redirectUri: string | URL; + resource?: URL; + addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; + fetchFn?: FetchLike; +}): Promise; +/** + * Exchange a refresh token for an updated access token. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Preserves the original refresh token if a new one is not returned + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, refresh token, etc. + * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) + * @throws {Error} When token refresh fails or authentication is invalid + */ +export declare function refreshAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }: { + metadata?: AuthorizationServerMetadata; + clientInformation: OAuthClientInformationMixed; + refreshToken: string; + resource?: URL; + addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; + fetchFn?: FetchLike; +}): Promise; +/** + * Unified token fetching that works with any grant type via provider.prepareTokenRequest(). + * + * This function provides a single entry point for obtaining tokens regardless of the + * OAuth grant type. The provider's prepareTokenRequest() method determines which grant + * to use and supplies the grant-specific parameters. + * + * @param provider - OAuth client provider that implements prepareTokenRequest() + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration for the token request + * @returns Promise resolving to OAuth tokens + * @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails + * + * @example + * // Provider for client_credentials: + * class MyProvider implements OAuthClientProvider { + * prepareTokenRequest(scope) { + * const params = new URLSearchParams({ grant_type: 'client_credentials' }); + * if (scope) params.set('scope', scope); + * return params; + * } + * // ... other methods + * } + * + * const tokens = await fetchToken(provider, authServerUrl, { metadata }); + */ +export declare function fetchToken(provider: OAuthClientProvider, authorizationServerUrl: string | URL, { metadata, resource, authorizationCode, fetchFn }?: { + metadata?: AuthorizationServerMetadata; + resource?: URL; + /** Authorization code for the default authorization_code grant flow */ + authorizationCode?: string; + fetchFn?: FetchLike; +}): Promise; +/** + * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. + */ +export declare function registerClient(authorizationServerUrl: string | URL, { metadata, clientMetadata, fetchFn }: { + metadata?: AuthorizationServerMetadata; + clientMetadata: OAuthClientMetadata; + fetchFn?: FetchLike; +}): Promise; +export {}; +//# sourceMappingURL=auth.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.ts.map new file mode 100644 index 000000000..012c44018 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":"AAEA,OAAO,EACH,mBAAmB,EAEnB,2BAA2B,EAC3B,WAAW,EACX,aAAa,EACb,0BAA0B,EAC1B,8BAA8B,EAE9B,2BAA2B,EAE9B,MAAM,mBAAmB,CAAC;AAQ3B,OAAO,EAKH,UAAU,EAGb,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG,CAClC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,eAAe,EACvB,GAAG,EAAE,MAAM,GAAG,GAAG,EACjB,QAAQ,CAAC,EAAE,2BAA2B,KACrC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE1B;;;;;;GAMG;AACH,MAAM,WAAW,mBAAmB;IAChC;;;;OAIG;IACH,IAAI,WAAW,IAAI,MAAM,GAAG,GAAG,GAAG,SAAS,C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;;;;;;;;;;GAWG;AACH,wBAAsB,oBAAoB,CACtC,sBAAsB,EAAE,MAAM,GAAG,GAAG,EACpC,EACI,QAAQ,EACR,iBAAiB,EACjB,YAAY,EACZ,QAAQ,EACR,uBAAuB,EACvB,OAAO,EACV,EAAE;IACC,QAAQ,CAAC,EAAE,2BAA2B,CAAC;IACvC,iBAAiB,EAAE,2BAA2B,CAAC;IAC/C,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,GAAG,CAAC;IACf,uBAAuB,CAAC,EAAE,mBAAmB,CAAC,yBAAyB,CAAC,CAAC;IACzE,OAAO,CAAC,EAAE,SAAS,CAAC;CACvB,GACF,OAAO,CAAC,WAAW,CAAC,CAiBtB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,UAAU,CAC5B,QAAQ,EAAE,mBAAmB,EAC7B,sBAAsB,EAAE,MAAM,GAAG,GAAG,EACpC,EACI,QAAQ,EACR,QAAQ,EACR,iBAAiB,EACjB,OAAO,EACV,GAAE;IACC,QAAQ,CAAC,EAAE,2BAA2B,CAAC;IACvC,QAAQ,CAAC,EAAE,GAAG,CAAC;IACf,uEAAuE;IACvE,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,OAAO,CAAC,EAAE,SAAS,CAAC;CAClB,GACP,OAAO,CAAC,WAAW,CAAC,CA+BtB;AAED;;GAEG;AACH,wBAAsB,cAAc,CAChC,sBAAsB,EAAE,MAAM,GAAG,GAAG,EACpC,EACI,QAAQ,EACR,cAAc,EACd,OAAO,EACV,EAAE;IACC,QAAQ,CAAC,EAAE,2BAA2B,CAAC;IACvC,cAAc,EAAE,mBAAmB,CAAC;IACpC,OAAO,CAAC,EAAE,SAAS,CAAC;CACvB,GACF,OAAO,CAAC,0BAA0B,CAAC,CA0BrC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.js new file mode 100644 index 000000000..f89657ffd --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.js @@ -0,0 +1,848 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UnauthorizedError = void 0; +exports.selectClientAuthMethod = selectClientAuthMethod; +exports.parseErrorResponse = parseErrorResponse; +exports.auth = auth; +exports.isHttpsUrl = isHttpsUrl; +exports.selectResourceURL = selectResourceURL; +exports.extractWWWAuthenticateParams = extractWWWAuthenticateParams; +exports.extractResourceMetadataUrl = extractResourceMetadataUrl; +exports.discoverOAuthProtectedResourceMetadata = discoverOAuthProtectedResourceMetadata; +exports.discoverOAuthMetadata = discoverOAuthMetadata; +exports.buildDiscoveryUrls = buildDiscoveryUrls; +exports.discoverAuthorizationServerMetadata = discoverAuthorizationServerMetadata; +exports.startAuthorization = startAuthorization; +exports.prepareAuthorizationCodeRequest = prepareAuthorizationCodeRequest; +exports.exchangeAuthorization = exchangeAuthorization; +exports.refreshAuthorization = refreshAuthorization; +exports.fetchToken = fetchToken; +exports.registerClient = registerClient; +const pkce_challenge_1 = __importDefault(require("pkce-challenge")); +const types_js_1 = require("../types.js"); +const auth_js_1 = require("../shared/auth.js"); +const auth_js_2 = require("../shared/auth.js"); +const auth_utils_js_1 = require("../shared/auth-utils.js"); +const errors_js_1 = require("../server/auth/errors.js"); +class UnauthorizedError extends Error { + constructor(message) { + super(message ?? 'Unauthorized'); + } +} +exports.UnauthorizedError = UnauthorizedError; +function isClientAuthMethod(method) { + return ['client_secret_basic', 'client_secret_post', 'none'].includes(method); +} +const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code'; +const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256'; +/** + * Determines the best client authentication method to use based on server support and client configuration. + * + * Priority order (highest to lowest): + * 1. client_secret_basic (if client secret is available) + * 2. client_secret_post (if client secret is available) + * 3. none (for public clients) + * + * @param clientInformation - OAuth client information containing credentials + * @param supportedMethods - Authentication methods supported by the authorization server + * @returns The selected authentication method + */ +function selectClientAuthMethod(clientInformation, supportedMethods) { + const hasClientSecret = clientInformation.client_secret !== undefined; + // If server doesn't specify supported methods, use RFC 6749 defaults + if (supportedMethods.length === 0) { + return hasClientSecret ? 'client_secret_post' : 'none'; + } + // Prefer the method returned by the server during client registration if valid and supported + if ('token_endpoint_auth_method' in clientInformation && + clientInformation.token_endpoint_auth_method && + isClientAuthMethod(clientInformation.token_endpoint_auth_method) && + supportedMethods.includes(clientInformation.token_endpoint_auth_method)) { + return clientInformation.token_endpoint_auth_method; + } + // Try methods in priority order (most secure first) + if (hasClientSecret && supportedMethods.includes('client_secret_basic')) { + return 'client_secret_basic'; + } + if (hasClientSecret && supportedMethods.includes('client_secret_post')) { + return 'client_secret_post'; + } + if (supportedMethods.includes('none')) { + return 'none'; + } + // Fallback: use what we have + return hasClientSecret ? 'client_secret_post' : 'none'; +} +/** + * Applies client authentication to the request based on the specified method. + * + * Implements OAuth 2.1 client authentication methods: + * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1) + * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1) + * - none: Public client authentication (RFC 6749 Section 2.1) + * + * @param method - The authentication method to use + * @param clientInformation - OAuth client information containing credentials + * @param headers - HTTP headers object to modify + * @param params - URL search parameters to modify + * @throws {Error} When required credentials are missing + */ +function applyClientAuthentication(method, clientInformation, headers, params) { + const { client_id, client_secret } = clientInformation; + switch (method) { + case 'client_secret_basic': + applyBasicAuth(client_id, client_secret, headers); + return; + case 'client_secret_post': + applyPostAuth(client_id, client_secret, params); + return; + case 'none': + applyPublicAuth(client_id, params); + return; + default: + throw new Error(`Unsupported client authentication method: ${method}`); + } +} +/** + * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1) + */ +function applyBasicAuth(clientId, clientSecret, headers) { + if (!clientSecret) { + throw new Error('client_secret_basic authentication requires a client_secret'); + } + const credentials = btoa(`${clientId}:${clientSecret}`); + headers.set('Authorization', `Basic ${credentials}`); +} +/** + * Applies POST body authentication (RFC 6749 Section 2.3.1) + */ +function applyPostAuth(clientId, clientSecret, params) { + params.set('client_id', clientId); + if (clientSecret) { + params.set('client_secret', clientSecret); + } +} +/** + * Applies public client authentication (RFC 6749 Section 2.1) + */ +function applyPublicAuth(clientId, params) { + params.set('client_id', clientId); +} +/** + * Parses an OAuth error response from a string or Response object. + * + * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec + * and an instance of the appropriate OAuthError subclass will be returned. + * If parsing fails, it falls back to a generic ServerError that includes + * the response status (if available) and original content. + * + * @param input - A Response object or string containing the error response + * @returns A Promise that resolves to an OAuthError instance + */ +async function parseErrorResponse(input) { + const statusCode = input instanceof Response ? input.status : undefined; + const body = input instanceof Response ? await input.text() : input; + try { + const result = auth_js_1.OAuthErrorResponseSchema.parse(JSON.parse(body)); + const { error, error_description, error_uri } = result; + const errorClass = errors_js_1.OAUTH_ERRORS[error] || errors_js_1.ServerError; + return new errorClass(error_description || '', error_uri); + } + catch (error) { + // Not a valid OAuth error response, but try to inform the user of the raw data anyway + const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`; + return new errors_js_1.ServerError(errorMessage); + } +} +/** + * Orchestrates the full auth flow with a server. + * + * This can be used as a single entry point for all authorization functionality, + * instead of linking together the other lower-level functions in this module. + */ +async function auth(provider, options) { + try { + return await authInternal(provider, options); + } + catch (error) { + // Handle recoverable error types by invalidating credentials and retrying + if (error instanceof errors_js_1.InvalidClientError || error instanceof errors_js_1.UnauthorizedClientError) { + await provider.invalidateCredentials?.('all'); + return await authInternal(provider, options); + } + else if (error instanceof errors_js_1.InvalidGrantError) { + await provider.invalidateCredentials?.('tokens'); + return await authInternal(provider, options); + } + // Throw otherwise + throw error; + } +} +async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) { + let resourceMetadata; + let authorizationServerUrl; + try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn); + if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { + authorizationServerUrl = resourceMetadata.authorization_servers[0]; + } + } + catch { + // Ignore errors and fall back to /.well-known/oauth-authorization-server + } + /** + * If we don't get a valid authorization server metadata from protected resource metadata, + * fallback to the legacy MCP spec's implementation (version 2025-03-26): MCP server base URL acts as the Authorization server. + */ + if (!authorizationServerUrl) { + authorizationServerUrl = new URL('/', serverUrl); + } + const resource = await selectResourceURL(serverUrl, provider, resourceMetadata); + const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { + fetchFn + }); + // Handle client registration if needed + let clientInformation = await Promise.resolve(provider.clientInformation()); + if (!clientInformation) { + if (authorizationCode !== undefined) { + throw new Error('Existing OAuth client information is required when exchanging an authorization code'); + } + const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true; + const clientMetadataUrl = provider.clientMetadataUrl; + if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) { + throw new errors_js_1.InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`); + } + const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl; + if (shouldUseUrlBasedClientId) { + // SEP-991: URL-based Client IDs + clientInformation = { + client_id: clientMetadataUrl + }; + await provider.saveClientInformation?.(clientInformation); + } + else { + // Fallback to dynamic registration + if (!provider.saveClientInformation) { + throw new Error('OAuth client information must be saveable for dynamic registration'); + } + const fullInformation = await registerClient(authorizationServerUrl, { + metadata, + clientMetadata: provider.clientMetadata, + fetchFn + }); + await provider.saveClientInformation(fullInformation); + clientInformation = fullInformation; + } + } + // Non-interactive flows (e.g., client_credentials, jwt-bearer) don't need a redirect URL + const nonInteractiveFlow = !provider.redirectUrl; + // Exchange authorization code for tokens, or fetch tokens directly for non-interactive flows + if (authorizationCode !== undefined || nonInteractiveFlow) { + const tokens = await fetchToken(provider, authorizationServerUrl, { + metadata, + resource, + authorizationCode, + fetchFn + }); + await provider.saveTokens(tokens); + return 'AUTHORIZED'; + } + const tokens = await provider.tokens(); + // Handle token refresh or new authorization + if (tokens?.refresh_token) { + try { + // Attempt to refresh the token + const newTokens = await refreshAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + refreshToken: tokens.refresh_token, + resource, + addClientAuthentication: provider.addClientAuthentication, + fetchFn + }); + await provider.saveTokens(newTokens); + return 'AUTHORIZED'; + } + catch (error) { + // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry. + if (!(error instanceof errors_js_1.OAuthError) || error instanceof errors_js_1.ServerError) { + // Could not refresh OAuth tokens + } + else { + // Refresh failed for another reason, re-throw + throw error; + } + } + } + const state = provider.state ? await provider.state() : undefined; + // Start new authorization flow + const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + state, + redirectUrl: provider.redirectUrl, + scope: scope || resourceMetadata?.scopes_supported?.join(' ') || provider.clientMetadata.scope, + resource + }); + await provider.saveCodeVerifier(codeVerifier); + await provider.redirectToAuthorization(authorizationUrl); + return 'REDIRECT'; +} +/** + * SEP-991: URL-based Client IDs + * Validate that the client_id is a valid URL with https scheme + */ +function isHttpsUrl(value) { + if (!value) + return false; + try { + const url = new URL(value); + return url.protocol === 'https:' && url.pathname !== '/'; + } + catch { + return false; + } +} +async function selectResourceURL(serverUrl, provider, resourceMetadata) { + const defaultResource = (0, auth_utils_js_1.resourceUrlFromServerUrl)(serverUrl); + // If provider has custom validation, delegate to it + if (provider.validateResourceURL) { + return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource); + } + // Only include resource parameter when Protected Resource Metadata is present + if (!resourceMetadata) { + return undefined; + } + // Validate that the metadata's resource is compatible with our request + if (!(0, auth_utils_js_1.checkResourceAllowed)({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) { + throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); + } + // Prefer the resource from metadata since it's what the server is telling us to request + return new URL(resourceMetadata.resource); +} +/** + * Extract resource_metadata, scope, and error from WWW-Authenticate header. + */ +function extractWWWAuthenticateParams(res) { + const authenticateHeader = res.headers.get('WWW-Authenticate'); + if (!authenticateHeader) { + return {}; + } + const [type, scheme] = authenticateHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !scheme) { + return {}; + } + const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined; + let resourceMetadataUrl; + if (resourceMetadataMatch) { + try { + resourceMetadataUrl = new URL(resourceMetadataMatch); + } + catch { + // Ignore invalid URL + } + } + const scope = extractFieldFromWwwAuth(res, 'scope') || undefined; + const error = extractFieldFromWwwAuth(res, 'error') || undefined; + return { + resourceMetadataUrl, + scope, + error + }; +} +/** + * Extracts a specific field's value from the WWW-Authenticate header string. + * + * @param response The HTTP response object containing the headers. + * @param fieldName The name of the field to extract (e.g., "realm", "nonce"). + * @returns The field value + */ +function extractFieldFromWwwAuth(response, fieldName) { + const wwwAuthHeader = response.headers.get('WWW-Authenticate'); + if (!wwwAuthHeader) { + return null; + } + const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`); + const match = wwwAuthHeader.match(pattern); + if (match) { + // Pattern matches: field_name="value" or field_name=value (unquoted) + return match[1] || match[2]; + } + return null; +} +/** + * Extract resource_metadata from response header. + * @deprecated Use `extractWWWAuthenticateParams` instead. + */ +function extractResourceMetadataUrl(res) { + const authenticateHeader = res.headers.get('WWW-Authenticate'); + if (!authenticateHeader) { + return undefined; + } + const [type, scheme] = authenticateHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !scheme) { + return undefined; + } + const regex = /resource_metadata="([^"]*)"/; + const match = regex.exec(authenticateHeader); + if (!match) { + return undefined; + } + try { + return new URL(match[1]); + } + catch { + return undefined; + } +} +/** + * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + */ +async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) { + const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, { + protocolVersion: opts?.protocolVersion, + metadataUrl: opts?.resourceMetadataUrl + }); + if (!response || response.status === 404) { + await response?.body?.cancel(); + throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); + } + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); + } + return auth_js_2.OAuthProtectedResourceMetadataSchema.parse(await response.json()); +} +/** + * Helper function to handle fetch with CORS retry logic + */ +async function fetchWithCorsRetry(url, headers, fetchFn = fetch) { + try { + return await fetchFn(url, { headers }); + } + catch (error) { + if (error instanceof TypeError) { + if (headers) { + // CORS errors come back as TypeError, retry without headers + return fetchWithCorsRetry(url, undefined, fetchFn); + } + else { + // We're getting CORS errors on retry too, return undefined + return undefined; + } + } + throw error; + } +} +/** + * Constructs the well-known path for auth-related metadata discovery + */ +function buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) { + // Strip trailing slash from pathname to avoid double slashes + if (pathname.endsWith('/')) { + pathname = pathname.slice(0, -1); + } + return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; +} +/** + * Tries to discover OAuth metadata at a specific URL + */ +async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) { + const headers = { + 'MCP-Protocol-Version': protocolVersion + }; + return await fetchWithCorsRetry(url, headers, fetchFn); +} +/** + * Determines if fallback to root discovery should be attempted + */ +function shouldAttemptFallback(response, pathname) { + return !response || (response.status >= 400 && response.status < 500 && pathname !== '/'); +} +/** + * Generic function for discovering OAuth metadata with fallback support + */ +async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) { + const issuer = new URL(serverUrl); + const protocolVersion = opts?.protocolVersion ?? types_js_1.LATEST_PROTOCOL_VERSION; + let url; + if (opts?.metadataUrl) { + url = new URL(opts.metadataUrl); + } + else { + // Try path-aware discovery first + const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); + url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer); + url.search = issuer.search; + } + let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn); + // If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery + if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) { + const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer); + response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn); + } + return response; +} +/** + * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + * + * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. + */ +async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) { + if (typeof issuer === 'string') { + issuer = new URL(issuer); + } + if (!authorizationServerUrl) { + authorizationServerUrl = issuer; + } + if (typeof authorizationServerUrl === 'string') { + authorizationServerUrl = new URL(authorizationServerUrl); + } + protocolVersion ?? (protocolVersion = types_js_1.LATEST_PROTOCOL_VERSION); + const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, { + protocolVersion, + metadataServerUrl: authorizationServerUrl + }); + if (!response || response.status === 404) { + await response?.body?.cancel(); + return undefined; + } + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`); + } + return auth_js_2.OAuthMetadataSchema.parse(await response.json()); +} +/** + * Builds a list of discovery URLs to try for authorization server metadata. + * URLs are returned in priority order: + * 1. OAuth metadata at the given URL + * 2. OIDC metadata endpoints at the given URL + */ +function buildDiscoveryUrls(authorizationServerUrl) { + const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl; + const hasPath = url.pathname !== '/'; + const urlsToTry = []; + if (!hasPath) { + // Root path: https://example.com/.well-known/oauth-authorization-server + urlsToTry.push({ + url: new URL('/.well-known/oauth-authorization-server', url.origin), + type: 'oauth' + }); + // OIDC: https://example.com/.well-known/openid-configuration + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration`, url.origin), + type: 'oidc' + }); + return urlsToTry; + } + // Strip trailing slash from pathname to avoid double slashes + let pathname = url.pathname; + if (pathname.endsWith('/')) { + pathname = pathname.slice(0, -1); + } + // 1. OAuth metadata at the given URL + // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1 + urlsToTry.push({ + url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin), + type: 'oauth' + }); + // 2. OIDC metadata endpoints + // RFC 8414 style: Insert /.well-known/openid-configuration before the path + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin), + type: 'oidc' + }); + // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path + urlsToTry.push({ + url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin), + type: 'oidc' + }); + return urlsToTry; +} +/** + * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata + * and OpenID Connect Discovery 1.0 specifications. + * + * This function implements a fallback strategy for authorization server discovery: + * 1. Attempts RFC 8414 OAuth metadata discovery first + * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery + * + * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's + * protected resource metadata, or the MCP server's URL if the + * metadata was not found. + * @param options - Configuration options + * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch + * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION + * @returns Promise resolving to authorization server metadata, or undefined if discovery fails + */ +async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = types_js_1.LATEST_PROTOCOL_VERSION } = {}) { + const headers = { + 'MCP-Protocol-Version': protocolVersion, + Accept: 'application/json' + }; + // Get the list of URLs to try + const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); + // Try each URL in order + for (const { url: endpointUrl, type } of urlsToTry) { + const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); + if (!response) { + /** + * CORS error occurred - don't throw as the endpoint may not allow CORS, + * continue trying other possible endpoints + */ + continue; + } + if (!response.ok) { + await response.body?.cancel(); + // Continue looking for any 4xx response code. + if (response.status >= 400 && response.status < 500) { + continue; // Try next URL + } + throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`); + } + // Parse and validate based on type + if (type === 'oauth') { + return auth_js_2.OAuthMetadataSchema.parse(await response.json()); + } + else { + return auth_js_1.OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); + } + } + return undefined; +} +/** + * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. + */ +async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) { + let authorizationUrl; + if (metadata) { + authorizationUrl = new URL(metadata.authorization_endpoint); + if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) { + throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); + } + if (metadata.code_challenge_methods_supported && + !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) { + throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); + } + } + else { + authorizationUrl = new URL('/authorize', authorizationServerUrl); + } + // Generate PKCE challenge + const challenge = await (0, pkce_challenge_1.default)(); + const codeVerifier = challenge.code_verifier; + const codeChallenge = challenge.code_challenge; + authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE); + authorizationUrl.searchParams.set('client_id', clientInformation.client_id); + authorizationUrl.searchParams.set('code_challenge', codeChallenge); + authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD); + authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl)); + if (state) { + authorizationUrl.searchParams.set('state', state); + } + if (scope) { + authorizationUrl.searchParams.set('scope', scope); + } + if (scope?.includes('offline_access')) { + // if the request includes the OIDC-only "offline_access" scope, + // we need to set the prompt to "consent" to ensure the user is prompted to grant offline access + // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess + authorizationUrl.searchParams.append('prompt', 'consent'); + } + if (resource) { + authorizationUrl.searchParams.set('resource', resource.href); + } + return { authorizationUrl, codeVerifier }; +} +/** + * Prepares token request parameters for an authorization code exchange. + * + * This is the default implementation used by fetchToken when the provider + * doesn't implement prepareTokenRequest. + * + * @param authorizationCode - The authorization code received from the authorization endpoint + * @param codeVerifier - The PKCE code verifier + * @param redirectUri - The redirect URI used in the authorization request + * @returns URLSearchParams for the authorization_code grant + */ +function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) { + return new URLSearchParams({ + grant_type: 'authorization_code', + code: authorizationCode, + code_verifier: codeVerifier, + redirect_uri: String(redirectUri) + }); +} +/** + * Internal helper to execute a token request with the given parameters. + * Used by exchangeAuthorization, refreshAuthorization, and fetchToken. + */ +async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) { + const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl); + const headers = new Headers({ + 'Content-Type': 'application/x-www-form-urlencoded', + Accept: 'application/json' + }); + if (resource) { + tokenRequestParams.set('resource', resource.href); + } + if (addClientAuthentication) { + await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata); + } + else if (clientInformation) { + const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? []; + const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); + applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams); + } + const response = await (fetchFn ?? fetch)(tokenUrl, { + method: 'POST', + headers, + body: tokenRequestParams + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return auth_js_2.OAuthTokensSchema.parse(await response.json()); +} +/** + * Exchanges an authorization code for an access token with the given server. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Falls back to appropriate defaults when server metadata is unavailable + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, auth code, etc. + * @returns Promise resolving to OAuth tokens + * @throws {Error} When token exchange fails or authentication is invalid + */ +async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) { + const tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri); + return executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation, + addClientAuthentication, + resource, + fetchFn + }); +} +/** + * Exchange a refresh token for an updated access token. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Preserves the original refresh token if a new one is not returned + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, refresh token, etc. + * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) + * @throws {Error} When token refresh fails or authentication is invalid + */ +async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) { + const tokenRequestParams = new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: refreshToken + }); + const tokens = await executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation, + addClientAuthentication, + resource, + fetchFn + }); + // Preserve original refresh token if server didn't return a new one + return { refresh_token: refreshToken, ...tokens }; +} +/** + * Unified token fetching that works with any grant type via provider.prepareTokenRequest(). + * + * This function provides a single entry point for obtaining tokens regardless of the + * OAuth grant type. The provider's prepareTokenRequest() method determines which grant + * to use and supplies the grant-specific parameters. + * + * @param provider - OAuth client provider that implements prepareTokenRequest() + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration for the token request + * @returns Promise resolving to OAuth tokens + * @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails + * + * @example + * // Provider for client_credentials: + * class MyProvider implements OAuthClientProvider { + * prepareTokenRequest(scope) { + * const params = new URLSearchParams({ grant_type: 'client_credentials' }); + * if (scope) params.set('scope', scope); + * return params; + * } + * // ... other methods + * } + * + * const tokens = await fetchToken(provider, authServerUrl, { metadata }); + */ +async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) { + const scope = provider.clientMetadata.scope; + // Use provider's prepareTokenRequest if available, otherwise fall back to authorization_code + let tokenRequestParams; + if (provider.prepareTokenRequest) { + tokenRequestParams = await provider.prepareTokenRequest(scope); + } + // Default to authorization_code grant if no custom prepareTokenRequest + if (!tokenRequestParams) { + if (!authorizationCode) { + throw new Error('Either provider.prepareTokenRequest() or authorizationCode is required'); + } + if (!provider.redirectUrl) { + throw new Error('redirectUrl is required for authorization_code flow'); + } + const codeVerifier = await provider.codeVerifier(); + tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl); + } + const clientInformation = await provider.clientInformation(); + return executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation: clientInformation ?? undefined, + addClientAuthentication: provider.addClientAuthentication, + resource, + fetchFn + }); +} +/** + * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. + */ +async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) { + let registrationUrl; + if (metadata) { + if (!metadata.registration_endpoint) { + throw new Error('Incompatible auth server: does not support dynamic client registration'); + } + registrationUrl = new URL(metadata.registration_endpoint); + } + else { + registrationUrl = new URL('/register', authorizationServerUrl); + } + const response = await (fetchFn ?? fetch)(registrationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(clientMetadata) + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return auth_js_2.OAuthClientInformationFullSchema.parse(await response.json()); +} +//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.js.map new file mode 100644 index 000000000..dab4f2aff --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":";;;;;;AA8NA,wDAiCC;AA+ED,gDAcC;AAQD,oBAyBC;AAsJD,gCAQC;AAED,8CAuBC;AAKD,oEA8BC;AA8BD,gEAsBC;AAQD,wFAoBC;AAgGD,sDAsCC;AAQD,gDAgDC;AAkBD,kFAkDC;AAKD,gDAmEC;AAaD,0EAWC;AAoED,sDAgCC;AAcD,oDAkCC;AA4BD,gCA8CC;AAKD,wCAqCC;AAjxCD,oEAA2C;AAC3C,0CAAsD;AACtD,+CAW2B;AAC3B,+CAK2B;AAC3B,2DAAyF;AACzF,wDAQkC;AAsKlC,MAAa,iBAAkB,SAAQ,KAAK;IACxC,YAAY,OAAgB;QACxB,KAAK,CAAC,OAAO,IAAI,cAAc,CAAC,CAAC;IACrC,CAAC;CACJ;AAJD,8CAIC;AAID,SAAS,kBAAkB,CAAC,MAAc;IACtC,OAAO,CAAC,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAClF,CAAC;AAED,MAAM,gCAAgC,GAAG,MAAM,CAAC;AAChD,MAAM,mCAAmC,GAAG,MAAM,CAAC;AAEnD;;;;;;;;;;;GAWG;AACH,SAAgB,sBAAsB,CAAC,iBAA8C,EAAE,gBAA0B;IAC7G,MAAM,eAAe,GAAG,iBAAiB,CAAC,aAAa,KAAK,SAAS,CAAC;IAEtE,qEAAqE;IACrE,IAAI,gBAAgB,CAAC,MAAM,KAAK,CAA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,CAAC,CAAC;IAC9D,CAAC;SAAM,CAAC;QACJ,eAAe,GAAG,IAAI,GAAG,CAAC,WAAW,EAAE,sBAAsB,CAAC,CAAC;IACnE,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,IAAI,KAAK,CAAC,CAAC,eAAe,EAAE;QACvD,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACL,cAAc,EAAE,kBAAkB;SACrC;QACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC;KACvC,CAAC,CAAC;IAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACf,MAAM,MAAM,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,0CAAgC,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;AACzE,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.d.ts new file mode 100644 index 000000000..efc018654 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.d.ts @@ -0,0 +1,588 @@ +import { Protocol, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; +import type { Transport } from '../shared/transport.js'; +import { type CallToolRequest, CallToolResultSchema, type ClientCapabilities, type ClientNotification, type ClientRequest, type ClientResult, type CompatibilityCallToolResultSchema, type CompleteRequest, type GetPromptRequest, type Implementation, type ListPromptsRequest, type ListResourcesRequest, type ListResourceTemplatesRequest, type ListToolsRequest, type LoggingLevel, type ReadResourceRequest, type ServerCapabilities, type SubscribeRequest, type UnsubscribeRequest, type ListChangedHandlers, type Request, type Notification, type Result } from '../types.js'; +import type { jsonSchemaValidator } from '../validation/types.js'; +import { AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js'; +import type { RequestHandlerExtra } from '../shared/protocol.js'; +import { ExperimentalClientTasks } from '../experimental/tasks/client.js'; +/** + * Determines which elicitation modes are supported based on declared client capabilities. + * + * According to the spec: + * - An empty elicitation capability object defaults to form mode support (backwards compatibility) + * - URL mode is only supported if explicitly declared + * + * @param capabilities - The client's elicitation capabilities + * @returns An object indicating which modes are supported + */ +export declare function getSupportedElicitationModes(capabilities: ClientCapabilities['elicitation']): { + supportsFormMode: boolean; + supportsUrlMode: boolean; +}; +export type ClientOptions = ProtocolOptions & { + /** + * Capabilities to advertise as being supported by this client. + */ + capabilities?: ClientCapabilities; + /** + * JSON Schema validator for tool output validation. + * + * The validator is used to validate structured content returned by tools + * against their declared output schemas. + * + * @default AjvJsonSchemaValidator + * + * @example + * ```typescript + * // ajv + * const client = new Client( + * { name: 'my-client', version: '1.0.0' }, + * { + * capabilities: {}, + * jsonSchemaValidator: new AjvJsonSchemaValidator() + * } + * ); + * + * // @cfworker/json-schema + * const client = new Client( + * { name: 'my-client', version: '1.0.0' }, + * { + * capabilities: {}, + * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() + * } + * ); + * ``` + */ + jsonSchemaValidator?: jsonSchemaValidator; + /** + * Configure handlers for list changed notifications (tools, prompts, resources). + * + * @example + * ```typescript + * const client = new Client( + * { name: 'my-client', version: '1.0.0' }, + * { + * listChanged: { + * tools: { + * onChanged: (error, tools) => { + * if (error) { + * console.error('Failed to refresh tools:', error); + * return; + * } + * console.log('Tools updated:', tools); + * } + * }, + * prompts: { + * onChanged: (error, prompts) => console.log('Prompts updated:', prompts) + * } + * } + * } + * ); + * ``` + */ + listChanged?: ListChangedHandlers; +}; +/** + * An MCP client on top of a pluggable transport. + * + * The client will automatically begin the initialization flow with the server when connect() is called. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed client + * const client = new Client({ + * name: "CustomClient", + * version: "1.0.0" + * }) + * ``` + */ +export declare class Client extends Protocol { + private _clientInfo; + private _serverCapabilities?; + private _serverVersion?; + private _capabilities; + private _instructions?; + private _jsonSchemaValidator; + private _cachedToolOutputValidators; + private _cachedKnownTaskTools; + private _cachedRequiredTaskTools; + private _experimental?; + private _listChangedDebounceTimers; + private _pendingListChangedConfig?; + /** + * Initializes this client with the given name and version information. + */ + constructor(_clientInfo: Implementation, options?: ClientOptions); + /** + * Set up handlers for list changed notifications based on config and server capabilities. + * This should only be called after initialization when server capabilities are known. + * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability. + * @internal + */ + private _setupListChangedHandlers; + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental(): { + tasks: ExperimentalClientTasks; + }; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities: ClientCapabilities): void; + /** + * Override request handler registration to enforce client-side validation for elicitation. + */ + setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => ClientResult | ResultT | Promise): void; + protected assertCapability(capability: keyof ServerCapabilities, method: string): void; + connect(transport: Transport, options?: RequestOptions): Promise; + /** + * After initialization has completed, this will be populated with the server's reported capabilities. + */ + getServerCapabilities(): ServerCapabilities | undefined; + /** + * After initialization has completed, this will be populated with information about the server's name and version. + */ + getServerVersion(): Implementation | undefined; + /** + * After initialization has completed, this may be populated with information about the server's instructions. + */ + getInstructions(): string | undefined; + protected assertCapabilityForMethod(method: RequestT['method']): void; + protected assertNotificationCapability(method: NotificationT['method']): void; + protected assertRequestHandlerCapability(method: string): void; + protected assertTaskCapability(method: string): void; + protected assertTaskHandlerCapability(method: string): void; + ping(options?: RequestOptions): Promise<{ + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + complete(params: CompleteRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + completion: { + [x: string]: unknown; + values: string[]; + total?: number | undefined; + hasMore?: boolean | undefined; + }; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + setLoggingLevel(level: LoggingLevel, options?: RequestOptions): Promise<{ + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + getPrompt(params: GetPromptRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + messages: { + role: "user" | "assistant"; + content: { + type: "text"; + text: string; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + type: "resource"; + resource: { + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + }; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + uri: string; + name: string; + type: "resource_link"; + description?: string | undefined; + mimeType?: string | undefined; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + theme?: "light" | "dark" | undefined; + }[] | undefined; + title?: string | undefined; + }; + }[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + description?: string | undefined; + }>; + listPrompts(params?: ListPromptsRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + prompts: { + name: string; + description?: string | undefined; + arguments?: { + name: string; + description?: string | undefined; + required?: boolean | undefined; + }[] | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + theme?: "light" | "dark" | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + nextCursor?: string | undefined; + }>; + listResources(params?: ListResourcesRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + resources: { + uri: string; + name: string; + description?: string | undefined; + mimeType?: string | undefined; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + theme?: "light" | "dark" | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + nextCursor?: string | undefined; + }>; + listResourceTemplates(params?: ListResourceTemplatesRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + resourceTemplates: { + uriTemplate: string; + name: string; + description?: string | undefined; + mimeType?: string | undefined; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + theme?: "light" | "dark" | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + nextCursor?: string | undefined; + }>; + readResource(params: ReadResourceRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + contents: ({ + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + })[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + subscribeResource(params: SubscribeRequest['params'], options?: RequestOptions): Promise<{ + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + unsubscribeResource(params: UnsubscribeRequest['params'], options?: RequestOptions): Promise<{ + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + /** + * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema. + * + * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead. + */ + callTool(params: CallToolRequest['params'], resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<{ + [x: string]: unknown; + content: ({ + type: "text"; + text: string; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + type: "resource"; + resource: { + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + }; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + uri: string; + name: string; + type: "resource_link"; + description?: string | undefined; + mimeType?: string | undefined; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + theme?: "light" | "dark" | undefined; + }[] | undefined; + title?: string | undefined; + })[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + structuredContent?: Record | undefined; + isError?: boolean | undefined; + } | { + [x: string]: unknown; + toolResult: unknown; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + private isToolTask; + /** + * Check if a tool requires task-based execution. + * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'. + */ + private isToolTaskRequired; + /** + * Cache validators for tool output schemas. + * Called after listTools() to pre-compile validators for better performance. + */ + private cacheToolMetadata; + /** + * Get cached validator for a tool + */ + private getToolOutputValidator; + listTools(params?: ListToolsRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + tools: { + inputSchema: { + [x: string]: unknown; + type: "object"; + properties?: Record | undefined; + required?: string[] | undefined; + }; + name: string; + description?: string | undefined; + outputSchema?: { + [x: string]: unknown; + type: "object"; + properties?: Record | undefined; + required?: string[] | undefined; + } | undefined; + annotations?: { + title?: string | undefined; + readOnlyHint?: boolean | undefined; + destructiveHint?: boolean | undefined; + idempotentHint?: boolean | undefined; + openWorldHint?: boolean | undefined; + } | undefined; + execution?: { + taskSupport?: "optional" | "required" | "forbidden" | undefined; + } | undefined; + _meta?: Record | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + theme?: "light" | "dark" | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + nextCursor?: string | undefined; + }>; + /** + * Set up a single list changed handler. + * @internal + */ + private _setupListChangedHandler; + sendRootsListChanged(): Promise; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.d.ts.map new file mode 100644 index 000000000..12d0abf3c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC/G,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAExD,OAAO,EACH,KAAK,eAAe,EACpB,oBAAoB,EACpB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,iCAAiC,EACtC,KAAK,eAAe,EAIpB,KAAK,gBAAgB,EAErB,KAAK,cAAc,EAGnB,KAAK,kBAAkB,EAEvB,KAAK,oBAAoB,EAEzB,KAAK,4BAA4B,EAEjC,KAAK,gBAAgB,EAErB,KAAK,YAAY,EAEjB,KAAK,mBAAmB,EAExB,KAAK,kBAAkB,EAEvB,KAAK,gBAAgB,EAErB,KAAK,kBAAkB,EAYvB,KAAK,mBAAmB,EACxB,KAAK,OAAO,EACZ,KAAK,YAAY,EACjB,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AAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;IAI9E,mBAAmB,CAAC,MAAM,EAAE,kBAAkB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;IAIxF;;;;OAIG;IACG,QAAQ,CACV,MAAM,EAAE,eAAe,CAAC,QAAQ,CAAC,EACjC,YAAY,GAAE,OAAO,oBAAoB,GAAG,OAAO,iCAAwD,EAC3G,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAkD5B,OAAO,CAAC,UAAU;IAQlB;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAI1B;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAuBzB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAIxB,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAS7E;;;OAGG;IACH,OAAO,CAAC,wBAAwB;IAwD1B,oBAAoB;CAG7B"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.js new file mode 100644 index 000000000..6ac1da14d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.js @@ -0,0 +1,629 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Client = void 0; +exports.getSupportedElicitationModes = getSupportedElicitationModes; +const protocol_js_1 = require("../shared/protocol.js"); +const types_js_1 = require("../types.js"); +const ajv_provider_js_1 = require("../validation/ajv-provider.js"); +const zod_compat_js_1 = require("../server/zod-compat.js"); +const client_js_1 = require("../experimental/tasks/client.js"); +const helpers_js_1 = require("../experimental/tasks/helpers.js"); +/** + * Elicitation default application helper. Applies defaults to the data based on the schema. + * + * @param schema - The schema to apply defaults to. + * @param data - The data to apply defaults to. + */ +function applyElicitationDefaults(schema, data) { + if (!schema || data === null || typeof data !== 'object') + return; + // Handle object properties + if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') { + const obj = data; + const props = schema.properties; + for (const key of Object.keys(props)) { + const propSchema = props[key]; + // If missing or explicitly undefined, apply default if present + if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) { + obj[key] = propSchema.default; + } + // Recurse into existing nested objects/arrays + if (obj[key] !== undefined) { + applyElicitationDefaults(propSchema, obj[key]); + } + } + } + if (Array.isArray(schema.anyOf)) { + for (const sub of schema.anyOf) { + // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults) + if (typeof sub !== 'boolean') { + applyElicitationDefaults(sub, data); + } + } + } + // Combine schemas + if (Array.isArray(schema.oneOf)) { + for (const sub of schema.oneOf) { + // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults) + if (typeof sub !== 'boolean') { + applyElicitationDefaults(sub, data); + } + } + } +} +/** + * Determines which elicitation modes are supported based on declared client capabilities. + * + * According to the spec: + * - An empty elicitation capability object defaults to form mode support (backwards compatibility) + * - URL mode is only supported if explicitly declared + * + * @param capabilities - The client's elicitation capabilities + * @returns An object indicating which modes are supported + */ +function getSupportedElicitationModes(capabilities) { + if (!capabilities) { + return { supportsFormMode: false, supportsUrlMode: false }; + } + const hasFormCapability = capabilities.form !== undefined; + const hasUrlCapability = capabilities.url !== undefined; + // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility) + const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability); + const supportsUrlMode = hasUrlCapability; + return { supportsFormMode, supportsUrlMode }; +} +/** + * An MCP client on top of a pluggable transport. + * + * The client will automatically begin the initialization flow with the server when connect() is called. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed client + * const client = new Client({ + * name: "CustomClient", + * version: "1.0.0" + * }) + * ``` + */ +class Client extends protocol_js_1.Protocol { + /** + * Initializes this client with the given name and version information. + */ + constructor(_clientInfo, options) { + super(options); + this._clientInfo = _clientInfo; + this._cachedToolOutputValidators = new Map(); + this._cachedKnownTaskTools = new Set(); + this._cachedRequiredTaskTools = new Set(); + this._listChangedDebounceTimers = new Map(); + this._capabilities = options?.capabilities ?? {}; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new ajv_provider_js_1.AjvJsonSchemaValidator(); + // Store list changed config for setup after connection (when we know server capabilities) + if (options?.listChanged) { + this._pendingListChangedConfig = options.listChanged; + } + } + /** + * Set up handlers for list changed notifications based on config and server capabilities. + * This should only be called after initialization when server capabilities are known. + * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability. + * @internal + */ + _setupListChangedHandlers(config) { + if (config.tools && this._serverCapabilities?.tools?.listChanged) { + this._setupListChangedHandler('tools', types_js_1.ToolListChangedNotificationSchema, config.tools, async () => { + const result = await this.listTools(); + return result.tools; + }); + } + if (config.prompts && this._serverCapabilities?.prompts?.listChanged) { + this._setupListChangedHandler('prompts', types_js_1.PromptListChangedNotificationSchema, config.prompts, async () => { + const result = await this.listPrompts(); + return result.prompts; + }); + } + if (config.resources && this._serverCapabilities?.resources?.listChanged) { + this._setupListChangedHandler('resources', types_js_1.ResourceListChangedNotificationSchema, config.resources, async () => { + const result = await this.listResources(); + return result.resources; + }); + } + } + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental() { + if (!this._experimental) { + this._experimental = { + tasks: new client_js_1.ExperimentalClientTasks(this) + }; + } + return this._experimental; + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error('Cannot register capabilities after connecting to transport'); + } + this._capabilities = (0, protocol_js_1.mergeCapabilities)(this._capabilities, capabilities); + } + /** + * Override request handler registration to enforce client-side validation for elicitation. + */ + setRequestHandler(requestSchema, handler) { + const shape = (0, zod_compat_js_1.getObjectShape)(requestSchema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + // Extract literal value using type-safe property access + let methodValue; + if ((0, zod_compat_js_1.isZ4Schema)(methodSchema)) { + const v4Schema = methodSchema; + const v4Def = v4Schema._zod?.def; + methodValue = v4Def?.value ?? v4Schema.value; + } + else { + const v3Schema = methodSchema; + const legacyDef = v3Schema._def; + methodValue = legacyDef?.value ?? v3Schema.value; + } + if (typeof methodValue !== 'string') { + throw new Error('Schema method literal must be a string'); + } + const method = methodValue; + if (method === 'elicitation/create') { + const wrappedHandler = async (request, extra) => { + const validatedRequest = (0, zod_compat_js_1.safeParse)(types_js_1.ElicitRequestSchema, request); + if (!validatedRequest.success) { + // Type guard: if success is false, error is guaranteed to exist + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + params.mode = params.mode ?? 'form'; + const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); + if (params.mode === 'form' && !supportsFormMode) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests'); + } + if (params.mode === 'url' && !supportsUrlMode) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests'); + } + const result = await Promise.resolve(handler(request, extra)); + // When task creation is requested, validate and return CreateTaskResult + if (params.task) { + const taskValidationResult = (0, zod_compat_js_1.safeParse)(types_js_1.CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error + ? taskValidationResult.error.message + : String(taskValidationResult.error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + // For non-task requests, validate against ElicitResultSchema + const validationResult = (0, zod_compat_js_1.safeParse)(types_js_1.ElicitResultSchema, result); + if (!validationResult.success) { + // Type guard: if success is false, error is guaranteed to exist + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`); + } + const validatedResult = validationResult.data; + const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined; + if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) { + if (this._capabilities.elicitation?.form?.applyDefaults) { + try { + applyElicitationDefaults(requestedSchema, validatedResult.content); + } + catch { + // gracefully ignore errors in default application + } + } + } + return validatedResult; + }; + // Install the wrapped handler + return super.setRequestHandler(requestSchema, wrappedHandler); + } + if (method === 'sampling/createMessage') { + const wrappedHandler = async (request, extra) => { + const validatedRequest = (0, zod_compat_js_1.safeParse)(types_js_1.CreateMessageRequestSchema, request); + if (!validatedRequest.success) { + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + const result = await Promise.resolve(handler(request, extra)); + // When task creation is requested, validate and return CreateTaskResult + if (params.task) { + const taskValidationResult = (0, zod_compat_js_1.safeParse)(types_js_1.CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error + ? taskValidationResult.error.message + : String(taskValidationResult.error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + // For non-task requests, validate against appropriate schema based on tools presence + const hasTools = params.tools || params.toolChoice; + const resultSchema = hasTools ? types_js_1.CreateMessageResultWithToolsSchema : types_js_1.CreateMessageResultSchema; + const validationResult = (0, zod_compat_js_1.safeParse)(resultSchema, result); + if (!validationResult.success) { + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`); + } + return validationResult.data; + }; + // Install the wrapped handler + return super.setRequestHandler(requestSchema, wrappedHandler); + } + // Other handlers use default behavior + return super.setRequestHandler(requestSchema, handler); + } + assertCapability(capability, method) { + if (!this._serverCapabilities?.[capability]) { + throw new Error(`Server does not support ${capability} (required for ${method})`); + } + } + async connect(transport, options) { + await super.connect(transport); + // When transport sessionId is already set this means we are trying to reconnect. + // In this case we don't need to initialize again. + if (transport.sessionId !== undefined) { + return; + } + try { + const result = await this.request({ + method: 'initialize', + params: { + protocolVersion: types_js_1.LATEST_PROTOCOL_VERSION, + capabilities: this._capabilities, + clientInfo: this._clientInfo + } + }, types_js_1.InitializeResultSchema, options); + if (result === undefined) { + throw new Error(`Server sent invalid initialize result: ${result}`); + } + if (!types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) { + throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); + } + this._serverCapabilities = result.capabilities; + this._serverVersion = result.serverInfo; + // HTTP transports must set the protocol version in each header after initialization. + if (transport.setProtocolVersion) { + transport.setProtocolVersion(result.protocolVersion); + } + this._instructions = result.instructions; + await this.notification({ + method: 'notifications/initialized' + }); + // Set up list changed handlers now that we know server capabilities + if (this._pendingListChangedConfig) { + this._setupListChangedHandlers(this._pendingListChangedConfig); + this._pendingListChangedConfig = undefined; + } + } + catch (error) { + // Disconnect if initialization fails. + void this.close(); + throw error; + } + } + /** + * After initialization has completed, this will be populated with the server's reported capabilities. + */ + getServerCapabilities() { + return this._serverCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the server's name and version. + */ + getServerVersion() { + return this._serverVersion; + } + /** + * After initialization has completed, this may be populated with information about the server's instructions. + */ + getInstructions() { + return this._instructions; + } + assertCapabilityForMethod(method) { + switch (method) { + case 'logging/setLevel': + if (!this._serverCapabilities?.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'prompts/get': + case 'prompts/list': + if (!this._serverCapabilities?.prompts) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case 'resources/list': + case 'resources/templates/list': + case 'resources/read': + case 'resources/subscribe': + case 'resources/unsubscribe': + if (!this._serverCapabilities?.resources) { + throw new Error(`Server does not support resources (required for ${method})`); + } + if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) { + throw new Error(`Server does not support resource subscriptions (required for ${method})`); + } + break; + case 'tools/call': + case 'tools/list': + if (!this._serverCapabilities?.tools) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case 'completion/complete': + if (!this._serverCapabilities?.completions) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case 'initialize': + // No specific capability required for initialize + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertNotificationCapability(method) { + switch (method) { + case 'notifications/roots/list_changed': + if (!this._capabilities.roots?.listChanged) { + throw new Error(`Client does not support roots list changed notifications (required for ${method})`); + } + break; + case 'notifications/initialized': + // No specific capability required for initialized + break; + case 'notifications/cancelled': + // Cancellation notifications are always allowed + break; + case 'notifications/progress': + // Progress notifications are always allowed + break; + } + } + assertRequestHandlerCapability(method) { + // Task handlers are registered in Protocol constructor before _capabilities is initialized + // Skip capability check for task methods during initialization + if (!this._capabilities) { + return; + } + switch (method) { + case 'sampling/createMessage': + if (!this._capabilities.sampling) { + throw new Error(`Client does not support sampling capability (required for ${method})`); + } + break; + case 'elicitation/create': + if (!this._capabilities.elicitation) { + throw new Error(`Client does not support elicitation capability (required for ${method})`); + } + break; + case 'roots/list': + if (!this._capabilities.roots) { + throw new Error(`Client does not support roots capability (required for ${method})`); + } + break; + case 'tasks/get': + case 'tasks/list': + case 'tasks/result': + case 'tasks/cancel': + if (!this._capabilities.tasks) { + throw new Error(`Client does not support tasks capability (required for ${method})`); + } + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertTaskCapability(method) { + (0, helpers_js_1.assertToolsCallTaskCapability)(this._serverCapabilities?.tasks?.requests, method, 'Server'); + } + assertTaskHandlerCapability(method) { + // Task handlers are registered in Protocol constructor before _capabilities is initialized + // Skip capability check for task methods during initialization + if (!this._capabilities) { + return; + } + (0, helpers_js_1.assertClientRequestTaskCapability)(this._capabilities.tasks?.requests, method, 'Client'); + } + async ping(options) { + return this.request({ method: 'ping' }, types_js_1.EmptyResultSchema, options); + } + async complete(params, options) { + return this.request({ method: 'completion/complete', params }, types_js_1.CompleteResultSchema, options); + } + async setLoggingLevel(level, options) { + return this.request({ method: 'logging/setLevel', params: { level } }, types_js_1.EmptyResultSchema, options); + } + async getPrompt(params, options) { + return this.request({ method: 'prompts/get', params }, types_js_1.GetPromptResultSchema, options); + } + async listPrompts(params, options) { + return this.request({ method: 'prompts/list', params }, types_js_1.ListPromptsResultSchema, options); + } + async listResources(params, options) { + return this.request({ method: 'resources/list', params }, types_js_1.ListResourcesResultSchema, options); + } + async listResourceTemplates(params, options) { + return this.request({ method: 'resources/templates/list', params }, types_js_1.ListResourceTemplatesResultSchema, options); + } + async readResource(params, options) { + return this.request({ method: 'resources/read', params }, types_js_1.ReadResourceResultSchema, options); + } + async subscribeResource(params, options) { + return this.request({ method: 'resources/subscribe', params }, types_js_1.EmptyResultSchema, options); + } + async unsubscribeResource(params, options) { + return this.request({ method: 'resources/unsubscribe', params }, types_js_1.EmptyResultSchema, options); + } + /** + * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema. + * + * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead. + */ + async callTool(params, resultSchema = types_js_1.CallToolResultSchema, options) { + // Guard: required-task tools need experimental API + if (this.isToolTaskRequired(params.name)) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`); + } + const result = await this.request({ method: 'tools/call', params }, resultSchema, options); + // Check if the tool has an outputSchema + const validator = this.getToolOutputValidator(params.name); + if (validator) { + // If tool has outputSchema, it MUST return structuredContent (unless it's an error) + if (!result.structuredContent && !result.isError) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`); + } + // Only validate structured content if present (not when there's an error) + if (result.structuredContent) { + try { + // Validate the structured content against the schema + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`); + } + } + catch (error) { + if (error instanceof types_js_1.McpError) { + throw error; + } + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`); + } + } + } + return result; + } + isToolTask(toolName) { + if (!this._serverCapabilities?.tasks?.requests?.tools?.call) { + return false; + } + return this._cachedKnownTaskTools.has(toolName); + } + /** + * Check if a tool requires task-based execution. + * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'. + */ + isToolTaskRequired(toolName) { + return this._cachedRequiredTaskTools.has(toolName); + } + /** + * Cache validators for tool output schemas. + * Called after listTools() to pre-compile validators for better performance. + */ + cacheToolMetadata(tools) { + this._cachedToolOutputValidators.clear(); + this._cachedKnownTaskTools.clear(); + this._cachedRequiredTaskTools.clear(); + for (const tool of tools) { + // If the tool has an outputSchema, create and cache the validator + if (tool.outputSchema) { + const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema); + this._cachedToolOutputValidators.set(tool.name, toolValidator); + } + // If the tool supports task-based execution, cache that information + const taskSupport = tool.execution?.taskSupport; + if (taskSupport === 'required' || taskSupport === 'optional') { + this._cachedKnownTaskTools.add(tool.name); + } + if (taskSupport === 'required') { + this._cachedRequiredTaskTools.add(tool.name); + } + } + } + /** + * Get cached validator for a tool + */ + getToolOutputValidator(toolName) { + return this._cachedToolOutputValidators.get(toolName); + } + async listTools(params, options) { + const result = await this.request({ method: 'tools/list', params }, types_js_1.ListToolsResultSchema, options); + // Cache the tools and their output schemas for future validation + this.cacheToolMetadata(result.tools); + return result; + } + /** + * Set up a single list changed handler. + * @internal + */ + _setupListChangedHandler(listType, notificationSchema, options, fetcher) { + // Validate options using Zod schema (validates autoRefresh and debounceMs) + const parseResult = types_js_1.ListChangedOptionsBaseSchema.safeParse(options); + if (!parseResult.success) { + throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`); + } + // Validate callback + if (typeof options.onChanged !== 'function') { + throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`); + } + const { autoRefresh, debounceMs } = parseResult.data; + const { onChanged } = options; + const refresh = async () => { + if (!autoRefresh) { + onChanged(null, null); + return; + } + try { + const items = await fetcher(); + onChanged(null, items); + } + catch (e) { + const error = e instanceof Error ? e : new Error(String(e)); + onChanged(error, null); + } + }; + const handler = () => { + if (debounceMs) { + // Clear any pending debounce timer for this list type + const existingTimer = this._listChangedDebounceTimers.get(listType); + if (existingTimer) { + clearTimeout(existingTimer); + } + // Set up debounced refresh + const timer = setTimeout(refresh, debounceMs); + this._listChangedDebounceTimers.set(listType, timer); + } + else { + // No debounce, refresh immediately + refresh(); + } + }; + // Register notification handler + this.setNotificationHandler(notificationSchema, handler); + } + async sendRootsListChanged() { + return this.notification({ method: 'notifications/roots/list_changed' }); + } +} +exports.Client = Client; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.js.map new file mode 100644 index 000000000..0601a04e8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","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KAAK,GAAG,MAAM,OAAO,EAAE,CAAC;gBAC9B,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAC3B,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC;gBACT,MAAM,KAAK,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC5D,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YAC3B,CAAC;QACL,CAAC,CAAC;QAEF,MAAM,OAAO,GAAG,GAAG,EAAE;YACjB,IAAI,UAAU,EAAE,CAAC;gBACb,sDAAsD;gBACtD,MAAM,aAAa,GAAG,IAAI,CAAC,0BAA0B,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;gBACpE,IAAI,aAAa,EAAE,CAAC;oBAChB,YAAY,CAAC,aAAa,CAAC,CAAC;gBAChC,CAAC;gBAED,2BAA2B;gBAC3B,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;gBAC9C,IAAI,CAAC,0BAA0B,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;YACzD,CAAC;iBAAM,CAAC;gBACJ,mCAAmC;gBACnC,OAAO,EAAE,CAAC;YACd,CAAC;QACL,CAAC,CAAC;QAEF,gCAAgC;QAChC,IAAI,CAAC,sBAAsB,CAAC,kBAAqC,EAAE,OAAO,CAAC,CAAC;IAChF,CAAC;IAED,KAAK,CAAC,oBAAoB;QACtB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC,CAAC;IAC7E,CAAC;CACJ;AAlqBD,wBAkqBC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.d.ts new file mode 100644 index 000000000..726ac578a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.d.ts @@ -0,0 +1,169 @@ +import { OAuthClientProvider } from './auth.js'; +import { FetchLike } from '../shared/transport.js'; +/** + * Middleware function that wraps and enhances fetch functionality. + * Takes a fetch handler and returns an enhanced fetch handler. + */ +export type Middleware = (next: FetchLike) => FetchLike; +/** + * Creates a fetch wrapper that handles OAuth authentication automatically. + * + * This wrapper will: + * - Add Authorization headers with access tokens + * - Handle 401 responses by attempting re-authentication + * - Retry the original request after successful auth + * - Handle OAuth errors appropriately (InvalidClientError, etc.) + * + * The baseUrl parameter is optional and defaults to using the domain from the request URL. + * However, you should explicitly provide baseUrl when: + * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) + * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) + * - The OAuth server is on a different domain than your API requests + * - You want to ensure consistent OAuth behavior regardless of request URLs + * + * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. + * + * Note: This wrapper is designed for general-purpose fetch operations. + * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling + * and should not need this wrapper. + * + * @param provider - OAuth client provider for authentication + * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) + * @returns A fetch middleware function + */ +export declare const withOAuth: (provider: OAuthClientProvider, baseUrl?: string | URL) => Middleware; +/** + * Logger function type for HTTP requests + */ +export type RequestLogger = (input: { + method: string; + url: string | URL; + status: number; + statusText: string; + duration: number; + requestHeaders?: Headers; + responseHeaders?: Headers; + error?: Error; +}) => void; +/** + * Configuration options for the logging middleware + */ +export type LoggingOptions = { + /** + * Custom logger function, defaults to console logging + */ + logger?: RequestLogger; + /** + * Whether to include request headers in logs + * @default false + */ + includeRequestHeaders?: boolean; + /** + * Whether to include response headers in logs + * @default false + */ + includeResponseHeaders?: boolean; + /** + * Status level filter - only log requests with status >= this value + * Set to 0 to log all requests, 400 to log only errors + * @default 0 + */ + statusLevel?: number; +}; +/** + * Creates a fetch middleware that logs HTTP requests and responses. + * + * When called without arguments `withLogging()`, it uses the default logger that: + * - Logs successful requests (2xx) to `console.log` + * - Logs error responses (4xx/5xx) and network errors to `console.error` + * - Logs all requests regardless of status (statusLevel: 0) + * - Does not include request or response headers in logs + * - Measures and displays request duration in milliseconds + * + * Important: the default logger uses both `console.log` and `console.error` so it should not be used with + * `stdio` transports and applications. + * + * @param options - Logging configuration options + * @returns A fetch middleware function + */ +export declare const withLogging: (options?: LoggingOptions) => Middleware; +/** + * Composes multiple fetch middleware functions into a single middleware pipeline. + * Middleware are applied in the order they appear, creating a chain of handlers. + * + * @example + * ```typescript + * // Create a middleware pipeline that handles both OAuth and logging + * const enhancedFetch = applyMiddlewares( + * withOAuth(oauthProvider, 'https://api.example.com'), + * withLogging({ statusLevel: 400 }) + * )(fetch); + * + * // Use the enhanced fetch - it will handle auth and log errors + * const response = await enhancedFetch('https://api.example.com/data'); + * ``` + * + * @param middleware - Array of fetch middleware to compose into a pipeline + * @returns A single composed middleware function + */ +export declare const applyMiddlewares: (...middleware: Middleware[]) => Middleware; +/** + * Helper function to create custom fetch middleware with cleaner syntax. + * Provides the next handler and request details as separate parameters for easier access. + * + * @example + * ```typescript + * // Create custom authentication middleware + * const customAuthMiddleware = createMiddleware(async (next, input, init) => { + * const headers = new Headers(init?.headers); + * headers.set('X-Custom-Auth', 'my-token'); + * + * const response = await next(input, { ...init, headers }); + * + * if (response.status === 401) { + * console.log('Authentication failed'); + * } + * + * return response; + * }); + * + * // Create conditional middleware + * const conditionalMiddleware = createMiddleware(async (next, input, init) => { + * const url = typeof input === 'string' ? input : input.toString(); + * + * // Only add headers for API routes + * if (url.includes('/api/')) { + * const headers = new Headers(init?.headers); + * headers.set('X-API-Version', 'v2'); + * return next(input, { ...init, headers }); + * } + * + * // Pass through for non-API routes + * return next(input, init); + * }); + * + * // Create caching middleware + * const cacheMiddleware = createMiddleware(async (next, input, init) => { + * const cacheKey = typeof input === 'string' ? input : input.toString(); + * + * // Check cache first + * const cached = await getFromCache(cacheKey); + * if (cached) { + * return new Response(cached, { status: 200 }); + * } + * + * // Make request and cache result + * const response = await next(input, init); + * if (response.ok) { + * await saveToCache(cacheKey, await response.clone().text()); + * } + * + * return response; + * }); + * ``` + * + * @param handler - Function that receives the next handler and request parameters + * @returns A fetch middleware function + */ +export declare const createMiddleware: (handler: (next: FetchLike, input: string | URL, init?: RequestInit) => Promise) => Middleware; +//# sourceMappingURL=middleware.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.d.ts.map new file mode 100644 index 000000000..88ac77806 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsC,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AACvG,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,SAAS,KAAK,SAAS,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,SAAS,aACP,mBAAmB,YAAY,MAAM,GAAG,GAAG,KAAG,UA0DxD,CAAC;AAEN;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,KAAK,CAAC,EAAE,KAAK,CAAC;CACjB,KAAK,IAAI,CAAC;AAEX;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IACzB;;OAEG;IACH,MAAM,CAAC,EAAE,aAAa,CAAC;IAEvB;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAEhC;;;OAGG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;IAEjC;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,WAAW,aAAa,cAAc,KAAQ,UA6E1D,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,gBAAgB,kBAAmB,UAAU,EAAE,KAAG,UAI9D,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AACH,eAAO,MAAM,gBAAgB,YAAa,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,KAAG,UAE3H,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.js new file mode 100644 index 000000000..4dae753fb --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.js @@ -0,0 +1,252 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createMiddleware = exports.applyMiddlewares = exports.withLogging = exports.withOAuth = void 0; +const auth_js_1 = require("./auth.js"); +/** + * Creates a fetch wrapper that handles OAuth authentication automatically. + * + * This wrapper will: + * - Add Authorization headers with access tokens + * - Handle 401 responses by attempting re-authentication + * - Retry the original request after successful auth + * - Handle OAuth errors appropriately (InvalidClientError, etc.) + * + * The baseUrl parameter is optional and defaults to using the domain from the request URL. + * However, you should explicitly provide baseUrl when: + * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) + * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) + * - The OAuth server is on a different domain than your API requests + * - You want to ensure consistent OAuth behavior regardless of request URLs + * + * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. + * + * Note: This wrapper is designed for general-purpose fetch operations. + * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling + * and should not need this wrapper. + * + * @param provider - OAuth client provider for authentication + * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) + * @returns A fetch middleware function + */ +const withOAuth = (provider, baseUrl) => next => { + return async (input, init) => { + const makeRequest = async () => { + const headers = new Headers(init?.headers); + // Add authorization header if tokens are available + const tokens = await provider.tokens(); + if (tokens) { + headers.set('Authorization', `Bearer ${tokens.access_token}`); + } + return await next(input, { ...init, headers }); + }; + let response = await makeRequest(); + // Handle 401 responses by attempting re-authentication + if (response.status === 401) { + try { + const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response); + // Use provided baseUrl or extract from request URL + const serverUrl = baseUrl || (typeof input === 'string' ? new URL(input).origin : input.origin); + const result = await (0, auth_js_1.auth)(provider, { + serverUrl, + resourceMetadataUrl, + scope, + fetchFn: next + }); + if (result === 'REDIRECT') { + throw new auth_js_1.UnauthorizedError('Authentication requires user authorization - redirect initiated'); + } + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError(`Authentication failed with result: ${result}`); + } + // Retry the request with fresh tokens + response = await makeRequest(); + } + catch (error) { + if (error instanceof auth_js_1.UnauthorizedError) { + throw error; + } + throw new auth_js_1.UnauthorizedError(`Failed to re-authenticate: ${error instanceof Error ? error.message : String(error)}`); + } + } + // If we still have a 401 after re-auth attempt, throw an error + if (response.status === 401) { + const url = typeof input === 'string' ? input : input.toString(); + throw new auth_js_1.UnauthorizedError(`Authentication failed for ${url}`); + } + return response; + }; +}; +exports.withOAuth = withOAuth; +/** + * Creates a fetch middleware that logs HTTP requests and responses. + * + * When called without arguments `withLogging()`, it uses the default logger that: + * - Logs successful requests (2xx) to `console.log` + * - Logs error responses (4xx/5xx) and network errors to `console.error` + * - Logs all requests regardless of status (statusLevel: 0) + * - Does not include request or response headers in logs + * - Measures and displays request duration in milliseconds + * + * Important: the default logger uses both `console.log` and `console.error` so it should not be used with + * `stdio` transports and applications. + * + * @param options - Logging configuration options + * @returns A fetch middleware function + */ +const withLogging = (options = {}) => { + const { logger, includeRequestHeaders = false, includeResponseHeaders = false, statusLevel = 0 } = options; + const defaultLogger = input => { + const { method, url, status, statusText, duration, requestHeaders, responseHeaders, error } = input; + let message = error + ? `HTTP ${method} ${url} failed: ${error.message} (${duration}ms)` + : `HTTP ${method} ${url} ${status} ${statusText} (${duration}ms)`; + // Add headers to message if requested + if (includeRequestHeaders && requestHeaders) { + const reqHeaders = Array.from(requestHeaders.entries()) + .map(([key, value]) => `${key}: ${value}`) + .join(', '); + message += `\n Request Headers: {${reqHeaders}}`; + } + if (includeResponseHeaders && responseHeaders) { + const resHeaders = Array.from(responseHeaders.entries()) + .map(([key, value]) => `${key}: ${value}`) + .join(', '); + message += `\n Response Headers: {${resHeaders}}`; + } + if (error || status >= 400) { + // eslint-disable-next-line no-console + console.error(message); + } + else { + // eslint-disable-next-line no-console + console.log(message); + } + }; + const logFn = logger || defaultLogger; + return next => async (input, init) => { + const startTime = performance.now(); + const method = init?.method || 'GET'; + const url = typeof input === 'string' ? input : input.toString(); + const requestHeaders = includeRequestHeaders ? new Headers(init?.headers) : undefined; + try { + const response = await next(input, init); + const duration = performance.now() - startTime; + // Only log if status meets the log level threshold + if (response.status >= statusLevel) { + logFn({ + method, + url, + status: response.status, + statusText: response.statusText, + duration, + requestHeaders, + responseHeaders: includeResponseHeaders ? response.headers : undefined + }); + } + return response; + } + catch (error) { + const duration = performance.now() - startTime; + // Always log errors regardless of log level + logFn({ + method, + url, + status: 0, + statusText: 'Network Error', + duration, + requestHeaders, + error: error + }); + throw error; + } + }; +}; +exports.withLogging = withLogging; +/** + * Composes multiple fetch middleware functions into a single middleware pipeline. + * Middleware are applied in the order they appear, creating a chain of handlers. + * + * @example + * ```typescript + * // Create a middleware pipeline that handles both OAuth and logging + * const enhancedFetch = applyMiddlewares( + * withOAuth(oauthProvider, 'https://api.example.com'), + * withLogging({ statusLevel: 400 }) + * )(fetch); + * + * // Use the enhanced fetch - it will handle auth and log errors + * const response = await enhancedFetch('https://api.example.com/data'); + * ``` + * + * @param middleware - Array of fetch middleware to compose into a pipeline + * @returns A single composed middleware function + */ +const applyMiddlewares = (...middleware) => { + return next => { + return middleware.reduce((handler, mw) => mw(handler), next); + }; +}; +exports.applyMiddlewares = applyMiddlewares; +/** + * Helper function to create custom fetch middleware with cleaner syntax. + * Provides the next handler and request details as separate parameters for easier access. + * + * @example + * ```typescript + * // Create custom authentication middleware + * const customAuthMiddleware = createMiddleware(async (next, input, init) => { + * const headers = new Headers(init?.headers); + * headers.set('X-Custom-Auth', 'my-token'); + * + * const response = await next(input, { ...init, headers }); + * + * if (response.status === 401) { + * console.log('Authentication failed'); + * } + * + * return response; + * }); + * + * // Create conditional middleware + * const conditionalMiddleware = createMiddleware(async (next, input, init) => { + * const url = typeof input === 'string' ? input : input.toString(); + * + * // Only add headers for API routes + * if (url.includes('/api/')) { + * const headers = new Headers(init?.headers); + * headers.set('X-API-Version', 'v2'); + * return next(input, { ...init, headers }); + * } + * + * // Pass through for non-API routes + * return next(input, init); + * }); + * + * // Create caching middleware + * const cacheMiddleware = createMiddleware(async (next, input, init) => { + * const cacheKey = typeof input === 'string' ? input : input.toString(); + * + * // Check cache first + * const cached = await getFromCache(cacheKey); + * if (cached) { + * return new Response(cached, { status: 200 }); + * } + * + * // Make request and cache result + * const response = await next(input, init); + * if (response.ok) { + * await saveToCache(cacheKey, await response.clone().text()); + * } + * + * return response; + * }); + * ``` + * + * @param handler - Function that receives the next handler and request parameters + * @returns A fetch middleware function + */ +const createMiddleware = (handler) => { + return next => (input, init) => handler(next, input, init); +}; +exports.createMiddleware = createMiddleware; +//# sourceMappingURL=middleware.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.js.map new file mode 100644 index 000000000..d28adffaa --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/middleware.js.map @@ -0,0 +1 @@ +{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":";;;AAAA,uCAAuG;AASvG;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACI,MAAM,SAAS,GAClB,CAAC,QAA6B,EAAE,OAAsB,EAAc,EAAE,CACtE,IAAI,CAAC,EAAE;IACH,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,WAAW,GAAG,KAAK,IAAuB,EAAE;YAC9C,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YAE3C,mDAAmD;YACnD,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,MAAM,EAAE,CAAC;YACvC,IAAI,MAAM,EAAE,CAAC;gBACT,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC;YAClE,CAAC;YAED,OAAO,MAAM,IAAI,CAAC,KAAK,EAAE,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;QACnD,CAAC,CAAC;QAEF,IAAI,QAAQ,GAAG,MAAM,WAAW,EAAE,CAAC;QAEnC,uDAAuD;QACvD,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YAC1B,IAAI,CAAC;gBACD,MAAM,EAAE,mBAAmB,EAAE,KAAK,EAAE,GAAG,IAAA,sCAA4B,EAAC,QAAQ,CAAC,CAAC;gBAE9E,mDAAmD;gBACnD,MAAM,SAAS,GAAG,OAAO,IAAI,CAAC,OAAO,KAAK,KA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AC;YAED,OAAO,QAAQ,CAAC;QACpB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,MAAM,QAAQ,GAAG,WAAW,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC;YAE/C,4CAA4C;YAC5C,KAAK,CAAC;gBACF,MAAM;gBACN,GAAG;gBACH,MAAM,EAAE,CAAC;gBACT,UAAU,EAAE,eAAe;gBAC3B,QAAQ;gBACR,cAAc;gBACd,KAAK,EAAE,KAAc;aACxB,CAAC,CAAC;YAEH,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC,CAAC;AACN,CAAC,CAAC;AA7EW,QAAA,WAAW,eA6EtB;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACI,MAAM,gBAAgB,GAAG,CAAC,GAAG,UAAwB,EAAc,EAAE;IACxE,OAAO,IAAI,CAAC,EAAE;QACV,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,CAAC;IACjE,CAAC,CAAC;AACN,CAAC,CAAC;AAJW,QAAA,gBAAgB,oBAI3B;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AACI,MAAM,gBAAgB,GAAG,CAAC,OAAwF,EAAc,EAAE;IACrI,OAAO,IAAI,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,KAAqB,EAAE,IAAI,CAAC,CAAC;AAC/E,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/sse.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/sse.d.ts new file mode 100644 index 000000000..acf99f1ea --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/sse.d.ts @@ -0,0 +1,81 @@ +import { type ErrorEvent, type EventSourceInit } from 'eventsource'; +import { Transport, FetchLike } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +import { OAuthClientProvider } from './auth.js'; +export declare class SseError extends Error { + readonly code: number | undefined; + readonly event: ErrorEvent; + constructor(code: number | undefined, message: string | undefined, event: ErrorEvent); +} +/** + * Configuration options for the `SSEClientTransport`. + */ +export type SSEClientTransportOptions = { + /** + * An OAuth client provider to use for authentication. + * + * When an `authProvider` is specified and the SSE connection is started: + * 1. The connection is attempted with any existing access token from the `authProvider`. + * 2. If the access token has expired, the `authProvider` is used to refresh the token. + * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. + * + * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `SSEClientTransport.finishAuth` with the authorization code before retrying the connection. + * + * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. + * + * `UnauthorizedError` might also be thrown when sending any message over the SSE transport, indicating that the session has expired, and needs to be re-authed and reconnected. + */ + authProvider?: OAuthClientProvider; + /** + * Customizes the initial SSE request to the server (the request that begins the stream). + * + * NOTE: Setting this property will prevent an `Authorization` header from + * being automatically attached to the SSE request, if an `authProvider` is + * also given. This can be worked around by setting the `Authorization` header + * manually. + */ + eventSourceInit?: EventSourceInit; + /** + * Customizes recurring POST requests to the server. + */ + requestInit?: RequestInit; + /** + * Custom fetch implementation used for all network requests. + */ + fetch?: FetchLike; +}; +/** + * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving + * messages and make separate POST requests for sending messages. + * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. + */ +export declare class SSEClientTransport implements Transport { + private _eventSource?; + private _endpoint?; + private _abortController?; + private _url; + private _resourceMetadataUrl?; + private _scope?; + private _eventSourceInit?; + private _requestInit?; + private _authProvider?; + private _fetch?; + private _fetchWithInit; + private _protocolVersion?; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(url: URL, opts?: SSEClientTransportOptions); + private _authThenStart; + private _commonHeaders; + private _startOrAuth; + start(): Promise; + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + finishAuth(authorizationCode: string): Promise; + close(): Promise; + send(message: JSONRPCMessage): Promise; + setProtocolVersion(version: string): void; +} +//# sourceMappingURL=sse.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/sse.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/sse.d.ts.map new file mode 100644 index 000000000..14ee939e2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/sse.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../../src/client/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,KAAK,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,SAAS,EAAyC,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AACnE,OAAO,EAAkD,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AAEnH,qBAAa,QAAS,SAAQ,KAAK;aAEX,IAAI,EAAE,MAAM,GAAG,SAAS;aAExB,KAAK,EAAE,UAAU;gBAFjB,IAAI,EAAE,MAAM,GAAG,SAAS,EACxC,OAAO,EAAE,MAAM,GAAG,SAAS,EACX,KAAK,EAAE,UAAU;CAIxC;AAED;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACpC;;;;;;;;;;;;;OAaG;IACH,YAAY,CAAC,EAAE,mBAAmB,CAAC;IAEnC;;;;;;;OAOG;IACH,eAAe,CAAC,EAAE,eAAe,CAAC;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/dist/cjs/client/sse.js new file mode 100644 index 000000000..8ca8dad65 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/sse.js @@ -0,0 +1,211 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SSEClientTransport = exports.SseError = void 0; +const eventsource_1 = require("eventsource"); +const transport_js_1 = require("../shared/transport.js"); +const types_js_1 = require("../types.js"); +const auth_js_1 = require("./auth.js"); +class SseError extends Error { + constructor(code, message, event) { + super(`SSE error: ${message}`); + this.code = code; + this.event = event; + } +} +exports.SseError = SseError; +/** + * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving + * messages and make separate POST requests for sending messages. + * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. + */ +class SSEClientTransport { + constructor(url, opts) { + this._url = url; + this._resourceMetadataUrl = undefined; + this._scope = undefined; + this._eventSourceInit = opts?.eventSourceInit; + this._requestInit = opts?.requestInit; + this._authProvider = opts?.authProvider; + this._fetch = opts?.fetch; + this._fetchWithInit = (0, transport_js_1.createFetchWithInit)(opts?.fetch, opts?.requestInit); + } + async _authThenStart() { + if (!this._authProvider) { + throw new auth_js_1.UnauthorizedError('No auth provider'); + } + let result; + try { + result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } + catch (error) { + this.onerror?.(error); + throw error; + } + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError(); + } + return await this._startOrAuth(); + } + async _commonHeaders() { + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) { + headers['Authorization'] = `Bearer ${tokens.access_token}`; + } + } + if (this._protocolVersion) { + headers['mcp-protocol-version'] = this._protocolVersion; + } + const extraHeaders = (0, transport_js_1.normalizeHeaders)(this._requestInit?.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + _startOrAuth() { + const fetchImpl = (this?._eventSourceInit?.fetch ?? this._fetch ?? fetch); + return new Promise((resolve, reject) => { + this._eventSource = new eventsource_1.EventSource(this._url.href, { + ...this._eventSourceInit, + fetch: async (url, init) => { + const headers = await this._commonHeaders(); + headers.set('Accept', 'text/event-stream'); + const response = await fetchImpl(url, { + ...init, + headers + }); + if (response.status === 401 && response.headers.has('www-authenticate')) { + const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + } + return response; + } + }); + this._abortController = new AbortController(); + this._eventSource.onerror = event => { + if (event.code === 401 && this._authProvider) { + this._authThenStart().then(resolve, reject); + return; + } + const error = new SseError(event.code, event.message, event); + reject(error); + this.onerror?.(error); + }; + this._eventSource.onopen = () => { + // The connection is open, but we need to wait for the endpoint to be received. + }; + this._eventSource.addEventListener('endpoint', (event) => { + const messageEvent = event; + try { + this._endpoint = new URL(messageEvent.data, this._url); + if (this._endpoint.origin !== this._url.origin) { + throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); + } + } + catch (error) { + reject(error); + this.onerror?.(error); + void this.close(); + return; + } + resolve(); + }); + this._eventSource.onmessage = (event) => { + const messageEvent = event; + let message; + try { + message = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); + } + catch (error) { + this.onerror?.(error); + return; + } + this.onmessage?.(message); + }; + }); + } + async start() { + if (this._eventSource) { + throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return await this._startOrAuth(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) { + throw new auth_js_1.UnauthorizedError('No auth provider'); + } + const result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError('Failed to authorize'); + } + } + async close() { + this._abortController?.abort(); + this._eventSource?.close(); + this.onclose?.(); + } + async send(message) { + if (!this._endpoint) { + throw new Error('Not connected'); + } + try { + const headers = await this._commonHeaders(); + headers.set('content-type', 'application/json'); + const init = { + ...this._requestInit, + method: 'POST', + headers, + body: JSON.stringify(message), + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._endpoint, init); + if (!response.ok) { + const text = await response.text().catch(() => null); + if (response.status === 401 && this._authProvider) { + const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + const result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError(); + } + // Purposely _not_ awaited, so we don't call onerror twice + return this.send(message); + } + throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); + } + // Release connection - POST responses don't have content we need + await response.body?.cancel(); + } + catch (error) { + this.onerror?.(error); + throw error; + } + } + setProtocolVersion(version) { + this._protocolVersion = version; + } +} +exports.SSEClientTransport = SSEClientTransport; +//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/sse.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/sse.js.map new file mode 100644 index 000000000..daa8b9890 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/sse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.js","sourceRoot":"","sources":["../../../src/client/sse.ts"],"names":[],"mappings":";;;AAAA,6CAAiF;AACjF,yDAAqG;AACrG,0CAAmE;AACnE,uCAAmH;AAEnH,MAAa,QAAS,SAAQ,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AAI,CAAC,OAAO,EAAE,CAAC,KAAc,CAAC,CAAC;YAC/B,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC;IAED,kBAAkB,CAAC,OAAe;QAC9B,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IACpC,CAAC;CACJ;AA1OD,gDA0OC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.d.ts new file mode 100644 index 000000000..a411dba81 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.d.ts @@ -0,0 +1,77 @@ +import { IOType } from 'node:child_process'; +import { Stream } from 'node:stream'; +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +export type StdioServerParameters = { + /** + * The executable to run to start the server. + */ + command: string; + /** + * Command line arguments to pass to the executable. + */ + args?: string[]; + /** + * The environment to use when spawning the process. + * + * If not specified, the result of getDefaultEnvironment() will be used. + */ + env?: Record; + /** + * How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`. + * + * The default is "inherit", meaning messages to stderr will be printed to the parent process's stderr. + */ + stderr?: IOType | Stream | number; + /** + * The working directory to use when spawning the process. + * + * If not specified, the current working directory will be inherited. + */ + cwd?: string; +}; +/** + * Environment variables to inherit by default, if an environment is not explicitly given. + */ +export declare const DEFAULT_INHERITED_ENV_VARS: string[]; +/** + * Returns a default environment object including only environment variables deemed safe to inherit. + */ +export declare function getDefaultEnvironment(): Record; +/** + * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. + * + * This transport is only available in Node.js environments. + */ +export declare class StdioClientTransport implements Transport { + private _process?; + private _readBuffer; + private _serverParams; + private _stderrStream; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(server: StdioServerParameters); + /** + * Starts the server process and prepares to communicate with it. + */ + start(): Promise; + /** + * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". + * + * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to + * attach listeners before the start method is invoked. This prevents loss of any early + * error output emitted by the child process. + */ + get stderr(): Stream | null; + /** + * The child process pid spawned by this transport. + * + * This is only available after the transport has been started. + */ + get pid(): number | null; + private processReadBuffer; + close(): Promise; + send(message: JSONRPCMessage): Promise; +} +//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.d.ts.map new file mode 100644 index 000000000..73b267bce --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,EAAE,MAAM,EAAe,MAAM,aAAa,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7C,MAAM,MAAM,qBAAqB,GAAG;IAChC;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAEhB;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAE7B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IAElC;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,0BAA0B,UAiBuB,CAAC;AAE/D;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAkB9D;AAED;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,SAAS;IAClD,OAAO,CAAC,QAAQ,CAAC,CAAe;IAChC,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,aAAa,CAAwB;IAC7C,OAAO,CAAC,aAAa,CAA4B;IAEjD,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,MAAM,EAAE,qBAAqB;IAOzC;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAqD5B;;;;;;OAMG;IACH,IAAI,MAAM,IAAI,MAAM,GAAG,IAAI,CAM1B;IAED;;;;OAIG;IACH,IAAI,GAAG,IAAI,MAAM,GAAG,IAAI,CAEvB;IAED,OAAO,CAAC,iBAAiB;IAenB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAyC5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAc/C"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.js new file mode 100644 index 000000000..ee48b40d2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.js @@ -0,0 +1,199 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StdioClientTransport = exports.DEFAULT_INHERITED_ENV_VARS = void 0; +exports.getDefaultEnvironment = getDefaultEnvironment; +const cross_spawn_1 = __importDefault(require("cross-spawn")); +const node_process_1 = __importDefault(require("node:process")); +const node_stream_1 = require("node:stream"); +const stdio_js_1 = require("../shared/stdio.js"); +/** + * Environment variables to inherit by default, if an environment is not explicitly given. + */ +exports.DEFAULT_INHERITED_ENV_VARS = node_process_1.default.platform === 'win32' + ? [ + 'APPDATA', + 'HOMEDRIVE', + 'HOMEPATH', + 'LOCALAPPDATA', + 'PATH', + 'PROCESSOR_ARCHITECTURE', + 'SYSTEMDRIVE', + 'SYSTEMROOT', + 'TEMP', + 'USERNAME', + 'USERPROFILE', + 'PROGRAMFILES' + ] + : /* list inspired by the default env inheritance of sudo */ + ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER']; +/** + * Returns a default environment object including only environment variables deemed safe to inherit. + */ +function getDefaultEnvironment() { + const env = {}; + for (const key of exports.DEFAULT_INHERITED_ENV_VARS) { + const value = node_process_1.default.env[key]; + if (value === undefined) { + continue; + } + if (value.startsWith('()')) { + // Skip functions, which are a security risk. + continue; + } + env[key] = value; + } + return env; +} +/** + * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. + * + * This transport is only available in Node.js environments. + */ +class StdioClientTransport { + constructor(server) { + this._readBuffer = new stdio_js_1.ReadBuffer(); + this._stderrStream = null; + this._serverParams = server; + if (server.stderr === 'pipe' || server.stderr === 'overlapped') { + this._stderrStream = new node_stream_1.PassThrough(); + } + } + /** + * Starts the server process and prepares to communicate with it. + */ + async start() { + if (this._process) { + throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return new Promise((resolve, reject) => { + this._process = (0, cross_spawn_1.default)(this._serverParams.command, this._serverParams.args ?? [], { + // merge default env with server env because mcp server needs some env vars + env: { + ...getDefaultEnvironment(), + ...this._serverParams.env + }, + stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'], + shell: false, + windowsHide: node_process_1.default.platform === 'win32' && isElectron(), + cwd: this._serverParams.cwd + }); + this._process.on('error', error => { + reject(error); + this.onerror?.(error); + }); + this._process.on('spawn', () => { + resolve(); + }); + this._process.on('close', _code => { + this._process = undefined; + this.onclose?.(); + }); + this._process.stdin?.on('error', error => { + this.onerror?.(error); + }); + this._process.stdout?.on('data', chunk => { + this._readBuffer.append(chunk); + this.processReadBuffer(); + }); + this._process.stdout?.on('error', error => { + this.onerror?.(error); + }); + if (this._stderrStream && this._process.stderr) { + this._process.stderr.pipe(this._stderrStream); + } + }); + } + /** + * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". + * + * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to + * attach listeners before the start method is invoked. This prevents loss of any early + * error output emitted by the child process. + */ + get stderr() { + if (this._stderrStream) { + return this._stderrStream; + } + return this._process?.stderr ?? null; + } + /** + * The child process pid spawned by this transport. + * + * This is only available after the transport has been started. + */ + get pid() { + return this._process?.pid ?? null; + } + processReadBuffer() { + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + this.onmessage?.(message); + } + catch (error) { + this.onerror?.(error); + } + } + } + async close() { + if (this._process) { + const processToClose = this._process; + this._process = undefined; + const closePromise = new Promise(resolve => { + processToClose.once('close', () => { + resolve(); + }); + }); + try { + processToClose.stdin?.end(); + } + catch { + // ignore + } + await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]); + if (processToClose.exitCode === null) { + try { + processToClose.kill('SIGTERM'); + } + catch { + // ignore + } + await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]); + } + if (processToClose.exitCode === null) { + try { + processToClose.kill('SIGKILL'); + } + catch { + // ignore + } + } + } + this._readBuffer.clear(); + } + send(message) { + return new Promise(resolve => { + if (!this._process?.stdin) { + throw new Error('Not connected'); + } + const json = (0, stdio_js_1.serializeMessage)(message); + if (this._process.stdin.write(json)) { + resolve(); + } + else { + this._process.stdin.once('drain', resolve); + } + }); + } +} +exports.StdioClientTransport = StdioClientTransport; +function isElectron() { + return 'type' in node_process_1.default; +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.js.map new file mode 100644 index 000000000..40253bc3a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":";;;;;;AAkEA,sDAkBC;AAnFD,8DAAgC;AAChC,gEAAmC;AACnC,6CAAkD;AAClD,iDAAkE;AAqClE;;GAEG;AACU,QAAA,0BAA0B,GACnC,sBAAO,CAAC,QAAQ,KAAK,OAAO;IACxB,CAAC,CAAC;QACI,SAAS;QACT,WAAW;QACX,UAAU;QACV,cAAc;QACd,MAAM;QACN,wBAAwB;QACxB,aAAa;QACb,YAAY;QACZ,MAAM;QACN,UAAU;QACV,aAAa;QACb,cAAc;KACjB;IACH,CAAC,CAAC,0DAA0D;QAC1D,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAE/D;;GAEG;AACH,SAAgB,qBAAqB;IACjC,MAAM,GAAG,GAA2B,EAAE,CAAC;IAEvC,KAAK,MAAM,GAAG,IAAI,kCAA0B,EAAE,CAAC;QAC3C,MAAM,KAAK,GAAG,sBAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC/B,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACtB,SAAS;QACb,CAAC;QAED,IAAI,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;YACzB,6CAA6C;YAC7C,SAAS;QACb,CAAC;QAED,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,OAAO,GAAG,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,MAAa,oBAAoB;IAU7B,YAAY,MAA6B;QARjC,gBAAW,GAAe,IAAI,qBAAU,EAAE,CAAC;QAE3C,kBAAa,GAAuB,IAAI,CAAC;QAO7C,IAAI,CAAC,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I,CAAC,CAAC,YAAY,EAAE,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,IAAK,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;YACnG,CAAC;YAED,IAAI,cAAc,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC;gBACnC,IAAI,CAAC;oBACD,cAAc,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBACnC,CAAC;gBAAC,MAAM,CAAC;oBACL,SAAS;gBACb,CAAC;YACL,CAAC;QACL,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,CAAC,OAAuB;QACxB,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;YACzB,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC;gBACxB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;YACrC,CAAC;YAED,MAAM,IAAI,GAAG,IAAA,2BAAgB,EAAC,OAAO,CAAC,CAAC;YACvC,IAAI,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAClC,OAAO,EAAE,CAAC;YACd,CAAC;iBAAM,CAAC;gBACJ,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC/C,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAvKD,oDAuKC;AAED,SAAS,UAAU;IACf,OAAO,MAAM,IAAI,sBAAO,CAAC;AAC7B,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.d.ts new file mode 100644 index 000000000..6035b2462 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.d.ts @@ -0,0 +1,171 @@ +import { Transport, FetchLike } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +import { OAuthClientProvider } from './auth.js'; +export declare class StreamableHTTPError extends Error { + readonly code: number | undefined; + constructor(code: number | undefined, message: string | undefined); +} +/** + * Options for starting or authenticating an SSE connection + */ +export interface StartSSEOptions { + /** + * The resumption token used to continue long-running requests that were interrupted. + * + * This allows clients to reconnect and continue from where they left off. + */ + resumptionToken?: string; + /** + * A callback that is invoked when the resumption token changes. + * + * This allows clients to persist the latest token for potential reconnection. + */ + onresumptiontoken?: (token: string) => void; + /** + * Override Message ID to associate with the replay message + * so that response can be associate with the new resumed request. + */ + replayMessageId?: string | number; +} +/** + * Configuration options for reconnection behavior of the StreamableHTTPClientTransport. + */ +export interface StreamableHTTPReconnectionOptions { + /** + * Maximum backoff time between reconnection attempts in milliseconds. + * Default is 30000 (30 seconds). + */ + maxReconnectionDelay: number; + /** + * Initial backoff time between reconnection attempts in milliseconds. + * Default is 1000 (1 second). + */ + initialReconnectionDelay: number; + /** + * The factor by which the reconnection delay increases after each attempt. + * Default is 1.5. + */ + reconnectionDelayGrowFactor: number; + /** + * Maximum number of reconnection attempts before giving up. + * Default is 2. + */ + maxRetries: number; +} +/** + * Configuration options for the `StreamableHTTPClientTransport`. + */ +export type StreamableHTTPClientTransportOptions = { + /** + * An OAuth client provider to use for authentication. + * + * When an `authProvider` is specified and the connection is started: + * 1. The connection is attempted with any existing access token from the `authProvider`. + * 2. If the access token has expired, the `authProvider` is used to refresh the token. + * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. + * + * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `StreamableHTTPClientTransport.finishAuth` with the authorization code before retrying the connection. + * + * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. + * + * `UnauthorizedError` might also be thrown when sending any message over the transport, indicating that the session has expired, and needs to be re-authed and reconnected. + */ + authProvider?: OAuthClientProvider; + /** + * Customizes HTTP requests to the server. + */ + requestInit?: RequestInit; + /** + * Custom fetch implementation used for all network requests. + */ + fetch?: FetchLike; + /** + * Options to configure the reconnection behavior. + */ + reconnectionOptions?: StreamableHTTPReconnectionOptions; + /** + * Session ID for the connection. This is used to identify the session on the server. + * When not provided and connecting to a server that supports session IDs, the server will generate a new session ID. + */ + sessionId?: string; +}; +/** + * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events + * for receiving messages. + */ +export declare class StreamableHTTPClientTransport implements Transport { + private _abortController?; + private _url; + private _resourceMetadataUrl?; + private _scope?; + private _requestInit?; + private _authProvider?; + private _fetch?; + private _fetchWithInit; + private _sessionId?; + private _reconnectionOptions; + private _protocolVersion?; + private _hasCompletedAuthFlow; + private _lastUpscopingHeader?; + private _serverRetryMs?; + private _reconnectionTimeout?; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(url: URL, opts?: StreamableHTTPClientTransportOptions); + private _authThenStart; + private _commonHeaders; + private _startOrAuthSse; + /** + * Calculates the next reconnection delay using backoff algorithm + * + * @param attempt Current reconnection attempt count for the specific stream + * @returns Time to wait in milliseconds before next reconnection attempt + */ + private _getNextReconnectionDelay; + /** + * Schedule a reconnection attempt using server-provided retry interval or backoff + * + * @param lastEventId The ID of the last received event for resumability + * @param attemptCount Current reconnection attempt count for this specific stream + */ + private _scheduleReconnection; + private _handleSseStream; + start(): Promise; + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + finishAuth(authorizationCode: string): Promise; + close(): Promise; + send(message: JSONRPCMessage | JSONRPCMessage[], options?: { + resumptionToken?: string; + onresumptiontoken?: (token: string) => void; + }): Promise; + get sessionId(): string | undefined; + /** + * Terminates the current session by sending a DELETE request to the server. + * + * Clients that no longer need a particular session + * (e.g., because the user is leaving the client application) SHOULD send an + * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly + * terminate the session. + * + * The server MAY respond with HTTP 405 Method Not Allowed, indicating that + * the server does not allow clients to terminate sessions. + */ + terminateSession(): Promise; + setProtocolVersion(version: string): void; + get protocolVersion(): string | undefined; + /** + * Resume an SSE stream from a previous event ID. + * Opens a GET SSE connection with Last-Event-ID header to replay missed events. + * + * @param lastEventId The event ID to resume from + * @param options Optional callback to receive new resumption tokens + */ + resumeStream(lastEventId: string, options?: { + onresumptiontoken?: (token: string) => void; + }): Promise; +} +//# sourceMappingURL=streamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.d.ts.map new file mode 100644 index 000000000..5b6ffb8a3 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.d.ts","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAyC,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAwE,cAAc,EAAwB,MAAM,aAAa,CAAC;AACzI,OAAO,EAAkD,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AAWnH,qBAAa,mBAAoB,SAAQ,KAAK;aAEtB,IAAI,EAAE,MAAM,GAAG,SAAS;gBAAxB,IAAI,EAAE,MAAM,GAAG,SAAS,EACxC,OAAO,EAAE,MAAM,GAAG,SAAS;CAIlC;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC5B;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAE5C;;;OAGG;IACH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AC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,oCAAoC;YAYnD,cAAc;YAyBd,cAAc;YAwBd,eAAe;IA4C7B;;;;;OAKG;IACH,OAAO,CAAC,yBAAyB;IAejC;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IAwB7B,OAAO,CAAC,gBAAgB;IA+GlB,KAAK;IAUX;;OAEG;IACG,UAAU,CAAC,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiBpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAStB,IAAI,CACN,OAAO,EAAE,cAAc,GAAG,cAAc,EAAE,EAC1C,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,MAAM,CAAC;QAAC,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;KAAE,GACpF,OAAO,CAAC,IAAI,CAAC;IA0JhB,IAAI,SAAS,IAAI,MAAM,GAAG,SAAS,CAElC;IAED;;;;;;;;;;OAUG;IACG,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IA+BvC,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAGzC,IAAI,eAAe,IAAI,MAAM,GAAG,SAAS,CAExC;IAED;;;;;;OAMG;IACG,YAAY,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAMpH"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.js new file mode 100644 index 000000000..a29a7d3a0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.js @@ -0,0 +1,482 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamableHTTPClientTransport = exports.StreamableHTTPError = void 0; +const transport_js_1 = require("../shared/transport.js"); +const types_js_1 = require("../types.js"); +const auth_js_1 = require("./auth.js"); +const stream_1 = require("eventsource-parser/stream"); +// Default reconnection options for StreamableHTTP connections +const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = { + initialReconnectionDelay: 1000, + maxReconnectionDelay: 30000, + reconnectionDelayGrowFactor: 1.5, + maxRetries: 2 +}; +class StreamableHTTPError extends Error { + constructor(code, message) { + super(`Streamable HTTP error: ${message}`); + this.code = code; + } +} +exports.StreamableHTTPError = StreamableHTTPError; +/** + * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events + * for receiving messages. + */ +class StreamableHTTPClientTransport { + constructor(url, opts) { + this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401 + this._url = url; + this._resourceMetadataUrl = undefined; + this._scope = undefined; + this._requestInit = opts?.requestInit; + this._authProvider = opts?.authProvider; + this._fetch = opts?.fetch; + this._fetchWithInit = (0, transport_js_1.createFetchWithInit)(opts?.fetch, opts?.requestInit); + this._sessionId = opts?.sessionId; + this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; + } + async _authThenStart() { + if (!this._authProvider) { + throw new auth_js_1.UnauthorizedError('No auth provider'); + } + let result; + try { + result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } + catch (error) { + this.onerror?.(error); + throw error; + } + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError(); + } + return await this._startOrAuthSse({ resumptionToken: undefined }); + } + async _commonHeaders() { + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) { + headers['Authorization'] = `Bearer ${tokens.access_token}`; + } + } + if (this._sessionId) { + headers['mcp-session-id'] = this._sessionId; + } + if (this._protocolVersion) { + headers['mcp-protocol-version'] = this._protocolVersion; + } + const extraHeaders = (0, transport_js_1.normalizeHeaders)(this._requestInit?.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + async _startOrAuthSse(options) { + const { resumptionToken } = options; + try { + // Try to open an initial SSE stream with GET to listen for server messages + // This is optional according to the spec - server may not support it + const headers = await this._commonHeaders(); + headers.set('Accept', 'text/event-stream'); + // Include Last-Event-ID header for resumable streams if provided + if (resumptionToken) { + headers.set('last-event-id', resumptionToken); + } + const response = await (this._fetch ?? fetch)(this._url, { + method: 'GET', + headers, + signal: this._abortController?.signal + }); + if (!response.ok) { + await response.body?.cancel(); + if (response.status === 401 && this._authProvider) { + // Need to authenticate + return await this._authThenStart(); + } + // 405 indicates that the server does not offer an SSE stream at GET endpoint + // This is an expected case that should not trigger an error + if (response.status === 405) { + return; + } + throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`); + } + this._handleSseStream(response.body, options, true); + } + catch (error) { + this.onerror?.(error); + throw error; + } + } + /** + * Calculates the next reconnection delay using backoff algorithm + * + * @param attempt Current reconnection attempt count for the specific stream + * @returns Time to wait in milliseconds before next reconnection attempt + */ + _getNextReconnectionDelay(attempt) { + // Use server-provided retry value if available + if (this._serverRetryMs !== undefined) { + return this._serverRetryMs; + } + // Fall back to exponential backoff + const initialDelay = this._reconnectionOptions.initialReconnectionDelay; + const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; + const maxDelay = this._reconnectionOptions.maxReconnectionDelay; + // Cap at maximum delay + return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); + } + /** + * Schedule a reconnection attempt using server-provided retry interval or backoff + * + * @param lastEventId The ID of the last received event for resumability + * @param attemptCount Current reconnection attempt count for this specific stream + */ + _scheduleReconnection(options, attemptCount = 0) { + // Use provided options or default options + const maxRetries = this._reconnectionOptions.maxRetries; + // Check if we've exceeded maximum retry attempts + if (attemptCount >= maxRetries) { + this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); + return; + } + // Calculate next delay based on current attempt count + const delay = this._getNextReconnectionDelay(attemptCount); + // Schedule the reconnection + this._reconnectionTimeout = setTimeout(() => { + // Use the last event ID to resume where we left off + this._startOrAuthSse(options).catch(error => { + this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`)); + // Schedule another attempt if this one failed, incrementing the attempt counter + this._scheduleReconnection(options, attemptCount + 1); + }); + }, delay); + } + _handleSseStream(stream, options, isReconnectable) { + if (!stream) { + return; + } + const { onresumptiontoken, replayMessageId } = options; + let lastEventId; + // Track whether we've received a priming event (event with ID) + // Per spec, server SHOULD send a priming event with ID before closing + let hasPrimingEvent = false; + // Track whether we've received a response - if so, no need to reconnect + // Reconnection is for when server disconnects BEFORE sending response + let receivedResponse = false; + const processStream = async () => { + // this is the closest we can get to trying to catch network errors + // if something happens reader will throw + try { + // Create a pipeline: binary stream -> text decoder -> SSE parser + const reader = stream + .pipeThrough(new TextDecoderStream()) + .pipeThrough(new stream_1.EventSourceParserStream({ + onRetry: (retryMs) => { + // Capture server-provided retry value for reconnection timing + this._serverRetryMs = retryMs; + } + })) + .getReader(); + while (true) { + const { value: event, done } = await reader.read(); + if (done) { + break; + } + // Update last event ID if provided + if (event.id) { + lastEventId = event.id; + // Mark that we've received a priming event - stream is now resumable + hasPrimingEvent = true; + onresumptiontoken?.(event.id); + } + // Skip events with no data (priming events, keep-alives) + if (!event.data) { + continue; + } + if (!event.event || event.event === 'message') { + try { + const message = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(event.data)); + if ((0, types_js_1.isJSONRPCResultResponse)(message)) { + // Mark that we received a response - no need to reconnect for this request + receivedResponse = true; + if (replayMessageId !== undefined) { + message.id = replayMessageId; + } + } + this.onmessage?.(message); + } + catch (error) { + this.onerror?.(error); + } + } + } + // Handle graceful server-side disconnect + // Server may close connection after sending event ID and retry field + // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID) + // BUT don't reconnect if we already received a response - the request is complete + const canResume = isReconnectable || hasPrimingEvent; + const needsReconnect = canResume && !receivedResponse; + if (needsReconnect && this._abortController && !this._abortController.signal.aborted) { + this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId + }, 0); + } + } + catch (error) { + // Handle stream errors - likely a network disconnect + this.onerror?.(new Error(`SSE stream disconnected: ${error}`)); + // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing + // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID) + // BUT don't reconnect if we already received a response - the request is complete + const canResume = isReconnectable || hasPrimingEvent; + const needsReconnect = canResume && !receivedResponse; + if (needsReconnect && this._abortController && !this._abortController.signal.aborted) { + // Use the exponential backoff reconnection strategy + try { + this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId + }, 0); + } + catch (error) { + this.onerror?.(new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`)); + } + } + } + }; + processStream(); + } + async start() { + if (this._abortController) { + throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + this._abortController = new AbortController(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) { + throw new auth_js_1.UnauthorizedError('No auth provider'); + } + const result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError('Failed to authorize'); + } + } + async close() { + if (this._reconnectionTimeout) { + clearTimeout(this._reconnectionTimeout); + this._reconnectionTimeout = undefined; + } + this._abortController?.abort(); + this.onclose?.(); + } + async send(message, options) { + try { + const { resumptionToken, onresumptiontoken } = options || {}; + if (resumptionToken) { + // If we have at last event ID, we need to reconnect the SSE stream + this._startOrAuthSse({ resumptionToken, replayMessageId: (0, types_js_1.isJSONRPCRequest)(message) ? message.id : undefined }).catch(err => this.onerror?.(err)); + return; + } + const headers = await this._commonHeaders(); + headers.set('content-type', 'application/json'); + headers.set('accept', 'application/json, text/event-stream'); + const init = { + ...this._requestInit, + method: 'POST', + headers, + body: JSON.stringify(message), + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._url, init); + // Handle session ID received during initialization + const sessionId = response.headers.get('mcp-session-id'); + if (sessionId) { + this._sessionId = sessionId; + } + if (!response.ok) { + const text = await response.text().catch(() => null); + if (response.status === 401 && this._authProvider) { + // Prevent infinite recursion when server returns 401 after successful auth + if (this._hasCompletedAuthFlow) { + throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication'); + } + const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + const result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError(); + } + // Mark that we completed auth flow + this._hasCompletedAuthFlow = true; + // Purposely _not_ awaited, so we don't call onerror twice + return this.send(message); + } + if (response.status === 403 && this._authProvider) { + const { resourceMetadataUrl, scope, error } = (0, auth_js_1.extractWWWAuthenticateParams)(response); + if (error === 'insufficient_scope') { + const wwwAuthHeader = response.headers.get('WWW-Authenticate'); + // Check if we've already tried upscoping with this header to prevent infinite loops. + if (this._lastUpscopingHeader === wwwAuthHeader) { + throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping'); + } + if (scope) { + this._scope = scope; + } + if (resourceMetadataUrl) { + this._resourceMetadataUrl = resourceMetadataUrl; + } + // Mark that upscoping was tried. + this._lastUpscopingHeader = wwwAuthHeader ?? undefined; + const result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetch + }); + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError(); + } + return this.send(message); + } + } + throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`); + } + // Reset auth loop flag on successful response + this._hasCompletedAuthFlow = false; + this._lastUpscopingHeader = undefined; + // If the response is 202 Accepted, there's no body to process + if (response.status === 202) { + await response.body?.cancel(); + // if the accepted notification is initialized, we start the SSE stream + // if it's supported by the server + if ((0, types_js_1.isInitializedNotification)(message)) { + // Start without a lastEventId since this is a fresh connection + this._startOrAuthSse({ resumptionToken: undefined }).catch(err => this.onerror?.(err)); + } + return; + } + // Get original message(s) for detecting request IDs + const messages = Array.isArray(message) ? message : [message]; + const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0; + // Check the response type + const contentType = response.headers.get('content-type'); + if (hasRequests) { + if (contentType?.includes('text/event-stream')) { + // Handle SSE stream responses for requests + // We use the same handler as standalone streams, which now supports + // reconnection with the last event ID + this._handleSseStream(response.body, { onresumptiontoken }, false); + } + else if (contentType?.includes('application/json')) { + // For non-streaming servers, we might get direct JSON responses + const data = await response.json(); + const responseMessages = Array.isArray(data) + ? data.map(msg => types_js_1.JSONRPCMessageSchema.parse(msg)) + : [types_js_1.JSONRPCMessageSchema.parse(data)]; + for (const msg of responseMessages) { + this.onmessage?.(msg); + } + } + else { + await response.body?.cancel(); + throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`); + } + } + else { + // No requests in message but got 200 OK - still need to release connection + await response.body?.cancel(); + } + } + catch (error) { + this.onerror?.(error); + throw error; + } + } + get sessionId() { + return this._sessionId; + } + /** + * Terminates the current session by sending a DELETE request to the server. + * + * Clients that no longer need a particular session + * (e.g., because the user is leaving the client application) SHOULD send an + * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly + * terminate the session. + * + * The server MAY respond with HTTP 405 Method Not Allowed, indicating that + * the server does not allow clients to terminate sessions. + */ + async terminateSession() { + if (!this._sessionId) { + return; // No session to terminate + } + try { + const headers = await this._commonHeaders(); + const init = { + ...this._requestInit, + method: 'DELETE', + headers, + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._url, init); + await response.body?.cancel(); + // We specifically handle 405 as a valid response according to the spec, + // meaning the server does not support explicit session termination + if (!response.ok && response.status !== 405) { + throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`); + } + this._sessionId = undefined; + } + catch (error) { + this.onerror?.(error); + throw error; + } + } + setProtocolVersion(version) { + this._protocolVersion = version; + } + get protocolVersion() { + return this._protocolVersion; + } + /** + * Resume an SSE stream from a previous event ID. + * Opens a GET SSE connection with Last-Event-ID header to replay missed events. + * + * @param lastEventId The event ID to resume from + * @param options Optional callback to receive new resumption tokens + */ + async resumeStream(lastEventId, options) { + await this._startOrAuthSse({ + resumptionToken: lastEventId, + onresumptiontoken: options?.onresumptiontoken + }); + } +} +exports.StreamableHTTPClientTransport = StreamableHTTPClientTransport; +//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.js.map new file mode 100644 index 000000000..9e12cb7df --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.js","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":";;;AAAA,yDAAqG;AACrG,0CAAyI;AACzI,uCAAmH;AACnH,sDAAoE;AAEpE,8DAA8D;AAC9D,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C;IAED,kBAAkB,CAAC,OAAe;QAC9B,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IACpC,CAAC;IACD,IAAI,eAAe;QACf,OAAO,IAAI,CAAC,gBAAgB,CAAC;IACjC,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,YAAY,CAAC,WAAmB,EAAE,OAAyD;QAC7F,MAAM,IAAI,CAAC,eAAe,CAAC;YACvB,eAAe,EAAE,WAAW;YAC5B,iBAAiB,EAAE,OAAO,EAAE,iBAAiB;SAChD,CAAC,CAAC;IACP,CAAC;CACJ;AAtiBD,sEAsiBC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/websocket.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/websocket.d.ts new file mode 100644 index 000000000..78f95de3b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/websocket.d.ts @@ -0,0 +1,17 @@ +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +/** + * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. + */ +export declare class WebSocketClientTransport implements Transport { + private _socket?; + private _url; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(url: URL); + start(): Promise; + close(): Promise; + send(message: JSONRPCMessage): Promise; +} +//# sourceMappingURL=websocket.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/websocket.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/websocket.d.ts.map new file mode 100644 index 000000000..2882d9822 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/websocket.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAInE;;GAEG;AACH,qBAAa,wBAAyB,YAAW,SAAS;IACtD,OAAO,CAAC,OAAO,CAAC,CAAY;IAC5B,OAAO,CAAC,IAAI,CAAM;IAElB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG;IAIpB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAsChB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAW/C"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/websocket.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/websocket.js new file mode 100644 index 000000000..0cadb384a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/websocket.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebSocketClientTransport = void 0; +const types_js_1 = require("../types.js"); +const SUBPROTOCOL = 'mcp'; +/** + * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. + */ +class WebSocketClientTransport { + constructor(url) { + this._url = url; + } + start() { + if (this._socket) { + throw new Error('WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return new Promise((resolve, reject) => { + this._socket = new WebSocket(this._url, SUBPROTOCOL); + this._socket.onerror = event => { + const error = 'error' in event ? event.error : new Error(`WebSocket error: ${JSON.stringify(event)}`); + reject(error); + this.onerror?.(error); + }; + this._socket.onopen = () => { + resolve(); + }; + this._socket.onclose = () => { + this.onclose?.(); + }; + this._socket.onmessage = (event) => { + let message; + try { + message = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(event.data)); + } + catch (error) { + this.onerror?.(error); + return; + } + this.onmessage?.(message); + }; + }); + } + async close() { + this._socket?.close(); + } + send(message) { + return new Promise((resolve, reject) => { + if (!this._socket) { + reject(new Error('Not connected')); + return; + } + this._socket?.send(JSON.stringify(message)); + resolve(); + }); + } +} +exports.WebSocketClientTransport = WebSocketClientTransport; +//# sourceMappingURL=websocket.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/websocket.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/websocket.js.map new file mode 100644 index 000000000..ff439d9b6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/websocket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.js","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":";;;AACA,0CAAmE;AAEnE,MAAM,WAAW,GAAG,KAAK,CAAC;AAE1B;;GAEG;AACH,MAAa,wBAAwB;IAQjC,YAAY,GAAQ;QAChB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;IACpB,CAAC;IAED,KAAK;QACD,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CACX,mHAAmH,CACtH,CAAC;QACN,CAAC;QAED,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACnC,IAAI,CAAC,OAAO,GAAG,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;YAErD,IAAI,CAAC,OAAO,CAAC,OAAO,GAAG,KAAK,CAAC,EAAE;gBAC3B,MAAM,KAAK,GAAG,OAAO,IAAI,KAAK,CAAC,CAAC,CAAE,KAAK,CAAC,KAAe,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,oBAAoB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;gBACjH,MAAM,CAAC,KAAK,CAAC,CAAC;gBACd,IAAI,CAAC,OAAO,EAAE,CAAC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/client/elicitationUrlExample.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/elicitationUrlExample.d.ts new file mode 100644 index 000000000..611f6eba2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/elicitationUrlExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=elicitationUrlExample.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/elicitationUrlExample.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/elicitationUrlExample.d.ts.map new file mode 100644 index 000000000..e749adfb9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/elicitationUrlExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/elicitationUrlExample.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/elicitationUrlExample.js new file mode 100644 index 000000000..cb4d58b21 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/elicitationUrlExample.js @@ -0,0 +1,692 @@ +"use strict"; +// Run with: npx tsx src/examples/client/elicitationUrlExample.ts +// +// This example demonstrates how to use URL elicitation to securely +// collect user input in a remote (HTTP) server. +// URL elicitation allows servers to prompt the end-user to open a URL in their browser +// to collect sensitive information. +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const node_readline_1 = require("node:readline"); +const types_js_1 = require("../../types.js"); +const metadataUtils_js_1 = require("../../shared/metadataUtils.js"); +const node_child_process_1 = require("node:child_process"); +const simpleOAuthClientProvider_js_1 = require("./simpleOAuthClientProvider.js"); +const auth_js_1 = require("../../client/auth.js"); +const node_http_1 = require("node:http"); +// Set up OAuth (required for this example) +const OAUTH_CALLBACK_PORT = 8090; // Use different port than auth server (3001) +const OAUTH_CALLBACK_URL = `http://localhost:${OAUTH_CALLBACK_PORT}/callback`; +let oauthProvider = undefined; +console.log('Getting OAuth token...'); +const clientMetadata = { + client_name: 'Elicitation MCP Client', + redirect_uris: [OAUTH_CALLBACK_URL], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'client_secret_post', + scope: 'mcp:tools' +}; +oauthProvider = new simpleOAuthClientProvider_js_1.InMemoryOAuthClientProvider(OAUTH_CALLBACK_URL, clientMetadata, (redirectUrl) => { + console.log(`🌐 Opening browser for OAuth redirect: ${redirectUrl.toString()}`); + openBrowser(redirectUrl.toString()); +}); +// Create readline interface for user input +const readline = (0, node_readline_1.createInterface)({ + input: process.stdin, + output: process.stdout +}); +let abortCommand = new AbortController(); +// Global client and transport for interactive commands +let client = null; +let transport = null; +let serverUrl = 'http://localhost:3000/mcp'; +let sessionId = undefined; +let isProcessingCommand = false; +let isProcessingElicitations = false; +const elicitationQueue = []; +let elicitationQueueSignal = null; +let elicitationsCompleteSignal = null; +// Map to track pending URL elicitations waiting for completion notifications +const pendingURLElicitations = new Map(); +async function main() { + console.log('MCP Interactive Client'); + console.log('====================='); + // Connect to server immediately with default settings + await connect(); + // Start the elicitation loop in the background + elicitationLoop().catch(error => { + console.error('Unexpected error in elicitation loop:', error); + process.exit(1); + }); + // Short delay allowing the server to send any SSE elicitations on connection + await new Promise(resolve => setTimeout(resolve, 200)); + // Wait until we are done processing any initial elicitations + await waitForElicitationsToComplete(); + // Print help and start the command loop + printHelp(); + await commandLoop(); +} +async function waitForElicitationsToComplete() { + // Wait until the queue is empty and nothing is being processed + while (elicitationQueue.length > 0 || isProcessingElicitations) { + await new Promise(resolve => setTimeout(resolve, 100)); + } +} +function printHelp() { + console.log('\nAvailable commands:'); + console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); + console.log(' disconnect - Disconnect from server'); + console.log(' terminate-session - Terminate the current session'); + console.log(' reconnect - Reconnect to the server'); + console.log(' list-tools - List available tools'); + console.log(' call-tool [args] - Call a tool with optional JSON arguments'); + console.log(' payment-confirm - Test URL elicitation via error response with payment-confirm tool'); + console.log(' third-party-auth - Test tool that requires third-party OAuth credentials'); + console.log(' help - Show this help'); + console.log(' quit - Exit the program'); +} +async function commandLoop() { + await new Promise(resolve => { + if (!isProcessingElicitations) { + resolve(); + } + else { + elicitationsCompleteSignal = resolve; + } + }); + readline.question('\n> ', { signal: abortCommand.signal }, async (input) => { + isProcessingCommand = true; + const args = input.trim().split(/\s+/); + const command = args[0]?.toLowerCase(); + try { + switch (command) { + case 'connect': + await connect(args[1]); + break; + case 'disconnect': + await disconnect(); + break; + case 'terminate-session': + await terminateSession(); + break; + case 'reconnect': + await reconnect(); + break; + case 'list-tools': + await listTools(); + break; + case 'call-tool': + if (args.length < 2) { + console.log('Usage: call-tool [args]'); + } + else { + const toolName = args[1]; + let toolArgs = {}; + if (args.length > 2) { + try { + toolArgs = JSON.parse(args.slice(2).join(' ')); + } + catch { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await callTool(toolName, toolArgs); + } + break; + case 'payment-confirm': + await callPaymentConfirmTool(); + break; + case 'third-party-auth': + await callThirdPartyAuthTool(); + break; + case 'help': + printHelp(); + break; + case 'quit': + case 'exit': + await cleanup(); + return; + default: + if (command) { + console.log(`Unknown command: ${command}`); + } + break; + } + } + catch (error) { + console.error(`Error executing command: ${error}`); + } + finally { + isProcessingCommand = false; + } + // Process another command after we've processed the this one + await commandLoop(); + }); +} +async function elicitationLoop() { + while (true) { + // Wait until we have elicitations to process + await new Promise(resolve => { + if (elicitationQueue.length > 0) { + resolve(); + } + else { + elicitationQueueSignal = resolve; + } + }); + isProcessingElicitations = true; + abortCommand.abort(); // Abort the command loop if it's running + // Process all queued elicitations + while (elicitationQueue.length > 0) { + const queued = elicitationQueue.shift(); + console.log(`📤 Processing queued elicitation (${elicitationQueue.length} remaining)`); + try { + const result = await handleElicitationRequest(queued.request); + queued.resolve(result); + } + catch (error) { + queued.reject(error instanceof Error ? error : new Error(String(error))); + } + } + console.log('✅ All queued elicitations processed. Resuming command loop...\n'); + isProcessingElicitations = false; + // Reset the abort controller for the next command loop + abortCommand = new AbortController(); + // Resume the command loop + if (elicitationsCompleteSignal) { + elicitationsCompleteSignal(); + elicitationsCompleteSignal = null; + } + } +} +async function openBrowser(url) { + const command = `open "${url}"`; + (0, node_child_process_1.exec)(command, error => { + if (error) { + console.error(`Failed to open browser: ${error.message}`); + console.log(`Please manually open: ${url}`); + } + }); +} +/** + * Enqueues an elicitation request and returns the result. + * + * This function is used so that our CLI (which can only handle one input request at a time) + * can handle elicitation requests and the command loop. + * + * @param request - The elicitation request to be handled + * @returns The elicitation result + */ +async function elicitationRequestHandler(request) { + // If we are processing a command, handle this elicitation immediately + if (isProcessingCommand) { + console.log('📋 Processing elicitation immediately (during command execution)'); + return await handleElicitationRequest(request); + } + // Otherwise, queue the request to be handled by the elicitation loop + console.log(`📥 Queueing elicitation request (queue size will be: ${elicitationQueue.length + 1})`); + return new Promise((resolve, reject) => { + elicitationQueue.push({ + request, + resolve, + reject + }); + // Signal the elicitation loop that there's work to do + if (elicitationQueueSignal) { + elicitationQueueSignal(); + elicitationQueueSignal = null; + } + }); +} +/** + * Handles an elicitation request. + * + * This function is used to handle the elicitation request and return the result. + * + * @param request - The elicitation request to be handled + * @returns The elicitation result + */ +async function handleElicitationRequest(request) { + const mode = request.params.mode; + console.log('\n🔔 Elicitation Request Received:'); + console.log(`Mode: ${mode}`); + if (mode === 'url') { + return { + action: await handleURLElicitation(request.params) + }; + } + else { + // Should not happen because the client declares its capabilities to the server, + // but being defensive is a good practice: + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Unsupported elicitation mode: ${mode}`); + } +} +/** + * Handles a URL elicitation by opening the URL in the browser. + * + * Note: This is a shared code for both request handlers and error handlers. + * As a result of sharing schema, there is no big forking of logic for the client. + * + * @param params - The URL elicitation request parameters + * @returns The action to take (accept, cancel, or decline) + */ +async function handleURLElicitation(params) { + const url = params.url; + const elicitationId = params.elicitationId; + const message = params.message; + console.log(`🆔 Elicitation ID: ${elicitationId}`); // Print for illustration + // Parse URL to show domain for security + let domain = 'unknown domain'; + try { + const parsedUrl = new URL(url); + domain = parsedUrl.hostname; + } + catch { + console.error('Invalid URL provided by server'); + return 'decline'; + } + // Example security warning to help prevent phishing attacks + console.log('\n⚠️ \x1b[33mSECURITY WARNING\x1b[0m ⚠️'); + console.log('\x1b[33mThe server is requesting you to open an external URL.\x1b[0m'); + console.log('\x1b[33mOnly proceed if you trust this server and understand why it needs this.\x1b[0m\n'); + console.log(`🌐 Target domain: \x1b[36m${domain}\x1b[0m`); + console.log(`🔗 Full URL: \x1b[36m${url}\x1b[0m`); + console.log(`\nℹ️ Server's reason:\n\n\x1b[36m${message}\x1b[0m\n`); + // 1. Ask for user consent to open the URL + const consent = await new Promise(resolve => { + readline.question('\nDo you want to open this URL in your browser? (y/n): ', input => { + resolve(input.trim().toLowerCase()); + }); + }); + // 2. If user did not consent, return appropriate result + if (consent === 'no' || consent === 'n') { + console.log('❌ URL navigation declined.'); + return 'decline'; + } + else if (consent !== 'yes' && consent !== 'y') { + console.log('🚫 Invalid response. Cancelling elicitation.'); + return 'cancel'; + } + // 3. Wait for completion notification in the background + const completionPromise = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + pendingURLElicitations.delete(elicitationId); + console.log(`\x1b[31m❌ Elicitation ${elicitationId} timed out waiting for completion.\x1b[0m`); + reject(new Error('Elicitation completion timeout')); + }, 5 * 60 * 1000); // 5 minute timeout + pendingURLElicitations.set(elicitationId, { + resolve: () => { + clearTimeout(timeout); + resolve(); + }, + reject, + timeout + }); + }); + completionPromise.catch(error => { + console.error('Background completion wait failed:', error); + }); + // 4. Open the URL in the browser + console.log(`\n🚀 Opening browser to: ${url}`); + await openBrowser(url); + console.log('\n⏳ Waiting for you to complete the interaction in your browser...'); + console.log(' The server will send a notification once you complete the action.'); + // 5. Acknowledge the user accepted the elicitation + return 'accept'; +} +/** + * Example OAuth callback handler - in production, use a more robust approach + * for handling callbacks and storing tokens + */ +/** + * Starts a temporary HTTP server to receive the OAuth callback + */ +async function waitForOAuthCallback() { + return new Promise((resolve, reject) => { + const server = (0, node_http_1.createServer)((req, res) => { + // Ignore favicon requests + if (req.url === '/favicon.ico') { + res.writeHead(404); + res.end(); + return; + } + console.log(`📥 Received callback: ${req.url}`); + const parsedUrl = new URL(req.url || '', 'http://localhost'); + const code = parsedUrl.searchParams.get('code'); + const error = parsedUrl.searchParams.get('error'); + if (code) { + console.log(`✅ Authorization code received: ${code?.substring(0, 10)}...`); + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Successful!

+

This simulates successful authorization of the MCP client, which now has an access token for the MCP server.

+

This window will close automatically in 10 seconds.

+ + + + `); + resolve(code); + setTimeout(() => server.close(), 15000); + } + else if (error) { + console.log(`❌ Authorization error: ${error}`); + res.writeHead(400, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Failed

+

Error: ${error}

+ + + `); + reject(new Error(`OAuth authorization failed: ${error}`)); + } + else { + console.log(`❌ No authorization code or error in callback`); + res.writeHead(400); + res.end('Bad request'); + reject(new Error('No authorization code provided')); + } + }); + server.listen(OAUTH_CALLBACK_PORT, () => { + console.log(`OAuth callback server started on http://localhost:${OAUTH_CALLBACK_PORT}`); + }); + }); +} +/** + * Attempts to connect to the MCP server with OAuth authentication. + * Handles OAuth flow recursively if authorization is required. + */ +async function attemptConnection(oauthProvider) { + console.log('🚢 Creating transport with OAuth provider...'); + const baseUrl = new URL(serverUrl); + transport = new streamableHttp_js_1.StreamableHTTPClientTransport(baseUrl, { + sessionId: sessionId, + authProvider: oauthProvider + }); + console.log('🚢 Transport created'); + try { + console.log('🔌 Attempting connection (this will trigger OAuth redirect if needed)...'); + await client.connect(transport); + sessionId = transport.sessionId; + console.log('Transport created with session ID:', sessionId); + console.log('✅ Connected successfully'); + } + catch (error) { + if (error instanceof auth_js_1.UnauthorizedError) { + console.log('🔐 OAuth required - waiting for authorization...'); + const callbackPromise = waitForOAuthCallback(); + const authCode = await callbackPromise; + await transport.finishAuth(authCode); + console.log('🔐 Authorization code received:', authCode); + console.log('🔌 Reconnecting with authenticated transport...'); + // Recursively retry connection after OAuth completion + await attemptConnection(oauthProvider); + } + else { + console.error('❌ Connection failed with non-auth error:', error); + throw error; + } + } +} +async function connect(url) { + if (client) { + console.log('Already connected. Disconnect first.'); + return; + } + if (url) { + serverUrl = url; + } + console.log(`🔗 Attempting to connect to ${serverUrl}...`); + // Create a new client with elicitation capability + console.log('👤 Creating MCP client...'); + client = new index_js_1.Client({ + name: 'example-client', + version: '1.0.0' + }, { + capabilities: { + elicitation: { + // Only URL elicitation is supported in this demo + // (see server/elicitationExample.ts for a demo of form mode elicitation) + url: {} + } + } + }); + console.log('👤 Client created'); + // Set up elicitation request handler with proper validation + client.setRequestHandler(types_js_1.ElicitRequestSchema, elicitationRequestHandler); + // Set up notification handler for elicitation completion + client.setNotificationHandler(types_js_1.ElicitationCompleteNotificationSchema, notification => { + const { elicitationId } = notification.params; + const pending = pendingURLElicitations.get(elicitationId); + if (pending) { + clearTimeout(pending.timeout); + pendingURLElicitations.delete(elicitationId); + console.log(`\x1b[32m✅ Elicitation ${elicitationId} completed!\x1b[0m`); + pending.resolve(); + } + else { + // Shouldn't happen - discard it! + console.warn(`Received completion notification for unknown elicitation: ${elicitationId}`); + } + }); + try { + console.log('🔐 Starting OAuth flow...'); + await attemptConnection(oauthProvider); + console.log('Connected to MCP server'); + // Set up error handler after connection is established so we don't double log errors + client.onerror = error => { + console.error('\x1b[31mClient error:', error, '\x1b[0m'); + }; + } + catch (error) { + console.error('Failed to connect:', error); + client = null; + transport = null; + return; + } +} +async function disconnect() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + await transport.close(); + console.log('Disconnected from MCP server'); + client = null; + transport = null; + } + catch (error) { + console.error('Error disconnecting:', error); + } +} +async function terminateSession() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + console.log('Terminating session with ID:', transport.sessionId); + await transport.terminateSession(); + console.log('Session terminated successfully'); + // Check if sessionId was cleared after termination + if (!transport.sessionId) { + console.log('Session ID has been cleared'); + sessionId = undefined; + // Also close the transport and clear client objects + await transport.close(); + console.log('Transport closed after session termination'); + client = null; + transport = null; + } + else { + console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); + console.log('Session ID is still active:', transport.sessionId); + } + } + catch (error) { + console.error('Error terminating session:', error); + } +} +async function reconnect() { + if (client) { + await disconnect(); + } + await connect(); +} +async function listTools() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - id: ${tool.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(tool)}, description: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server (${error})`); + } +} +async function callTool(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const request = { + method: 'tools/call', + params: { + name, + arguments: args + } + }; + console.log(`Calling tool '${name}' with args:`, args); + const result = await client.request(request, types_js_1.CallToolResultSchema); + console.log('Tool result:'); + const resourceLinks = []; + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else if (item.type === 'resource_link') { + const resourceLink = item; + resourceLinks.push(resourceLink); + console.log(` 📁 Resource Link: ${resourceLink.name}`); + console.log(` URI: ${resourceLink.uri}`); + if (resourceLink.mimeType) { + console.log(` Type: ${resourceLink.mimeType}`); + } + if (resourceLink.description) { + console.log(` Description: ${resourceLink.description}`); + } + } + else if (item.type === 'resource') { + console.log(` [Embedded Resource: ${item.resource.uri}]`); + } + else if (item.type === 'image') { + console.log(` [Image: ${item.mimeType}]`); + } + else if (item.type === 'audio') { + console.log(` [Audio: ${item.mimeType}]`); + } + else { + console.log(` [Unknown content type]:`, item); + } + }); + // Offer to read resource links + if (resourceLinks.length > 0) { + console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); + } + } + catch (error) { + if (error instanceof types_js_1.UrlElicitationRequiredError) { + console.log('\n🔔 Elicitation Required Error Received:'); + console.log(`Message: ${error.message}`); + for (const e of error.elicitations) { + await handleURLElicitation(e); // For the error handler, we discard the action result because we don't respond to an error response + } + return; + } + console.log(`Error calling tool ${name}: ${error}`); + } +} +async function cleanup() { + if (client && transport) { + try { + // First try to terminate the session gracefully + if (transport.sessionId) { + try { + console.log('Terminating session before exit...'); + await transport.terminateSession(); + console.log('Session terminated successfully'); + } + catch (error) { + console.error('Error terminating session:', error); + } + } + // Then close the transport + await transport.close(); + } + catch (error) { + console.error('Error closing transport:', error); + } + } + process.stdin.setRawMode(false); + readline.close(); + console.log('\nGoodbye!'); + process.exit(0); +} +async function callPaymentConfirmTool() { + console.log('Calling payment-confirm tool...'); + await callTool('payment-confirm', { cartId: 'cart_123' }); +} +async function callThirdPartyAuthTool() { + console.log('Calling third-party-auth tool...'); + await callTool('third-party-auth', { param1: 'test' }); +} +// Set up raw mode for keyboard input to capture Escape key +process.stdin.setRawMode(true); +process.stdin.on('data', async (data) => { + // Check for Escape key (27) + if (data.length === 1 && data[0] === 27) { + console.log('\nESC key pressed. Disconnecting from server...'); + // Abort current operation and disconnect from server + if (client && transport) { + await disconnect(); + console.log('Disconnected. Press Enter to continue.'); + } + else { + console.log('Not connected to server.'); + } + // Re-display the prompt + process.stdout.write('> '); + } +}); +// Handle Ctrl+C +process.on('SIGINT', async () => { + console.log('\nReceived SIGINT. Cleaning up...'); + await cleanup(); +}); +// Start the interactive client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=elicitationUrlExample.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/elicitationUrlExample.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/elicitationUrlExample.js.map new file mode 100644 index 000000000..fd32734f3 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/elicitationUrlExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.js","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":";AAAA,iEAAiE;AACjE,EAAE;AACF,mEAAmE;AACnE,gDAAgD;AAChD,uFAAuF;AACvF,oCAAoC;;AAEpC,oDAA+C;AAC/C,sEAA+E;AAC/E,iDAAgD;AAChD,6CAcwB;AACxB,oEAA+D;AAE/D,2DAA0C;AAC1C,iFAA6E;AAC7E,kDAAyD;AACzD,yCAAyC;AAEzC,2CAA2C;AAC3C,MAAM,mBAAmB,GAAG,IAAI,CAAC,CAAC,6CAA6C;AAC/E,MAAM,kBAAkB,GAAG,oBAAoB,mBAAmB,WAAW,CAAC;AAC9E,IAAI,aAAa,GAA4C,SAAS,CAAC;AAEvE,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;AACtC,MAAM,cAAc,GAAwB;IACxC,WAAW,EAAE,wBAAwB;IACrC,aAAa,EAAE,CAAC,kBAAkB,CAAC;IACnC,WAAW,EAAE,CAAC,oBAAoB,EAAE,eAAe,CAAC;IACpD,cAAc,EAAE,CAAC,MAAM,CAAC;IACxB,0BAA0B,EAAE,oBAAoB;IAChD,KAAK,EAAE,WAAW;CACrB,CAAC;AACF,aAAa,GAAG,IAAI,0DAA2B,CAAC,kBAAkB,EAAE,cAAc,EAAE,CAAC,WAAgB,EAAE,EAAE;IACrG,OAAO,CAAC,GAAG,CAAC,0CAA0C,WAAW,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAChF,WAAW,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC;AACxC,CAAC,CAAC,CA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E,CAAC;YACnB,OAAO,CAAC,GAAG,CAAC,wCAAwC,CAAC,CAAC;QAC1D,CAAC;aAAM,CAAC;YACJ,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QAC5C,CAAC;QAED,wBAAwB;QACxB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,gBAAgB;AAChB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;IACjD,MAAM,OAAO,EAAE,CAAC;AACpB,CAAC,CAAC,CAAC;AAEH,+BAA+B;AAC/B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/multipleClientsParallel.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/multipleClientsParallel.d.ts new file mode 100644 index 000000000..0ac5af8e5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/multipleClientsParallel.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=multipleClientsParallel.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/multipleClientsParallel.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/multipleClientsParallel.d.ts.map new file mode 100644 index 000000000..91051dc94 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/multipleClientsParallel.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"multipleClientsParallel.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/multipleClientsParallel.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/multipleClientsParallel.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/multipleClientsParallel.js new file mode 100644 index 000000000..5cfbb2f4d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/multipleClientsParallel.js @@ -0,0 +1,134 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const types_js_1 = require("../../types.js"); +/** + * Multiple Clients MCP Example + * + * This client demonstrates how to: + * 1. Create multiple MCP clients in parallel + * 2. Each client calls a single tool + * 3. Track notifications from each client independently + */ +// Command line args processing +const args = process.argv.slice(2); +const serverUrl = args[0] || 'http://localhost:3000/mcp'; +async function createAndRunClient(config) { + console.log(`[${config.id}] Creating client: ${config.name}`); + const client = new index_js_1.Client({ + name: config.name, + version: '1.0.0' + }); + const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(serverUrl)); + // Set up client-specific error handler + client.onerror = error => { + console.error(`[${config.id}] Client error:`, error); + }; + // Set up client-specific notification handler + client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { + console.log(`[${config.id}] Notification: ${notification.params.data}`); + }); + try { + // Connect to the server + await client.connect(transport); + console.log(`[${config.id}] Connected to MCP server`); + // Call the specified tool + console.log(`[${config.id}] Calling tool: ${config.toolName}`); + const toolRequest = { + method: 'tools/call', + params: { + name: config.toolName, + arguments: { + ...config.toolArguments, + // Add client ID to arguments for identification in notifications + caller: config.id + } + } + }; + const result = await client.request(toolRequest, types_js_1.CallToolResultSchema); + console.log(`[${config.id}] Tool call completed`); + // Keep the connection open for a bit to receive notifications + await new Promise(resolve => setTimeout(resolve, 5000)); + // Disconnect + await transport.close(); + console.log(`[${config.id}] Disconnected from MCP server`); + return { id: config.id, result }; + } + catch (error) { + console.error(`[${config.id}] Error:`, error); + throw error; + } +} +async function main() { + console.log('MCP Multiple Clients Example'); + console.log('============================'); + console.log(`Server URL: ${serverUrl}`); + console.log(''); + try { + // Define client configurations + const clientConfigs = [ + { + id: 'client1', + name: 'basic-client-1', + toolName: 'start-notification-stream', + toolArguments: { + interval: 3, // 1 second between notifications + count: 5 // Send 5 notifications + } + }, + { + id: 'client2', + name: 'basic-client-2', + toolName: 'start-notification-stream', + toolArguments: { + interval: 2, // 2 seconds between notifications + count: 3 // Send 3 notifications + } + }, + { + id: 'client3', + name: 'basic-client-3', + toolName: 'start-notification-stream', + toolArguments: { + interval: 1, // 0.5 second between notifications + count: 8 // Send 8 notifications + } + } + ]; + // Start all clients in parallel + console.log(`Starting ${clientConfigs.length} clients in parallel...`); + console.log(''); + const clientPromises = clientConfigs.map(config => createAndRunClient(config)); + const results = await Promise.all(clientPromises); + // Display results from all clients + console.log('\n=== Final Results ==='); + results.forEach(({ id, result }) => { + console.log(`\n[${id}] Tool result:`); + if (Array.isArray(result.content)) { + result.content.forEach((item) => { + if (item.type === 'text' && item.text) { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + else { + console.log(` Unexpected result format:`, result); + } + }); + console.log('\n=== All clients completed successfully ==='); + } + catch (error) { + console.error('Error running multiple clients:', error); + process.exit(1); + } +} +// Start the example +main().catch((error) => { + console.error('Error running MCP multiple clients example:', error); + process.exit(1); +}); +//# sourceMappingURL=multipleClientsParallel.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/multipleClientsParallel.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/multipleClientsParallel.js.map new file mode 100644 index 000000000..05812d11a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/multipleClientsParallel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"multipleClientsParallel.js","sourceRoot":"","sources":["../../../../src/examples/client/multip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CAAC,IAAqC,EAAE,EAAE;oBAC7D,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;wBACpC,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;oBAClC,CAAC;yBAAM,CAAC;wBACJ,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,WAAW,EAAE,IAAI,CAAC,CAAC;oBACjD,CAAC;gBACL,CAAC,CAAC,CAAC;YACP,CAAC;iBAAM,CAAC;gBACJ,OAAO,CAAC,GAAG,CAAC,6BAA6B,EAAE,MAAM,CAAC,CAAC;YACvD,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,GAAG,CAAC,8CAA8C,CAAC,CAAC;IAChE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;QACxD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACL,CAAC;AAED,oBAAoB;AACpB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,CAAC,CAAC;IACpE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/parallelToolCallsClient.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/parallelToolCallsClient.d.ts new file mode 100644 index 000000000..e93d4d69d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/parallelToolCallsClient.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=parallelToolCallsClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/parallelToolCallsClient.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/parallelToolCallsClient.d.ts.map new file mode 100644 index 000000000..25a3b820c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/parallelToolCallsClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parallelToolCallsClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/parallelToolCallsClient.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/parallelToolCallsClient.js new file mode 100644 index 000000000..e5a9829e9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/parallelToolCallsClient.js @@ -0,0 +1,176 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const types_js_1 = require("../../types.js"); +/** + * Parallel Tool Calls MCP Client + * + * This client demonstrates how to: + * 1. Start multiple tool calls in parallel + * 2. Track notifications from each tool call using a caller parameter + */ +// Command line args processing +const args = process.argv.slice(2); +const serverUrl = args[0] || 'http://localhost:3000/mcp'; +async function main() { + console.log('MCP Parallel Tool Calls Client'); + console.log('=============================='); + console.log(`Connecting to server at: ${serverUrl}`); + let client; + let transport; + try { + // Create client with streamable HTTP transport + client = new index_js_1.Client({ + name: 'parallel-tool-calls-client', + version: '1.0.0' + }); + client.onerror = error => { + console.error('Client error:', error); + }; + // Connect to the server + transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(serverUrl)); + await client.connect(transport); + console.log('Successfully connected to MCP server'); + // Set up notification handler with caller identification + client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { + console.log(`Notification: ${notification.params.data}`); + }); + console.log('List tools'); + const toolsRequest = await listTools(client); + console.log('Tools: ', toolsRequest); + // 2. Start multiple notification tools in parallel + console.log('\n=== Starting Multiple Notification Streams in Parallel ==='); + const toolResults = await startParallelNotificationTools(client); + // Log the results from each tool call + for (const [caller, result] of Object.entries(toolResults)) { + console.log(`\n=== Tool result for ${caller} ===`); + result.content.forEach((item) => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + // 3. Wait for all notifications (10 seconds) + console.log('\n=== Waiting for all notifications ==='); + await new Promise(resolve => setTimeout(resolve, 10000)); + // 4. Disconnect + console.log('\n=== Disconnecting ==='); + await transport.close(); + console.log('Disconnected from MCP server'); + } + catch (error) { + console.error('Error running client:', error); + process.exit(1); + } +} +/** + * List available tools on the server + */ +async function listTools(client) { + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - ${tool.name}: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server: ${error}`); + } +} +/** + * Start multiple notification tools in parallel with different configurations + * Each tool call includes a caller parameter to identify its notifications + */ +async function startParallelNotificationTools(client) { + try { + // Define multiple tool calls with different configurations + const toolCalls = [ + { + caller: 'fast-notifier', + request: { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 2, // 0.5 second between notifications + count: 10, // Send 10 notifications + caller: 'fast-notifier' // Identify this tool call + } + } + } + }, + { + caller: 'slow-notifier', + request: { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 5, // 2 seconds between notifications + count: 5, // Send 5 notifications + caller: 'slow-notifier' // Identify this tool call + } + } + } + }, + { + caller: 'burst-notifier', + request: { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 1, // 0.1 second between notifications + count: 3, // Send just 3 notifications + caller: 'burst-notifier' // Identify this tool call + } + } + } + } + ]; + console.log(`Starting ${toolCalls.length} notification tools in parallel...`); + // Start all tool calls in parallel + const toolPromises = toolCalls.map(({ caller, request }) => { + console.log(`Starting tool call for ${caller}...`); + return client + .request(request, types_js_1.CallToolResultSchema) + .then(result => ({ caller, result })) + .catch(error => { + console.error(`Error in tool call for ${caller}:`, error); + throw error; + }); + }); + // Wait for all tool calls to complete + const results = await Promise.all(toolPromises); + // Organize results by caller + const resultsByTool = {}; + results.forEach(({ caller, result }) => { + resultsByTool[caller] = result; + }); + return resultsByTool; + } + catch (error) { + console.error(`Error starting parallel notification tools:`, error); + throw error; + } +} +// Start the client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=parallelToolCallsClient.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/parallelToolCallsClient.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/parallelToolCallsClient.js.map new file mode 100644 index 000000000..dabdf4895 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/parallelToolCallsClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parallelToolCallsClient.js","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,6CAMwB;AAExB;;;;;;GAMG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AAEzD,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,4BAA4B,SAAS,EAAE,CAAC,CAAC;IAErD,IAAI,MAAc,CAAC;IACnB,IAAI,SAA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,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleClientCredentials.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleClientCredentials.d.ts new file mode 100644 index 000000000..876d25d3a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleClientCredentials.d.ts @@ -0,0 +1,20 @@ +#!/usr/bin/env node +/** + * Example demonstrating client_credentials grant for machine-to-machine authentication. + * + * Supports two authentication methods based on environment variables: + * + * 1. client_secret_basic (default): + * MCP_CLIENT_ID - OAuth client ID (required) + * MCP_CLIENT_SECRET - OAuth client secret (required) + * + * 2. private_key_jwt (when MCP_CLIENT_PRIVATE_KEY_PEM is set): + * MCP_CLIENT_ID - OAuth client ID (required) + * MCP_CLIENT_PRIVATE_KEY_PEM - PEM-encoded private key for JWT signing (required) + * MCP_CLIENT_ALGORITHM - Signing algorithm (default: RS256) + * + * Common: + * MCP_SERVER_URL - Server URL (default: http://localhost:3000/mcp) + */ +export {}; +//# sourceMappingURL=simpleClientCredentials.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleClientCredentials.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleClientCredentials.d.ts.map new file mode 100644 index 000000000..7a935db41 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleClientCredentials.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleClientCredentials.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleClientCredentials.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;;;;;GAgBG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleClientCredentials.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleClientCredentials.js new file mode 100644 index 000000000..0b251b1a1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleClientCredentials.js @@ -0,0 +1,70 @@ +#!/usr/bin/env node +"use strict"; +/** + * Example demonstrating client_credentials grant for machine-to-machine authentication. + * + * Supports two authentication methods based on environment variables: + * + * 1. client_secret_basic (default): + * MCP_CLIENT_ID - OAuth client ID (required) + * MCP_CLIENT_SECRET - OAuth client secret (required) + * + * 2. private_key_jwt (when MCP_CLIENT_PRIVATE_KEY_PEM is set): + * MCP_CLIENT_ID - OAuth client ID (required) + * MCP_CLIENT_PRIVATE_KEY_PEM - PEM-encoded private key for JWT signing (required) + * MCP_CLIENT_ALGORITHM - Signing algorithm (default: RS256) + * + * Common: + * MCP_SERVER_URL - Server URL (default: http://localhost:3000/mcp) + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const auth_extensions_js_1 = require("../../client/auth-extensions.js"); +const DEFAULT_SERVER_URL = process.env.MCP_SERVER_URL || 'http://localhost:3000/mcp'; +function createProvider() { + const clientId = process.env.MCP_CLIENT_ID; + if (!clientId) { + console.error('MCP_CLIENT_ID environment variable is required'); + process.exit(1); + } + // If private key is provided, use private_key_jwt authentication + const privateKeyPem = process.env.MCP_CLIENT_PRIVATE_KEY_PEM; + if (privateKeyPem) { + const algorithm = process.env.MCP_CLIENT_ALGORITHM || 'RS256'; + console.log('Using private_key_jwt authentication'); + return new auth_extensions_js_1.PrivateKeyJwtProvider({ + clientId, + privateKey: privateKeyPem, + algorithm + }); + } + // Otherwise, use client_secret_basic authentication + const clientSecret = process.env.MCP_CLIENT_SECRET; + if (!clientSecret) { + console.error('MCP_CLIENT_SECRET or MCP_CLIENT_PRIVATE_KEY_PEM environment variable is required'); + process.exit(1); + } + console.log('Using client_secret_basic authentication'); + return new auth_extensions_js_1.ClientCredentialsProvider({ + clientId, + clientSecret + }); +} +async function main() { + const provider = createProvider(); + const client = new index_js_1.Client({ name: 'client-credentials-example', version: '1.0.0' }, { capabilities: {} }); + const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(DEFAULT_SERVER_URL), { + authProvider: provider + }); + await client.connect(transport); + console.log('Connected successfully.'); + const tools = await client.listTools(); + console.log('Available tools:', tools.tools.map(t => t.name).join(', ') || '(none)'); + await transport.close(); +} +main().catch(err => { + console.error(err); + process.exit(1); +}); +//# sourceMappingURL=simpleClientCredentials.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleClientCredentials.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleClientCredentials.js.map new file mode 100644 index 000000000..65e4b525b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleClientCredentials.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleClientCredentials.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleClientCredentials.ts"],"names":[],"mappings":";;AAEA;;;;;;;;;;;;;;;;GAgBG;;AAEH,oDAA+C;AAC/C,sEAA+E;AAC/E,wEAAmG;AAGnG,MAAM,kBAAkB,GAAG,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,2BAA2B,CAAC;AAErF,SAAS,cAAc;IACnB,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;IAC3C,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,OAAO,CAAC,KAAK,CAAC,gDAAgD,CAAC,CAAC;QAChE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IAED,iEAAiE;IACjE,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC;IAC7D,IAAI,aAAa,EAAE,CAAC;QAChB,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,oBAAoB,IAAI,OAAO,CAAC;QAC9D,OAAO,CAAC,GAAG,CAAC,sCAAsC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IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;IACf,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClient.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClient.d.ts new file mode 100644 index 000000000..e4b43dbc0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClient.d.ts @@ -0,0 +1,3 @@ +#!/usr/bin/env node +export {}; +//# sourceMappingURL=simpleOAuthClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClient.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClient.d.ts.map new file mode 100644 index 000000000..c09eef86e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClient.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClient.js new file mode 100644 index 000000000..4b74120be --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClient.js @@ -0,0 +1,413 @@ +#!/usr/bin/env node +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const node_http_1 = require("node:http"); +const node_readline_1 = require("node:readline"); +const node_url_1 = require("node:url"); +const node_child_process_1 = require("node:child_process"); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const types_js_1 = require("../../types.js"); +const auth_js_1 = require("../../client/auth.js"); +const simpleOAuthClientProvider_js_1 = require("./simpleOAuthClientProvider.js"); +// Configuration +const DEFAULT_SERVER_URL = 'http://localhost:3000/mcp'; +const CALLBACK_PORT = 8090; // Use different port than auth server (3001) +const CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`; +/** + * Interactive MCP client with OAuth authentication + * Demonstrates the complete OAuth flow with browser-based authorization + */ +class InteractiveOAuthClient { + constructor(serverUrl, clientMetadataUrl) { + this.serverUrl = serverUrl; + this.clientMetadataUrl = clientMetadataUrl; + this.client = null; + this.rl = (0, node_readline_1.createInterface)({ + input: process.stdin, + output: process.stdout + }); + } + /** + * Prompts user for input via readline + */ + async question(query) { + return new Promise(resolve => { + this.rl.question(query, resolve); + }); + } + /** + * Opens the authorization URL in the user's default browser + */ + async openBrowser(url) { + console.log(`🌐 Opening browser for authorization: ${url}`); + const command = `open "${url}"`; + (0, node_child_process_1.exec)(command, error => { + if (error) { + console.error(`Failed to open browser: ${error.message}`); + console.log(`Please manually open: ${url}`); + } + }); + } + /** + * Example OAuth callback handler - in production, use a more robust approach + * for handling callbacks and storing tokens + */ + /** + * Starts a temporary HTTP server to receive the OAuth callback + */ + async waitForOAuthCallback() { + return new Promise((resolve, reject) => { + const server = (0, node_http_1.createServer)((req, res) => { + // Ignore favicon requests + if (req.url === '/favicon.ico') { + res.writeHead(404); + res.end(); + return; + } + console.log(`📥 Received callback: ${req.url}`); + const parsedUrl = new node_url_1.URL(req.url || '', 'http://localhost'); + const code = parsedUrl.searchParams.get('code'); + const error = parsedUrl.searchParams.get('error'); + if (code) { + console.log(`✅ Authorization code received: ${code?.substring(0, 10)}...`); + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Successful!

+

You can close this window and return to the terminal.

+ + + + `); + resolve(code); + setTimeout(() => server.close(), 3000); + } + else if (error) { + console.log(`❌ Authorization error: ${error}`); + res.writeHead(400, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Failed

+

Error: ${error}

+ + + `); + reject(new Error(`OAuth authorization failed: ${error}`)); + } + else { + console.log(`❌ No authorization code or error in callback`); + res.writeHead(400); + res.end('Bad request'); + reject(new Error('No authorization code provided')); + } + }); + server.listen(CALLBACK_PORT, () => { + console.log(`OAuth callback server started on http://localhost:${CALLBACK_PORT}`); + }); + }); + } + async attemptConnection(oauthProvider) { + console.log('🚢 Creating transport with OAuth provider...'); + const baseUrl = new node_url_1.URL(this.serverUrl); + const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(baseUrl, { + authProvider: oauthProvider + }); + console.log('🚢 Transport created'); + try { + console.log('🔌 Attempting connection (this will trigger OAuth redirect)...'); + await this.client.connect(transport); + console.log('✅ Connected successfully'); + } + catch (error) { + if (error instanceof auth_js_1.UnauthorizedError) { + console.log('🔐 OAuth required - waiting for authorization...'); + const callbackPromise = this.waitForOAuthCallback(); + const authCode = await callbackPromise; + await transport.finishAuth(authCode); + console.log('🔐 Authorization code received:', authCode); + console.log('🔌 Reconnecting with authenticated transport...'); + await this.attemptConnection(oauthProvider); + } + else { + console.error('❌ Connection failed with non-auth error:', error); + throw error; + } + } + } + /** + * Establishes connection to the MCP server with OAuth authentication + */ + async connect() { + console.log(`🔗 Attempting to connect to ${this.serverUrl}...`); + const clientMetadata = { + client_name: 'Simple OAuth MCP Client', + redirect_uris: [CALLBACK_URL], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'client_secret_post' + }; + console.log('🔐 Creating OAuth provider...'); + const oauthProvider = new simpleOAuthClientProvider_js_1.InMemoryOAuthClientProvider(CALLBACK_URL, clientMetadata, (redirectUrl) => { + console.log(`📌 OAuth redirect handler called - opening browser`); + console.log(`Opening browser to: ${redirectUrl.toString()}`); + this.openBrowser(redirectUrl.toString()); + }, this.clientMetadataUrl); + console.log('🔐 OAuth provider created'); + console.log('👤 Creating MCP client...'); + this.client = new index_js_1.Client({ + name: 'simple-oauth-client', + version: '1.0.0' + }, { capabilities: {} }); + console.log('👤 Client created'); + console.log('🔐 Starting OAuth flow...'); + await this.attemptConnection(oauthProvider); + // Start interactive loop + await this.interactiveLoop(); + } + /** + * Main interactive loop for user commands + */ + async interactiveLoop() { + console.log('\n🎯 Interactive MCP Client with OAuth'); + console.log('Commands:'); + console.log(' list - List available tools'); + console.log(' call [args] - Call a tool'); + console.log(' stream [args] - Call a tool with streaming (shows task status)'); + console.log(' quit - Exit the client'); + console.log(); + while (true) { + try { + const command = await this.question('mcp> '); + if (!command.trim()) { + continue; + } + if (command === 'quit') { + console.log('\n👋 Goodbye!'); + this.close(); + process.exit(0); + } + else if (command === 'list') { + await this.listTools(); + } + else if (command.startsWith('call ')) { + await this.handleCallTool(command); + } + else if (command.startsWith('stream ')) { + await this.handleStreamTool(command); + } + else { + console.log("❌ Unknown command. Try 'list', 'call ', 'stream ', or 'quit'"); + } + } + catch (error) { + if (error instanceof Error && error.message === 'SIGINT') { + console.log('\n\n👋 Goodbye!'); + break; + } + console.error('❌ Error:', error); + } + } + } + async listTools() { + if (!this.client) { + console.log('❌ Not connected to server'); + return; + } + try { + const request = { + method: 'tools/list', + params: {} + }; + const result = await this.client.request(request, types_js_1.ListToolsResultSchema); + if (result.tools && result.tools.length > 0) { + console.log('\n📋 Available tools:'); + result.tools.forEach((tool, index) => { + console.log(`${index + 1}. ${tool.name}`); + if (tool.description) { + console.log(` Description: ${tool.description}`); + } + console.log(); + }); + } + else { + console.log('No tools available'); + } + } + catch (error) { + console.error('❌ Failed to list tools:', error); + } + } + async handleCallTool(command) { + const parts = command.split(/\s+/); + const toolName = parts[1]; + if (!toolName) { + console.log('❌ Please specify a tool name'); + return; + } + // Parse arguments (simple JSON-like format) + let toolArgs = {}; + if (parts.length > 2) { + const argsString = parts.slice(2).join(' '); + try { + toolArgs = JSON.parse(argsString); + } + catch { + console.log('❌ Invalid arguments format (expected JSON)'); + return; + } + } + await this.callTool(toolName, toolArgs); + } + async callTool(toolName, toolArgs) { + if (!this.client) { + console.log('❌ Not connected to server'); + return; + } + try { + const request = { + method: 'tools/call', + params: { + name: toolName, + arguments: toolArgs + } + }; + const result = await this.client.request(request, types_js_1.CallToolResultSchema); + console.log(`\n🔧 Tool '${toolName}' result:`); + if (result.content) { + result.content.forEach(content => { + if (content.type === 'text') { + console.log(content.text); + } + else { + console.log(content); + } + }); + } + else { + console.log(result); + } + } + catch (error) { + console.error(`❌ Failed to call tool '${toolName}':`, error); + } + } + async handleStreamTool(command) { + const parts = command.split(/\s+/); + const toolName = parts[1]; + if (!toolName) { + console.log('❌ Please specify a tool name'); + return; + } + // Parse arguments (simple JSON-like format) + let toolArgs = {}; + if (parts.length > 2) { + const argsString = parts.slice(2).join(' '); + try { + toolArgs = JSON.parse(argsString); + } + catch { + console.log('❌ Invalid arguments format (expected JSON)'); + return; + } + } + await this.streamTool(toolName, toolArgs); + } + async streamTool(toolName, toolArgs) { + if (!this.client) { + console.log('❌ Not connected to server'); + return; + } + try { + // Using the experimental tasks API - WARNING: may change without notice + console.log(`\n🔧 Streaming tool '${toolName}'...`); + const stream = this.client.experimental.tasks.callToolStream({ + name: toolName, + arguments: toolArgs + }, types_js_1.CallToolResultSchema, { + task: { + taskId: `task-${Date.now()}`, + ttl: 60000 + } + }); + // Iterate through all messages yielded by the generator + for await (const message of stream) { + switch (message.type) { + case 'taskCreated': + console.log(`✓ Task created: ${message.task.taskId}`); + break; + case 'taskStatus': + console.log(`⟳ Status: ${message.task.status}`); + if (message.task.statusMessage) { + console.log(` ${message.task.statusMessage}`); + } + break; + case 'result': + console.log('✓ Completed!'); + message.result.content.forEach(content => { + if (content.type === 'text') { + console.log(content.text); + } + else { + console.log(content); + } + }); + break; + case 'error': + console.log('✗ Error:'); + console.log(` ${message.error.message}`); + break; + } + } + } + catch (error) { + console.error(`❌ Failed to stream tool '${toolName}':`, error); + } + } + close() { + this.rl.close(); + if (this.client) { + // Note: Client doesn't have a close method in the current implementation + // This would typically close the transport connection + } + } +} +/** + * Main entry point + */ +async function main() { + const args = process.argv.slice(2); + const serverUrl = args[0] || DEFAULT_SERVER_URL; + const clientMetadataUrl = args[1]; + console.log('🚀 Simple MCP OAuth Client'); + console.log(`Connecting to: ${serverUrl}`); + if (clientMetadataUrl) { + console.log(`Client Metadata URL: ${clientMetadataUrl}`); + } + console.log(); + const client = new InteractiveOAuthClient(serverUrl, clientMetadataUrl); + // Handle graceful shutdown + process.on('SIGINT', () => { + console.log('\n\n👋 Goodbye!'); + client.close(); + process.exit(0); + }); + try { + await client.connect(); + } + catch (error) { + console.error('Failed to start client:', error); + process.exit(1); + } + finally { + client.close(); + } +} +// Run if this file is executed directly +main().catch(error => { + console.error('Unhandled error:', error); + process.exit(1); +}); +//# sourceMappingURL=simpleOAuthClient.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClient.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClient.js.map new file mode 100644 index 000000000..312652490 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClient.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":";;;AAEA,yCAAyC;AACzC,iDAAgD;AAChD,uCAA+B;AAC/B,2DAA0C;AAC1C,oDAA+C;AAC/C,sEAA+E;AAE/E,6CAAgH;AAChH,kDAAyD;AACzD,iFAA6E;AAE7E,gBAAgB;AAChB,MAAM,kBAAkB,GAAG,2BAA2B,CAAC;AACvD,MAAM,aAAa,GAAG,IAAI,CAAC,CAAC,6CAA6C;AACzE,MAAM,YAAY,GAAG,oBAAoB,aAAa,WAAW,CAAC;AAElE;;;GAGG;AACH,MAAM,sBAAsB;IAOxB,YACY,SAAiB,EACjB,iBAA0B;QAD1B,cAAS,GAAT,SAAS,CAAQ;QACjB,sBAAiB,GAAjB,iBAAiB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M,iBAAiB,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IAElC,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,kBAAkB,SAAS,EAAE,CAAC,CAAC;IAC3C,IAAI,iBAAiB,EAAE,CAAC;QACpB,OAAO,CAAC,GAAG,CAAC,wBAAwB,iBAAiB,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,CAAC,GAAG,EAAE,CAAC;IAEd,MAAM,MAAM,GAAG,IAAI,sBAAsB,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;IAExE,2BAA2B;IAC3B,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;QACtB,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC;QACD,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;YAAS,CAAC;QACP,MAAM,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;AACL,CAAC;AAED,wCAAwC;AACxC,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;IACzC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts new file mode 100644 index 000000000..092616cf5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts @@ -0,0 +1,26 @@ +import { OAuthClientProvider } from '../../client/auth.js'; +import { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from '../../shared/auth.js'; +/** + * In-memory OAuth client provider for demonstration purposes + * In production, you should persist tokens securely + */ +export declare class InMemoryOAuthClientProvider implements OAuthClientProvider { + private readonly _redirectUrl; + private readonly _clientMetadata; + readonly clientMetadataUrl?: string | undefined; + private _clientInformation?; + private _tokens?; + private _codeVerifier?; + constructor(_redirectUrl: string | URL, _clientMetadata: OAuthClientMetadata, onRedirect?: (url: URL) => void, clientMetadataUrl?: string | undefined); + private _onRedirect; + get redirectUrl(): string | URL; + get clientMetadata(): OAuthClientMetadata; + clientInformation(): OAuthClientInformationMixed | undefined; + saveClientInformation(clientInformation: OAuthClientInformationMixed): void; + tokens(): OAuthTokens | undefined; + saveTokens(tokens: OAuthTokens): void; + redirectToAuthorization(authorizationUrl: URL): void; + saveCodeVerifier(codeVerifier: string): void; + codeVerifier(): string; +} +//# sourceMappingURL=simpleOAuthClientProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts.map new file mode 100644 index 000000000..21efe9444 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClientProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAErG;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IAM/D,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,eAAe;aAEhB,iBAAiB,CAAC,EAAE,MAAM;IAR9C,OAAO,CAAC,kBAAkB,CAAC,CAA8B;IACzD,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,aAAa,CAAC,CAAS;gBAGV,YAAY,EAAE,MAAM,GAAG,GAAG,EAC1B,eAAe,EAAE,mBAAmB,EACrD,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,EACf,iBAAiB,CAAC,EAAE,MAAM,YAAA;IAS9C,OAAO,CAAC,WAAW,CAAqB;IAExC,IAAI,WAAW,IAAI,MAAM,GAAG,GAAG,CAE9B;IAED,IAAI,cAAc,IAAI,mBAAmB,CAExC;IAED,iBAAiB,IAAI,2BAA2B,GAAG,SAAS;IAI5D,qBAAqB,CAAC,iBAAiB,EAAE,2BAA2B,GAAG,IAAI;IAI3E,MAAM,IAAI,WAAW,GAAG,SAAS;IAIjC,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI;IAIrC,uBAAuB,CAAC,gBAAgB,EAAE,GAAG,GAAG,IAAI;IAIpD,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI;IAI5C,YAAY,IAAI,MAAM;CAMzB"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClientProvider.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClientProvider.js new file mode 100644 index 000000000..58959bbfc --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClientProvider.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InMemoryOAuthClientProvider = void 0; +/** + * In-memory OAuth client provider for demonstration purposes + * In production, you should persist tokens securely + */ +class InMemoryOAuthClientProvider { + constructor(_redirectUrl, _clientMetadata, onRedirect, clientMetadataUrl) { + this._redirectUrl = _redirectUrl; + this._clientMetadata = _clientMetadata; + this.clientMetadataUrl = clientMetadataUrl; + this._onRedirect = + onRedirect || + (url => { + console.log(`Redirect to: ${url.toString()}`); + }); + } + get redirectUrl() { + return this._redirectUrl; + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInformation; + } + saveClientInformation(clientInformation) { + this._clientInformation = clientInformation; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization(authorizationUrl) { + this._onRedirect(authorizationUrl); + } + saveCodeVerifier(codeVerifier) { + this._codeVerifier = codeVerifier; + } + codeVerifier() { + if (!this._codeVerifier) { + throw new Error('No code verifier saved'); + } + return this._codeVerifier; + } +} +exports.InMemoryOAuthClientProvider = InMemoryOAuthClientProvider; +//# sourceMappingURL=simpleOAuthClientProvider.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClientProvider.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClientProvider.js.map new file mode 100644 index 000000000..10771f8e5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleOAuthClientProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClientProvider.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":";;;AAGA;;;GAGG;AACH,MAAa,2BAA2B;IAKpC,YACqB,YAA0B,EAC1B,eAAoC,EACrD,UAA+B,EACf,iBAA0B;QAHzB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,oBAAe,GAAf,eAAe,CAAqB;QAErC,sBAAiB,GAAjB,iBAAiB,CAAS;QAE1C,IAAI,CAAC,WAAW;YACZ,UAAU;gBACV,CAAC,GAAG,CAAC,EAAE;oBACH,OAAO,CAAC,GAAG,CAAC,gBAAgB,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;gBAClD,CAAC,CAAC,CAAC;IACX,CAAC;IAID,IAAI,WAAW;QACX,OAAO,IAAI,CAAC,YAAY,CAAC;IAC7B,CAAC;IAED,IAAI,cAAc;QACd,OAAO,IAAI,CAAC,eAAe,CAAC;IAChC,CAAC;IAED,iBAAiB;QACb,OAAO,IAAI,CAAC,kBAAkB,CAAC;IACnC,CAAC;IAED,qBAAqB,CAAC,iBAA8C;QAChE,IAAI,CAAC,kBAAkB,GAAG,iBAAiB,CAAC;IAChD,CAAC;IAED,MAAM;QACF,OAAO,IAAI,CAAC,OAAO,CAAC;IACxB,CAAC;IAED,UAAU,CAAC,MAAmB;QAC1B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAED,uBAAuB,CAAC,gBAAqB;QACzC,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;IACvC,CAAC;IAED,gBAAgB,CAAC,YAAoB;QACjC,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;IACtC,CAAC;IAED,YAAY;QACR,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC;IAC9B,CAAC;CACJ;AA1DD,kEA0DC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleStreamableHttp.d.ts new file mode 100644 index 000000000..a20be42ca --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleStreamableHttp.d.ts.map new file mode 100644 index 000000000..28406b0c1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleStreamableHttp.js new file mode 100644 index 000000000..bb0dec92c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleStreamableHttp.js @@ -0,0 +1,818 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const node_readline_1 = require("node:readline"); +const types_js_1 = require("../../types.js"); +const metadataUtils_js_1 = require("../../shared/metadataUtils.js"); +const ajv_1 = require("ajv"); +// Create readline interface for user input +const readline = (0, node_readline_1.createInterface)({ + input: process.stdin, + output: process.stdout +}); +// Track received notifications for debugging resumability +let notificationCount = 0; +// Global client and transport for interactive commands +let client = null; +let transport = null; +let serverUrl = 'http://localhost:3000/mcp'; +let notificationsToolLastEventId = undefined; +let sessionId = undefined; +async function main() { + console.log('MCP Interactive Client'); + console.log('====================='); + // Connect to server immediately with default settings + await connect(); + // Print help and start the command loop + printHelp(); + commandLoop(); +} +function printHelp() { + console.log('\nAvailable commands:'); + console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); + console.log(' disconnect - Disconnect from server'); + console.log(' terminate-session - Terminate the current session'); + console.log(' reconnect - Reconnect to the server'); + console.log(' list-tools - List available tools'); + console.log(' call-tool [args] - Call a tool with optional JSON arguments'); + console.log(' call-tool-task [args] - Call a tool with task-based execution (example: call-tool-task delay {"duration":3000})'); + console.log(' greet [name] - Call the greet tool'); + console.log(' multi-greet [name] - Call the multi-greet tool with notifications'); + console.log(' collect-info [type] - Test form elicitation with collect-user-info tool (contact/preferences/feedback)'); + console.log(' start-notifications [interval] [count] - Start periodic notifications'); + console.log(' run-notifications-tool-with-resumability [interval] [count] - Run notification tool with resumability'); + console.log(' list-prompts - List available prompts'); + console.log(' get-prompt [name] [args] - Get a prompt with optional JSON arguments'); + console.log(' list-resources - List available resources'); + console.log(' read-resource - Read a specific resource by URI'); + console.log(' help - Show this help'); + console.log(' quit - Exit the program'); +} +function commandLoop() { + readline.question('\n> ', async (input) => { + const args = input.trim().split(/\s+/); + const command = args[0]?.toLowerCase(); + try { + switch (command) { + case 'connect': + await connect(args[1]); + break; + case 'disconnect': + await disconnect(); + break; + case 'terminate-session': + await terminateSession(); + break; + case 'reconnect': + await reconnect(); + break; + case 'list-tools': + await listTools(); + break; + case 'call-tool': + if (args.length < 2) { + console.log('Usage: call-tool [args]'); + } + else { + const toolName = args[1]; + let toolArgs = {}; + if (args.length > 2) { + try { + toolArgs = JSON.parse(args.slice(2).join(' ')); + } + catch { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await callTool(toolName, toolArgs); + } + break; + case 'greet': + await callGreetTool(args[1] || 'MCP User'); + break; + case 'multi-greet': + await callMultiGreetTool(args[1] || 'MCP User'); + break; + case 'collect-info': + await callCollectInfoTool(args[1] || 'contact'); + break; + case 'start-notifications': { + const interval = args[1] ? parseInt(args[1], 10) : 2000; + const count = args[2] ? parseInt(args[2], 10) : 10; + await startNotifications(interval, count); + break; + } + case 'run-notifications-tool-with-resumability': { + const interval = args[1] ? parseInt(args[1], 10) : 2000; + const count = args[2] ? parseInt(args[2], 10) : 10; + await runNotificationsToolWithResumability(interval, count); + break; + } + case 'call-tool-task': + if (args.length < 2) { + console.log('Usage: call-tool-task [args]'); + } + else { + const toolName = args[1]; + let toolArgs = {}; + if (args.length > 2) { + try { + toolArgs = JSON.parse(args.slice(2).join(' ')); + } + catch { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await callToolTask(toolName, toolArgs); + } + break; + case 'list-prompts': + await listPrompts(); + break; + case 'get-prompt': + if (args.length < 2) { + console.log('Usage: get-prompt [args]'); + } + else { + const promptName = args[1]; + let promptArgs = {}; + if (args.length > 2) { + try { + promptArgs = JSON.parse(args.slice(2).join(' ')); + } + catch { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await getPrompt(promptName, promptArgs); + } + break; + case 'list-resources': + await listResources(); + break; + case 'read-resource': + if (args.length < 2) { + console.log('Usage: read-resource '); + } + else { + await readResource(args[1]); + } + break; + case 'help': + printHelp(); + break; + case 'quit': + case 'exit': + await cleanup(); + return; + default: + if (command) { + console.log(`Unknown command: ${command}`); + } + break; + } + } + catch (error) { + console.error(`Error executing command: ${error}`); + } + // Continue the command loop + commandLoop(); + }); +} +async function connect(url) { + if (client) { + console.log('Already connected. Disconnect first.'); + return; + } + if (url) { + serverUrl = url; + } + console.log(`Connecting to ${serverUrl}...`); + try { + // Create a new client with form elicitation capability + client = new index_js_1.Client({ + name: 'example-client', + version: '1.0.0' + }, { + capabilities: { + elicitation: { + form: {} + } + } + }); + client.onerror = error => { + console.error('\x1b[31mClient error:', error, '\x1b[0m'); + }; + // Set up elicitation request handler with proper validation + client.setRequestHandler(types_js_1.ElicitRequestSchema, async (request) => { + if (request.params.mode !== 'form') { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`); + } + console.log('\n🔔 Elicitation (form) Request Received:'); + console.log(`Message: ${request.params.message}`); + console.log(`Related Task: ${request.params._meta?.[types_js_1.RELATED_TASK_META_KEY]?.taskId}`); + console.log('Requested Schema:'); + console.log(JSON.stringify(request.params.requestedSchema, null, 2)); + const schema = request.params.requestedSchema; + const properties = schema.properties; + const required = schema.required || []; + // Set up AJV validator for the requested schema + const ajv = new ajv_1.Ajv(); + const validate = ajv.compile(schema); + let attempts = 0; + const maxAttempts = 3; + while (attempts < maxAttempts) { + attempts++; + console.log(`\nPlease provide the following information (attempt ${attempts}/${maxAttempts}):`); + const content = {}; + let inputCancelled = false; + // Collect input for each field + for (const [fieldName, fieldSchema] of Object.entries(properties)) { + const field = fieldSchema; + const isRequired = required.includes(fieldName); + let prompt = `${field.title || fieldName}`; + // Add helpful information to the prompt + if (field.description) { + prompt += ` (${field.description})`; + } + if (field.enum) { + prompt += ` [options: ${field.enum.join(', ')}]`; + } + if (field.type === 'number' || field.type === 'integer') { + if (field.minimum !== undefined && field.maximum !== undefined) { + prompt += ` [${field.minimum}-${field.maximum}]`; + } + else if (field.minimum !== undefined) { + prompt += ` [min: ${field.minimum}]`; + } + else if (field.maximum !== undefined) { + prompt += ` [max: ${field.maximum}]`; + } + } + if (field.type === 'string' && field.format) { + prompt += ` [format: ${field.format}]`; + } + if (isRequired) { + prompt += ' *required*'; + } + if (field.default !== undefined) { + prompt += ` [default: ${field.default}]`; + } + prompt += ': '; + const answer = await new Promise(resolve => { + readline.question(prompt, input => { + resolve(input.trim()); + }); + }); + // Check for cancellation + if (answer.toLowerCase() === 'cancel' || answer.toLowerCase() === 'c') { + inputCancelled = true; + break; + } + // Parse and validate the input + try { + if (answer === '' && field.default !== undefined) { + content[fieldName] = field.default; + } + else if (answer === '' && !isRequired) { + // Skip optional empty fields + continue; + } + else if (answer === '') { + throw new Error(`${fieldName} is required`); + } + else { + // Parse the value based on type + let parsedValue; + if (field.type === 'boolean') { + parsedValue = answer.toLowerCase() === 'true' || answer.toLowerCase() === 'yes' || answer === '1'; + } + else if (field.type === 'number') { + parsedValue = parseFloat(answer); + if (isNaN(parsedValue)) { + throw new Error(`${fieldName} must be a valid number`); + } + } + else if (field.type === 'integer') { + parsedValue = parseInt(answer, 10); + if (isNaN(parsedValue)) { + throw new Error(`${fieldName} must be a valid integer`); + } + } + else if (field.enum) { + if (!field.enum.includes(answer)) { + throw new Error(`${fieldName} must be one of: ${field.enum.join(', ')}`); + } + parsedValue = answer; + } + else { + parsedValue = answer; + } + content[fieldName] = parsedValue; + } + } + catch (error) { + console.log(`❌ Error: ${error}`); + // Continue to next attempt + break; + } + } + if (inputCancelled) { + return { action: 'cancel' }; + } + // If we didn't complete all fields due to an error, try again + if (Object.keys(content).length !== + Object.keys(properties).filter(name => required.includes(name) || content[name] !== undefined).length) { + if (attempts < maxAttempts) { + console.log('Please try again...'); + continue; + } + else { + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + } + } + // Validate the complete object against the schema + const isValid = validate(content); + if (!isValid) { + console.log('❌ Validation errors:'); + validate.errors?.forEach(error => { + console.log(` - ${error.instancePath || 'root'}: ${error.message}`); + }); + if (attempts < maxAttempts) { + console.log('Please correct the errors and try again...'); + continue; + } + else { + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + } + } + // Show the collected data and ask for confirmation + console.log('\n✅ Collected data:'); + console.log(JSON.stringify(content, null, 2)); + const confirmAnswer = await new Promise(resolve => { + readline.question('\nSubmit this information? (yes/no/cancel): ', input => { + resolve(input.trim().toLowerCase()); + }); + }); + if (confirmAnswer === 'yes' || confirmAnswer === 'y') { + return { + action: 'accept', + content + }; + } + else if (confirmAnswer === 'cancel' || confirmAnswer === 'c') { + return { action: 'cancel' }; + } + else if (confirmAnswer === 'no' || confirmAnswer === 'n') { + if (attempts < maxAttempts) { + console.log('Please re-enter the information...'); + continue; + } + else { + return { action: 'decline' }; + } + } + } + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + }); + transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(serverUrl), { + sessionId: sessionId + }); + // Set up notification handlers + client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { + notificationCount++; + console.log(`\nNotification #${notificationCount}: ${notification.params.level} - ${notification.params.data}`); + // Re-display the prompt + process.stdout.write('> '); + }); + client.setNotificationHandler(types_js_1.ResourceListChangedNotificationSchema, async (_) => { + console.log(`\nResource list changed notification received!`); + try { + if (!client) { + console.log('Client disconnected, cannot fetch resources'); + return; + } + const resourcesResult = await client.request({ + method: 'resources/list', + params: {} + }, types_js_1.ListResourcesResultSchema); + console.log('Available resources count:', resourcesResult.resources.length); + } + catch { + console.log('Failed to list resources after change notification'); + } + // Re-display the prompt + process.stdout.write('> '); + }); + // Connect the client + await client.connect(transport); + sessionId = transport.sessionId; + console.log('Transport created with session ID:', sessionId); + console.log('Connected to MCP server'); + } + catch (error) { + console.error('Failed to connect:', error); + client = null; + transport = null; + } +} +async function disconnect() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + await transport.close(); + console.log('Disconnected from MCP server'); + client = null; + transport = null; + } + catch (error) { + console.error('Error disconnecting:', error); + } +} +async function terminateSession() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + console.log('Terminating session with ID:', transport.sessionId); + await transport.terminateSession(); + console.log('Session terminated successfully'); + // Check if sessionId was cleared after termination + if (!transport.sessionId) { + console.log('Session ID has been cleared'); + sessionId = undefined; + // Also close the transport and clear client objects + await transport.close(); + console.log('Transport closed after session termination'); + client = null; + transport = null; + } + else { + console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); + console.log('Session ID is still active:', transport.sessionId); + } + } + catch (error) { + console.error('Error terminating session:', error); + } +} +async function reconnect() { + if (client) { + await disconnect(); + } + await connect(); +} +async function listTools() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - id: ${tool.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(tool)}, description: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server (${error})`); + } +} +async function callTool(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const request = { + method: 'tools/call', + params: { + name, + arguments: args + } + }; + console.log(`Calling tool '${name}' with args:`, args); + const result = await client.request(request, types_js_1.CallToolResultSchema); + console.log('Tool result:'); + const resourceLinks = []; + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else if (item.type === 'resource_link') { + const resourceLink = item; + resourceLinks.push(resourceLink); + console.log(` 📁 Resource Link: ${resourceLink.name}`); + console.log(` URI: ${resourceLink.uri}`); + if (resourceLink.mimeType) { + console.log(` Type: ${resourceLink.mimeType}`); + } + if (resourceLink.description) { + console.log(` Description: ${resourceLink.description}`); + } + } + else if (item.type === 'resource') { + console.log(` [Embedded Resource: ${item.resource.uri}]`); + } + else if (item.type === 'image') { + console.log(` [Image: ${item.mimeType}]`); + } + else if (item.type === 'audio') { + console.log(` [Audio: ${item.mimeType}]`); + } + else { + console.log(` [Unknown content type]:`, item); + } + }); + // Offer to read resource links + if (resourceLinks.length > 0) { + console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); + } + } + catch (error) { + console.log(`Error calling tool ${name}: ${error}`); + } +} +async function callGreetTool(name) { + await callTool('greet', { name }); +} +async function callMultiGreetTool(name) { + console.log('Calling multi-greet tool with notifications...'); + await callTool('multi-greet', { name }); +} +async function callCollectInfoTool(infoType) { + console.log(`Testing form elicitation with collect-user-info tool (${infoType})...`); + await callTool('collect-user-info', { infoType }); +} +async function startNotifications(interval, count) { + console.log(`Starting notification stream: interval=${interval}ms, count=${count || 'unlimited'}`); + await callTool('start-notification-stream', { interval, count }); +} +async function runNotificationsToolWithResumability(interval, count) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + console.log(`Starting notification stream with resumability: interval=${interval}ms, count=${count || 'unlimited'}`); + console.log(`Using resumption token: ${notificationsToolLastEventId || 'none'}`); + const request = { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { interval, count } + } + }; + const onLastEventIdUpdate = (event) => { + notificationsToolLastEventId = event; + console.log(`Updated resumption token: ${event}`); + }; + const result = await client.request(request, types_js_1.CallToolResultSchema, { + resumptionToken: notificationsToolLastEventId, + onresumptiontoken: onLastEventIdUpdate + }); + console.log('Tool result:'); + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + catch (error) { + console.log(`Error starting notification stream: ${error}`); + } +} +async function listPrompts() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const promptsRequest = { + method: 'prompts/list', + params: {} + }; + const promptsResult = await client.request(promptsRequest, types_js_1.ListPromptsResultSchema); + console.log('Available prompts:'); + if (promptsResult.prompts.length === 0) { + console.log(' No prompts available'); + } + else { + for (const prompt of promptsResult.prompts) { + console.log(` - id: ${prompt.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(prompt)}, description: ${prompt.description}`); + } + } + } + catch (error) { + console.log(`Prompts not supported by this server (${error})`); + } +} +async function getPrompt(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const promptRequest = { + method: 'prompts/get', + params: { + name, + arguments: args + } + }; + const promptResult = await client.request(promptRequest, types_js_1.GetPromptResultSchema); + console.log('Prompt template:'); + promptResult.messages.forEach((msg, index) => { + console.log(` [${index + 1}] ${msg.role}: ${msg.content.type === 'text' ? msg.content.text : JSON.stringify(msg.content)}`); + }); + } + catch (error) { + console.log(`Error getting prompt ${name}: ${error}`); + } +} +async function listResources() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const resourcesRequest = { + method: 'resources/list', + params: {} + }; + const resourcesResult = await client.request(resourcesRequest, types_js_1.ListResourcesResultSchema); + console.log('Available resources:'); + if (resourcesResult.resources.length === 0) { + console.log(' No resources available'); + } + else { + for (const resource of resourcesResult.resources) { + console.log(` - id: ${resource.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(resource)}, description: ${resource.uri}`); + } + } + } + catch (error) { + console.log(`Resources not supported by this server (${error})`); + } +} +async function readResource(uri) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const request = { + method: 'resources/read', + params: { uri } + }; + console.log(`Reading resource: ${uri}`); + const result = await client.request(request, types_js_1.ReadResourceResultSchema); + console.log('Resource contents:'); + for (const content of result.contents) { + console.log(` URI: ${content.uri}`); + if (content.mimeType) { + console.log(` Type: ${content.mimeType}`); + } + if ('text' in content && typeof content.text === 'string') { + console.log(' Content:'); + console.log(' ---'); + console.log(content.text + .split('\n') + .map((line) => ' ' + line) + .join('\n')); + console.log(' ---'); + } + else if ('blob' in content && typeof content.blob === 'string') { + console.log(` [Binary data: ${content.blob.length} bytes]`); + } + } + } + catch (error) { + console.log(`Error reading resource ${uri}: ${error}`); + } +} +async function callToolTask(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + console.log(`Calling tool '${name}' with task-based execution...`); + console.log('Arguments:', args); + // Use task-based execution - call now, fetch later + // Using the experimental tasks API - WARNING: may change without notice + console.log('This will return immediately while processing continues in the background...'); + try { + // Call the tool with task metadata using streaming API + const stream = client.experimental.tasks.callToolStream({ + name, + arguments: args + }, types_js_1.CallToolResultSchema, { + task: { + ttl: 60000 // Keep results for 60 seconds + } + }); + console.log('Waiting for task completion...'); + let lastStatus = ''; + for await (const message of stream) { + switch (message.type) { + case 'taskCreated': + console.log('Task created successfully with ID:', message.task.taskId); + break; + case 'taskStatus': + if (lastStatus !== message.task.status) { + console.log(` ${message.task.status}${message.task.statusMessage ? ` - ${message.task.statusMessage}` : ''}`); + } + lastStatus = message.task.status; + break; + case 'result': + console.log('Task completed!'); + console.log('Tool result:'); + message.result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + }); + break; + case 'error': + throw message.error; + } + } + } + catch (error) { + console.log(`Error with task-based execution: ${error}`); + } +} +async function cleanup() { + if (client && transport) { + try { + // First try to terminate the session gracefully + if (transport.sessionId) { + try { + console.log('Terminating session before exit...'); + await transport.terminateSession(); + console.log('Session terminated successfully'); + } + catch (error) { + console.error('Error terminating session:', error); + } + } + // Then close the transport + await transport.close(); + } + catch (error) { + console.error('Error closing transport:', error); + } + } + process.stdin.setRawMode(false); + readline.close(); + console.log('\nGoodbye!'); + process.exit(0); +} +// Set up raw mode for keyboard input to capture Escape key +process.stdin.setRawMode(true); +process.stdin.on('data', async (data) => { + // Check for Escape key (27) + if (data.length === 1 && data[0] === 27) { + console.log('\nESC key pressed. Disconnecting from server...'); + // Abort current operation and disconnect from server + if (client && transport) { + await disconnect(); + console.log('Disconnected. Press Enter to continue.'); + } + else { + console.log('Not connected to server.'); + } + // Re-display the prompt + process.stdout.write('> '); + } +}); +// Handle Ctrl+C +process.on('SIGINT', async () => { + console.log('\nReceived SIGINT. Cleaning up...'); + await cleanup(); +}); +// Start the interactive client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=simpleStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleStreamableHttp.js.map new file mode 100644 index 000000000..f97526954 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,iDAAgD;AAChD,6CAoBwB;AACxB,oEAA+D;AAC/D,6BAA0B;AAE1B,2CAA2C;AAC3C,MAAM,QAAQ,GAAG,IAAA,+BAAe,EAAC;IAC7B,KAAK,EAAE,OAAO,CAAC,KAAK;IACpB,MAAM,EAAE,OAAO,CAAC,MAAM;CACzB,CAAC,CAAC;AAEH,0DAA0D;AAC1D,IAAI,iBAAiB,GAAG,CAAC,CAAC;AAE1B,uDAAuD;AACvD,IAAI,MAAM,GAAkB,IAAI,CAAC;AACjC,IAAI,SAAS,GAAyC,IAAI,CAAC;AAC3D,IAAI,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AO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;IACjD,MAAM,OAAO,EAAE,CAAC;AACpB,CAAC,CAAC,CAAC;AAEH,+BAA+B;AAC/B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleTaskInteractiveClient.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleTaskInteractiveClient.d.ts new file mode 100644 index 000000000..c79406602 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleTaskInteractiveClient.d.ts @@ -0,0 +1,10 @@ +/** + * Simple interactive task client demonstrating elicitation and sampling responses. + * + * This client connects to simpleTaskInteractive.ts server and demonstrates: + * - Handling elicitation requests (y/n confirmation) + * - Handling sampling requests (returns a hardcoded haiku) + * - Using task-based tool execution with streaming + */ +export {}; +//# sourceMappingURL=simpleTaskInteractiveClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleTaskInteractiveClient.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleTaskInteractiveClient.d.ts.map new file mode 100644 index 000000000..89b73386e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleTaskInteractiveClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleTaskInteractiveClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleTaskInteractiveClient.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleTaskInteractiveClient.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleTaskInteractiveClient.js new file mode 100644 index 000000000..d08970d5c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleTaskInteractiveClient.js @@ -0,0 +1,157 @@ +"use strict"; +/** + * Simple interactive task client demonstrating elicitation and sampling responses. + * + * This client connects to simpleTaskInteractive.ts server and demonstrates: + * - Handling elicitation requests (y/n confirmation) + * - Handling sampling requests (returns a hardcoded haiku) + * - Using task-based tool execution with streaming + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const node_readline_1 = require("node:readline"); +const types_js_1 = require("../../types.js"); +// Create readline interface for user input +const readline = (0, node_readline_1.createInterface)({ + input: process.stdin, + output: process.stdout +}); +function question(prompt) { + return new Promise(resolve => { + readline.question(prompt, answer => { + resolve(answer.trim()); + }); + }); +} +function getTextContent(result) { + const textContent = result.content.find((c) => c.type === 'text'); + return textContent?.text ?? '(no text)'; +} +async function elicitationCallback(params) { + console.log(`\n[Elicitation] Server asks: ${params.message}`); + // Simple terminal prompt for y/n + const response = await question('Your response (y/n): '); + const confirmed = ['y', 'yes', 'true', '1'].includes(response.toLowerCase()); + console.log(`[Elicitation] Responding with: confirm=${confirmed}`); + return { action: 'accept', content: { confirm: confirmed } }; +} +async function samplingCallback(params) { + // Get the prompt from the first message + let prompt = 'unknown'; + if (params.messages && params.messages.length > 0) { + const firstMessage = params.messages[0]; + const content = firstMessage.content; + if (typeof content === 'object' && !Array.isArray(content) && content.type === 'text' && 'text' in content) { + prompt = content.text; + } + else if (Array.isArray(content)) { + const textPart = content.find(c => c.type === 'text' && 'text' in c); + if (textPart && 'text' in textPart) { + prompt = textPart.text; + } + } + } + console.log(`\n[Sampling] Server requests LLM completion for: ${prompt}`); + // Return a hardcoded haiku (in real use, call your LLM here) + const haiku = `Cherry blossoms fall +Softly on the quiet pond +Spring whispers goodbye`; + console.log('[Sampling] Responding with haiku'); + return { + model: 'mock-haiku-model', + role: 'assistant', + content: { type: 'text', text: haiku } + }; +} +async function run(url) { + console.log('Simple Task Interactive Client'); + console.log('=============================='); + console.log(`Connecting to ${url}...`); + // Create client with elicitation and sampling capabilities + const client = new index_js_1.Client({ name: 'simple-task-interactive-client', version: '1.0.0' }, { + capabilities: { + elicitation: { form: {} }, + sampling: {} + } + }); + // Set up elicitation request handler + client.setRequestHandler(types_js_1.ElicitRequestSchema, async (request) => { + if (request.params.mode && request.params.mode !== 'form') { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`); + } + return elicitationCallback(request.params); + }); + // Set up sampling request handler + client.setRequestHandler(types_js_1.CreateMessageRequestSchema, async (request) => { + return samplingCallback(request.params); + }); + // Connect to server + const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(url)); + await client.connect(transport); + console.log('Connected!\n'); + // List tools + const toolsResult = await client.listTools(); + console.log(`Available tools: ${toolsResult.tools.map(t => t.name).join(', ')}`); + // Demo 1: Elicitation (confirm_delete) + console.log('\n--- Demo 1: Elicitation ---'); + console.log('Calling confirm_delete tool...'); + const confirmStream = client.experimental.tasks.callToolStream({ name: 'confirm_delete', arguments: { filename: 'important.txt' } }, types_js_1.CallToolResultSchema, { task: { ttl: 60000 } }); + for await (const message of confirmStream) { + switch (message.type) { + case 'taskCreated': + console.log(`Task created: ${message.task.taskId}`); + break; + case 'taskStatus': + console.log(`Task status: ${message.task.status}`); + break; + case 'result': + console.log(`Result: ${getTextContent(message.result)}`); + break; + case 'error': + console.error(`Error: ${message.error}`); + break; + } + } + // Demo 2: Sampling (write_haiku) + console.log('\n--- Demo 2: Sampling ---'); + console.log('Calling write_haiku tool...'); + const haikuStream = client.experimental.tasks.callToolStream({ name: 'write_haiku', arguments: { topic: 'autumn leaves' } }, types_js_1.CallToolResultSchema, { + task: { ttl: 60000 } + }); + for await (const message of haikuStream) { + switch (message.type) { + case 'taskCreated': + console.log(`Task created: ${message.task.taskId}`); + break; + case 'taskStatus': + console.log(`Task status: ${message.task.status}`); + break; + case 'result': + console.log(`Result:\n${getTextContent(message.result)}`); + break; + case 'error': + console.error(`Error: ${message.error}`); + break; + } + } + // Cleanup + console.log('\nDemo complete. Closing connection...'); + await transport.close(); + readline.close(); +} +// Parse command line arguments +const args = process.argv.slice(2); +let url = 'http://localhost:8000/mcp'; +for (let i = 0; i < args.length; i++) { + if (args[i] === '--url' && args[i + 1]) { + url = args[i + 1]; + i++; + } +} +// Run the client +run(url).catch(error => { + console.error('Error running client:', error); + process.exit(1); +}); +//# sourceMappingURL=simpleTaskInteractiveClient.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleTaskInteractiveClient.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleTaskInteractiveClient.js.map new file mode 100644 index 000000000..c766c87b4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/simpleTaskInteractiveClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleTaskInteractiveClient.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleTaskInteractiveClient.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;AAEH,oDAA+C;AAC/C,sEAA+E;AAC/E,iDAAgD;AAChD,6CASwB;AAExB,2CAA2C;AAC3C,MAAM,QAAQ,GAAG,IAAA,+BAAe,EAAC;IAC7B,KAAK,EAAE,OAAO,CAAC,KAAK;IACpB,MAAM,EAAE,OAAO,CAAC,MAAM;CACzB,CAAC,CAAC;AAEH,SAAS,QAAQ,CAAC,MAAc;IAC5B,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;QACzB,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE;YAC/B,OAAO,CAAC,MAAM,CAAC,IAA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contextprotocol/sdk/dist/cjs/examples/client/ssePollingClient.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/ssePollingClient.d.ts new file mode 100644 index 000000000..134b4b0cf --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/ssePollingClient.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=ssePollingClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/ssePollingClient.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/ssePollingClient.d.ts.map new file mode 100644 index 000000000..59e4153d2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/ssePollingClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ssePollingClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/ssePollingClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/ssePollingClient.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/ssePollingClient.js new file mode 100644 index 000000000..a529ae55b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/ssePollingClient.js @@ -0,0 +1,95 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * SSE Polling Example Client (SEP-1699) + * + * This example demonstrates client-side behavior during server-initiated + * SSE stream disconnection and automatic reconnection. + * + * Key features demonstrated: + * - Automatic reconnection when server closes SSE stream + * - Event replay via Last-Event-ID header + * - Resumption token tracking via onresumptiontoken callback + * + * Run with: npx tsx src/examples/client/ssePollingClient.ts + * Requires: ssePollingExample.ts server running on port 3001 + */ +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const types_js_1 = require("../../types.js"); +const SERVER_URL = 'http://localhost:3001/mcp'; +async function main() { + console.log('SSE Polling Example Client'); + console.log('=========================='); + console.log(`Connecting to ${SERVER_URL}...`); + console.log(''); + // Create transport with reconnection options + const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(SERVER_URL), { + // Use default reconnection options - SDK handles automatic reconnection + }); + // Track the last event ID for debugging + let lastEventId; + // Set up transport error handler to observe disconnections + // Filter out expected errors from SSE reconnection + transport.onerror = error => { + // Skip abort errors during intentional close + if (error.message.includes('AbortError')) + return; + // Show SSE disconnect (expected when server closes stream) + if (error.message.includes('Unexpected end of JSON')) { + console.log('[Transport] SSE stream disconnected - client will auto-reconnect'); + return; + } + console.log(`[Transport] Error: ${error.message}`); + }; + // Set up transport close handler + transport.onclose = () => { + console.log('[Transport] Connection closed'); + }; + // Create and connect client + const client = new index_js_1.Client({ + name: 'sse-polling-client', + version: '1.0.0' + }); + // Set up notification handler to receive progress updates + client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { + const data = notification.params.data; + console.log(`[Notification] ${data}`); + }); + try { + await client.connect(transport); + console.log('[Client] Connected successfully'); + console.log(''); + // Call the long-task tool + console.log('[Client] Calling long-task tool...'); + console.log('[Client] Server will disconnect mid-task to demonstrate polling'); + console.log(''); + const result = await client.request({ + method: 'tools/call', + params: { + name: 'long-task', + arguments: {} + } + }, types_js_1.CallToolResultSchema, { + // Track resumption tokens for debugging + onresumptiontoken: token => { + lastEventId = token; + console.log(`[Event ID] ${token}`); + } + }); + console.log(''); + console.log('[Client] Tool completed!'); + console.log(`[Result] ${JSON.stringify(result.content, null, 2)}`); + console.log(''); + console.log(`[Debug] Final event ID: ${lastEventId}`); + } + catch (error) { + console.error('[Error]', error); + } + finally { + await transport.close(); + console.log('[Client] Disconnected'); + } +} +main().catch(console.error); +//# sourceMappingURL=ssePollingClient.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/ssePollingClient.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/ssePollingClient.js.map new file mode 100644 index 000000000..bcc881d98 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/ssePollingClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ssePollingClient.js","sourceRoot":"","sources":["../../../../src/examples/client/ssePollingClient.ts"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;GAaG;AACH,oDAA+C;AAC/C,sEAA+E;AAC/E,6CAAwF;AAExF,MAAM,UAAU,GAAG,2BAA2B,CAAC;AAE/C,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,iBAAiB,UAAU,KAAK,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAEhB,6CAA6C;IAC7C,MAAM,SAAS,GAAG,IAAI,iDAA6B,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,EAAE;IACrE,wEAAwE;KAC3E,CAAC,CAAC;IAEH,wCAAwC;IACxC,IAAI,WAA+B,CAAC;IAEpC,2DAA2D;IAC3D,mDAAmD;IACnD,SAAS,CAAC,OAAO,GAAG,KAAK,CAAC,EAAE;QACxB,6CAA6C;QAC7C,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAC;YAAE,OAAO;QACjD,2DAA2D;QAC3D,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,wBAAwB,CAAC,EAAE,CAAC;YACnD,OAAO,CAAC,GAAG,CAAC,kEAAkE,CAAC,CAAC;YAChF,OAAO;QACX,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,sBAAsB,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IACvD,CAAC,CAAC;IAEF,iCAAiC;IACjC,SAAS,CAAC,OAAO,GAAG,GAAG,EAAE;QACrB,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;IACjD,CAAC,CAAC;IAEF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I,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;QACnE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAChB,OAAO,CAAC,GAAG,CAAC,2BAA2B,WAAW,EAAE,CAAC,CAAC;IAC1D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;IACpC,CAAC;YAAS,CAAC;QACP,MAAM,SAAS,CAAC,KAAK,EAAE,CAAC;QACxB,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IACzC,CAAC;AACL,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts new file mode 100644 index 000000000..c2679e669 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=streamableHttpWithSseFallbackClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts.map new file mode 100644 index 000000000..b79ae2a72 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttpWithSseFallbackClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js new file mode 100644 index 000000000..bf3e9a885 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js @@ -0,0 +1,168 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const sse_js_1 = require("../../client/sse.js"); +const types_js_1 = require("../../types.js"); +/** + * Simplified Backwards Compatible MCP Client + * + * This client demonstrates backward compatibility with both: + * 1. Modern servers using Streamable HTTP transport (protocol version 2025-03-26) + * 2. Older servers using HTTP+SSE transport (protocol version 2024-11-05) + * + * Following the MCP specification for backwards compatibility: + * - Attempts to POST an initialize request to the server URL first (modern transport) + * - If that fails with 4xx status, falls back to GET request for SSE stream (older transport) + */ +// Command line args processing +const args = process.argv.slice(2); +const serverUrl = args[0] || 'http://localhost:3000/mcp'; +async function main() { + console.log('MCP Backwards Compatible Client'); + console.log('==============================='); + console.log(`Connecting to server at: ${serverUrl}`); + let client; + let transport; + try { + // Try connecting with automatic transport detection + const connection = await connectWithBackwardsCompatibility(serverUrl); + client = connection.client; + transport = connection.transport; + // Set up notification handler + client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { + console.log(`Notification: ${notification.params.level} - ${notification.params.data}`); + }); + // DEMO WORKFLOW: + // 1. List available tools + console.log('\n=== Listing Available Tools ==='); + await listTools(client); + // 2. Call the notification tool + console.log('\n=== Starting Notification Stream ==='); + await startNotificationTool(client); + // 3. Wait for all notifications (5 seconds) + console.log('\n=== Waiting for all notifications ==='); + await new Promise(resolve => setTimeout(resolve, 5000)); + // 4. Disconnect + console.log('\n=== Disconnecting ==='); + await transport.close(); + console.log('Disconnected from MCP server'); + } + catch (error) { + console.error('Error running client:', error); + process.exit(1); + } +} +/** + * Connect to an MCP server with backwards compatibility + * Following the spec for client backward compatibility + */ +async function connectWithBackwardsCompatibility(url) { + console.log('1. Trying Streamable HTTP transport first...'); + // Step 1: Try Streamable HTTP transport first + const client = new index_js_1.Client({ + name: 'backwards-compatible-client', + version: '1.0.0' + }); + client.onerror = error => { + console.error('Client error:', error); + }; + const baseUrl = new URL(url); + try { + // Create modern transport + const streamableTransport = new streamableHttp_js_1.StreamableHTTPClientTransport(baseUrl); + await client.connect(streamableTransport); + console.log('Successfully connected using modern Streamable HTTP transport.'); + return { + client, + transport: streamableTransport, + transportType: 'streamable-http' + }; + } + catch (error) { + // Step 2: If transport fails, try the older SSE transport + console.log(`StreamableHttp transport connection failed: ${error}`); + console.log('2. Falling back to deprecated HTTP+SSE transport...'); + try { + // Create SSE transport pointing to /sse endpoint + const sseTransport = new sse_js_1.SSEClientTransport(baseUrl); + const sseClient = new index_js_1.Client({ + name: 'backwards-compatible-client', + version: '1.0.0' + }); + await sseClient.connect(sseTransport); + console.log('Successfully connected using deprecated HTTP+SSE transport.'); + return { + client: sseClient, + transport: sseTransport, + transportType: 'sse' + }; + } + catch (sseError) { + console.error(`Failed to connect with either transport method:\n1. Streamable HTTP error: ${error}\n2. SSE error: ${sseError}`); + throw new Error('Could not connect to server with any available transport'); + } + } +} +/** + * List available tools on the server + */ +async function listTools(client) { + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - ${tool.name}: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server: ${error}`); + } +} +/** + * Start a notification stream by calling the notification tool + */ +async function startNotificationTool(client) { + try { + // Call the notification tool using reasonable defaults + const request = { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 1000, // 1 second between notifications + count: 5 // Send 5 notifications + } + } + }; + console.log('Calling notification tool...'); + const result = await client.request(request, types_js_1.CallToolResultSchema); + console.log('Tool result:'); + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + catch (error) { + console.log(`Error calling notification tool: ${error}`); + } +} +// Start the client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=streamableHttpWithSseFallbackClient.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js.map new file mode 100644 index 000000000..f3bec99c5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttpWithSseFallbackClient.js","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,gDAAyD;AACzD,6CAMwB;AAExB;;;;;;;;;;GAUG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AAEzD,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,4BAA4B,SAAS,EAAE,CAAC,CAAC;IAErD,IAAI,MAAc,CAAC;IACnB,IAAI,SAA6D,CAAC;IAElE,IAAI,CAAC;QACD,oDAAoD;QACpD,MAAM,UAAU,GAAG,MAAM,iCAAiC,CAAC,SAAS,CAAC,CAAC;QACtE,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC;QAC3B,SAAS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AAC,cAAc,CAAC,CAAC;QAC5B,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;YAC1B,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBACvB,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAClC,CAAC;iBAAM,CAAC;gBACJ,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,WAAW,EAAE,IAAI,CAAC,CAAC;YACjD,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,GAAG,CAAC,oCAAoC,KAAK,EAAE,CAAC,CAAC;IAC7D,CAAC;AACL,CAAC;AAED,mBAAmB;AACnB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts new file mode 100644 index 000000000..218aeac8b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts @@ -0,0 +1,78 @@ +import { AuthorizationParams, OAuthServerProvider } from '../../server/auth/provider.js'; +import { OAuthRegisteredClientsStore } from '../../server/auth/clients.js'; +import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from '../../shared/auth.js'; +import { Response } from 'express'; +import { AuthInfo } from '../../server/auth/types.js'; +export declare class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { + private clients; + getClient(clientId: string): Promise<{ + redirect_uris: string[]; + client_id: string; + token_endpoint_auth_method?: string | undefined; + grant_types?: string[] | undefined; + response_types?: string[] | undefined; + client_name?: string | undefined; + client_uri?: string | undefined; + logo_uri?: string | undefined; + scope?: string | undefined; + contacts?: string[] | undefined; + tos_uri?: string | undefined; + policy_uri?: string | undefined; + jwks_uri?: string | undefined; + jwks?: any; + software_id?: string | undefined; + software_version?: string | undefined; + software_statement?: string | undefined; + client_secret?: string | undefined; + client_id_issued_at?: number | undefined; + client_secret_expires_at?: number | undefined; + } | undefined>; + registerClient(clientMetadata: OAuthClientInformationFull): Promise<{ + redirect_uris: string[]; + client_id: string; + token_endpoint_auth_method?: string | undefined; + grant_types?: string[] | undefined; + response_types?: string[] | undefined; + client_name?: string | undefined; + client_uri?: string | undefined; + logo_uri?: string | undefined; + scope?: string | undefined; + contacts?: string[] | undefined; + tos_uri?: string | undefined; + policy_uri?: string | undefined; + jwks_uri?: string | undefined; + jwks?: any; + software_id?: string | undefined; + software_version?: string | undefined; + software_statement?: string | undefined; + client_secret?: string | undefined; + client_id_issued_at?: number | undefined; + client_secret_expires_at?: number | undefined; + }>; +} +/** + * 🚨 DEMO ONLY - NOT FOR PRODUCTION + * + * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, + * for example: + * - Persistent token storage + * - Rate limiting + */ +export declare class DemoInMemoryAuthProvider implements OAuthServerProvider { + private validateResource?; + clientsStore: DemoInMemoryClientsStore; + private codes; + private tokens; + constructor(validateResource?: ((resource?: URL) => boolean) | undefined); + authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; + challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; + exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, _codeVerifier?: string): Promise; + exchangeRefreshToken(_client: OAuthClientInformationFull, _refreshToken: string, _scopes?: string[], _resource?: URL): Promise; + verifyAccessToken(token: string): Promise; +} +export declare const setupAuthServer: ({ authServerUrl, mcpServerUrl, strictResource }: { + authServerUrl: URL; + mcpServerUrl: URL; + strictResource: boolean; +}) => OAuthMetadata; +//# sourceMappingURL=demoInMemoryOAuthProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts.map new file mode 100644 index 000000000..8a4a43fe8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"demoInMemoryOAuthProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACzF,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAgB,EAAW,QAAQ,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAKtD,qBAAa,wBAAyB,YAAW,2BAA2B;IACxE,OAAO,CAAC,OAAO,CAAiD;IAE1D,SAAS,CAAC,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;IAI1B,cAAc,CAAC,cAAc,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;CAIlE;AAED;;;;;;;GAOG;AACH,qBAAa,wBAAyB,YAAW,mBAAmB;IAWpD,OAAO,CAAC,gBAAgB,CAAC;IAVrC,YAAY,2BAAkC;IAC9C,OAAO,CAAC,KAAK,CAMT;IACJ,OAAO,CAAC,MAAM,CAA+B;gBAEzB,gBAAgB,CAAC,GAAE,CAAC,QAAQ,CAAC,EAAE,GAAG,KAAK,OAAO,aAAA;IAE5D,SAAS,CAAC,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAwCxG,6BAA6B,CAAC,MAAM,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAU7G,yBAAyB,CAC3B,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EAGzB,aAAa,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,WAAW,CAAC;IAoCjB,oBAAoB,CACtB,OAAO,EAAE,0BAA0B,EACnC,aAAa,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE,MAAM,EAAE,EAClB,SAAS,CAAC,EAAE,GAAG,GAChB,OAAO,CAAC,WAAW,CAAC;IAIjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAc5D;AAED,eAAO,MAAM,eAAe,oDAIzB;IACC,aAAa,EAAE,GAAG,CAAC;IACnB,YAAY,EAAE,GAAG,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;CAC3B,KAAG,aA+EH,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/demoInMemoryOAuthProvider.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/demoInMemoryOAuthProvider.js new file mode 100644 index 000000000..c439a3403 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/demoInMemoryOAuthProvider.js @@ -0,0 +1,205 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setupAuthServer = exports.DemoInMemoryAuthProvider = exports.DemoInMemoryClientsStore = void 0; +const node_crypto_1 = require("node:crypto"); +const express_1 = __importDefault(require("express")); +const router_js_1 = require("../../server/auth/router.js"); +const auth_utils_js_1 = require("../../shared/auth-utils.js"); +const errors_js_1 = require("../../server/auth/errors.js"); +class DemoInMemoryClientsStore { + constructor() { + this.clients = new Map(); + } + async getClient(clientId) { + return this.clients.get(clientId); + } + async registerClient(clientMetadata) { + this.clients.set(clientMetadata.client_id, clientMetadata); + return clientMetadata; + } +} +exports.DemoInMemoryClientsStore = DemoInMemoryClientsStore; +/** + * 🚨 DEMO ONLY - NOT FOR PRODUCTION + * + * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, + * for example: + * - Persistent token storage + * - Rate limiting + */ +class DemoInMemoryAuthProvider { + constructor(validateResource) { + this.validateResource = validateResource; + this.clientsStore = new DemoInMemoryClientsStore(); + this.codes = new Map(); + this.tokens = new Map(); + } + async authorize(client, params, res) { + const code = (0, node_crypto_1.randomUUID)(); + const searchParams = new URLSearchParams({ + code + }); + if (params.state !== undefined) { + searchParams.set('state', params.state); + } + this.codes.set(code, { + client, + params + }); + // Simulate a user login + // Set a secure HTTP-only session cookie with authorization info + if (res.cookie) { + const authCookieData = { + userId: 'demo_user', + name: 'Demo User', + timestamp: Date.now() + }; + res.cookie('demo_session', JSON.stringify(authCookieData), { + httpOnly: true, + secure: false, // In production, this should be true + sameSite: 'lax', + maxAge: 24 * 60 * 60 * 1000, // 24 hours - for demo purposes + path: '/' // Available to all routes + }); + } + if (!client.redirect_uris.includes(params.redirectUri)) { + throw new errors_js_1.InvalidRequestError('Unregistered redirect_uri'); + } + const targetUrl = new URL(params.redirectUri); + targetUrl.search = searchParams.toString(); + res.redirect(targetUrl.toString()); + } + async challengeForAuthorizationCode(client, authorizationCode) { + // Store the challenge with the code data + const codeData = this.codes.get(authorizationCode); + if (!codeData) { + throw new Error('Invalid authorization code'); + } + return codeData.params.codeChallenge; + } + async exchangeAuthorizationCode(client, authorizationCode, + // Note: code verifier is checked in token.ts by default + // it's unused here for that reason. + _codeVerifier) { + const codeData = this.codes.get(authorizationCode); + if (!codeData) { + throw new Error('Invalid authorization code'); + } + if (codeData.client.client_id !== client.client_id) { + throw new Error(`Authorization code was not issued to this client, ${codeData.client.client_id} != ${client.client_id}`); + } + if (this.validateResource && !this.validateResource(codeData.params.resource)) { + throw new Error(`Invalid resource: ${codeData.params.resource}`); + } + this.codes.delete(authorizationCode); + const token = (0, node_crypto_1.randomUUID)(); + const tokenData = { + token, + clientId: client.client_id, + scopes: codeData.params.scopes || [], + expiresAt: Date.now() + 3600000, // 1 hour + resource: codeData.params.resource, + type: 'access' + }; + this.tokens.set(token, tokenData); + return { + access_token: token, + token_type: 'bearer', + expires_in: 3600, + scope: (codeData.params.scopes || []).join(' ') + }; + } + async exchangeRefreshToken(_client, _refreshToken, _scopes, _resource) { + throw new Error('Not implemented for example demo'); + } + async verifyAccessToken(token) { + const tokenData = this.tokens.get(token); + if (!tokenData || !tokenData.expiresAt || tokenData.expiresAt < Date.now()) { + throw new Error('Invalid or expired token'); + } + return { + token, + clientId: tokenData.clientId, + scopes: tokenData.scopes, + expiresAt: Math.floor(tokenData.expiresAt / 1000), + resource: tokenData.resource + }; + } +} +exports.DemoInMemoryAuthProvider = DemoInMemoryAuthProvider; +const setupAuthServer = ({ authServerUrl, mcpServerUrl, strictResource }) => { + // Create separate auth server app + // NOTE: This is a separate app on a separate port to illustrate + // how to separate an OAuth Authorization Server from a Resource + // server in the SDK. The SDK is not intended to be provide a standalone + // authorization server. + const validateResource = strictResource + ? (resource) => { + if (!resource) + return false; + const expectedResource = (0, auth_utils_js_1.resourceUrlFromServerUrl)(mcpServerUrl); + return resource.toString() === expectedResource.toString(); + } + : undefined; + const provider = new DemoInMemoryAuthProvider(validateResource); + const authApp = (0, express_1.default)(); + authApp.use(express_1.default.json()); + // For introspection requests + authApp.use(express_1.default.urlencoded()); + // Add OAuth routes to the auth server + // NOTE: this will also add a protected resource metadata route, + // but it won't be used, so leave it. + authApp.use((0, router_js_1.mcpAuthRouter)({ + provider, + issuerUrl: authServerUrl, + scopesSupported: ['mcp:tools'] + })); + authApp.post('/introspect', async (req, res) => { + try { + const { token } = req.body; + if (!token) { + res.status(400).json({ error: 'Token is required' }); + return; + } + const tokenInfo = await provider.verifyAccessToken(token); + res.json({ + active: true, + client_id: tokenInfo.clientId, + scope: tokenInfo.scopes.join(' '), + exp: tokenInfo.expiresAt, + aud: tokenInfo.resource + }); + return; + } + catch (error) { + res.status(401).json({ + active: false, + error: 'Unauthorized', + error_description: `Invalid token: ${error}` + }); + } + }); + const auth_port = authServerUrl.port; + // Start the auth server + authApp.listen(auth_port, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`OAuth Authorization Server listening on port ${auth_port}`); + }); + // Note: we could fetch this from the server, but then we end up + // with some top level async which gets annoying. + const oauthMetadata = (0, router_js_1.createOAuthMetadata)({ + provider, + issuerUrl: authServerUrl, + scopesSupported: ['mcp:tools'] + }); + oauthMetadata.introspection_endpoint = new URL('/introspect', authServerUrl).href; + return oauthMetadata; +}; +exports.setupAuthServer = setupAuthServer; +//# sourceMappingURL=demoInMemoryOAuthProvider.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/demoInMemoryOAuthProvider.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/demoInMemoryOAuthProvider.js.map new file mode 100644 index 000000000..e19a20db9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/demoInMemoryOAuthProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"demoInMemoryOAuthProvider.js","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":";;;;;;AAAA,6CAAyC;AAIzC,sDAAqD;AAErD,2DAAiF;AACjF,8DAAsE;AACtE,2DAAkE;AAElE,MAAa,wBAAwB;IAArC;QACY,YAAO,GAAG,IAAI,GAAG,EAAsC,CAAC;IAUpE,CAAC;IARG,KAAK,CAAC,SAAS,CAAC,QAAgB;QAC5B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACtC,CA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B,EAAE,KAAK,CAAC,CAAC;YAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,SAAS,EAAE,CAAC,CAAC;IAC7E,CAAC,CAAC,CAAC;IAEH,gEAAgE;IAChE,iDAAiD;IACjD,MAAM,aAAa,GAAkB,IAAA,+BAAmB,EAAC;QACrD,QAAQ;QACR,SAAS,EAAE,aAAa;QACxB,eAAe,EAAE,CAAC,WAAW,CAAC;KACjC,CAAC,CAAC;IAEH,aAAa,CAAC,sBAAsB,GAAG,IAAI,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC,IAAI,CAAC;IAElF,OAAO,aAAa,CAAC;AACzB,CAAC,CAAC;AAvFW,QAAA,eAAe,mBAuF1B"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationFormExample.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationFormExample.d.ts new file mode 100644 index 000000000..e4b736e0f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationFormExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=elicitationFormExample.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationFormExample.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationFormExample.d.ts.map new file mode 100644 index 000000000..c569df428 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationFormExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationFormExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationFormExample.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationFormExample.js new file mode 100644 index 000000000..c9f60fa16 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationFormExample.js @@ -0,0 +1,431 @@ +"use strict"; +// Run with: npx tsx src/examples/server/elicitationFormExample.ts +// +// This example demonstrates how to use form elicitation to collect structured user input +// with JSON Schema validation via a local HTTP server with SSE streaming. +// Form elicitation allows servers to request *non-sensitive* user input through the client +// with schema-based validation. +// Note: See also elicitationUrlExample.ts for an example of using URL elicitation +// to collect *sensitive* user input via a browser. +Object.defineProperty(exports, "__esModule", { value: true }); +const node_crypto_1 = require("node:crypto"); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const types_js_1 = require("../../types.js"); +const express_js_1 = require("../../server/express.js"); +// Create MCP server - it will automatically use AjvJsonSchemaValidator with sensible defaults +// The validator supports format validation (email, date, etc.) if ajv-formats is installed +const mcpServer = new mcp_js_1.McpServer({ + name: 'form-elicitation-example-server', + version: '1.0.0' +}, { + capabilities: {} +}); +/** + * Example 1: Simple user registration tool + * Collects username, email, and password from the user + */ +mcpServer.registerTool('register_user', { + description: 'Register a new user account by collecting their information', + inputSchema: {} +}, async () => { + try { + // Request user information through form elicitation + const result = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Please provide your registration information:', + requestedSchema: { + type: 'object', + properties: { + username: { + type: 'string', + title: 'Username', + description: 'Your desired username (3-20 characters)', + minLength: 3, + maxLength: 20 + }, + email: { + type: 'string', + title: 'Email', + description: 'Your email address', + format: 'email' + }, + password: { + type: 'string', + title: 'Password', + description: 'Your password (min 8 characters)', + minLength: 8 + }, + newsletter: { + type: 'boolean', + title: 'Newsletter', + description: 'Subscribe to newsletter?', + default: false + } + }, + required: ['username', 'email', 'password'] + } + }); + // Handle the different possible actions + if (result.action === 'accept' && result.content) { + const { username, email, newsletter } = result.content; + return { + content: [ + { + type: 'text', + text: `Registration successful!\n\nUsername: ${username}\nEmail: ${email}\nNewsletter: ${newsletter ? 'Yes' : 'No'}` + } + ] + }; + } + else if (result.action === 'decline') { + return { + content: [ + { + type: 'text', + text: 'Registration cancelled by user.' + } + ] + }; + } + else { + return { + content: [ + { + type: 'text', + text: 'Registration was cancelled.' + } + ] + }; + } + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Registration failed: ${error instanceof Error ? error.message : String(error)}` + } + ], + isError: true + }; + } +}); +/** + * Example 2: Multi-step workflow with multiple form elicitation requests + * Demonstrates how to collect information in multiple steps + */ +mcpServer.registerTool('create_event', { + description: 'Create a calendar event by collecting event details', + inputSchema: {} +}, async () => { + try { + // Step 1: Collect basic event information + const basicInfo = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Step 1: Enter basic event information', + requestedSchema: { + type: 'object', + properties: { + title: { + type: 'string', + title: 'Event Title', + description: 'Name of the event', + minLength: 1 + }, + description: { + type: 'string', + title: 'Description', + description: 'Event description (optional)' + } + }, + required: ['title'] + } + }); + if (basicInfo.action !== 'accept' || !basicInfo.content) { + return { + content: [{ type: 'text', text: 'Event creation cancelled.' }] + }; + } + // Step 2: Collect date and time + const dateTime = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Step 2: Enter date and time', + requestedSchema: { + type: 'object', + properties: { + date: { + type: 'string', + title: 'Date', + description: 'Event date', + format: 'date' + }, + startTime: { + type: 'string', + title: 'Start Time', + description: 'Event start time (HH:MM)' + }, + duration: { + type: 'integer', + title: 'Duration', + description: 'Duration in minutes', + minimum: 15, + maximum: 480 + } + }, + required: ['date', 'startTime', 'duration'] + } + }); + if (dateTime.action !== 'accept' || !dateTime.content) { + return { + content: [{ type: 'text', text: 'Event creation cancelled.' }] + }; + } + // Combine all collected information + const event = { + ...basicInfo.content, + ...dateTime.content + }; + return { + content: [ + { + type: 'text', + text: `Event created successfully!\n\n${JSON.stringify(event, null, 2)}` + } + ] + }; + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Event creation failed: ${error instanceof Error ? error.message : String(error)}` + } + ], + isError: true + }; + } +}); +/** + * Example 3: Collecting address information + * Demonstrates validation with patterns and optional fields + */ +mcpServer.registerTool('update_shipping_address', { + description: 'Update shipping address with validation', + inputSchema: {} +}, async () => { + try { + const result = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Please provide your shipping address:', + requestedSchema: { + type: 'object', + properties: { + name: { + type: 'string', + title: 'Full Name', + description: 'Recipient name', + minLength: 1 + }, + street: { + type: 'string', + title: 'Street Address', + minLength: 1 + }, + city: { + type: 'string', + title: 'City', + minLength: 1 + }, + state: { + type: 'string', + title: 'State/Province', + minLength: 2, + maxLength: 2 + }, + zipCode: { + type: 'string', + title: 'ZIP/Postal Code', + description: '5-digit ZIP code' + }, + phone: { + type: 'string', + title: 'Phone Number (optional)', + description: 'Contact phone number' + } + }, + required: ['name', 'street', 'city', 'state', 'zipCode'] + } + }); + if (result.action === 'accept' && result.content) { + return { + content: [ + { + type: 'text', + text: `Address updated successfully!\n\n${JSON.stringify(result.content, null, 2)}` + } + ] + }; + } + else if (result.action === 'decline') { + return { + content: [{ type: 'text', text: 'Address update cancelled by user.' }] + }; + } + else { + return { + content: [{ type: 'text', text: 'Address update was cancelled.' }] + }; + } + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Address update failed: ${error instanceof Error ? error.message : String(error)}` + } + ], + isError: true + }; + } +}); +async function main() { + const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000; + const app = (0, express_js_1.createMcpExpressApp)(); + // Map to store transports by session ID + const transports = {}; + // MCP POST endpoint + const mcpPostHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (sessionId) { + console.log(`Received MCP request for session: ${sessionId}`); + } + try { + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport for this session + transport = transports[sessionId]; + } + else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { + // New initialization request - create new transport + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + } + }; + // Connect the transport to the MCP server BEFORE handling the request + await mcpServer.connect(transport); + await transport.handleRequest(req, res, req.body); + return; + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } + }; + app.post('/mcp', mcpPostHandler); + // Handle GET requests for SSE streams + const mcpGetHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Establishing SSE stream for session ${sessionId}`); + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + }; + app.get('/mcp', mcpGetHandler); + // Handle DELETE requests for session termination + const mcpDeleteHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Received session termination request for session ${sessionId}`); + try { + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + } + catch (error) { + console.error('Error handling session termination:', error); + if (!res.headersSent) { + res.status(500).send('Error processing session termination'); + } + } + }; + app.delete('/mcp', mcpDeleteHandler); + // Start listening + app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Form elicitation example server is running on http://localhost:${PORT}/mcp`); + console.log('Available tools:'); + console.log(' - register_user: Collect user registration information'); + console.log(' - create_event: Multi-step event creation'); + console.log(' - update_shipping_address: Collect and validate address'); + console.log('\nConnect your MCP client to this server using the HTTP transport.'); + }); + // Handle server shutdown + process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); + }); +} +main().catch(error => { + console.error('Server error:', error); + process.exit(1); +}); +//# sourceMappingURL=elicitationFormExample.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationFormExample.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationFormExample.js.map new file mode 100644 index 000000000..f294edd27 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationFormExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationFormExample.js","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":";AAAA,kEAAkE;AAClE,EAAE;AACF,yFAAyF;AACzF,0EAA0E;AAC1E,2FAA2F;AAC3F,gCAAgC;AAChC,kFAAkF;AAClF,mDAAmD;;AAEnD,6CAAyC;AAEzC,gDAAgD;AAChD,sEAA+E;AAC/E,6CAAqD;AACrD,wDAA8D;AAE9D,8FAA8F;AAC9F,2FAA2F;AAC3F,MAAM,SAAS,GAAG,IAAI,kBAAS,CAC3B;IACI,IAAI,EAAE,iCAAiC;IACvC,OAAO,EAAE,OAAO;CACnB,EACD;IACI,YAAY,EAAE,EAAE;CACnB,CACJ,CAAC;AAEF;;;GAGG;AACH,SAAS,CAAC,YAAY,CAClB,eAAe,EACf;IACI,WAAW,EAAE,6DAA6D;IAC1E,WAAW,EAAE,EAAE;CAClB,EACD,KAAK,IAAI,EAAE;IACP,IAAI,CAAC;QACD,oDAAoD;QACpD,MAAM,MAAM,GAAG,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uC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;YAC9E,CAAC;QACL,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationUrlExample.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationUrlExample.d.ts new file mode 100644 index 000000000..611f6eba2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationUrlExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=elicitationUrlExample.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationUrlExample.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationUrlExample.d.ts.map new file mode 100644 index 000000000..04acd6664 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationUrlExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationUrlExample.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationUrlExample.js new file mode 100644 index 000000000..53c860bf9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationUrlExample.js @@ -0,0 +1,656 @@ +"use strict"; +// Run with: npx tsx src/examples/server/elicitationUrlExample.ts +// +// This example demonstrates how to use URL elicitation to securely collect +// *sensitive* user input in a remote (HTTP) server. +// URL elicitation allows servers to prompt the end-user to open a URL in their browser +// to collect sensitive information. +// Note: See also elicitationFormExample.ts for an example of using form (not URL) elicitation +// to collect *non-sensitive* user input with a structured schema. +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const express_1 = __importDefault(require("express")); +const node_crypto_1 = require("node:crypto"); +const zod_1 = require("zod"); +const mcp_js_1 = require("../../server/mcp.js"); +const express_js_1 = require("../../server/express.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const router_js_1 = require("../../server/auth/router.js"); +const bearerAuth_js_1 = require("../../server/auth/middleware/bearerAuth.js"); +const types_js_1 = require("../../types.js"); +const inMemoryEventStore_js_1 = require("../shared/inMemoryEventStore.js"); +const demoInMemoryOAuthProvider_js_1 = require("./demoInMemoryOAuthProvider.js"); +const auth_utils_js_1 = require("../../shared/auth-utils.js"); +const cors_1 = __importDefault(require("cors")); +// Create an MCP server with implementation details +const getServer = () => { + const mcpServer = new mcp_js_1.McpServer({ + name: 'url-elicitation-http-server', + version: '1.0.0' + }, { + capabilities: { logging: {} } + }); + mcpServer.registerTool('payment-confirm', { + description: 'A tool that confirms a payment directly with a user', + inputSchema: { + cartId: zod_1.z.string().describe('The ID of the cart to confirm') + } + }, async ({ cartId }, extra) => { + /* + In a real world scenario, there would be some logic here to check if the user has the provided cartId. + For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to confirm payment) + */ + const sessionId = extra.sessionId; + if (!sessionId) { + throw new Error('Expected a Session ID'); + } + // Create and track the elicitation + const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId)); + throw new types_js_1.UrlElicitationRequiredError([ + { + mode: 'url', + message: 'This tool requires a payment confirmation. Open the link to confirm payment!', + url: `http://localhost:${MCP_PORT}/confirm-payment?session=${sessionId}&elicitation=${elicitationId}&cartId=${encodeURIComponent(cartId)}`, + elicitationId + } + ]); + }); + mcpServer.registerTool('third-party-auth', { + description: 'A demo tool that requires third-party OAuth credentials', + inputSchema: { + param1: zod_1.z.string().describe('First parameter') + } + }, async (_, extra) => { + /* + In a real world scenario, there would be some logic here to check if we already have a valid access token for the user. + Auth info (with a subject or `sub` claim) can be typically be found in `extra.authInfo`. + If we do, we can just return the result of the tool call. + If we don't, we can throw an ElicitationRequiredError to request the user to authenticate. + For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to authenticate). + */ + const sessionId = extra.sessionId; + if (!sessionId) { + throw new Error('Expected a Session ID'); + } + // Create and track the elicitation + const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId)); + // Simulate OAuth callback and token exchange after 5 seconds + // In a real app, this would be called from your OAuth callback handler + setTimeout(() => { + console.log(`Simulating OAuth token received for elicitation ${elicitationId}`); + completeURLElicitation(elicitationId); + }, 5000); + throw new types_js_1.UrlElicitationRequiredError([ + { + mode: 'url', + message: 'This tool requires access to your example.com account. Open the link to authenticate!', + url: 'https://www.example.com/oauth/authorize', + elicitationId + } + ]); + }); + return mcpServer; +}; +const elicitationsMap = new Map(); +// Clean up old elicitations after 1 hour to prevent memory leaks +const ELICITATION_TTL_MS = 60 * 60 * 1000; // 1 hour +const CLEANUP_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes +function cleanupOldElicitations() { + const now = new Date(); + for (const [id, metadata] of elicitationsMap.entries()) { + if (now.getTime() - metadata.createdAt.getTime() > ELICITATION_TTL_MS) { + elicitationsMap.delete(id); + console.log(`Cleaned up expired elicitation: ${id}`); + } + } +} +setInterval(cleanupOldElicitations, CLEANUP_INTERVAL_MS); +/** + * Elicitation IDs must be unique strings within the MCP session + * UUIDs are used in this example for simplicity + */ +function generateElicitationId() { + return (0, node_crypto_1.randomUUID)(); +} +/** + * Helper function to create and track a new elicitation. + */ +function generateTrackedElicitation(sessionId, createCompletionNotifier) { + const elicitationId = generateElicitationId(); + // Create a Promise and its resolver for tracking completion + let completeResolver; + const completedPromise = new Promise(resolve => { + completeResolver = resolve; + }); + const completionNotifier = createCompletionNotifier ? createCompletionNotifier(elicitationId) : undefined; + // Store the elicitation in our map + elicitationsMap.set(elicitationId, { + status: 'pending', + completedPromise, + completeResolver: completeResolver, + createdAt: new Date(), + sessionId, + completionNotifier + }); + return elicitationId; +} +/** + * Helper function to complete an elicitation. + */ +function completeURLElicitation(elicitationId) { + const elicitation = elicitationsMap.get(elicitationId); + if (!elicitation) { + console.warn(`Attempted to complete unknown elicitation: ${elicitationId}`); + return; + } + if (elicitation.status === 'complete') { + console.warn(`Elicitation already complete: ${elicitationId}`); + return; + } + // Update metadata + elicitation.status = 'complete'; + // Send completion notification to the client + if (elicitation.completionNotifier) { + console.log(`Sending notifications/elicitation/complete notification for elicitation ${elicitationId}`); + elicitation.completionNotifier().catch(error => { + console.error(`Failed to send completion notification for elicitation ${elicitationId}:`, error); + }); + } + // Resolve the promise to unblock any waiting code + elicitation.completeResolver(); +} +const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; +const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; +const app = (0, express_js_1.createMcpExpressApp)(); +// Allow CORS all domains, expose the Mcp-Session-Id header +app.use((0, cors_1.default)({ + origin: '*', // Allow all origins + exposedHeaders: ['Mcp-Session-Id'], + credentials: true // Allow cookies to be sent cross-origin +})); +// Set up OAuth (required for this example) +let authMiddleware = null; +// Create auth middleware for MCP endpoints +const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); +const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); +const oauthMetadata = (0, demoInMemoryOAuthProvider_js_1.setupAuthServer)({ authServerUrl, mcpServerUrl, strictResource: true }); +const tokenVerifier = { + verifyAccessToken: async (token) => { + const endpoint = oauthMetadata.introspection_endpoint; + if (!endpoint) { + throw new Error('No token verification endpoint available in metadata'); + } + const response = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: new URLSearchParams({ + token: token + }).toString() + }); + if (!response.ok) { + const text = await response.text().catch(() => null); + throw new Error(`Invalid or expired token: ${text}`); + } + const data = await response.json(); + if (!data.aud) { + throw new Error(`Resource Indicator (RFC8707) missing`); + } + if (!(0, auth_utils_js_1.checkResourceAllowed)({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { + throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); + } + // Convert the response to AuthInfo format + return { + token, + clientId: data.client_id, + scopes: data.scope ? data.scope.split(' ') : [], + expiresAt: data.exp + }; + } +}; +// Add metadata routes to the main MCP server +app.use((0, router_js_1.mcpAuthMetadataRouter)({ + oauthMetadata, + resourceServerUrl: mcpServerUrl, + scopesSupported: ['mcp:tools'], + resourceName: 'MCP Demo Server' +})); +authMiddleware = (0, bearerAuth_js_1.requireBearerAuth)({ + verifier: tokenVerifier, + requiredScopes: [], + resourceMetadataUrl: (0, router_js_1.getOAuthProtectedResourceMetadataUrl)(mcpServerUrl) +}); +/** + * API Key Form Handling + * + * Many servers today require an API key to operate, but there's no scalable way to do this dynamically for remote servers within MCP protocol. + * URL-mode elicitation enables the server to host a simple form and get the secret data securely from the user without involving the LLM or client. + **/ +async function sendApiKeyElicitation(sessionId, sender, createCompletionNotifier) { + if (!sessionId) { + console.error('No session ID provided'); + throw new Error('Expected a Session ID to track elicitation'); + } + console.log('🔑 URL elicitation demo: Requesting API key from client...'); + const elicitationId = generateTrackedElicitation(sessionId, createCompletionNotifier); + try { + const result = await sender({ + mode: 'url', + message: 'Please provide your API key to authenticate with this server', + // Host the form on the same server. In a real app, you might coordinate passing these state variables differently. + url: `http://localhost:${MCP_PORT}/api-key-form?session=${sessionId}&elicitation=${elicitationId}`, + elicitationId + }); + switch (result.action) { + case 'accept': + console.log('🔑 URL elicitation demo: Client accepted the API key elicitation (now pending form submission)'); + // Wait for the API key to be submitted via the form + // The form submission will complete the elicitation + break; + default: + console.log('🔑 URL elicitation demo: Client declined to provide an API key'); + // In a real app, this might close the connection, but for the demo, we'll continue + break; + } + } + catch (error) { + console.error('Error during API key elicitation:', error); + } +} +// API Key Form endpoint - serves a simple HTML form +app.get('/api-key-form', (req, res) => { + const mcpSessionId = req.query.session; + const elicitationId = req.query.elicitation; + if (!mcpSessionId || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie + // In production, this is often handled by some user auth middleware to ensure the user has a valid session + // This session is different from the MCP session. + // This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in. + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + // Serve a simple HTML form + res.send(` + + + + Submit Your API Key + + + +

API Key Required

+
✓ Logged in as: ${userSession.name}
+
+ + + + +
+
This is a demo showing how a server can securely elicit sensitive data from a user using a URL.
+ + + `); +}); +// Handle API key form submission +app.post('/api-key-form', express_1.default.urlencoded(), (req, res) => { + const { session: sessionId, apiKey, elicitation: elicitationId } = req.body; + if (!sessionId || !apiKey || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie here too + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + // A real app might store this API key to be used later for the user. + console.log(`🔑 Received API key \x1b[32m${apiKey}\x1b[0m for session ${sessionId}`); + // If we have an elicitationId, complete the elicitation + completeURLElicitation(elicitationId); + // Send a success response + res.send(` + + + + Success + + + +
+

Success ✓

+

API key received.

+
+

You can close this window and return to your MCP client.

+ + + `); +}); +// Helper to get the user session from the demo_session cookie +function getUserSessionCookie(cookieHeader) { + if (!cookieHeader) + return null; + const cookies = cookieHeader.split(';'); + for (const cookie of cookies) { + const [name, value] = cookie.trim().split('='); + if (name === 'demo_session' && value) { + try { + return JSON.parse(decodeURIComponent(value)); + } + catch (error) { + console.error('Failed to parse demo_session cookie:', error); + return null; + } + } + } + return null; +} +/** + * Payment Confirmation Form Handling + * + * This demonstrates how a server can use URL-mode elicitation to get user confirmation + * for sensitive operations like payment processing. + **/ +// Payment Confirmation Form endpoint - serves a simple HTML form +app.get('/confirm-payment', (req, res) => { + const mcpSessionId = req.query.session; + const elicitationId = req.query.elicitation; + const cartId = req.query.cartId; + if (!mcpSessionId || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie + // In production, this is often handled by some user auth middleware to ensure the user has a valid session + // This session is different from the MCP session. + // This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in. + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + // Serve a simple HTML form + res.send(` + + + + Confirm Payment + + + +

Confirm Payment

+
✓ Logged in as: ${userSession.name}
+ ${cartId ? `
Cart ID: ${cartId}
` : ''} +
+ ⚠️ Please review your order before confirming. +
+
+ + + ${cartId ? `` : ''} + + +
+
This is a demo showing how a server can securely get user confirmation for sensitive operations using URL-mode elicitation.
+ + + `); +}); +// Handle Payment Confirmation form submission +app.post('/confirm-payment', express_1.default.urlencoded(), (req, res) => { + const { session: sessionId, elicitation: elicitationId, cartId, action } = req.body; + if (!sessionId || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie here too + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + if (action === 'confirm') { + // A real app would process the payment here + console.log(`💳 Payment confirmed for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`); + // Complete the elicitation + completeURLElicitation(elicitationId); + // Send a success response + res.send(` + + + + Payment Confirmed + + + +
+

Payment Confirmed ✓

+

Your payment has been successfully processed.

+ ${cartId ? `

Cart ID: ${cartId}

` : ''} +
+

You can close this window and return to your MCP client.

+ + + `); + } + else if (action === 'cancel') { + console.log(`💳 Payment cancelled for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`); + // The client will still receive a notifications/elicitation/complete notification, + // which indicates that the out-of-band interaction is complete (but not necessarily successful) + completeURLElicitation(elicitationId); + res.send(` + + + + Payment Cancelled + + + +
+

Payment Cancelled

+

Your payment has been cancelled.

+
+

You can close this window and return to your MCP client.

+ + + `); + } + else { + res.status(400).send('

Error

Invalid action

'); + } +}); +// Map to store transports by session ID +const transports = {}; +const sessionsNeedingElicitation = {}; +// MCP POST endpoint +const mcpPostHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + console.debug(`Received MCP POST for session: ${sessionId || 'unknown'}`); + try { + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { + const server = getServer(); + // New initialization request + const eventStore = new inMemoryEventStore_js_1.InMemoryEventStore(); + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + eventStore, // Enable resumability + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + sessionsNeedingElicitation[sessionId] = { + elicitationSender: params => server.server.elicitInput(params), + createCompletionNotifier: elicitationId => server.server.createElicitationCompletionNotifier(elicitationId) + }; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + delete sessionsNeedingElicitation[sid]; + } + }; + // Connect the transport to the MCP server BEFORE handling the request + // so responses can flow back through the same transport + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport - no need to reconnect + // The existing transport is already connected to the server + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}; +// Set up routes with auth middleware +app.post('/mcp', authMiddleware, mcpPostHandler); +// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) +const mcpGetHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + // Check for Last-Event-ID header for resumability + const lastEventId = req.headers['last-event-id']; + if (lastEventId) { + console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); + } + else { + console.log(`Establishing new SSE stream for session ${sessionId}`); + } + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + if (sessionsNeedingElicitation[sessionId]) { + const { elicitationSender, createCompletionNotifier } = sessionsNeedingElicitation[sessionId]; + // Send an elicitation request to the client in the background + sendApiKeyElicitation(sessionId, elicitationSender, createCompletionNotifier) + .then(() => { + // Only delete on successful send for this demo + delete sessionsNeedingElicitation[sessionId]; + console.log(`🔑 URL elicitation demo: Finished sending API key elicitation request for session ${sessionId}`); + }) + .catch(error => { + console.error('Error sending API key elicitation:', error); + // Keep in map to potentially retry on next reconnect + }); + } +}; +// Set up GET route with conditional auth middleware +app.get('/mcp', authMiddleware, mcpGetHandler); +// Handle DELETE requests for session termination (according to MCP spec) +const mcpDeleteHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Received session termination request for session ${sessionId}`); + try { + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + } + catch (error) { + console.error('Error handling session termination:', error); + if (!res.headersSent) { + res.status(500).send('Error processing session termination'); + } + } +}; +// Set up DELETE route with auth middleware +app.delete('/mcp', authMiddleware, mcpDeleteHandler); +app.listen(MCP_PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + delete sessionsNeedingElicitation[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=elicitationUrlExample.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationUrlExample.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationUrlExample.js.map new file mode 100644 index 000000000..a37e1960a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/elicitationUrlExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.js","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":";AAAA,iEAAiE;AACjE,EAAE;AACF,2EAA2E;AAC3E,oDAAoD;AACpD,uFAAuF;AACvF,oCAAoC;AACpC,8FAA8F;AAC9F,kEAAkE;;;;;AAElE,sDAAqD;AACrD,6CAAyC;AACzC,6BAAwB;AACxB,gDAAgD;AAChD,wDAA8D;AAC9D,sEAA+E;AAC/E,2DAA0G;AAC1G,8EAA+E;AAC/E,6CAAwI;AACxI,2EAAqE;AACrE,iFAAiE;AAEjE,8DAAkE;AAElE,gDAAwB;AAExB,mDAAmD;AACnD,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,SAAS,GAAG,IAAI,kBAAS,CAC3B;QACI,IAA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AAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/honoWebStandardStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/honoWebStandardStreamableHttp.d.ts new file mode 100644 index 000000000..bc6abddea --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/honoWebStandardStreamableHttp.d.ts @@ -0,0 +1,10 @@ +/** + * Example MCP server using Hono with WebStandardStreamableHTTPServerTransport + * + * This example demonstrates using the Web Standard transport directly with Hono, + * which works on any runtime: Node.js, Cloudflare Workers, Deno, Bun, etc. + * + * Run with: npx tsx src/examples/server/honoWebStandardStreamableHttp.ts + */ +export {}; +//# sourceMappingURL=honoWebStandardStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/honoWebStandardStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/honoWebStandardStreamableHttp.d.ts.map new file mode 100644 index 000000000..a6a6199d6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/honoWebStandardStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"honoWebStandardStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/honoWebStandardStreamableHttp.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/honoWebStandardStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/honoWebStandardStreamableHttp.js new file mode 100644 index 000000000..8d96cfe35 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/honoWebStandardStreamableHttp.js @@ -0,0 +1,81 @@ +"use strict"; +/** + * Example MCP server using Hono with WebStandardStreamableHTTPServerTransport + * + * This example demonstrates using the Web Standard transport directly with Hono, + * which works on any runtime: Node.js, Cloudflare Workers, Deno, Bun, etc. + * + * Run with: npx tsx src/examples/server/honoWebStandardStreamableHttp.ts + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const hono_1 = require("hono"); +const cors_1 = require("hono/cors"); +const node_server_1 = require("@hono/node-server"); +const z = __importStar(require("zod/v4")); +const mcp_js_1 = require("../../server/mcp.js"); +const webStandardStreamableHttp_js_1 = require("../../server/webStandardStreamableHttp.js"); +// Create the MCP server +const server = new mcp_js_1.McpServer({ + name: 'hono-webstandard-mcp-server', + version: '1.0.0' +}); +// Register a simple greeting tool +server.registerTool('greet', { + title: 'Greeting Tool', + description: 'A simple greeting tool', + inputSchema: { name: z.string().describe('Name to greet') } +}, async ({ name }) => { + return { + content: [{ type: 'text', text: `Hello, ${name}! (from Hono + WebStandard transport)` }] + }; +}); +// Create a stateless transport (no options = no session management) +const transport = new webStandardStreamableHttp_js_1.WebStandardStreamableHTTPServerTransport(); +// Create the Hono app +const app = new hono_1.Hono(); +// Enable CORS for all origins +app.use('*', (0, cors_1.cors)({ + origin: '*', + allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS'], + allowHeaders: ['Content-Type', 'mcp-session-id', 'Last-Event-ID', 'mcp-protocol-version'], + exposeHeaders: ['mcp-session-id', 'mcp-protocol-version'] +})); +// Health check endpoint +app.get('/health', c => c.json({ status: 'ok' })); +// MCP endpoint +app.all('/mcp', c => transport.handleRequest(c.req.raw)); +// Start the server +const PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; +server.connect(transport).then(() => { + console.log(`Starting Hono MCP server on port ${PORT}`); + console.log(`Health check: http://localhost:${PORT}/health`); + console.log(`MCP endpoint: http://localhost:${PORT}/mcp`); + (0, node_server_1.serve)({ + fetch: app.fetch, + port: PORT + }); +}); +//# sourceMappingURL=honoWebStandardStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/honoWebStandardStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/honoWebStandardStreamableHttp.js.map new file mode 100644 index 000000000..4f3bc2d4e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/honoWebStandardStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"honoWebStandardStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/honoWebStandardStreamableHttp.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,+BAA4B;AAC5B,oCAAiC;AACjC,mDAA0C;AAC1C,0CAA4B;AAC5B,gDAAgD;AAChD,4FAAqG;AAGrG,wBAAwB;AACxB,MAAM,MAAM,GAAG,IAAI,kBAAS,CAAC;IACzB,IAAI,EAAE,6BAA6B;IACnC,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,kCAAkC;AAClC,MAAM,CAAC,YAAY,CACf,OAAO,EACP;IACI,KAAK,EAAE,eAAe;IACtB,WAAW,EAAE,wBAAwB;IACrC,WAAW,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM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AAI,CAAC,GAAG,EAAE;IAChC,OAAO,CAAC,GAAG,CAAC,oCAAoC,IAAI,EAAE,CAAC,CAAC;IACxD,OAAO,CAAC,GAAG,CAAC,kCAAkC,IAAI,SAAS,CAAC,CAAC;IAC7D,OAAO,CAAC,GAAG,CAAC,kCAAkC,IAAI,MAAM,CAAC,CAAC;IAE1D,IAAA,mBAAK,EAAC;QACF,KAAK,EAAE,GAAG,CAAC,KAAK;QAChB,IAAI,EAAE,IAAI;KACb,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts new file mode 100644 index 000000000..477fa6bae --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=jsonResponseStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts.map new file mode 100644 index 000000000..ee8117ee2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonResponseStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/jsonResponseStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/jsonResponseStreamableHttp.js new file mode 100644 index 000000000..ecd769b06 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/jsonResponseStreamableHttp.js @@ -0,0 +1,171 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const node_crypto_1 = require("node:crypto"); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const z = __importStar(require("zod/v4")); +const types_js_1 = require("../../types.js"); +const express_js_1 = require("../../server/express.js"); +// Create an MCP server with implementation details +const getServer = () => { + const server = new mcp_js_1.McpServer({ + name: 'json-response-streamable-http-server', + version: '1.0.0' + }, { + capabilities: { + logging: {} + } + }); + // Register a simple tool that returns a greeting + server.registerTool('greet', { + description: 'A simple greeting tool', + inputSchema: { + name: z.string().describe('Name to greet') + } + }, async ({ name }) => { + return { + content: [ + { + type: 'text', + text: `Hello, ${name}!` + } + ] + }; + }); + // Register a tool that sends multiple greetings with notifications + server.registerTool('multi-greet', { + description: 'A tool that sends different greetings with delays between them', + inputSchema: { + name: z.string().describe('Name to greet') + } + }, async ({ name }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + await server.sendLoggingMessage({ + level: 'debug', + data: `Starting multi-greet for ${name}` + }, extra.sessionId); + await sleep(1000); // Wait 1 second before first greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending first greeting to ${name}` + }, extra.sessionId); + await sleep(1000); // Wait another second before second greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending second greeting to ${name}` + }, extra.sessionId); + return { + content: [ + { + type: 'text', + text: `Good morning, ${name}!` + } + ] + }; + }); + return server; +}; +const app = (0, express_js_1.createMcpExpressApp)(); +// Map to store transports by session ID +const transports = {}; +app.post('/mcp', async (req, res) => { + console.log('Received MCP request:', req.body); + try { + // Check for existing session ID + const sessionId = req.headers['mcp-session-id']; + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { + // New initialization request - use JSON response mode + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + enableJsonResponse: true, // Enable JSON response mode + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Connect the transport to the MCP server BEFORE handling the request + const server = getServer(); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport - no need to reconnect + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +// Handle GET requests for SSE streams according to spec +app.get('/mcp', async (req, res) => { + // Since this is a very simple example, we don't support GET requests for this server + // The spec requires returning 405 Method Not Allowed in this case + res.status(405).set('Allow', 'POST').send('Method Not Allowed'); +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Streamable HTTP Server listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + process.exit(0); +}); +//# sourceMappingURL=jsonResponseStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/jsonResponseStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/jsonResponseStreamableHttp.js.map new file mode 100644 index 000000000..dd8782c1f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/jsonResponseStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonResponseStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,6CAAyC;AACzC,gDAAgD;AAChD,sEAA+E;AAC/E,0CAA4B;AAC5B,6CAAqE;AACrE,wDAA8D;AAE9D,mDAAmD;AACnD,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,kBAAS,CACxB;QACI,IAAI,EAAE,sCAAsC;QAC5C,OAAO,EAAE,OAAO;KACnB,EACD;QACI,YAAY,EAAE;YACV,OAAO,EAAE,EAAE;SACd;KACJ,CACJ,CAAC;IAEF,iDAAiD;IACjD,MAAM,CAAC,YAAY,CACf,OAAO,EACP;QACI,WAAW,EAAE,wBAAwB;QACrC,WAAW,EAAE;YACT,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,eAAe,CAAC;SAC7C;KACJ,EACD,KAAK,EAAE,EAAE,IAAI,EAAE,EAA2B,EAAE;QACxC,OAAO;YACH,OAAO,EAAE;gBACL;oBACI,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,UAAU,IAAI,GAAG;iBAC1B;aACJ;SACJ,CAAC;IACN,CAAC,CACJ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IAAI,EAAE,CAAC,CAAC;AACxE,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/mcpServerOutputSchema.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/mcpServerOutputSchema.d.ts new file mode 100644 index 000000000..a6cb49747 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/mcpServerOutputSchema.d.ts @@ -0,0 +1,7 @@ +#!/usr/bin/env node +/** + * Example MCP server using the high-level McpServer API with outputSchema + * This demonstrates how to easily create tools with structured output + */ +export {}; +//# sourceMappingURL=mcpServerOutputSchema.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/mcpServerOutputSchema.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/mcpServerOutputSchema.d.ts.map new file mode 100644 index 000000000..bd3abdcc2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/mcpServerOutputSchema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mcpServerOutputSchema.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";AACA;;;GAGG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/mcpServerOutputSchema.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/mcpServerOutputSchema.js new file mode 100644 index 000000000..4ac7e5cda --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/mcpServerOutputSchema.js @@ -0,0 +1,95 @@ +#!/usr/bin/env node +"use strict"; +/** + * Example MCP server using the high-level McpServer API with outputSchema + * This demonstrates how to easily create tools with structured output + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const mcp_js_1 = require("../../server/mcp.js"); +const stdio_js_1 = require("../../server/stdio.js"); +const z = __importStar(require("zod/v4")); +const server = new mcp_js_1.McpServer({ + name: 'mcp-output-schema-high-level-example', + version: '1.0.0' +}); +// Define a tool with structured output - Weather data +server.registerTool('get_weather', { + description: 'Get weather information for a city', + inputSchema: { + city: z.string().describe('City name'), + country: z.string().describe('Country code (e.g., US, UK)') + }, + outputSchema: { + temperature: z.object({ + celsius: z.number(), + fahrenheit: z.number() + }), + conditions: z.enum(['sunny', 'cloudy', 'rainy', 'stormy', 'snowy']), + humidity: z.number().min(0).max(100), + wind: z.object({ + speed_kmh: z.number(), + direction: z.string() + }) + } +}, async ({ city, country }) => { + // Parameters are available but not used in this example + void city; + void country; + // Simulate weather API call + const temp_c = Math.round((Math.random() * 35 - 5) * 10) / 10; + const conditions = ['sunny', 'cloudy', 'rainy', 'stormy', 'snowy'][Math.floor(Math.random() * 5)]; + const structuredContent = { + temperature: { + celsius: temp_c, + fahrenheit: Math.round(((temp_c * 9) / 5 + 32) * 10) / 10 + }, + conditions, + humidity: Math.round(Math.random() * 100), + wind: { + speed_kmh: Math.round(Math.random() * 50), + direction: ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][Math.floor(Math.random() * 8)] + } + }; + return { + content: [ + { + type: 'text', + text: JSON.stringify(structuredContent, null, 2) + } + ], + structuredContent + }; +}); +async function main() { + const transport = new stdio_js_1.StdioServerTransport(); + await server.connect(transport); + console.error('High-level Output Schema Example Server running on stdio'); +} +main().catch(error => { + console.error('Server error:', error); + process.exit(1); +}); +//# sourceMappingURL=mcpServerOutputSchema.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/mcpServerOutputSchema.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/mcpServerOutputSchema.js.map new file mode 100644 index 000000000..ba0f8b24c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/mcpServerOutputSchema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mcpServerOutputSchema.js","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";;AACA;;;GAGG;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,gDAAgD;AAChD,oDAA6D;AAC7D,0CAA4B;AAE5B,MAAM,MAAM,GAAG,IAAI,kBAAS,CAAC;IACzB,IAAI,EAAE,sCAAsC;IAC5C,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,sDAAsD;AACtD,MAAM,CAAC,YAAY,CACf,aAAa,EACb;IACI,WAAW,EAAE,oCAAoC;IACjD,WAAW,EAAE;QACT,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,WAAW,CAAC;QACtC,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,6BAA6B,CAAC;KAC9D;IACD,YAAY,EAAE;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CAAC,MAAM,EAAE,GAAG,GAAG,CAAC;QACzC,IAAI,EAAE;YACF,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC;YACzC,SAAS,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;SACzF;KACJ,CAAC;IAEF,OAAO;QACH,OAAO,EAAE;YACL;gBACI,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC;aACnD;SACJ;QACD,iBAAiB;KACpB,CAAC;AACN,CAAC,CACJ,CAAC;AAEF,KAAK,UAAU,IAAI;IACf,MAAM,SAAS,GAAG,IAAI,+BAAoB,EAAE,CAAC;IAC7C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,CAAC,KAAK,CAAC,0DAA0D,CAAC,CAAC;AAC9E,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleSseServer.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleSseServer.d.ts new file mode 100644 index 000000000..4269b7814 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleSseServer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleSseServer.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleSseServer.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleSseServer.d.ts.map new file mode 100644 index 000000000..08a1b4502 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleSseServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleSseServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleSseServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleSseServer.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleSseServer.js new file mode 100644 index 000000000..ed1efd5e3 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleSseServer.js @@ -0,0 +1,168 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const mcp_js_1 = require("../../server/mcp.js"); +const sse_js_1 = require("../../server/sse.js"); +const z = __importStar(require("zod/v4")); +const express_js_1 = require("../../server/express.js"); +/** + * This example server demonstrates the deprecated HTTP+SSE transport + * (protocol version 2024-11-05). It mainly used for testing backward compatible clients. + * + * The server exposes two endpoints: + * - /mcp: For establishing the SSE stream (GET) + * - /messages: For receiving client messages (POST) + * + */ +// Create an MCP server instance +const getServer = () => { + const server = new mcp_js_1.McpServer({ + name: 'simple-sse-server', + version: '1.0.0' + }, { capabilities: { logging: {} } }); + server.registerTool('start-notification-stream', { + description: 'Starts sending periodic notifications', + inputSchema: { + interval: z.number().describe('Interval in milliseconds between notifications').default(1000), + count: z.number().describe('Number of notifications to send').default(10) + } + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + // Send the initial notification + await server.sendLoggingMessage({ + level: 'info', + data: `Starting notification stream with ${count} messages every ${interval}ms` + }, extra.sessionId); + // Send periodic notifications + while (counter < count) { + counter++; + await sleep(interval); + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + } + return { + content: [ + { + type: 'text', + text: `Completed sending ${count} notifications every ${interval}ms` + } + ] + }; + }); + return server; +}; +const app = (0, express_js_1.createMcpExpressApp)(); +// Store transports by session ID +const transports = {}; +// SSE endpoint for establishing the stream +app.get('/mcp', async (req, res) => { + console.log('Received GET request to /sse (establishing SSE stream)'); + try { + // Create a new SSE transport for the client + // The endpoint for POST messages is '/messages' + const transport = new sse_js_1.SSEServerTransport('/messages', res); + // Store the transport by session ID + const sessionId = transport.sessionId; + transports[sessionId] = transport; + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + console.log(`SSE transport closed for session ${sessionId}`); + delete transports[sessionId]; + }; + // Connect the transport to the MCP server + const server = getServer(); + await server.connect(transport); + console.log(`Established SSE stream with session ID: ${sessionId}`); + } + catch (error) { + console.error('Error establishing SSE stream:', error); + if (!res.headersSent) { + res.status(500).send('Error establishing SSE stream'); + } + } +}); +// Messages endpoint for receiving client JSON-RPC requests +app.post('/messages', async (req, res) => { + console.log('Received POST request to /messages'); + // Extract session ID from URL query parameter + // In the SSE protocol, this is added by the client based on the endpoint event + const sessionId = req.query.sessionId; + if (!sessionId) { + console.error('No session ID provided in request URL'); + res.status(400).send('Missing sessionId parameter'); + return; + } + const transport = transports[sessionId]; + if (!transport) { + console.error(`No active transport found for session ID: ${sessionId}`); + res.status(404).send('Session not found'); + return; + } + try { + // Handle the POST message with the transport + await transport.handlePostMessage(req, res, req.body); + } + catch (error) { + console.error('Error handling request:', error); + if (!res.headersSent) { + res.status(500).send('Error handling request'); + } + } +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Simple SSE Server (deprecated protocol version 2024-11-05) listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=simpleSseServer.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleSseServer.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleSseServer.js.map new file mode 100644 index 000000000..e3a334c73 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleSseServer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleSseServer.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleSseServer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,gDAAgD;AAChD,gDAAyD;AACzD,0CAA4B;AAE5B,wDAA8D;AAE9D;;;;;;;;GAQG;AAEH,gCAAgC;AAChC,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,kBA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CAAC,CAAC;QACnD,CAAC;IACL,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gFAAgF,IAAI,EAAE,CAAC,CAAC;AACxG,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAEvC,6DAA6D;IAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts new file mode 100644 index 000000000..0aa4ad243 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleStatelessStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts.map new file mode 100644 index 000000000..92deb06ec --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStatelessStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleStatelessStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStatelessStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStatelessStreamableHttp.js new file mode 100644 index 000000000..87601ab97 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStatelessStreamableHttp.js @@ -0,0 +1,166 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const z = __importStar(require("zod/v4")); +const express_js_1 = require("../../server/express.js"); +const getServer = () => { + // Create an MCP server with implementation details + const server = new mcp_js_1.McpServer({ + name: 'stateless-streamable-http-server', + version: '1.0.0' + }, { capabilities: { logging: {} } }); + // Register a simple prompt + server.registerPrompt('greeting-template', { + description: 'A simple greeting prompt template', + argsSchema: { + name: z.string().describe('Name to include in greeting') + } + }, async ({ name }) => { + return { + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please greet ${name} in a friendly manner.` + } + } + ] + }; + }); + // Register a tool specifically for testing resumability + server.registerTool('start-notification-stream', { + description: 'Starts sending periodic notifications for testing resumability', + inputSchema: { + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(10) + } + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + while (count === 0 || counter < count) { + counter++; + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Periodic notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + // Wait for the specified interval + await sleep(interval); + } + return { + content: [ + { + type: 'text', + text: `Started sending periodic notifications every ${interval}ms` + } + ] + }; + }); + // Create a simple resource at a fixed URI + server.registerResource('greeting-resource', 'https://example.com/greetings/default', { mimeType: 'text/plain' }, async () => { + return { + contents: [ + { + uri: 'https://example.com/greetings/default', + text: 'Hello, world!' + } + ] + }; + }); + return server; +}; +const app = (0, express_js_1.createMcpExpressApp)(); +app.post('/mcp', async (req, res) => { + const server = getServer(); + try { + const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: undefined + }); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + res.on('close', () => { + console.log('Request closed'); + transport.close(); + server.close(); + }); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +app.get('/mcp', async (req, res) => { + console.log('Received GET MCP request'); + res.writeHead(405).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + })); +}); +app.delete('/mcp', async (req, res) => { + console.log('Received DELETE MCP request'); + res.writeHead(405).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + })); +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Stateless Streamable HTTP Server listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + process.exit(0); +}); +//# sourceMappingURL=simpleStatelessStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStatelessStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStatelessStreamableHttp.js.map new file mode 100644 index 000000000..e87774a9a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStatelessStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStatelessStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleStatelessStreamableHttp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,gDAAgD;AAChD,sEAA+E;AAC/E,0CAA4B;AAE5B,wDAA8D;AAE9D,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,mDAAmD;IACnD,MAAM,MAAM,GAAG,IAAI,kBAAS,CACxB;QACI,IAAI,EAAE,kCAAkC;QACxC,OAAO,EAAE,OAAO;KACnB,EACD,EAAE,Y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KAAK,EAAE;YACH,IAAI,EAAE,CAAC,KAAK;YACZ,OAAO,EAAE,qBAAqB;SACjC;QACD,EAAE,EAAE,IAAI;KACX,CAAC,CACL,CAAC;AACN,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,EAAE,CAAC,CAAC;AAClF,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStreamableHttp.d.ts new file mode 100644 index 000000000..a20be42ca --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStreamableHttp.d.ts.map new file mode 100644 index 000000000..e3cf04224 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStreamableHttp.js new file mode 100644 index 000000000..5fb8e3c22 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStreamableHttp.js @@ -0,0 +1,661 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const node_crypto_1 = require("node:crypto"); +const z = __importStar(require("zod/v4")); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const router_js_1 = require("../../server/auth/router.js"); +const bearerAuth_js_1 = require("../../server/auth/middleware/bearerAuth.js"); +const express_js_1 = require("../../server/express.js"); +const types_js_1 = require("../../types.js"); +const inMemoryEventStore_js_1 = require("../shared/inMemoryEventStore.js"); +const in_memory_js_1 = require("../../experimental/tasks/stores/in-memory.js"); +const demoInMemoryOAuthProvider_js_1 = require("./demoInMemoryOAuthProvider.js"); +const auth_utils_js_1 = require("../../shared/auth-utils.js"); +// Check for OAuth flag +const useOAuth = process.argv.includes('--oauth'); +const strictOAuth = process.argv.includes('--oauth-strict'); +// Create shared task store for demonstration +const taskStore = new in_memory_js_1.InMemoryTaskStore(); +// Create an MCP server with implementation details +const getServer = () => { + const server = new mcp_js_1.McpServer({ + name: 'simple-streamable-http-server', + version: '1.0.0', + icons: [{ src: './mcp.svg', sizes: ['512x512'], mimeType: 'image/svg+xml' }], + websiteUrl: 'https://github.com/modelcontextprotocol/typescript-sdk' + }, { + capabilities: { logging: {}, tasks: { requests: { tools: { call: {} } } } }, + taskStore, // Enable task support + taskMessageQueue: new in_memory_js_1.InMemoryTaskMessageQueue() + }); + // Register a simple tool that returns a greeting + server.registerTool('greet', { + title: 'Greeting Tool', // Display name for UI + description: 'A simple greeting tool', + inputSchema: { + name: z.string().describe('Name to greet') + } + }, async ({ name }) => { + return { + content: [ + { + type: 'text', + text: `Hello, ${name}!` + } + ] + }; + }); + // Register a tool that sends multiple greetings with notifications (with annotations) + server.registerTool('multi-greet', { + description: 'A tool that sends different greetings with delays between them', + inputSchema: { + name: z.string().describe('Name to greet') + }, + annotations: { + title: 'Multiple Greeting Tool', + readOnlyHint: true, + openWorldHint: false + } + }, async ({ name }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + await server.sendLoggingMessage({ + level: 'debug', + data: `Starting multi-greet for ${name}` + }, extra.sessionId); + await sleep(1000); // Wait 1 second before first greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending first greeting to ${name}` + }, extra.sessionId); + await sleep(1000); // Wait another second before second greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending second greeting to ${name}` + }, extra.sessionId); + return { + content: [ + { + type: 'text', + text: `Good morning, ${name}!` + } + ] + }; + }); + // Register a tool that demonstrates form elicitation (user input collection with a schema) + // This creates a closure that captures the server instance + server.registerTool('collect-user-info', { + description: 'A tool that collects user information through form elicitation', + inputSchema: { + infoType: z.enum(['contact', 'preferences', 'feedback']).describe('Type of information to collect') + } + }, async ({ infoType }, extra) => { + let message; + let requestedSchema; + switch (infoType) { + case 'contact': + message = 'Please provide your contact information'; + requestedSchema = { + type: 'object', + properties: { + name: { + type: 'string', + title: 'Full Name', + description: 'Your full name' + }, + email: { + type: 'string', + title: 'Email Address', + description: 'Your email address', + format: 'email' + }, + phone: { + type: 'string', + title: 'Phone Number', + description: 'Your phone number (optional)' + } + }, + required: ['name', 'email'] + }; + break; + case 'preferences': + message = 'Please set your preferences'; + requestedSchema = { + type: 'object', + properties: { + theme: { + type: 'string', + title: 'Theme', + description: 'Choose your preferred theme', + enum: ['light', 'dark', 'auto'], + enumNames: ['Light', 'Dark', 'Auto'] + }, + notifications: { + type: 'boolean', + title: 'Enable Notifications', + description: 'Would you like to receive notifications?', + default: true + }, + frequency: { + type: 'string', + title: 'Notification Frequency', + description: 'How often would you like notifications?', + enum: ['daily', 'weekly', 'monthly'], + enumNames: ['Daily', 'Weekly', 'Monthly'] + } + }, + required: ['theme'] + }; + break; + case 'feedback': + message = 'Please provide your feedback'; + requestedSchema = { + type: 'object', + properties: { + rating: { + type: 'integer', + title: 'Rating', + description: 'Rate your experience (1-5)', + minimum: 1, + maximum: 5 + }, + comments: { + type: 'string', + title: 'Comments', + description: 'Additional comments (optional)', + maxLength: 500 + }, + recommend: { + type: 'boolean', + title: 'Would you recommend this?', + description: 'Would you recommend this to others?' + } + }, + required: ['rating', 'recommend'] + }; + break; + default: + throw new Error(`Unknown info type: ${infoType}`); + } + try { + // Use sendRequest through the extra parameter to elicit input + const result = await extra.sendRequest({ + method: 'elicitation/create', + params: { + mode: 'form', + message, + requestedSchema + } + }, types_js_1.ElicitResultSchema); + if (result.action === 'accept') { + return { + content: [ + { + type: 'text', + text: `Thank you! Collected ${infoType} information: ${JSON.stringify(result.content, null, 2)}` + } + ] + }; + } + else if (result.action === 'decline') { + return { + content: [ + { + type: 'text', + text: `No information was collected. User declined ${infoType} information request.` + } + ] + }; + } + else { + return { + content: [ + { + type: 'text', + text: `Information collection was cancelled by the user.` + } + ] + }; + } + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Error collecting ${infoType} information: ${error}` + } + ] + }; + } + }); + // Register a simple prompt with title + server.registerPrompt('greeting-template', { + title: 'Greeting Template', // Display name for UI + description: 'A simple greeting prompt template', + argsSchema: { + name: z.string().describe('Name to include in greeting') + } + }, async ({ name }) => { + return { + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please greet ${name} in a friendly manner.` + } + } + ] + }; + }); + // Register a tool specifically for testing resumability + server.registerTool('start-notification-stream', { + description: 'Starts sending periodic notifications for testing resumability', + inputSchema: { + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(50) + } + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + while (count === 0 || counter < count) { + counter++; + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Periodic notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + // Wait for the specified interval + await sleep(interval); + } + return { + content: [ + { + type: 'text', + text: `Started sending periodic notifications every ${interval}ms` + } + ] + }; + }); + // Create a simple resource at a fixed URI + server.registerResource('greeting-resource', 'https://example.com/greetings/default', { + title: 'Default Greeting', // Display name for UI + description: 'A simple greeting resource', + mimeType: 'text/plain' + }, async () => { + return { + contents: [ + { + uri: 'https://example.com/greetings/default', + text: 'Hello, world!' + } + ] + }; + }); + // Create additional resources for ResourceLink demonstration + server.registerResource('example-file-1', 'file:///example/file1.txt', { + title: 'Example File 1', + description: 'First example file for ResourceLink demonstration', + mimeType: 'text/plain' + }, async () => { + return { + contents: [ + { + uri: 'file:///example/file1.txt', + text: 'This is the content of file 1' + } + ] + }; + }); + server.registerResource('example-file-2', 'file:///example/file2.txt', { + title: 'Example File 2', + description: 'Second example file for ResourceLink demonstration', + mimeType: 'text/plain' + }, async () => { + return { + contents: [ + { + uri: 'file:///example/file2.txt', + text: 'This is the content of file 2' + } + ] + }; + }); + // Register a tool that returns ResourceLinks + server.registerTool('list-files', { + title: 'List Files with ResourceLinks', + description: 'Returns a list of files as ResourceLinks without embedding their content', + inputSchema: { + includeDescriptions: z.boolean().optional().describe('Whether to include descriptions in the resource links') + } + }, async ({ includeDescriptions = true }) => { + const resourceLinks = [ + { + type: 'resource_link', + uri: 'https://example.com/greetings/default', + name: 'Default Greeting', + mimeType: 'text/plain', + ...(includeDescriptions && { description: 'A simple greeting resource' }) + }, + { + type: 'resource_link', + uri: 'file:///example/file1.txt', + name: 'Example File 1', + mimeType: 'text/plain', + ...(includeDescriptions && { description: 'First example file for ResourceLink demonstration' }) + }, + { + type: 'resource_link', + uri: 'file:///example/file2.txt', + name: 'Example File 2', + mimeType: 'text/plain', + ...(includeDescriptions && { description: 'Second example file for ResourceLink demonstration' }) + } + ]; + return { + content: [ + { + type: 'text', + text: 'Here are the available files as resource links:' + }, + ...resourceLinks, + { + type: 'text', + text: '\nYou can read any of these resources using their URI.' + } + ] + }; + }); + // Register a long-running tool that demonstrates task execution + // Using the experimental tasks API - WARNING: may change without notice + server.experimental.tasks.registerToolTask('delay', { + title: 'Delay', + description: 'A simple tool that delays for a specified duration, useful for testing task execution', + inputSchema: { + duration: z.number().describe('Duration in milliseconds').default(5000) + } + }, { + async createTask({ duration }, { taskStore, taskRequestedTtl }) { + // Create the task + const task = await taskStore.createTask({ + ttl: taskRequestedTtl + }); + // Simulate out-of-band work + (async () => { + await new Promise(resolve => setTimeout(resolve, duration)); + await taskStore.storeTaskResult(task.taskId, 'completed', { + content: [ + { + type: 'text', + text: `Completed ${duration}ms delay` + } + ] + }); + })(); + // Return CreateTaskResult with the created task + return { + task + }; + }, + async getTask(_args, { taskId, taskStore }) { + return await taskStore.getTask(taskId); + }, + async getTaskResult(_args, { taskId, taskStore }) { + const result = await taskStore.getTaskResult(taskId); + return result; + } + }); + return server; +}; +const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; +const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; +const app = (0, express_js_1.createMcpExpressApp)(); +// Set up OAuth if enabled +let authMiddleware = null; +if (useOAuth) { + // Create auth middleware for MCP endpoints + const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); + const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); + const oauthMetadata = (0, demoInMemoryOAuthProvider_js_1.setupAuthServer)({ authServerUrl, mcpServerUrl, strictResource: strictOAuth }); + const tokenVerifier = { + verifyAccessToken: async (token) => { + const endpoint = oauthMetadata.introspection_endpoint; + if (!endpoint) { + throw new Error('No token verification endpoint available in metadata'); + } + const response = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: new URLSearchParams({ + token: token + }).toString() + }); + if (!response.ok) { + const text = await response.text().catch(() => null); + throw new Error(`Invalid or expired token: ${text}`); + } + const data = await response.json(); + if (strictOAuth) { + if (!data.aud) { + throw new Error(`Resource Indicator (RFC8707) missing`); + } + if (!(0, auth_utils_js_1.checkResourceAllowed)({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { + throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); + } + } + // Convert the response to AuthInfo format + return { + token, + clientId: data.client_id, + scopes: data.scope ? data.scope.split(' ') : [], + expiresAt: data.exp + }; + } + }; + // Add metadata routes to the main MCP server + app.use((0, router_js_1.mcpAuthMetadataRouter)({ + oauthMetadata, + resourceServerUrl: mcpServerUrl, + scopesSupported: ['mcp:tools'], + resourceName: 'MCP Demo Server' + })); + authMiddleware = (0, bearerAuth_js_1.requireBearerAuth)({ + verifier: tokenVerifier, + requiredScopes: [], + resourceMetadataUrl: (0, router_js_1.getOAuthProtectedResourceMetadataUrl)(mcpServerUrl) + }); +} +// Map to store transports by session ID +const transports = {}; +// MCP POST endpoint with optional auth +const mcpPostHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (sessionId) { + console.log(`Received MCP request for session: ${sessionId}`); + } + else { + console.log('Request body:', req.body); + } + if (useOAuth && req.auth) { + console.log('Authenticated user:', req.auth); + } + try { + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { + // New initialization request + const eventStore = new inMemoryEventStore_js_1.InMemoryEventStore(); + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + eventStore, // Enable resumability + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + } + }; + // Connect the transport to the MCP server BEFORE handling the request + // so responses can flow back through the same transport + const server = getServer(); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport - no need to reconnect + // The existing transport is already connected to the server + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}; +// Set up routes with conditional auth middleware +if (useOAuth && authMiddleware) { + app.post('/mcp', authMiddleware, mcpPostHandler); +} +else { + app.post('/mcp', mcpPostHandler); +} +// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) +const mcpGetHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + if (useOAuth && req.auth) { + console.log('Authenticated SSE connection from user:', req.auth); + } + // Check for Last-Event-ID header for resumability + const lastEventId = req.headers['last-event-id']; + if (lastEventId) { + console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); + } + else { + console.log(`Establishing new SSE stream for session ${sessionId}`); + } + const transport = transports[sessionId]; + await transport.handleRequest(req, res); +}; +// Set up GET route with conditional auth middleware +if (useOAuth && authMiddleware) { + app.get('/mcp', authMiddleware, mcpGetHandler); +} +else { + app.get('/mcp', mcpGetHandler); +} +// Handle DELETE requests for session termination (according to MCP spec) +const mcpDeleteHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Received session termination request for session ${sessionId}`); + try { + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + } + catch (error) { + console.error('Error handling session termination:', error); + if (!res.headersSent) { + res.status(500).send('Error processing session termination'); + } + } +}; +// Set up DELETE route with conditional auth middleware +if (useOAuth && authMiddleware) { + app.delete('/mcp', authMiddleware, mcpDeleteHandler); +} +else { + app.delete('/mcp', mcpDeleteHandler); +} +app.listen(MCP_PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=simpleStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStreamableHttp.js.map new file mode 100644 index 000000000..bd27afcd4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleStreamableHttp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,6CAAyC;AACzC,0CAA4B;AAC5B,gDAAgD;AAChD,sEAA+E;AAC/E,2DAA0G;AAC1G,8EAA+E;AAC/E,wDAA8D;AAC9D,6CAQwB;AACxB,2EAAqE;AACrE,+EAA2G;AAC3G,iFAAiE;AAEjE,8DAAkE;AAElE,uBAAuB;AACvB,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AAClD,MAAM,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;AAE5D,6CAA6C;AAC7C,MAAM,SAAS,GAAG,IAAI,gCAAiB,EAAE,CAAC;AAE1C,mDAAmD;AACnD,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,kBAAS,CACxB;QACI,IAAI,EAAE,+BAA+B;QACrC,OAAO,EAAE,OAAO;QAChB,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC,SAAS,CAAC,EAAE,QAAQ,EAAE,eAAe,EAAE,CAAC;QAC5E,UAAU,EAAE,wDAAwD;KACvE,EACD;QACI,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;QAC3E,SAAS,EAAE,sBAAsB;QACjC,gBAAgB,EAAE,IAAI,uCAAwB,EAAE;KACnD,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,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleTaskInteractive.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleTaskInteractive.d.ts new file mode 100644 index 000000000..661c9f010 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleTaskInteractive.d.ts @@ -0,0 +1,12 @@ +/** + * Simple interactive task server demonstrating elicitation and sampling. + * + * This server demonstrates the task message queue pattern from the MCP Tasks spec: + * - confirm_delete: Uses elicitation to ask the user for confirmation + * - write_haiku: Uses sampling to request an LLM to generate content + * + * Both tools use the "call-now, fetch-later" pattern where the initial call + * creates a task, and the result is fetched via tasks/result endpoint. + */ +export {}; +//# sourceMappingURL=simpleTaskInteractive.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleTaskInteractive.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleTaskInteractive.d.ts.map new file mode 100644 index 000000000..3e48b9e76 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleTaskInteractive.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleTaskInteractive.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleTaskInteractive.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleTaskInteractive.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleTaskInteractive.js new file mode 100644 index 000000000..cd9514078 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleTaskInteractive.js @@ -0,0 +1,600 @@ +"use strict"; +/** + * Simple interactive task server demonstrating elicitation and sampling. + * + * This server demonstrates the task message queue pattern from the MCP Tasks spec: + * - confirm_delete: Uses elicitation to ask the user for confirmation + * - write_haiku: Uses sampling to request an LLM to generate content + * + * Both tools use the "call-now, fetch-later" pattern where the initial call + * creates a task, and the result is fetched via tasks/result endpoint. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const node_crypto_1 = require("node:crypto"); +const index_js_1 = require("../../server/index.js"); +const express_js_1 = require("../../server/express.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const types_js_1 = require("../../types.js"); +const interfaces_js_1 = require("../../experimental/tasks/interfaces.js"); +const in_memory_js_1 = require("../../experimental/tasks/stores/in-memory.js"); +// ============================================================================ +// Resolver - Promise-like for passing results between async operations +// ============================================================================ +class Resolver { + constructor() { + this._done = false; + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + } + setResult(value) { + if (this._done) + return; + this._done = true; + this._resolve(value); + } + setException(error) { + if (this._done) + return; + this._done = true; + this._reject(error); + } + wait() { + return this._promise; + } + done() { + return this._done; + } +} +class TaskMessageQueueWithResolvers { + constructor() { + this.queues = new Map(); + this.waitResolvers = new Map(); + } + getQueue(taskId) { + let queue = this.queues.get(taskId); + if (!queue) { + queue = []; + this.queues.set(taskId, queue); + } + return queue; + } + async enqueue(taskId, message, _sessionId, maxSize) { + const queue = this.getQueue(taskId); + if (maxSize !== undefined && queue.length >= maxSize) { + throw new Error(`Task message queue overflow: queue size (${queue.length}) exceeds maximum (${maxSize})`); + } + queue.push(message); + // Notify any waiters + this.notifyWaiters(taskId); + } + async enqueueWithResolver(taskId, message, resolver, originalRequestId) { + const queue = this.getQueue(taskId); + const queuedMessage = { + type: 'request', + message, + timestamp: Date.now(), + resolver, + originalRequestId + }; + queue.push(queuedMessage); + this.notifyWaiters(taskId); + } + async dequeue(taskId, _sessionId) { + const queue = this.getQueue(taskId); + return queue.shift(); + } + async dequeueAll(taskId, _sessionId) { + const queue = this.queues.get(taskId) ?? []; + this.queues.delete(taskId); + return queue; + } + async waitForMessage(taskId) { + // Check if there are already messages + const queue = this.getQueue(taskId); + if (queue.length > 0) + return; + // Wait for a message to be added + return new Promise(resolve => { + let waiters = this.waitResolvers.get(taskId); + if (!waiters) { + waiters = []; + this.waitResolvers.set(taskId, waiters); + } + waiters.push(resolve); + }); + } + notifyWaiters(taskId) { + const waiters = this.waitResolvers.get(taskId); + if (waiters) { + this.waitResolvers.delete(taskId); + for (const resolve of waiters) { + resolve(); + } + } + } + cleanup() { + this.queues.clear(); + this.waitResolvers.clear(); + } +} +// ============================================================================ +// Extended task store with wait functionality +// ============================================================================ +class TaskStoreWithNotifications extends in_memory_js_1.InMemoryTaskStore { + constructor() { + super(...arguments); + this.updateResolvers = new Map(); + } + async updateTaskStatus(taskId, status, statusMessage, sessionId) { + await super.updateTaskStatus(taskId, status, statusMessage, sessionId); + this.notifyUpdate(taskId); + } + async storeTaskResult(taskId, status, result, sessionId) { + await super.storeTaskResult(taskId, status, result, sessionId); + this.notifyUpdate(taskId); + } + async waitForUpdate(taskId) { + return new Promise(resolve => { + let waiters = this.updateResolvers.get(taskId); + if (!waiters) { + waiters = []; + this.updateResolvers.set(taskId, waiters); + } + waiters.push(resolve); + }); + } + notifyUpdate(taskId) { + const waiters = this.updateResolvers.get(taskId); + if (waiters) { + this.updateResolvers.delete(taskId); + for (const resolve of waiters) { + resolve(); + } + } + } +} +// ============================================================================ +// Task Result Handler - delivers queued messages and routes responses +// ============================================================================ +class TaskResultHandler { + constructor(store, queue) { + this.store = store; + this.queue = queue; + this.pendingRequests = new Map(); + } + async handle(taskId, server, _sessionId) { + while (true) { + // Get fresh task state + const task = await this.store.getTask(taskId); + if (!task) { + throw new Error(`Task not found: ${taskId}`); + } + // Dequeue and send all pending messages + await this.deliverQueuedMessages(taskId, server, _sessionId); + // If task is terminal, return result + if ((0, interfaces_js_1.isTerminal)(task.status)) { + const result = await this.store.getTaskResult(taskId); + // Add related-task metadata per spec + return { + ...result, + _meta: { + ...(result._meta || {}), + [types_js_1.RELATED_TASK_META_KEY]: { taskId } + } + }; + } + // Wait for task update or new message + await this.waitForUpdate(taskId); + } + } + async deliverQueuedMessages(taskId, server, _sessionId) { + while (true) { + const message = await this.queue.dequeue(taskId); + if (!message) + break; + console.log(`[Server] Delivering queued ${message.type} message for task ${taskId}`); + if (message.type === 'request') { + const reqMessage = message; + // Send the request via the server + // Store the resolver so we can route the response back + if (reqMessage.resolver && reqMessage.originalRequestId) { + this.pendingRequests.set(reqMessage.originalRequestId, reqMessage.resolver); + } + // Send the message - for elicitation/sampling, we use the server's methods + // But since we're in tasks/result context, we need to send via transport + // This is simplified - in production you'd use proper message routing + try { + const request = reqMessage.message; + let response; + if (request.method === 'elicitation/create') { + // Send elicitation request to client + const params = request.params; + response = await server.elicitInput(params); + } + else if (request.method === 'sampling/createMessage') { + // Send sampling request to client + const params = request.params; + response = await server.createMessage(params); + } + else { + throw new Error(`Unknown request method: ${request.method}`); + } + // Route response back to resolver + if (reqMessage.resolver) { + reqMessage.resolver.setResult(response); + } + } + catch (error) { + if (reqMessage.resolver) { + reqMessage.resolver.setException(error instanceof Error ? error : new Error(String(error))); + } + } + } + // For notifications, we'd send them too but this example focuses on requests + } + } + async waitForUpdate(taskId) { + // Race between store update and queue message + await Promise.race([this.store.waitForUpdate(taskId), this.queue.waitForMessage(taskId)]); + } + routeResponse(requestId, response) { + const resolver = this.pendingRequests.get(requestId); + if (resolver && !resolver.done()) { + this.pendingRequests.delete(requestId); + resolver.setResult(response); + return true; + } + return false; + } + routeError(requestId, error) { + const resolver = this.pendingRequests.get(requestId); + if (resolver && !resolver.done()) { + this.pendingRequests.delete(requestId); + resolver.setException(error); + return true; + } + return false; + } +} +// ============================================================================ +// Task Session - wraps server to enqueue requests during task execution +// ============================================================================ +class TaskSession { + constructor(server, taskId, store, queue) { + this.server = server; + this.taskId = taskId; + this.store = store; + this.queue = queue; + this.requestCounter = 0; + } + nextRequestId() { + return `task-${this.taskId}-${++this.requestCounter}`; + } + async elicit(message, requestedSchema) { + // Update task status to input_required + await this.store.updateTaskStatus(this.taskId, 'input_required'); + const requestId = this.nextRequestId(); + // Build the elicitation request with related-task metadata + const params = { + message, + requestedSchema, + mode: 'form', + _meta: { + [types_js_1.RELATED_TASK_META_KEY]: { taskId: this.taskId } + } + }; + const jsonrpcRequest = { + jsonrpc: '2.0', + id: requestId, + method: 'elicitation/create', + params + }; + // Create resolver to wait for response + const resolver = new Resolver(); + // Enqueue the request + await this.queue.enqueueWithResolver(this.taskId, jsonrpcRequest, resolver, requestId); + try { + // Wait for response + const response = await resolver.wait(); + // Update status back to working + await this.store.updateTaskStatus(this.taskId, 'working'); + return response; + } + catch (error) { + await this.store.updateTaskStatus(this.taskId, 'working'); + throw error; + } + } + async createMessage(messages, maxTokens) { + // Update task status to input_required + await this.store.updateTaskStatus(this.taskId, 'input_required'); + const requestId = this.nextRequestId(); + // Build the sampling request with related-task metadata + const params = { + messages, + maxTokens, + _meta: { + [types_js_1.RELATED_TASK_META_KEY]: { taskId: this.taskId } + } + }; + const jsonrpcRequest = { + jsonrpc: '2.0', + id: requestId, + method: 'sampling/createMessage', + params + }; + // Create resolver to wait for response + const resolver = new Resolver(); + // Enqueue the request + await this.queue.enqueueWithResolver(this.taskId, jsonrpcRequest, resolver, requestId); + try { + // Wait for response + const response = await resolver.wait(); + // Update status back to working + await this.store.updateTaskStatus(this.taskId, 'working'); + return response; + } + catch (error) { + await this.store.updateTaskStatus(this.taskId, 'working'); + throw error; + } + } +} +// ============================================================================ +// Server Setup +// ============================================================================ +const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 8000; +// Create shared stores +const taskStore = new TaskStoreWithNotifications(); +const messageQueue = new TaskMessageQueueWithResolvers(); +const taskResultHandler = new TaskResultHandler(taskStore, messageQueue); +// Track active task executions +const activeTaskExecutions = new Map(); +// Create the server +const createServer = () => { + const server = new index_js_1.Server({ name: 'simple-task-interactive', version: '1.0.0' }, { + capabilities: { + tools: {}, + tasks: { + requests: { + tools: { call: {} } + } + } + } + }); + // Register tools + server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => { + return { + tools: [ + { + name: 'confirm_delete', + description: 'Asks for confirmation before deleting (demonstrates elicitation)', + inputSchema: { + type: 'object', + properties: { + filename: { type: 'string' } + } + }, + execution: { taskSupport: 'required' } + }, + { + name: 'write_haiku', + description: 'Asks LLM to write a haiku (demonstrates sampling)', + inputSchema: { + type: 'object', + properties: { + topic: { type: 'string' } + } + }, + execution: { taskSupport: 'required' } + } + ] + }; + }); + // Handle tool calls + server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => { + const { name, arguments: args } = request.params; + const taskParams = (request.params._meta?.task || request.params.task); + // Validate task mode - these tools require tasks + if (!taskParams) { + throw new Error(`Tool ${name} requires task mode`); + } + // Create task + const taskOptions = { + ttl: taskParams.ttl, + pollInterval: taskParams.pollInterval ?? 1000 + }; + const task = await taskStore.createTask(taskOptions, extra.requestId, request, extra.sessionId); + console.log(`\n[Server] ${name} called, task created: ${task.taskId}`); + // Start background task execution + const taskExecution = (async () => { + try { + const taskSession = new TaskSession(server, task.taskId, taskStore, messageQueue); + if (name === 'confirm_delete') { + const filename = args?.filename ?? 'unknown.txt'; + console.log(`[Server] confirm_delete: asking about '${filename}'`); + console.log('[Server] Sending elicitation request to client...'); + const result = await taskSession.elicit(`Are you sure you want to delete '${filename}'?`, { + type: 'object', + properties: { + confirm: { type: 'boolean' } + }, + required: ['confirm'] + }); + console.log(`[Server] Received elicitation response: action=${result.action}, content=${JSON.stringify(result.content)}`); + let text; + if (result.action === 'accept' && result.content) { + const confirmed = result.content.confirm; + text = confirmed ? `Deleted '${filename}'` : 'Deletion cancelled'; + } + else { + text = 'Deletion cancelled'; + } + console.log(`[Server] Completing task with result: ${text}`); + await taskStore.storeTaskResult(task.taskId, 'completed', { + content: [{ type: 'text', text }] + }); + } + else if (name === 'write_haiku') { + const topic = args?.topic ?? 'nature'; + console.log(`[Server] write_haiku: topic '${topic}'`); + console.log('[Server] Sending sampling request to client...'); + const result = await taskSession.createMessage([ + { + role: 'user', + content: { type: 'text', text: `Write a haiku about ${topic}` } + } + ], 50); + let haiku = 'No response'; + if (result.content && 'text' in result.content) { + haiku = result.content.text; + } + console.log(`[Server] Received sampling response: ${haiku.substring(0, 50)}...`); + console.log('[Server] Completing task with haiku'); + await taskStore.storeTaskResult(task.taskId, 'completed', { + content: [{ type: 'text', text: `Haiku:\n${haiku}` }] + }); + } + } + catch (error) { + console.error(`[Server] Task ${task.taskId} failed:`, error); + await taskStore.storeTaskResult(task.taskId, 'failed', { + content: [{ type: 'text', text: `Error: ${error}` }], + isError: true + }); + } + finally { + activeTaskExecutions.delete(task.taskId); + } + })(); + activeTaskExecutions.set(task.taskId, { + promise: taskExecution, + server, + sessionId: extra.sessionId ?? '' + }); + return { task }; + }); + // Handle tasks/get + server.setRequestHandler(types_js_1.GetTaskRequestSchema, async (request) => { + const { taskId } = request.params; + const task = await taskStore.getTask(taskId); + if (!task) { + throw new Error(`Task ${taskId} not found`); + } + return task; + }); + // Handle tasks/result + server.setRequestHandler(types_js_1.GetTaskPayloadRequestSchema, async (request, extra) => { + const { taskId } = request.params; + console.log(`[Server] tasks/result called for task ${taskId}`); + return taskResultHandler.handle(taskId, server, extra.sessionId ?? ''); + }); + return server; +}; +// ============================================================================ +// Express App Setup +// ============================================================================ +const app = (0, express_js_1.createMcpExpressApp)(); +// Map to store transports by session ID +const transports = {}; +// Helper to check if request is initialize +const isInitializeRequest = (body) => { + return typeof body === 'object' && body !== null && 'method' in body && body.method === 'initialize'; +}; +// MCP POST endpoint +app.post('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + try { + let transport; + if (sessionId && transports[sessionId]) { + transport = transports[sessionId]; + } + else if (!sessionId && isInitializeRequest(req.body)) { + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + onsessioninitialized: sid => { + console.log(`Session initialized: ${sid}`); + transports[sid] = transport; + } + }); + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}`); + delete transports[sid]; + } + }; + const server = createServer(); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; + } + else { + res.status(400).json({ + jsonrpc: '2.0', + error: { code: -32000, message: 'Bad Request: No valid session ID' }, + id: null + }); + return; + } + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { code: -32603, message: 'Internal server error' }, + id: null + }); + } + } +}); +// Handle GET requests for SSE streams +app.get('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + const transport = transports[sessionId]; + await transport.handleRequest(req, res); +}); +// Handle DELETE requests for session termination +app.delete('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Session termination request: ${sessionId}`); + const transport = transports[sessionId]; + await transport.handleRequest(req, res); +}); +// Start server +app.listen(PORT, () => { + console.log(`Starting server on http://localhost:${PORT}/mcp`); + console.log('\nAvailable tools:'); + console.log(' - confirm_delete: Demonstrates elicitation (asks user y/n)'); + console.log(' - write_haiku: Demonstrates sampling (requests LLM completion)'); +}); +// Handle shutdown +process.on('SIGINT', async () => { + console.log('\nShutting down server...'); + for (const sessionId of Object.keys(transports)) { + try { + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing session ${sessionId}:`, error); + } + } + taskStore.cleanup(); + messageQueue.cleanup(); + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=simpleTaskInteractive.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleTaskInteractive.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleTaskInteractive.js.map new file mode 100644 index 000000000..faabd3ff0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/simpleTaskInteractive.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleTaskInteractive.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleTaskInteractive.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;AAGH,6CAAyC;AACzC,oDAA+C;AAC/C,wDAA8D;AAC9D,sEAA+E;AAC/E,6CAsBwB;AACxB,0EAAuI;AACvI,+EAAiF;AAEjF,+EAA+E;AAC/E,uEAAuE;AACvE,+EAA+E;AAE/E,MAAM,QAAQ;IAMV;QAFQ,UAAK,GAAG,KAAK,CAAC;QAGlB,IAAI,CAAC,QAAQ,GAAG,IAAI,OAAO,CAAI,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC/C,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;YACxB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QAC1B,CAAC,CAAC,CAAC;IACP,CAAC;IAED,SAAS,CAAC,KAAQ;QACd,IAAI,IAAI,CAAC,KAAK;YAAE,OAAO;QACvB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IAED,YAAY,CAAC,KAAY;QACrB,IAAI,IAAI,CAAC,KAAK;YAAE,OAAO;QACvB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IAED,IAAI;QACA,OAAO,IAAI,CAAC,QAAQ,CAAC;IACzB,CAAC;IAED,IAAI;QACA,OAAO,IAAI,CAAC,KAAK,CAAC;IACtB,CAAC;CACJ;AAaD,MAAM,6BAA6B;IAAnC;QACY,WAAM,GAAG,IAAI,GAAG,EAAuC,CAAC;QACxD,kBAAa,GAAG,IAAI,GAAG,EAA0B,CAAC;IAgF9D,CAAC;IA9EW,QAAQ,CAAC,MAAc;QAC3B,IAAI,KAAK,GAAG,IAAI,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AAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IAClC,OAAO,CAAC,GAAG,CAAC,8DAA8D,CAAC,CAAC;IAC5E,OAAO,CAAC,GAAG,CAAC,kEAAkE,CAAC,CAAC;AACpF,CAAC,CAAC,CAAC;AAEH,kBAAkB;AAClB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;IACzC,KAAK,MAAM,SAAS,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QAC9C,IAAI,CAAC;YACD,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,yBAAyB,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAChE,CAAC;IACL,CAAC;IACD,SAAS,CAAC,OAAO,EAAE,CAAC;IACpB,YAAY,CAAC,OAAO,EAAE,CAAC;IACvB,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts new file mode 100644 index 000000000..c536d0c80 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map new file mode 100644 index 000000000..fb982c84a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sseAndStreamableHttpCompatibleServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/sseAndStreamableHttpCompatibleServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js new file mode 100644 index 000000000..6e2c1b44f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js @@ -0,0 +1,256 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const node_crypto_1 = require("node:crypto"); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const sse_js_1 = require("../../server/sse.js"); +const z = __importStar(require("zod/v4")); +const types_js_1 = require("../../types.js"); +const inMemoryEventStore_js_1 = require("../shared/inMemoryEventStore.js"); +const express_js_1 = require("../../server/express.js"); +/** + * This example server demonstrates backwards compatibility with both: + * 1. The deprecated HTTP+SSE transport (protocol version 2024-11-05) + * 2. The Streamable HTTP transport (protocol version 2025-11-25) + * + * It maintains a single MCP server instance but exposes two transport options: + * - /mcp: The new Streamable HTTP endpoint (supports GET/POST/DELETE) + * - /sse: The deprecated SSE endpoint for older clients (GET to establish stream) + * - /messages: The deprecated POST endpoint for older clients (POST to send messages) + */ +const getServer = () => { + const server = new mcp_js_1.McpServer({ + name: 'backwards-compatible-server', + version: '1.0.0' + }, { capabilities: { logging: {} } }); + // Register a simple tool that sends notifications over time + server.registerTool('start-notification-stream', { + description: 'Starts sending periodic notifications for testing resumability', + inputSchema: { + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(50) + } + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + while (count === 0 || counter < count) { + counter++; + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Periodic notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + // Wait for the specified interval + await sleep(interval); + } + return { + content: [ + { + type: 'text', + text: `Started sending periodic notifications every ${interval}ms` + } + ] + }; + }); + return server; +}; +// Create Express application +const app = (0, express_js_1.createMcpExpressApp)(); +// Store transports by session ID +const transports = {}; +//============================================================================= +// STREAMABLE HTTP TRANSPORT (PROTOCOL VERSION 2025-11-25) +//============================================================================= +// Handle all MCP Streamable HTTP requests (GET, POST, DELETE) on a single endpoint +app.all('/mcp', async (req, res) => { + console.log(`Received ${req.method} request to /mcp`); + try { + // Check for existing session ID + const sessionId = req.headers['mcp-session-id']; + let transport; + if (sessionId && transports[sessionId]) { + // Check if the transport is of the correct type + const existingTransport = transports[sessionId]; + if (existingTransport instanceof streamableHttp_js_1.StreamableHTTPServerTransport) { + // Reuse existing transport + transport = existingTransport; + } + else { + // Transport exists but is not a StreamableHTTPServerTransport (could be SSEServerTransport) + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Session exists but uses a different transport protocol' + }, + id: null + }); + return; + } + } + else if (!sessionId && req.method === 'POST' && (0, types_js_1.isInitializeRequest)(req.body)) { + const eventStore = new inMemoryEventStore_js_1.InMemoryEventStore(); + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + eventStore, // Enable resumability + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + console.log(`StreamableHTTP session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + } + }; + // Connect the transport to the MCP server + const server = getServer(); + await server.connect(transport); + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with the transport + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +//============================================================================= +// DEPRECATED HTTP+SSE TRANSPORT (PROTOCOL VERSION 2024-11-05) +//============================================================================= +app.get('/sse', async (req, res) => { + console.log('Received GET request to /sse (deprecated SSE transport)'); + const transport = new sse_js_1.SSEServerTransport('/messages', res); + transports[transport.sessionId] = transport; + res.on('close', () => { + delete transports[transport.sessionId]; + }); + const server = getServer(); + await server.connect(transport); +}); +app.post('/messages', async (req, res) => { + const sessionId = req.query.sessionId; + let transport; + const existingTransport = transports[sessionId]; + if (existingTransport instanceof sse_js_1.SSEServerTransport) { + // Reuse existing transport + transport = existingTransport; + } + else { + // Transport exists but is not a SSEServerTransport (could be StreamableHTTPServerTransport) + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Session exists but uses a different transport protocol' + }, + id: null + }); + return; + } + if (transport) { + await transport.handlePostMessage(req, res, req.body); + } + else { + res.status(400).send('No transport found for sessionId'); + } +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Backwards compatible MCP server listening on port ${PORT}`); + console.log(` +============================================== +SUPPORTED TRANSPORT OPTIONS: + +1. Streamable Http(Protocol version: 2025-11-25) + Endpoint: /mcp + Methods: GET, POST, DELETE + Usage: + - Initialize with POST to /mcp + - Establish SSE stream with GET to /mcp + - Send requests with POST to /mcp + - Terminate session with DELETE to /mcp + +2. Http + SSE (Protocol version: 2024-11-05) + Endpoints: /sse (GET) and /messages (POST) + Usage: + - Establish SSE stream with GET to /sse + - Send requests with POST to /messages?sessionId= +============================================== +`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js.map new file mode 100644 index 000000000..3f6331a8b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sseAndStreamableHttpCompatibleServer.js","sourceRoot":"","sources":["../../../../src/examples/server/sseAndStreamableHttpCompatibleServer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,6CAAyC;AACzC,gDAAgD;AAChD,sEAA+E;AAC/E,gDAAyD;AACzD,0CAA4B;AAC5B,6CAAqE;AACrE,2EAAqE;AACrE,wDAA8D;AAE9D;;;;;;;;;GASG;AAEH,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,kBAAS,CACxB;QACI,IAAI,EAAE,6BAA6B;QACnC,OAAO,EAAE,OAAO;KACnB,EACD,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,CACpC,CAAC;IAEF,4DAA4D;IAC5D,MAAM,CAAC,YAAY,CACf,2BAA2B,EAC3B;QACI,WAAW,EAAE,gEAAgE;QAC7E,WAAW,EAAE;YACT,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,gDAAgD,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC;YAC5F,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,6CAA6C,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;SACxF;KACJ,EACD,KAAK,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,KAAK,EAA2B,EAAE;QAC1D,MAAM,KAAK,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;QAC9E,IAAI,OAAO,GAAG,CAAC,CAAC;QAEhB,OAAO,KAAK,KAAK,CAAC,IAAI,OAAO,GAAG,KAAK,EAAE,CAAC;YACpC,OAAO,EAAE,CAAC;YACV,IAAI,CAAC;gBACD,MAAM,MAAM,CAAC,kBAAkB,CAC3B;oBAC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D,IAAI,EAAE,CAAC,CAAC;IACzE,OAAO,CAAC,GAAG,CAAC;;;;;;;;;;;;;;;;;;;CAmBf,CAAC,CAAC;AACH,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAEvC,6DAA6D;IAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/ssePollingExample.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/ssePollingExample.d.ts new file mode 100644 index 000000000..63e45548e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/ssePollingExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=ssePollingExample.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/ssePollingExample.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/ssePollingExample.d.ts.map new file mode 100644 index 000000000..93827316a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/ssePollingExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ssePollingExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/ssePollingExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/ssePollingExample.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/ssePollingExample.js new file mode 100644 index 000000000..479289699 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/ssePollingExample.js @@ -0,0 +1,102 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const node_crypto_1 = require("node:crypto"); +const mcp_js_1 = require("../../server/mcp.js"); +const express_js_1 = require("../../server/express.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const inMemoryEventStore_js_1 = require("../shared/inMemoryEventStore.js"); +const cors_1 = __importDefault(require("cors")); +// Create the MCP server +const server = new mcp_js_1.McpServer({ + name: 'sse-polling-example', + version: '1.0.0' +}, { + capabilities: { logging: {} } +}); +// Register a long-running tool that demonstrates server-initiated disconnect +server.tool('long-task', 'A long-running task that sends progress updates. Server will disconnect mid-task to demonstrate polling.', {}, async (_args, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + console.log(`[${extra.sessionId}] Starting long-task...`); + // Send first progress notification + await server.sendLoggingMessage({ + level: 'info', + data: 'Progress: 25% - Starting work...' + }, extra.sessionId); + await sleep(1000); + // Send second progress notification + await server.sendLoggingMessage({ + level: 'info', + data: 'Progress: 50% - Halfway there...' + }, extra.sessionId); + await sleep(1000); + // Server decides to disconnect the client to free resources + // Client will reconnect via GET with Last-Event-ID after the transport's retryInterval + // Use extra.closeSSEStream callback - available when eventStore is configured + if (extra.closeSSEStream) { + console.log(`[${extra.sessionId}] Closing SSE stream to trigger client polling...`); + extra.closeSSEStream(); + } + // Continue processing while client is disconnected + // Events are stored in eventStore and will be replayed on reconnect + await sleep(500); + await server.sendLoggingMessage({ + level: 'info', + data: 'Progress: 75% - Almost done (sent while client disconnected)...' + }, extra.sessionId); + await sleep(500); + await server.sendLoggingMessage({ + level: 'info', + data: 'Progress: 100% - Complete!' + }, extra.sessionId); + console.log(`[${extra.sessionId}] Task complete`); + return { + content: [ + { + type: 'text', + text: 'Long task completed successfully!' + } + ] + }; +}); +// Set up Express app +const app = (0, express_js_1.createMcpExpressApp)(); +app.use((0, cors_1.default)()); +// Create event store for resumability +const eventStore = new inMemoryEventStore_js_1.InMemoryEventStore(); +// Track transports by session ID for session reuse +const transports = new Map(); +// Handle all MCP requests +app.all('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + // Reuse existing transport or create new one + let transport = sessionId ? transports.get(sessionId) : undefined; + if (!transport) { + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + eventStore, + retryInterval: 2000, // Default retry interval for priming events + onsessioninitialized: id => { + console.log(`[${id}] Session initialized`); + transports.set(id, transport); + } + }); + // Connect the MCP server to the transport + await server.connect(transport); + } + await transport.handleRequest(req, res, req.body); +}); +// Start the server +const PORT = 3001; +app.listen(PORT, () => { + console.log(`SSE Polling Example Server running on http://localhost:${PORT}/mcp`); + console.log(''); + console.log('This server demonstrates SEP-1699 SSE polling:'); + console.log('- retryInterval: 2000ms (client waits 2s before reconnecting)'); + console.log('- eventStore: InMemoryEventStore (events are persisted for replay)'); + console.log(''); + console.log('Try calling the "long-task" tool to see server-initiated disconnect in action.'); +}); +//# sourceMappingURL=ssePollingExample.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/ssePollingExample.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/ssePollingExample.js.map new file mode 100644 index 000000000..99267c811 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/ssePollingExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ssePollingExample.js","sourceRoot":"","sources":["../../../../src/examples/server/ssePollingExample.ts"],"names":[],"mappings":";;;;;AAeA,6CAAyC;AACzC,gDAAgD;AAChD,wDAA8D;AAC9D,sEAA+E;AAE/E,2EAAqE;AACrE,gDAAwB;AAExB,wBAAwB;AACxB,MAAM,MAAM,GAAG,IAAI,kBAAS,CACxB;IACI,IAAI,EAAE,qBAAqB;IAC3B,OAAO,EAAE,OAAO;CACnB,EACD;IACI,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;CAChC,CACJ,CAAC;AAEF,6EAA6E;AAC7E,MAAM,CAAC,IAAI,CACP,WAAW,EACX,0GAA0G,EAC1G,EAAE,EACF,KAAK,EAAE,KAAK,EAAE,KAAK,EAA2B,EAAE;IAC5C,MAAM,KAAK,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;IAE9E,OAAO,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,SAAS,yBAAyB,CAAC,CAAC;IAE1D,mCAAmC;IACnC,MAAM,MAAM,CAAC,kBAAkB,CAC3B;QACI,KAAK,EAAE,MAAM;QACb,IAAI,EAAE,kCAAkC;KAC3C,EACD,KAAK,CAAC,SAAS,CAClB,CAAC;IACF,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC;IAElB,oCAAoC;IACpC,MAAM,MAAM,CAAC,kBAAkB,CAC3B;QACI,KAAK,EAAE,MAAM;QACb,IAAI,EAAE,kCAAkC;KAC3C,EACD,KAAK,CAAC,SAAS,CAClB,CAAC;IACF,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC;IAElB,4DAA4D;IAC5D,uFAAuF;IACvF,8EAA8E;IAC9E,IAAI,KAAK,CAAC,cAAc,EAAE,CAAC;QACvB,OAAO,CAAC,GAAG,CAAC,IA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E,IAAI,CAAC,SAAS,EAAE,CAAC;QACb,SAAS,GAAG,IAAI,iDAA6B,CAAC;YAC1C,kBAAkB,EAAE,GAAG,EAAE,CAAC,IAAA,wBAAU,GAAE;YACtC,UAAU;YACV,aAAa,EAAE,IAAI,EAAE,4CAA4C;YACjE,oBAAoB,EAAE,EAAE,CAAC,EAAE;gBACvB,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,uBAAuB,CAAC,CAAC;gBAC3C,UAAU,CAAC,GAAG,CAAC,EAAE,EAAE,SAAU,CAAC,CAAC;YACnC,CAAC;SACJ,CAAC,CAAC;QAEH,0CAA0C;QAC1C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACpC,CAAC;IAED,MAAM,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;AACtD,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE;IAClB,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,MAAM,CAAC,CAAC;IAClF,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,gDAAgD,CAAC,CAAC;IAC9D,OAAO,CAAC,GAAG,CAAC,+DAA+D,CAAC,CAAC;IAC7E,OAAO,CAAC,GAAG,CAAC,oEAAoE,CAAC,CAAC;IAClF,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,gFAAgF,CAAC,CAAC;AAClG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts new file mode 100644 index 000000000..4df17831b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=standaloneSseWithGetStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map new file mode 100644 index 000000000..df60dc51b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"standaloneSseWithGetStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/standaloneSseWithGetStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js new file mode 100644 index 000000000..31a8f06fa --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js @@ -0,0 +1,112 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const node_crypto_1 = require("node:crypto"); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const types_js_1 = require("../../types.js"); +const express_js_1 = require("../../server/express.js"); +// Create an MCP server with implementation details +const server = new mcp_js_1.McpServer({ + name: 'resource-list-changed-notification-server', + version: '1.0.0' +}); +// Store transports by session ID to send notifications +const transports = {}; +const addResource = (name, content) => { + const uri = `https://mcp-example.com/dynamic/${encodeURIComponent(name)}`; + server.registerResource(name, uri, { mimeType: 'text/plain', description: `Dynamic resource: ${name}` }, async () => { + return { + contents: [{ uri, text: content }] + }; + }); +}; +addResource('example-resource', 'Initial content for example-resource'); +const resourceChangeInterval = setInterval(() => { + const name = (0, node_crypto_1.randomUUID)(); + addResource(name, `Content for ${name}`); +}, 5000); // Change resources every 5 seconds for testing +const app = (0, express_js_1.createMcpExpressApp)(); +app.post('/mcp', async (req, res) => { + console.log('Received MCP request:', req.body); + try { + // Check for existing session ID + const sessionId = req.headers['mcp-session-id']; + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { + // New initialization request + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Connect the transport to the MCP server + await server.connect(transport); + // Handle the request - the onsessioninitialized callback will store the transport + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +// Handle GET requests for SSE streams (now using built-in support from StreamableHTTP) +app.get('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Establishing SSE stream for session ${sessionId}`); + const transport = transports[sessionId]; + await transport.handleRequest(req, res); +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Server listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + clearInterval(resourceChangeInterval); + await server.close(); + process.exit(0); +}); +//# sourceMappingURL=standaloneSseWithGetStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js.map new file mode 100644 index 000000000..84753c6ef --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"standaloneSseWithGetStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/standaloneSseWithGetStreamableHttp.ts"],"names":[],"mappings":";;AACA,6CAAyC;AACzC,gDAAgD;AAChD,sEAA+E;AAC/E,6CAAyE;AACzE,wDAA8D;AAE9D,mDAAmD;AACnD,MAAM,MAAM,GAAG,IAAI,kBAAS,CAAC;IACzB,IAAI,EAAE,2CAA2C;IACjD,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,uDAAuD;AACvD,MAAM,UAAU,GAA2D,EAAE,CAAC;AAE9E,MAAM,WAAW,GAAG,CAAC,IAAY,EAAE,OAAe,EAAE,EAAE;IAClD,MAAM,GAAG,GAAG,mCAAmC,kBAAkB,CAAC,IAAI,CAAC,EAAE,CAAC;IAC1E,MAAM,CAAC,gBAAgB,CACnB,IAAI,EACJ,GAAG,EACH,EAAE,QAAQ,EAAE,YAAY,EAAE,WAAW,EAAE,qBAAqB,IAAI,EAAE,EAAE,EACpE,KAAK,IAAiC,EAAE;QACpC,OAAO;YACH,QAAQ,EAAE,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;SACrC,CAAC;IACN,CAAC,CACJ,CAAC;AACN,CAAC,CAAC;AAEF,WAAW,CAAC,kBAAkB,EAAE,sCAAsC,CAAC,CAAC;AAExE,MAAM,sBAAsB,GAAG,WAA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;IAChE,MAAM,SAAS,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;IACxC,MAAM,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,4BAA4B,IAAI,EAAE,CAAC,CAAC;AACpD,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,aAAa,CAAC,sBAAsB,CAAC,CAAC;IACtC,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;IACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/toolWithSampleServer.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/toolWithSampleServer.d.ts new file mode 100644 index 000000000..acc24b6a5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/toolWithSampleServer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=toolWithSampleServer.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/toolWithSampleServer.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/toolWithSampleServer.d.ts.map new file mode 100644 index 000000000..bd0cebcf1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/toolWithSampleServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"toolWithSampleServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/toolWithSampleServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/toolWithSampleServer.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/toolWithSampleServer.js new file mode 100644 index 000000000..45d38374d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/toolWithSampleServer.js @@ -0,0 +1,73 @@ +"use strict"; +// Run with: npx tsx src/examples/server/toolWithSampleServer.ts +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const mcp_js_1 = require("../../server/mcp.js"); +const stdio_js_1 = require("../../server/stdio.js"); +const z = __importStar(require("zod/v4")); +const mcpServer = new mcp_js_1.McpServer({ + name: 'tools-with-sample-server', + version: '1.0.0' +}); +// Tool that uses LLM sampling to summarize any text +mcpServer.registerTool('summarize', { + description: 'Summarize any text using an LLM', + inputSchema: { + text: z.string().describe('Text to summarize') + } +}, async ({ text }) => { + // Call the LLM through MCP sampling + const response = await mcpServer.server.createMessage({ + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please summarize the following text concisely:\n\n${text}` + } + } + ], + maxTokens: 500 + }); + // Since we're not passing tools param to createMessage, response.content is single content + return { + content: [ + { + type: 'text', + text: response.content.type === 'text' ? response.content.text : 'Unable to generate summary' + } + ] + }; +}); +async function main() { + const transport = new stdio_js_1.StdioServerTransport(); + await mcpServer.connect(transport); + console.log('MCP server is running...'); +} +main().catch(error => { + console.error('Server error:', error); + process.exit(1); +}); +//# sourceMappingURL=toolWithSampleServer.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/toolWithSampleServer.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/toolWithSampleServer.js.map new file mode 100644 index 000000000..287e11ee9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/server/toolWithSampleServer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"toolWithSampleServer.js","sourceRoot":"","sources":["../../../../src/examples/server/toolWithSampleServer.ts"],"names":[],"mappings":";AAAA,gEAAgE;;;;;;;;;;;;;;;;;;;;;;;;;AAEhE,gDAAgD;AAChD,oDAA6D;AAC7D,0CAA4B;AAE5B,MAAM,SAAS,GAAG,IAAI,kBAAS,CAAC;IAC5B,IAAI,EAAE,0BAA0B;IAChC,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,oDAAoD;AACpD,SAAS,CAAC,YAAY,CAClB,WAAW,EACX;IACI,WAAW,EAAE,iCAAiC;IAC9C,WAAW,EAAE;QACT,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,mBAAmB,CAAC;KACjD;CACJ,EACD,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE;IACf,oCAAoC;IACpC,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,MAAM,CAAC,aAAa,CAAC;QAClD,QAAQ,EAAE;YACN;gBACI,IAAI,EAAE,MAAM;gBACZ,OAAO,EAAE;oBACL,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,qDAAqD,IAAI,EAAE;iBACpE;aACJ;SACJ;QACD,SAAS,EAAE,GAAG;KACjB,CAAC,CAAC;IAEH,2FAA2F;IAC3F,OAAO;QACH,OAAO,EAAE;YACL;gBACI,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,4BAA4B;aAChG;SACJ;KACJ,CAAC;AACN,CAAC,CACJ,CAAC;AAEF,KAAK,UAAU,IAAI;IACf,MAAM,SAAS,GAAG,IAAI,+BAAoB,EAAE,CAAC;IAC7C,MAAM,SAAS,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACnC,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;AAC5C,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/shared/inMemoryEventStore.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/shared/inMemoryEventStore.d.ts new file mode 100644 index 000000000..26ff38cf9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/shared/inMemoryEventStore.d.ts @@ -0,0 +1,31 @@ +import { JSONRPCMessage } from '../../types.js'; +import { EventStore } from '../../server/streamableHttp.js'; +/** + * Simple in-memory implementation of the EventStore interface for resumability + * This is primarily intended for examples and testing, not for production use + * where a persistent storage solution would be more appropriate. + */ +export declare class InMemoryEventStore implements EventStore { + private events; + /** + * Generates a unique event ID for a given stream ID + */ + private generateEventId; + /** + * Extracts the stream ID from an event ID + */ + private getStreamIdFromEventId; + /** + * Stores an event with a generated event ID + * Implements EventStore.storeEvent + */ + storeEvent(streamId: string, message: JSONRPCMessage): Promise; + /** + * Replays events that occurred after a specific event ID + * Implements EventStore.replayEventsAfter + */ + replayEventsAfter(lastEventId: string, { send }: { + send: (eventId: string, message: JSONRPCMessage) => Promise; + }): Promise; +} +//# sourceMappingURL=inMemoryEventStore.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/shared/inMemoryEventStore.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/shared/inMemoryEventStore.d.ts.map new file mode 100644 index 000000000..a67ee6cd1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/shared/inMemoryEventStore.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemoryEventStore.d.ts","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAE5D;;;;GAIG;AACH,qBAAa,kBAAmB,YAAW,UAAU;IACjD,OAAO,CAAC,MAAM,CAAyE;IAEvF;;OAEG;IACH,OAAO,CAAC,eAAe;IAIvB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAK9B;;;OAGG;IACG,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAM5E;;;OAGG;IACG,iBAAiB,CACnB,WAAW,EAAE,MAAM,EACnB,EAAE,IAAI,EAAE,EAAE;QAAE,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;KAAE,GAChF,OAAO,CAAC,MAAM,CAAC;CAkCrB"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/shared/inMemoryEventStore.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/shared/inMemoryEventStore.js new file mode 100644 index 000000000..d33ffdb5c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/shared/inMemoryEventStore.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InMemoryEventStore = void 0; +/** + * Simple in-memory implementation of the EventStore interface for resumability + * This is primarily intended for examples and testing, not for production use + * where a persistent storage solution would be more appropriate. + */ +class InMemoryEventStore { + constructor() { + this.events = new Map(); + } + /** + * Generates a unique event ID for a given stream ID + */ + generateEventId(streamId) { + return `${streamId}_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`; + } + /** + * Extracts the stream ID from an event ID + */ + getStreamIdFromEventId(eventId) { + const parts = eventId.split('_'); + return parts.length > 0 ? parts[0] : ''; + } + /** + * Stores an event with a generated event ID + * Implements EventStore.storeEvent + */ + async storeEvent(streamId, message) { + const eventId = this.generateEventId(streamId); + this.events.set(eventId, { streamId, message }); + return eventId; + } + /** + * Replays events that occurred after a specific event ID + * Implements EventStore.replayEventsAfter + */ + async replayEventsAfter(lastEventId, { send }) { + if (!lastEventId || !this.events.has(lastEventId)) { + return ''; + } + // Extract the stream ID from the event ID + const streamId = this.getStreamIdFromEventId(lastEventId); + if (!streamId) { + return ''; + } + let foundLastEvent = false; + // Sort events by eventId for chronological ordering + const sortedEvents = [...this.events.entries()].sort((a, b) => a[0].localeCompare(b[0])); + for (const [eventId, { streamId: eventStreamId, message }] of sortedEvents) { + // Only include events from the same stream + if (eventStreamId !== streamId) { + continue; + } + // Start sending events after we find the lastEventId + if (eventId === lastEventId) { + foundLastEvent = true; + continue; + } + if (foundLastEvent) { + await send(eventId, message); + } + } + return streamId; + } +} +exports.InMemoryEventStore = InMemoryEventStore; +//# sourceMappingURL=inMemoryEventStore.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/shared/inMemoryEventStore.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/shared/inMemoryEventStore.js.map new file mode 100644 index 000000000..d69645063 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/examples/shared/inMemoryEventStore.js.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemoryEventStore.js","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":";;;AAGA;;;;GAIG;AACH,MAAa,kBAAkB;IAA/B;QACY,WAAM,GAA+D,IAAI,GAAG,EAAE,CAAC;IAoE3F,CAAC;IAlEG;;OAEG;IACK,eAAe,CAAC,QAAgB;QACpC,OAAO,GAAG,QAAQ,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;IACtF,CAAC;IAED;;OAEG;IACK,sBAAsB,CAAC,OAAe;QAC1C,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACjC,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC5C,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,UAAU,CAAC,QAAgB,EAAE,OAAuB;QACtD,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC;QAC/C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;QAChD,OAAO,OAAO,CAAC;IACnB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,iBAAiB,CACnB,WAAmB,EACnB,EAAE,IAAI,EAAyE;QAE/E,IAAI,CAAC,WAAW,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;YAChD,OAAO,EAAE,CAAC;QACd,CAAC;QAED,0CAA0C;QAC1C,MAAM,QAAQ,GAAG,IAAI,CAAC,sBAAsB,CAAC,WAAW,CAAC,CAAC;QAC1D,IAAI,CAAC,QAAQ,EAAE,CAAC;YACZ,OAAO,EAAE,CAAC;QACd,CAAC;QAED,IAAI,cAAc,GAAG,KAAK,CAAC;QAE3B,oDAAoD;QACpD,MAAM,YAAY,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAEzF,KAAK,MAAM,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC,IAAI,YAAY,EAAE,CAAC;YACzE,2CAA2C;YAC3C,IAAI,aAAa,KAAK,QAAQ,EAAE,CAAC;gBAC7B,SAAS;YACb,CAAC;YAED,qDAAqD;YACrD,IAAI,OAAO,KAAK,WAAW,EAAE,CAAC;gBAC1B,cAAc,GAAG,IAAI,CAAC;gBACtB,SAAS;YACb,CAAC;YAED,IAAI,cAAc,EAAE,CAAC;gBACjB,MAAM,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACjC,CAAC;QACL,CAAC;QACD,OAAO,QAAQ,CAAC;IACpB,CAAC;CACJ;AArED,gDAqEC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/index.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/index.d.ts new file mode 100644 index 000000000..2a8633553 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/index.d.ts @@ -0,0 +1,13 @@ +/** + * Experimental MCP SDK features. + * WARNING: These APIs are experimental and may change without notice. + * + * Import experimental features from this module: + * ```typescript + * import { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/experimental'; + * ``` + * + * @experimental + */ +export * from './tasks/index.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/index.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/index.d.ts.map new file mode 100644 index 000000000..410892aa4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/experimental/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,cAAc,kBAAkB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/index.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/index.js new file mode 100644 index 000000000..7634e674c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/index.js @@ -0,0 +1,29 @@ +"use strict"; +/** + * Experimental MCP SDK features. + * WARNING: These APIs are experimental and may change without notice. + * + * Import experimental features from this module: + * ```typescript + * import { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/experimental'; + * ``` + * + * @experimental + */ +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 }); +__exportStar(require("./tasks/index.js"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/index.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/index.js.map new file mode 100644 index 000000000..110189e9f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/experimental/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;;;;;;;;;;;;;;AAEH,mDAAiC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/client.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/client.d.ts new file mode 100644 index 000000000..9c7a92834 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/client.d.ts @@ -0,0 +1,121 @@ +/** + * Experimental client task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +import type { Client } from '../../client/index.js'; +import type { RequestOptions } from '../../shared/protocol.js'; +import type { ResponseMessage } from '../../shared/responseMessage.js'; +import type { AnyObjectSchema, SchemaOutput } from '../../server/zod-compat.js'; +import type { CallToolRequest, ClientRequest, Notification, Request, Result } from '../../types.js'; +import { CallToolResultSchema, type CompatibilityCallToolResultSchema } from '../../types.js'; +import type { GetTaskResult, ListTasksResult, CancelTaskResult } from './types.js'; +/** + * Experimental task features for MCP clients. + * + * Access via `client.experimental.tasks`: + * ```typescript + * const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} }); + * const task = await client.experimental.tasks.getTask(taskId); + * ``` + * + * @experimental + */ +export declare class ExperimentalClientTasks { + private readonly _client; + constructor(_client: Client); + /** + * Calls a tool and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to tool execution, allowing you to + * observe intermediate task status updates for long-running tool calls. + * Automatically validates structured output if the tool has an outputSchema. + * + * @example + * ```typescript + * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} }); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Tool execution started:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Tool status:', message.task.status); + * break; + * case 'result': + * console.log('Tool result:', message.result); + * break; + * case 'error': + * console.error('Tool error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - Tool call parameters (name and arguments) + * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema) + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + callToolStream(params: CallToolRequest['params'], resultSchema?: T, options?: RequestOptions): AsyncGenerator>, void, void>; + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + getTask(taskId: string, options?: RequestOptions): Promise; + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + getTaskResult(taskId: string, resultSchema?: T, options?: RequestOptions): Promise>; + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + listTasks(cursor?: string, options?: RequestOptions): Promise; + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + cancelTask(taskId: string, options?: RequestOptions): Promise; + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request: ClientRequest | RequestT, resultSchema: T, options?: RequestOptions): AsyncGenerator>, void, void>; +} +//# sourceMappingURL=client.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/client.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/client.d.ts.map new file mode 100644 index 000000000..e54158d65 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/client.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../../src/experimental/tasks/client.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAChF,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACpG,OAAO,EAAE,oBAAoB,EAAE,KAAK,iCAAiC,EAAuB,MAAM,gBAAgB,CAAC;AAEnH,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAgBnF;;;;;;;;;;GAUG;AACH,qBAAa,uBAAuB,CAChC,QAAQ,SAAS,OAAO,GAAG,OAAO,EAClC,aAAa,SAAS,YAAY,GAAG,YAAY,EACjD,OAAO,SAAS,MAAM,GAAG,MAAM;IAEnB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,MAAM,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,CAAC;IAE9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCG;IACI,cAAc,CAAC,CAAC,SAAS,OAAO,oBAAoB,GAAG,OAAO,iCAAiC,EAClG,MAAM,EAAE,eAAe,CAAC,QAAQ,CAAC,EACjC,YAAY,GAAE,CAA6B,EAC3C,OAAO,CAAC,EAAE,cAAc,GACzB,cAAc,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAyE/D;;;;;;;;OAQG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC;IAM/E;;;;;;;;;OASG;IACG,aAAa,CAAC,CAAC,SAAS,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;IAapI;;;;;;;;OAQG;IACG,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,eAAe,CAAC;IASpF;;;;;;;OAOG;IACG,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,gBAAgB,CAAC;IASrF;;;;;;;;;;;;;OAaG;IACH,aAAa,CAAC,CAAC,SAAS,eAAe,EACnC,OAAO,EAAE,aAAa,GAAG,QAAQ,EACjC,YAAY,EAAE,CAAC,EACf,OAAO,CAAC,EAAE,cAAc,GACzB,cAAc,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;CAWlE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/client.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/client.js new file mode 100644 index 000000000..cb7d26f96 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/client.js @@ -0,0 +1,188 @@ +"use strict"; +/** + * Experimental client task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExperimentalClientTasks = void 0; +const types_js_1 = require("../../types.js"); +/** + * Experimental task features for MCP clients. + * + * Access via `client.experimental.tasks`: + * ```typescript + * const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} }); + * const task = await client.experimental.tasks.getTask(taskId); + * ``` + * + * @experimental + */ +class ExperimentalClientTasks { + constructor(_client) { + this._client = _client; + } + /** + * Calls a tool and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to tool execution, allowing you to + * observe intermediate task status updates for long-running tool calls. + * Automatically validates structured output if the tool has an outputSchema. + * + * @example + * ```typescript + * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} }); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Tool execution started:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Tool status:', message.task.status); + * break; + * case 'result': + * console.log('Tool result:', message.result); + * break; + * case 'error': + * console.error('Tool error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - Tool call parameters (name and arguments) + * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema) + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + async *callToolStream(params, resultSchema = types_js_1.CallToolResultSchema, options) { + // Access Client's internal methods + const clientInternal = this._client; + // Add task creation parameters if server supports it and not explicitly provided + const optionsWithTask = { + ...options, + // We check if the tool is known to be a task during auto-configuration, but assume + // the caller knows what they're doing if they pass this explicitly + task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : undefined) + }; + const stream = clientInternal.requestStream({ method: 'tools/call', params }, resultSchema, optionsWithTask); + // Get the validator for this tool (if it has an output schema) + const validator = clientInternal.getToolOutputValidator(params.name); + // Iterate through the stream and validate the final result if needed + for await (const message of stream) { + // If this is a result message and the tool has an output schema, validate it + if (message.type === 'result' && validator) { + const result = message.result; + // If tool has outputSchema, it MUST return structuredContent (unless it's an error) + if (!result.structuredContent && !result.isError) { + yield { + type: 'error', + error: new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`) + }; + return; + } + // Only validate structured content if present (not when there's an error) + if (result.structuredContent) { + try { + // Validate the structured content against the schema + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) { + yield { + type: 'error', + error: new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`) + }; + return; + } + } + catch (error) { + if (error instanceof types_js_1.McpError) { + yield { type: 'error', error }; + return; + } + yield { + type: 'error', + error: new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`) + }; + return; + } + } + } + // Yield the message (either validated result or any other message type) + yield message; + } + } + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + async getTask(taskId, options) { + return this._client.getTask({ taskId }, options); + } + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + async getTaskResult(taskId, resultSchema, options) { + // Delegate to the client's underlying Protocol method + return this._client.getTaskResult({ taskId }, resultSchema, options); + } + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + async listTasks(cursor, options) { + // Delegate to the client's underlying Protocol method + return this._client.listTasks(cursor ? { cursor } : undefined, options); + } + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + async cancelTask(taskId, options) { + // Delegate to the client's underlying Protocol method + return this._client.cancelTask({ taskId }, options); + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request, resultSchema, options) { + return this._client.requestStream(request, resultSchema, options); + } +} +exports.ExperimentalClientTasks = ExperimentalClientTasks; +//# sourceMappingURL=client.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/client.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/client.js.map new file mode 100644 index 000000000..a5dd7bd63 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/client.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAOH,6CAAmH;AAkBnH;;;;;;;;;;GAUG;AACH,MAAa,uBAAuB;IAKhC,YAA6B,OAAiD;QAAjD,YAAO,GAAP,OAAO,CAA0C;IAAG,CAAC;IAElF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCG;IACH,KAAK,CAAC,CAAC,cAAc,CACjB,MAAiC,EACjC,eAAkB,+BAAyB,EAC3C,OAAwB;QAExB,mCAAmC;QACnC,MAAM,cAAc,GAAG,IAAI,CAAC,OAA8C,CAAC;QAE3E,iFAAiF;QACjF,MAAM,eAAe,GAAG;YACpB,GAAG,OAAO;YACV,mFAAmF;YACnF,mEAAmE;YACnE,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAA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;;;;;;;;;OAaG;IACH,aAAa,CACT,OAAiC,EACjC,YAAe,EACf,OAAwB;QAUxB,OAAQ,IAAI,CAAC,OAA8C,CAAC,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;IAC9G,CAAC;CACJ;AA9ND,0DA8NC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/helpers.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/helpers.d.ts new file mode 100644 index 000000000..f5e505f81 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/helpers.d.ts @@ -0,0 +1,47 @@ +/** + * Experimental task capability assertion helpers. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +/** + * Type representing the task requests capability structure. + * This is derived from ClientTasksCapability.requests and ServerTasksCapability.requests. + */ +interface TaskRequestsCapability { + tools?: { + call?: object; + }; + sampling?: { + createMessage?: object; + }; + elicitation?: { + create?: object; + }; +} +/** + * Asserts that task creation is supported for tools/call. + * Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability. + * + * @param requests - The task requests capability object + * @param method - The method being checked + * @param entityName - 'Server' or 'Client' for error messages + * @throws Error if the capability is not supported + * + * @experimental + */ +export declare function assertToolsCallTaskCapability(requests: TaskRequestsCapability | undefined, method: string, entityName: 'Server' | 'Client'): void; +/** + * Asserts that task creation is supported for sampling/createMessage or elicitation/create. + * Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability. + * + * @param requests - The task requests capability object + * @param method - The method being checked + * @param entityName - 'Server' or 'Client' for error messages + * @throws Error if the capability is not supported + * + * @experimental + */ +export declare function assertClientRequestTaskCapability(requests: TaskRequestsCapability | undefined, method: string, entityName: 'Server' | 'Client'): void; +export {}; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/helpers.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/helpers.d.ts.map new file mode 100644 index 000000000..99dc90343 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../../src/experimental/tasks/helpers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;GAGG;AACH,UAAU,sBAAsB;IAC5B,KAAK,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1B,QAAQ,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACtC,WAAW,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACrC;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,6BAA6B,CACzC,QAAQ,EAAE,sBAAsB,GAAG,SAAS,EAC5C,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,QAAQ,GAAG,QAAQ,GAChC,IAAI,CAgBN;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,iCAAiC,CAC7C,QAAQ,EAAE,sBAAsB,GAAG,SAAS,EAC5C,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,QAAQ,GAAG,QAAQ,GAChC,IAAI,CAsBN"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/helpers.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/helpers.js new file mode 100644 index 000000000..6348ab0f9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/helpers.js @@ -0,0 +1,68 @@ +"use strict"; +/** + * Experimental task capability assertion helpers. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assertToolsCallTaskCapability = assertToolsCallTaskCapability; +exports.assertClientRequestTaskCapability = assertClientRequestTaskCapability; +/** + * Asserts that task creation is supported for tools/call. + * Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability. + * + * @param requests - The task requests capability object + * @param method - The method being checked + * @param entityName - 'Server' or 'Client' for error messages + * @throws Error if the capability is not supported + * + * @experimental + */ +function assertToolsCallTaskCapability(requests, method, entityName) { + if (!requests) { + throw new Error(`${entityName} does not support task creation (required for ${method})`); + } + switch (method) { + case 'tools/call': + if (!requests.tools?.call) { + throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`); + } + break; + default: + // Method doesn't support tasks, which is fine - no error + break; + } +} +/** + * Asserts that task creation is supported for sampling/createMessage or elicitation/create. + * Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability. + * + * @param requests - The task requests capability object + * @param method - The method being checked + * @param entityName - 'Server' or 'Client' for error messages + * @throws Error if the capability is not supported + * + * @experimental + */ +function assertClientRequestTaskCapability(requests, method, entityName) { + if (!requests) { + throw new Error(`${entityName} does not support task creation (required for ${method})`); + } + switch (method) { + case 'sampling/createMessage': + if (!requests.sampling?.createMessage) { + throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`); + } + break; + case 'elicitation/create': + if (!requests.elicitation?.create) { + throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`); + } + break; + default: + // Method doesn't support tasks, which is fine - no error + break; + } +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/helpers.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/helpers.js.map new file mode 100644 index 000000000..1054273d9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/helpers.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;AAuBH,sEAoBC;AAaD,8EA0BC;AAtED;;;;;;;;;;GAUG;AACH,SAAgB,6BAA6B,CACzC,QAA4C,EAC5C,MAAc,EACd,UAA+B;IAE/B,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,iDAAiD,MAAM,GAAG,CAAC,CAAC;IAC7F,CAAC;IAED,QAAQ,MAAM,EAAE,CAAC;QACb,KAAK,YAAY;YACb,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC;gBACxB,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,gEAAgE,MAAM,GAAG,CAAC,CAAC;YAC5G,CAAC;YACD,MAAM;QAEV;YACI,yDAAyD;YACzD,MAAM;IACd,CAAC;AACL,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,iCAAiC,CAC7C,QAA4C,EAC5C,MAAc,EACd,UAA+B;IAE/B,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,iDAAiD,MAAM,GAAG,CAAC,CAAC;IAC7F,CAAC;IAED,QAAQ,MAAM,EAAE,CAAC;QACb,KAAK,wBAAwB;YACzB,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,aAAa,EAAE,CAAC;gBACpC,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,4EAA4E,MAAM,GAAG,CAAC,CAAC;YACxH,CAAC;YACD,MAAM;QAEV,KAAK,oBAAoB;YACrB,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,MAAM,EAAE,CAAC;gBAChC,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,wEAAwE,MAAM,GAAG,CAAC,CAAC;YACpH,CAAC;YACD,MAAM;QAEV;YACI,yDAAyD;YACzD,MAAM;IACd,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/index.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/index.d.ts new file mode 100644 index 000000000..33ab79169 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/index.d.ts @@ -0,0 +1,16 @@ +/** + * Experimental task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +export * from './types.js'; +export * from './interfaces.js'; +export * from './helpers.js'; +export * from './client.js'; +export * from './server.js'; +export * from './mcp-server.js'; +export * from './stores/in-memory.js'; +export type { ResponseMessage, TaskStatusMessage, TaskCreatedMessage, ResultMessage, ErrorMessage, BaseResponseMessage } from '../../shared/responseMessage.js'; +export { takeResult, toArrayAsync } from '../../shared/responseMessage.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/index.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/index.d.ts.map new file mode 100644 index 000000000..cf117ed5f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/experimental/tasks/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,cAAc,YAAY,CAAC;AAG3B,cAAc,iBAAiB,CAAC;AAGhC,cAAc,cAAc,CAAC;AAG7B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAGhC,cAAc,uBAAuB,CAAC;AAGtC,YAAY,EACR,eAAe,EACf,iBAAiB,EACjB,kBAAkB,EAClB,aAAa,EACb,YAAY,EACZ,mBAAmB,EACtB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/index.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/index.js new file mode 100644 index 000000000..25296f6d6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/index.js @@ -0,0 +1,39 @@ +"use strict"; +/** + * Experimental task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +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.toArrayAsync = exports.takeResult = void 0; +// Re-export spec types for convenience +__exportStar(require("./types.js"), exports); +// SDK implementation interfaces +__exportStar(require("./interfaces.js"), exports); +// Assertion helpers +__exportStar(require("./helpers.js"), exports); +// Wrapper classes +__exportStar(require("./client.js"), exports); +__exportStar(require("./server.js"), exports); +__exportStar(require("./mcp-server.js"), exports); +// Store implementations +__exportStar(require("./stores/in-memory.js"), exports); +var responseMessage_js_1 = require("../../shared/responseMessage.js"); +Object.defineProperty(exports, "takeResult", { enumerable: true, get: function () { return responseMessage_js_1.takeResult; } }); +Object.defineProperty(exports, "toArrayAsync", { enumerable: true, get: function () { return responseMessage_js_1.toArrayAsync; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/index.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/index.js.map new file mode 100644 index 000000000..3d570658c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;;;;;;;;;;;;;;AAEH,uCAAuC;AACvC,6CAA2B;AAE3B,gCAAgC;AAChC,kDAAgC;AAEhC,oBAAoB;AACpB,+CAA6B;AAE7B,kBAAkB;AAClB,8CAA4B;AAC5B,8CAA4B;AAC5B,kDAAgC;AAEhC,wBAAwB;AACxB,wDAAsC;AAWtC,sEAA2E;AAAlE,gHAAA,UAAU,OAAA;AAAE,kHAAA,YAAY,OAAA"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/interfaces.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/interfaces.d.ts new file mode 100644 index 000000000..b0bb9895c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/interfaces.d.ts @@ -0,0 +1,232 @@ +/** + * Experimental task interfaces for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + */ +import { Task, RequestId, Result, JSONRPCRequest, JSONRPCNotification, JSONRPCResultResponse, JSONRPCErrorResponse, ServerRequest, ServerNotification, CallToolResult, GetTaskResult, ToolExecution, Request } from '../../types.js'; +import { CreateTaskResult } from './types.js'; +import type { RequestHandlerExtra, RequestTaskStore } from '../../shared/protocol.js'; +import type { ZodRawShapeCompat, AnySchema, ShapeOutput } from '../../server/zod-compat.js'; +/** + * Extended handler extra with task store for task creation. + * @experimental + */ +export interface CreateTaskRequestHandlerExtra extends RequestHandlerExtra { + taskStore: RequestTaskStore; +} +/** + * Extended handler extra with task ID and store for task operations. + * @experimental + */ +export interface TaskRequestHandlerExtra extends RequestHandlerExtra { + taskId: string; + taskStore: RequestTaskStore; +} +/** + * Base callback type for tool handlers. + * @experimental + */ +export type BaseToolCallback, Args extends undefined | ZodRawShapeCompat | AnySchema = undefined> = Args extends ZodRawShapeCompat ? (args: ShapeOutput, extra: ExtraT) => SendResultT | Promise : Args extends AnySchema ? (args: unknown, extra: ExtraT) => SendResultT | Promise : (extra: ExtraT) => SendResultT | Promise; +/** + * Handler for creating a task. + * @experimental + */ +export type CreateTaskRequestHandler = BaseToolCallback; +/** + * Handler for task operations (get, getResult). + * @experimental + */ +export type TaskRequestHandler = BaseToolCallback; +/** + * Interface for task-based tool handlers. + * @experimental + */ +export interface ToolTaskHandler { + createTask: CreateTaskRequestHandler; + getTask: TaskRequestHandler; + getTaskResult: TaskRequestHandler; +} +/** + * Task-specific execution configuration. + * taskSupport cannot be 'forbidden' for task-based tools. + * @experimental + */ +export type TaskToolExecution = Omit & { + taskSupport: TaskSupport extends 'forbidden' | undefined ? never : TaskSupport; +}; +/** + * Represents a message queued for side-channel delivery via tasks/result. + * + * This is a serializable data structure that can be stored in external systems. + * All fields are JSON-serializable. + */ +export type QueuedMessage = QueuedRequest | QueuedNotification | QueuedResponse | QueuedError; +export interface BaseQueuedMessage { + /** Type of message */ + type: string; + /** When the message was queued (milliseconds since epoch) */ + timestamp: number; +} +export interface QueuedRequest extends BaseQueuedMessage { + type: 'request'; + /** The actual JSONRPC request */ + message: JSONRPCRequest; +} +export interface QueuedNotification extends BaseQueuedMessage { + type: 'notification'; + /** The actual JSONRPC notification */ + message: JSONRPCNotification; +} +export interface QueuedResponse extends BaseQueuedMessage { + type: 'response'; + /** The actual JSONRPC response */ + message: JSONRPCResultResponse; +} +export interface QueuedError extends BaseQueuedMessage { + type: 'error'; + /** The actual JSONRPC error */ + message: JSONRPCErrorResponse; +} +/** + * Interface for managing per-task FIFO message queues. + * + * Similar to TaskStore, this allows pluggable queue implementations + * (in-memory, Redis, other distributed queues, etc.). + * + * Each method accepts taskId and optional sessionId parameters to enable + * a single queue instance to manage messages for multiple tasks, with + * isolation based on task ID and session ID. + * + * All methods are async to support external storage implementations. + * All data in QueuedMessage must be JSON-serializable. + * + * @experimental + */ +export interface TaskMessageQueue { + /** + * Adds a message to the end of the queue for a specific task. + * Atomically checks queue size and throws if maxSize would be exceeded. + * @param taskId The task identifier + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @param maxSize Optional maximum queue size - if specified and queue is full, throws an error + * @throws Error if maxSize is specified and would be exceeded + */ + enqueue(taskId: string, message: QueuedMessage, sessionId?: string, maxSize?: number): Promise; + /** + * Removes and returns the first message from the queue for a specific task. + * @param taskId The task identifier + * @param sessionId Optional session ID for binding the query to a specific session + * @returns The first message, or undefined if the queue is empty + */ + dequeue(taskId: string, sessionId?: string): Promise; + /** + * Removes and returns all messages from the queue for a specific task. + * Used when tasks are cancelled or failed to clean up pending messages. + * @param taskId The task identifier + * @param sessionId Optional session ID for binding the query to a specific session + * @returns Array of all messages that were in the queue + */ + dequeueAll(taskId: string, sessionId?: string): Promise; +} +/** + * Task creation options. + * @experimental + */ +export interface CreateTaskOptions { + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl?: number | null; + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval?: number; + /** + * Additional context to pass to the task store. + */ + context?: Record; +} +/** + * Interface for storing and retrieving task state and results. + * + * Similar to Transport, this allows pluggable task storage implementations + * (in-memory, database, distributed cache, etc.). + * + * @experimental + */ +export interface TaskStore { + /** + * Creates a new task with the given creation parameters and original request. + * The implementation must generate a unique taskId and createdAt timestamp. + * + * TTL Management: + * - The implementation receives the TTL suggested by the requestor via taskParams.ttl + * - The implementation MAY override the requested TTL (e.g., to enforce limits) + * - The actual TTL used MUST be returned in the Task object + * - Null TTL indicates unlimited task lifetime (no automatic cleanup) + * - Cleanup SHOULD occur automatically after TTL expires, regardless of task status + * + * @param taskParams - The task creation parameters from the request (ttl, pollInterval) + * @param requestId - The JSON-RPC request ID + * @param request - The original request that triggered task creation + * @param sessionId - Optional session ID for binding the task to a specific session + * @returns The created task object + */ + createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: Request, sessionId?: string): Promise; + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param sessionId - Optional session ID for binding the query to a specific session + * @returns The task object, or null if it does not exist + */ + getTask(taskId: string, sessionId?: string): Promise; + /** + * Stores the result of a task and sets its final status. + * + * @param taskId - The task identifier + * @param status - The final status: 'completed' for success, 'failed' for errors + * @param result - The result to store + * @param sessionId - Optional session ID for binding the operation to a specific session + */ + storeTaskResult(taskId: string, status: 'completed' | 'failed', result: Result, sessionId?: string): Promise; + /** + * Retrieves the stored result of a task. + * + * @param taskId - The task identifier + * @param sessionId - Optional session ID for binding the query to a specific session + * @returns The stored result + */ + getTaskResult(taskId: string, sessionId?: string): Promise; + /** + * Updates a task's status (e.g., to 'cancelled', 'failed', 'completed'). + * + * @param taskId - The task identifier + * @param status - The new status + * @param statusMessage - Optional diagnostic message for failed tasks or other status information + * @param sessionId - Optional session ID for binding the operation to a specific session + */ + updateTaskStatus(taskId: string, status: Task['status'], statusMessage?: string, sessionId?: string): Promise; + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @param cursor - Optional cursor for pagination + * @param sessionId - Optional session ID for binding the query to a specific session + * @returns An object containing the tasks array and an optional nextCursor + */ + listTasks(cursor?: string, sessionId?: string): Promise<{ + tasks: Task[]; + nextCursor?: string; + }>; +} +/** + * Checks if a task status represents a terminal state. + * Terminal states are those where the task has finished and will not change. + * + * @param status - The task status to check + * @returns True if the status is terminal (completed, failed, or cancelled) + * @experimental + */ +export declare function isTerminal(status: Task['status']): boolean; +//# sourceMappingURL=interfaces.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/interfaces.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/interfaces.d.ts.map new file mode 100644 index 000000000..afd1d70b0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/interfaces.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"interfaces.d.ts","sourceRoot":"","sources":["../../../../src/experimental/tasks/interfaces.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACH,IAAI,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AE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAErH;;;;;;OAMG;IACH,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC;IAElE;;;;;;;OAOG;IACH,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnH;;;;;;OAMG;IACH,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAEnE;;;;;;;OAOG;IACH,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,EAAE,aAAa,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEpH;;;;;;OAMG;IACH,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,IAAI,EAAE,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACnG;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,GAAG,OAAO,CAE1D"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/interfaces.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/interfaces.js new file mode 100644 index 000000000..8f533bbae --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/interfaces.js @@ -0,0 +1,19 @@ +"use strict"; +/** + * Experimental task interfaces for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isTerminal = isTerminal; +/** + * Checks if a task status represents a terminal state. + * Terminal states are those where the task has finished and will not change. + * + * @param status - The task status to check + * @returns True if the status is terminal (completed, failed, or cancelled) + * @experimental + */ +function isTerminal(status) { + return status === 'completed' || status === 'failed' || status === 'cancelled'; +} +//# sourceMappingURL=interfaces.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/interfaces.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/interfaces.js.map new file mode 100644 index 000000000..c3cd4edd2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/interfaces.js.map @@ -0,0 +1 @@ +{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/interfaces.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AA2RH,gCAEC;AAVD;;;;;;;GAOG;AACH,SAAgB,UAAU,CAAC,MAAsB;IAC7C,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,WAAW,CAAC;AACnF,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/mcp-server.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/mcp-server.d.ts new file mode 100644 index 000000000..b3244f9d6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/mcp-server.d.ts @@ -0,0 +1,77 @@ +/** + * Experimental McpServer task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +import type { McpServer, RegisteredTool } from '../../server/mcp.js'; +import type { ZodRawShapeCompat, AnySchema } from '../../server/zod-compat.js'; +import type { ToolAnnotations } from '../../types.js'; +import type { ToolTaskHandler, TaskToolExecution } from './interfaces.js'; +/** + * Experimental task features for McpServer. + * + * Access via `server.experimental.tasks`: + * ```typescript + * server.experimental.tasks.registerToolTask('long-running', config, handler); + * ``` + * + * @experimental + */ +export declare class ExperimentalMcpServerTasks { + private readonly _mcpServer; + constructor(_mcpServer: McpServer); + /** + * Registers a task-based tool with a config object and handler. + * + * Task-based tools support long-running operations that can be polled for status + * and results. The handler must implement `createTask`, `getTask`, and `getTaskResult` + * methods. + * + * @example + * ```typescript + * server.experimental.tasks.registerToolTask('long-computation', { + * description: 'Performs a long computation', + * inputSchema: { input: z.string() }, + * execution: { taskSupport: 'required' } + * }, { + * createTask: async (args, extra) => { + * const task = await extra.taskStore.createTask({ ttl: 300000 }); + * startBackgroundWork(task.taskId, args); + * return { task }; + * }, + * getTask: async (args, extra) => { + * return extra.taskStore.getTask(extra.taskId); + * }, + * getTaskResult: async (args, extra) => { + * return extra.taskStore.getTaskResult(extra.taskId); + * } + * }); + * ``` + * + * @param name - The tool name + * @param config - Tool configuration (description, schemas, etc.) + * @param handler - Task handler with createTask, getTask, getTaskResult methods + * @returns RegisteredTool for managing the tool's lifecycle + * + * @experimental + */ + registerToolTask(name: string, config: { + title?: string; + description?: string; + outputSchema?: OutputArgs; + annotations?: ToolAnnotations; + execution?: TaskToolExecution; + _meta?: Record; + }, handler: ToolTaskHandler): RegisteredTool; + registerToolTask(name: string, config: { + title?: string; + description?: string; + inputSchema: InputArgs; + outputSchema?: OutputArgs; + annotations?: ToolAnnotations; + execution?: TaskToolExecution; + _meta?: Record; + }, handler: ToolTaskHandler): RegisteredTool; +} +//# sourceMappingURL=mcp-server.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/mcp-server.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/mcp-server.d.ts.map new file mode 100644 index 000000000..84ee9e08d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/mcp-server.d.ts.map @@ -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UAAU,CAAC;QAC1B,WAAW,CAAC,EAAE,eAAe,CAAC;QAC9B,SAAS,CAAC,EAAE,iBAAiB,CAAC;QAC9B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACnC,EACD,OAAO,EAAE,eAAe,CAAC,SAAS,CAAC,GACpC,cAAc;CAsCpB"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/mcp-server.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/mcp-server.js new file mode 100644 index 000000000..a2718e1e0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/mcp-server.js @@ -0,0 +1,36 @@ +"use strict"; +/** + * Experimental McpServer task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExperimentalMcpServerTasks = void 0; +/** + * Experimental task features for McpServer. + * + * Access via `server.experimental.tasks`: + * ```typescript + * server.experimental.tasks.registerToolTask('long-running', config, handler); + * ``` + * + * @experimental + */ +class ExperimentalMcpServerTasks { + constructor(_mcpServer) { + this._mcpServer = _mcpServer; + } + registerToolTask(name, config, handler) { + // Validate that taskSupport is not 'forbidden' for task-based tools + const execution = { taskSupport: 'required', ...config.execution }; + if (execution.taskSupport === 'forbidden') { + throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`); + } + // Access McpServer's internal _createRegisteredTool method + const mcpServerInternal = this._mcpServer; + return mcpServerInternal._createRegisteredTool(name, config.title, config.description, config.inputSchema, config.outputSchema, config.annotations, execution, config._meta, handler); + } +} +exports.ExperimentalMcpServerTasks = ExperimentalMcpServerTasks; +//# sourceMappingURL=mcp-server.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/mcp-server.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/mcp-server.js.map new file mode 100644 index 000000000..ff3e8c49a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/mcp-server.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mcp-server.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/mcp-server.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAyBH;;;;;;;;;GASG;AACH,MAAa,0BAA0B;IACnC,YAA6B,UAAqB;QAArB,eAAU,GAAV,UAAU,CAAW;IAAG,CAAC;IAgEtD,gBAAgB,CAIZ,IAAY,EACZ,MAQC,EACD,OAAmC;QAEnC,oEAAoE;QACpE,MAAM,SAAS,GAAkB,EAAE,WAAW,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;QAClF,IAAI,SAAS,CAAC,WAAW,KAAK,WAAW,EAAE,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,oCAAoC,IAAI,6DAA6D,CAAC,CAAC;QAC3H,CAAC;QAED,2DAA2D;QAC3D,MAAM,iBAAiB,GAAG,IAAI,CAAC,UAA0C,CAAC;QAC1E,OAAO,iBAAiB,CAAC,qBAAqB,CAC1C,IAAI,EACJ,MAAM,CAAC,KAAK,EACZ,MAAM,CAAC,WAAW,EAClB,MAAM,CAAC,WAAW,EAClB,MAAM,CAAC,YAAY,EACnB,MAAM,CAAC,WAAW,EAClB,SAAS,EACT,MAAM,CAAC,KAAK,EACZ,OAAwD,CAC3D,CAAC;IACN,CAAC;CACJ;AArGD,gEAqGC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/server.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/server.d.ts new file mode 100644 index 000000000..185e0bab5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/server.d.ts @@ -0,0 +1,83 @@ +/** + * Experimental server task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +import type { Server } from '../../server/index.js'; +import type { RequestOptions } from '../../shared/protocol.js'; +import type { ResponseMessage } from '../../shared/responseMessage.js'; +import type { AnySchema, SchemaOutput } from '../../server/zod-compat.js'; +import type { ServerRequest, Notification, Request, Result, GetTaskResult, ListTasksResult, CancelTaskResult } from '../../types.js'; +/** + * Experimental task features for low-level MCP servers. + * + * Access via `server.experimental.tasks`: + * ```typescript + * const stream = server.experimental.tasks.requestStream(request, schema, options); + * ``` + * + * For high-level server usage with task-based tools, use `McpServer.experimental.tasks` instead. + * + * @experimental + */ +export declare class ExperimentalServerTasks { + private readonly _server; + constructor(_server: Server); + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request: ServerRequest | RequestT, resultSchema: T, options?: RequestOptions): AsyncGenerator>, void, void>; + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + getTask(taskId: string, options?: RequestOptions): Promise; + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + getTaskResult(taskId: string, resultSchema?: T, options?: RequestOptions): Promise>; + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + listTasks(cursor?: string, options?: RequestOptions): Promise; + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + cancelTask(taskId: string, options?: RequestOptions): Promise; +} +//# sourceMappingURL=server.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/server.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/server.d.ts.map new file mode 100644 index 000000000..a1681854f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/server.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../../../src/experimental/tasks/server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAErI;;;;;;;;;;;GAWG;AACH,qBAAa,uBAAuB,CAChC,QAAQ,SAAS,OAAO,GAAG,OAAO,EAClC,aAAa,SAAS,YAAY,GAAG,YAAY,EACjD,OAAO,SAAS,MAAM,GAAG,MAAM;IAEnB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,MAAM,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,CAAC;IAE9E;;;;;;;;;;;;;OAaG;IACH,aAAa,CAAC,CAAC,SAAS,SAAS,EAC7B,OAAO,EAAE,aAAa,GAAG,QAAQ,EACjC,YAAY,EAAE,CAAC,EACf,OAAO,CAAC,EAAE,cAAc,GACzB,cAAc,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAY/D;;;;;;;;OAQG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC;IAK/E;;;;;;;;;OASG;IACG,aAAa,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;IAY9H;;;;;;;;OAQG;IACG,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,eAAe,CAAC;IAQpF;;;;;;;OAOG;IACG,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,gBAAgB,CAAC;CAOxF"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/server.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/server.js new file mode 100644 index 000000000..200d4b96a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/server.js @@ -0,0 +1,93 @@ +"use strict"; +/** + * Experimental server task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExperimentalServerTasks = void 0; +/** + * Experimental task features for low-level MCP servers. + * + * Access via `server.experimental.tasks`: + * ```typescript + * const stream = server.experimental.tasks.requestStream(request, schema, options); + * ``` + * + * For high-level server usage with task-based tools, use `McpServer.experimental.tasks` instead. + * + * @experimental + */ +class ExperimentalServerTasks { + constructor(_server) { + this._server = _server; + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request, resultSchema, options) { + return this._server.requestStream(request, resultSchema, options); + } + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + async getTask(taskId, options) { + return this._server.getTask({ taskId }, options); + } + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + async getTaskResult(taskId, resultSchema, options) { + return this._server.getTaskResult({ taskId }, resultSchema, options); + } + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + async listTasks(cursor, options) { + return this._server.listTasks(cursor ? { cursor } : undefined, options); + } + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + async cancelTask(taskId, options) { + return this._server.cancelTask({ taskId }, options); + } +} +exports.ExperimentalServerTasks = ExperimentalServerTasks; +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/server.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/server.js.map new file mode 100644 index 000000000..905631d24 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/server.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/server.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAQH;;;;;;;;;;;GAWG;AACH,MAAa,uBAAuB;IAKhC,YAA6B,OAAiD;QAAjD,YAAO,GAAP,OAAO,CAA0C;IAAG,CAAC;IAElF;;;;;;;;;;;;;OAaG;IACH,aAAa,CACT,OAAiC,EACjC,YAAe,EACf,OAAwB;QAUxB,OAAQ,IAAI,CAAC,OAA8C,CAAC,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;IAC9G,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAwB;QAElD,OAAQ,IAAI,CAAC,OAAwC,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC;IACvF,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,aAAa,CAAsB,MAAc,EAAE,YAAgB,EAAE,OAAwB;QAC/F,OACI,IAAI,CAAC,OAOR,CAAC,aAAa,CAAC,EAAE,MAAM,EAAE,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;IACvD,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,SAAS,CAAC,MAAe,EAAE,OAAwB;QACrD,OACI,IAAI,CAAC,OAGR,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IAC1D,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,UAAU,CAAC,MAAc,EAAE,OAAwB;QACrD,OACI,IAAI,CAAC,OAGR,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC;CACJ;AAzGD,0DAyGC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/stores/in-memory.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/stores/in-memory.d.ts new file mode 100644 index 000000000..d30795e30 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/stores/in-memory.d.ts @@ -0,0 +1,94 @@ +/** + * In-memory implementations of TaskStore and TaskMessageQueue. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +import { Task, RequestId, Result, Request } from '../../../types.js'; +import { TaskStore, TaskMessageQueue, QueuedMessage, CreateTaskOptions } from '../interfaces.js'; +/** + * A simple in-memory implementation of TaskStore for demonstration purposes. + * + * This implementation stores all tasks in memory and provides automatic cleanup + * based on the ttl duration specified in the task creation parameters. + * + * Note: This is not suitable for production use as all data is lost on restart. + * For production, consider implementing TaskStore with a database or distributed cache. + * + * @experimental + */ +export declare class InMemoryTaskStore implements TaskStore { + private tasks; + private cleanupTimers; + /** + * Generates a unique task ID. + * Uses 16 bytes of random data encoded as hex (32 characters). + */ + private generateTaskId; + createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: Request, _sessionId?: string): Promise; + getTask(taskId: string, _sessionId?: string): Promise; + storeTaskResult(taskId: string, status: 'completed' | 'failed', result: Result, _sessionId?: string): Promise; + getTaskResult(taskId: string, _sessionId?: string): Promise; + updateTaskStatus(taskId: string, status: Task['status'], statusMessage?: string, _sessionId?: string): Promise; + listTasks(cursor?: string, _sessionId?: string): Promise<{ + tasks: Task[]; + nextCursor?: string; + }>; + /** + * Cleanup all timers (useful for testing or graceful shutdown) + */ + cleanup(): void; + /** + * Get all tasks (useful for debugging) + */ + getAllTasks(): Task[]; +} +/** + * A simple in-memory implementation of TaskMessageQueue for demonstration purposes. + * + * This implementation stores messages in memory, organized by task ID and optional session ID. + * Messages are stored in FIFO queues per task. + * + * Note: This is not suitable for production use in distributed systems. + * For production, consider implementing TaskMessageQueue with Redis or other distributed queues. + * + * @experimental + */ +export declare class InMemoryTaskMessageQueue implements TaskMessageQueue { + private queues; + /** + * Generates a queue key from taskId. + * SessionId is intentionally ignored because taskIds are globally unique + * and tasks need to be accessible across HTTP requests/sessions. + */ + private getQueueKey; + /** + * Gets or creates a queue for the given task and session. + */ + private getQueue; + /** + * Adds a message to the end of the queue for a specific task. + * Atomically checks queue size and throws if maxSize would be exceeded. + * @param taskId The task identifier + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @param maxSize Optional maximum queue size - if specified and queue is full, throws an error + * @throws Error if maxSize is specified and would be exceeded + */ + enqueue(taskId: string, message: QueuedMessage, sessionId?: string, maxSize?: number): Promise; + /** + * Removes and returns the first message from the queue for a specific task. + * @param taskId The task identifier + * @param sessionId Optional session ID for binding the query to a specific session + * @returns The first message, or undefined if the queue is empty + */ + dequeue(taskId: string, sessionId?: string): Promise; + /** + * Removes and returns all messages from the queue for a specific task. + * @param taskId The task identifier + * @param sessionId Optional session ID for binding the query to a specific session + * @returns Array of all messages that were in the queue + */ + dequeueAll(taskId: string, sessionId?: string): Promise; +} +//# sourceMappingURL=in-memory.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/stores/in-memory.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/stores/in-memory.d.ts.map new file mode 100644 index 000000000..1825e8751 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/stores/in-memory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"in-memory.d.ts","sourceRoot":"","sources":["../../../../../src/experimental/tasks/stores/in-memory.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,EAAE,SAAS,EAAc,gBAAgB,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAU7G;;;;;;;;;;GAUG;AACH,qBAAa,iBAAkB,YAAW,SAAS;IAC/C,OAAO,CAAC,KAAK,CAAiC;IAC9C,OAAO,CAAC,aAAa,CAAoD;IAEzE;;;OAGG;IACH,OAAO,CAAC,cAAc;IAIhB,UAAU,CAAC,UAAU,EAAE,iBAAiB,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA0CrH,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAKlE,eAAe,CAAC,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CAAC,aAAa,EAAE,CAAC;CAMjF"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/stores/in-memory.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/stores/in-memory.js new file mode 100644 index 000000000..fe1b1e7fc --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/stores/in-memory.js @@ -0,0 +1,251 @@ +"use strict"; +/** + * In-memory implementations of TaskStore and TaskMessageQueue. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InMemoryTaskMessageQueue = exports.InMemoryTaskStore = void 0; +const interfaces_js_1 = require("../interfaces.js"); +const node_crypto_1 = require("node:crypto"); +/** + * A simple in-memory implementation of TaskStore for demonstration purposes. + * + * This implementation stores all tasks in memory and provides automatic cleanup + * based on the ttl duration specified in the task creation parameters. + * + * Note: This is not suitable for production use as all data is lost on restart. + * For production, consider implementing TaskStore with a database or distributed cache. + * + * @experimental + */ +class InMemoryTaskStore { + constructor() { + this.tasks = new Map(); + this.cleanupTimers = new Map(); + } + /** + * Generates a unique task ID. + * Uses 16 bytes of random data encoded as hex (32 characters). + */ + generateTaskId() { + return (0, node_crypto_1.randomBytes)(16).toString('hex'); + } + async createTask(taskParams, requestId, request, _sessionId) { + // Generate a unique task ID + const taskId = this.generateTaskId(); + // Ensure uniqueness + if (this.tasks.has(taskId)) { + throw new Error(`Task with ID ${taskId} already exists`); + } + const actualTtl = taskParams.ttl ?? null; + // Create task with generated ID and timestamps + const createdAt = new Date().toISOString(); + const task = { + taskId, + status: 'working', + ttl: actualTtl, + createdAt, + lastUpdatedAt: createdAt, + pollInterval: taskParams.pollInterval ?? 1000 + }; + this.tasks.set(taskId, { + task, + request, + requestId + }); + // Schedule cleanup if ttl is specified + // Cleanup occurs regardless of task status + if (actualTtl) { + const timer = setTimeout(() => { + this.tasks.delete(taskId); + this.cleanupTimers.delete(taskId); + }, actualTtl); + this.cleanupTimers.set(taskId, timer); + } + return task; + } + async getTask(taskId, _sessionId) { + const stored = this.tasks.get(taskId); + return stored ? { ...stored.task } : null; + } + async storeTaskResult(taskId, status, result, _sessionId) { + const stored = this.tasks.get(taskId); + if (!stored) { + throw new Error(`Task with ID ${taskId} not found`); + } + // Don't allow storing results for tasks already in terminal state + if ((0, interfaces_js_1.isTerminal)(stored.task.status)) { + throw new Error(`Cannot store result for task ${taskId} in terminal status '${stored.task.status}'. Task results can only be stored once.`); + } + stored.result = result; + stored.task.status = status; + stored.task.lastUpdatedAt = new Date().toISOString(); + // Reset cleanup timer to start from now (if ttl is set) + if (stored.task.ttl) { + const existingTimer = this.cleanupTimers.get(taskId); + if (existingTimer) { + clearTimeout(existingTimer); + } + const timer = setTimeout(() => { + this.tasks.delete(taskId); + this.cleanupTimers.delete(taskId); + }, stored.task.ttl); + this.cleanupTimers.set(taskId, timer); + } + } + async getTaskResult(taskId, _sessionId) { + const stored = this.tasks.get(taskId); + if (!stored) { + throw new Error(`Task with ID ${taskId} not found`); + } + if (!stored.result) { + throw new Error(`Task ${taskId} has no result stored`); + } + return stored.result; + } + async updateTaskStatus(taskId, status, statusMessage, _sessionId) { + const stored = this.tasks.get(taskId); + if (!stored) { + throw new Error(`Task with ID ${taskId} not found`); + } + // Don't allow transitions from terminal states + if ((0, interfaces_js_1.isTerminal)(stored.task.status)) { + throw new Error(`Cannot update task ${taskId} from terminal status '${stored.task.status}' to '${status}'. Terminal states (completed, failed, cancelled) cannot transition to other states.`); + } + stored.task.status = status; + if (statusMessage) { + stored.task.statusMessage = statusMessage; + } + stored.task.lastUpdatedAt = new Date().toISOString(); + // If task is in a terminal state and has ttl, start cleanup timer + if ((0, interfaces_js_1.isTerminal)(status) && stored.task.ttl) { + const existingTimer = this.cleanupTimers.get(taskId); + if (existingTimer) { + clearTimeout(existingTimer); + } + const timer = setTimeout(() => { + this.tasks.delete(taskId); + this.cleanupTimers.delete(taskId); + }, stored.task.ttl); + this.cleanupTimers.set(taskId, timer); + } + } + async listTasks(cursor, _sessionId) { + const PAGE_SIZE = 10; + const allTaskIds = Array.from(this.tasks.keys()); + let startIndex = 0; + if (cursor) { + const cursorIndex = allTaskIds.indexOf(cursor); + if (cursorIndex >= 0) { + startIndex = cursorIndex + 1; + } + else { + // Invalid cursor - throw error + throw new Error(`Invalid cursor: ${cursor}`); + } + } + const pageTaskIds = allTaskIds.slice(startIndex, startIndex + PAGE_SIZE); + const tasks = pageTaskIds.map(taskId => { + const stored = this.tasks.get(taskId); + return { ...stored.task }; + }); + const nextCursor = startIndex + PAGE_SIZE < allTaskIds.length ? pageTaskIds[pageTaskIds.length - 1] : undefined; + return { tasks, nextCursor }; + } + /** + * Cleanup all timers (useful for testing or graceful shutdown) + */ + cleanup() { + for (const timer of this.cleanupTimers.values()) { + clearTimeout(timer); + } + this.cleanupTimers.clear(); + this.tasks.clear(); + } + /** + * Get all tasks (useful for debugging) + */ + getAllTasks() { + return Array.from(this.tasks.values()).map(stored => ({ ...stored.task })); + } +} +exports.InMemoryTaskStore = InMemoryTaskStore; +/** + * A simple in-memory implementation of TaskMessageQueue for demonstration purposes. + * + * This implementation stores messages in memory, organized by task ID and optional session ID. + * Messages are stored in FIFO queues per task. + * + * Note: This is not suitable for production use in distributed systems. + * For production, consider implementing TaskMessageQueue with Redis or other distributed queues. + * + * @experimental + */ +class InMemoryTaskMessageQueue { + constructor() { + this.queues = new Map(); + } + /** + * Generates a queue key from taskId. + * SessionId is intentionally ignored because taskIds are globally unique + * and tasks need to be accessible across HTTP requests/sessions. + */ + getQueueKey(taskId, _sessionId) { + return taskId; + } + /** + * Gets or creates a queue for the given task and session. + */ + getQueue(taskId, sessionId) { + const key = this.getQueueKey(taskId, sessionId); + let queue = this.queues.get(key); + if (!queue) { + queue = []; + this.queues.set(key, queue); + } + return queue; + } + /** + * Adds a message to the end of the queue for a specific task. + * Atomically checks queue size and throws if maxSize would be exceeded. + * @param taskId The task identifier + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @param maxSize Optional maximum queue size - if specified and queue is full, throws an error + * @throws Error if maxSize is specified and would be exceeded + */ + async enqueue(taskId, message, sessionId, maxSize) { + const queue = this.getQueue(taskId, sessionId); + // Atomically check size and enqueue + if (maxSize !== undefined && queue.length >= maxSize) { + throw new Error(`Task message queue overflow: queue size (${queue.length}) exceeds maximum (${maxSize})`); + } + queue.push(message); + } + /** + * Removes and returns the first message from the queue for a specific task. + * @param taskId The task identifier + * @param sessionId Optional session ID for binding the query to a specific session + * @returns The first message, or undefined if the queue is empty + */ + async dequeue(taskId, sessionId) { + const queue = this.getQueue(taskId, sessionId); + return queue.shift(); + } + /** + * Removes and returns all messages from the queue for a specific task. + * @param taskId The task identifier + * @param sessionId Optional session ID for binding the query to a specific session + * @returns Array of all messages that were in the queue + */ + async dequeueAll(taskId, sessionId) { + const key = this.getQueueKey(taskId, sessionId); + const queue = this.queues.get(key) ?? []; + this.queues.delete(key); + return queue; + } +} +exports.InMemoryTaskMessageQueue = InMemoryTaskMessageQueue; +//# sourceMappingURL=in-memory.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/stores/in-memory.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/stores/in-memory.js.map new file mode 100644 index 000000000..a4d21a90a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/stores/in-memory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"in-memory.js","sourceRoot":"","sources":["../../../../../src/experimental/tasks/stores/in-memory.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAGH,oDAA6G;AAC7G,6CAA0C;AAS1C;;;;;;;;;;GAUG;AACH,MAAa,iBAAiB;IAA9B;QACY,UAAK,GAAG,IAAI,GAAG,EAAsB,CAAC;QACtC,kBAAa,GAAG,IAAI,GAAG,EAAyC,CAAC;IAsL7E,CAAC;IApLG;;;OAGG;IACK,cAA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zC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACxB,OAAO,KAAK,CAAC;IACjB,CAAC;CACJ;AApED,4DAoEC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/types.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/types.d.ts new file mode 100644 index 000000000..6022e19b2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/types.d.ts @@ -0,0 +1,10 @@ +/** + * Re-exports of task-related types from the MCP protocol spec. + * WARNING: These APIs are experimental and may change without notice. + * + * These types are defined in types.ts (matching the protocol spec) and + * re-exported here for convenience when working with experimental task features. + */ +export { TaskCreationParamsSchema, RelatedTaskMetadataSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema } from '../../types.js'; +export type { Task, TaskCreationParams, RelatedTaskMetadata, CreateTaskResult, TaskStatusNotificationParams, TaskStatusNotification, GetTaskRequest, GetTaskResult, GetTaskPayloadRequest, ListTasksRequest, ListTasksResult, CancelTaskRequest, CancelTaskResult } from '../../types.js'; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/types.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/types.d.ts.map new file mode 100644 index 000000000..f7b9ead05 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/experimental/tasks/types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EACH,wBAAwB,EACxB,yBAAyB,EACzB,UAAU,EACV,sBAAsB,EACtB,kCAAkC,EAClC,4BAA4B,EAC5B,oBAAoB,EACpB,mBAAmB,EACnB,2BAA2B,EAC3B,sBAAsB,EACtB,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,EACtB,2BAA2B,EAC3B,2BAA2B,EAC9B,MAAM,gBAAgB,CAAC;AAGxB,YAAY,EACR,IAAI,EACJ,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,4BAA4B,EAC5B,sBAAsB,EACtB,cAAc,EACd,aAAa,EACb,qBAAqB,EACrB,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EACnB,MAAM,gBAAgB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/types.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/types.js new file mode 100644 index 000000000..b051c848b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/types.js @@ -0,0 +1,28 @@ +"use strict"; +/** + * Re-exports of task-related types from the MCP protocol spec. + * WARNING: These APIs are experimental and may change without notice. + * + * These types are defined in types.ts (matching the protocol spec) and + * re-exported here for convenience when working with experimental task features. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerTasksCapabilitySchema = exports.ClientTasksCapabilitySchema = exports.CancelTaskResultSchema = exports.CancelTaskRequestSchema = exports.ListTasksResultSchema = exports.ListTasksRequestSchema = exports.GetTaskPayloadRequestSchema = exports.GetTaskResultSchema = exports.GetTaskRequestSchema = exports.TaskStatusNotificationSchema = exports.TaskStatusNotificationParamsSchema = exports.CreateTaskResultSchema = exports.TaskSchema = exports.RelatedTaskMetadataSchema = exports.TaskCreationParamsSchema = void 0; +// Task schemas (Zod) +var types_js_1 = require("../../types.js"); +Object.defineProperty(exports, "TaskCreationParamsSchema", { enumerable: true, get: function () { return types_js_1.TaskCreationParamsSchema; } }); +Object.defineProperty(exports, "RelatedTaskMetadataSchema", { enumerable: true, get: function () { return types_js_1.RelatedTaskMetadataSchema; } }); +Object.defineProperty(exports, "TaskSchema", { enumerable: true, get: function () { return types_js_1.TaskSchema; } }); +Object.defineProperty(exports, "CreateTaskResultSchema", { enumerable: true, get: function () { return types_js_1.CreateTaskResultSchema; } }); +Object.defineProperty(exports, "TaskStatusNotificationParamsSchema", { enumerable: true, get: function () { return types_js_1.TaskStatusNotificationParamsSchema; } }); +Object.defineProperty(exports, "TaskStatusNotificationSchema", { enumerable: true, get: function () { return types_js_1.TaskStatusNotificationSchema; } }); +Object.defineProperty(exports, "GetTaskRequestSchema", { enumerable: true, get: function () { return types_js_1.GetTaskRequestSchema; } }); +Object.defineProperty(exports, "GetTaskResultSchema", { enumerable: true, get: function () { return types_js_1.GetTaskResultSchema; } }); +Object.defineProperty(exports, "GetTaskPayloadRequestSchema", { enumerable: true, get: function () { return types_js_1.GetTaskPayloadRequestSchema; } }); +Object.defineProperty(exports, "ListTasksRequestSchema", { enumerable: true, get: function () { return types_js_1.ListTasksRequestSchema; } }); +Object.defineProperty(exports, "ListTasksResultSchema", { enumerable: true, get: function () { return types_js_1.ListTasksResultSchema; } }); +Object.defineProperty(exports, "CancelTaskRequestSchema", { enumerable: true, get: function () { return types_js_1.CancelTaskRequestSchema; } }); +Object.defineProperty(exports, "CancelTaskResultSchema", { enumerable: true, get: function () { return types_js_1.CancelTaskResultSchema; } }); +Object.defineProperty(exports, "ClientTasksCapabilitySchema", { enumerable: true, get: function () { return types_js_1.ClientTasksCapabilitySchema; } }); +Object.defineProperty(exports, "ServerTasksCapabilitySchema", { enumerable: true, get: function () { return types_js_1.ServerTasksCapabilitySchema; } }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/types.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/types.js.map new file mode 100644 index 000000000..adfc3ab50 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/experimental/tasks/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/types.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,qBAAqB;AACrB,2CAgBwB;AAfpB,oHAAA,wBAAwB,OAAA;AACxB,qHAAA,yBAAyB,OAAA;AACzB,sGAAA,UAAU,OAAA;AACV,kHAAA,sBAAsB,OAAA;AACtB,8HAAA,kCAAkC,OAAA;AAClC,wHAAA,4BAA4B,OAAA;AAC5B,gHAAA,oBAAoB,OAAA;AACpB,+GAAA,mBAAmB,OAAA;AACnB,uHAAA,2BAA2B,OAAA;AAC3B,kHAAA,sBAAsB,OAAA;AACtB,iHAAA,qBAAqB,OAAA;AACrB,mHAAA,uBAAuB,OAAA;AACvB,kHAAA,sBAAsB,OAAA;AACtB,uHAAA,2BAA2B,OAAA;AAC3B,uHAAA,2BAA2B,OAAA"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/inMemory.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/inMemory.d.ts new file mode 100644 index 000000000..32a931a86 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/inMemory.d.ts @@ -0,0 +1,31 @@ +import { Transport } from './shared/transport.js'; +import { JSONRPCMessage, RequestId } from './types.js'; +import { AuthInfo } from './server/auth/types.js'; +/** + * In-memory transport for creating clients and servers that talk to each other within the same process. + */ +export declare class InMemoryTransport implements Transport { + private _otherTransport?; + private _messageQueue; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: { + authInfo?: AuthInfo; + }) => void; + sessionId?: string; + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. + */ + static createLinkedPair(): [InMemoryTransport, InMemoryTransport]; + start(): Promise; + close(): Promise; + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + send(message: JSONRPCMessage, options?: { + relatedRequestId?: RequestId; + authInfo?: AuthInfo; + }): Promise; +} +//# sourceMappingURL=inMemory.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/inMemory.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/inMemory.d.ts.map new file mode 100644 index 000000000..46bc74be1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/inMemory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemory.d.ts","sourceRoot":"","sources":["../../src/inMemory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAOlD;;GAEG;AACH,qBAAa,iBAAkB,YAAW,SAAS;IAC/C,OAAO,CAAC,eAAe,CAAC,CAAoB;IAC5C,OAAO,CAAC,aAAa,CAAuB;IAE5C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAAK,IAAI,CAAC;IAC/E,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,MAAM,CAAC,gBAAgB,IAAI,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;IAQ3D,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAQtB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAO5B;;;OAGG;IACG,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAC;QAAC,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAWtH"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/inMemory.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/inMemory.js new file mode 100644 index 000000000..9c6cb0e2c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/inMemory.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InMemoryTransport = void 0; +/** + * In-memory transport for creating clients and servers that talk to each other within the same process. + */ +class InMemoryTransport { + constructor() { + this._messageQueue = []; + } + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. + */ + static createLinkedPair() { + const clientTransport = new InMemoryTransport(); + const serverTransport = new InMemoryTransport(); + clientTransport._otherTransport = serverTransport; + serverTransport._otherTransport = clientTransport; + return [clientTransport, serverTransport]; + } + async start() { + // Process any messages that were queued before start was called + while (this._messageQueue.length > 0) { + const queuedMessage = this._messageQueue.shift(); + this.onmessage?.(queuedMessage.message, queuedMessage.extra); + } + } + async close() { + const other = this._otherTransport; + this._otherTransport = undefined; + await other?.close(); + this.onclose?.(); + } + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + async send(message, options) { + if (!this._otherTransport) { + throw new Error('Not connected'); + } + if (this._otherTransport.onmessage) { + this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); + } + else { + this._otherTransport._messageQueue.push({ message, extra: { authInfo: options?.authInfo } }); + } + } +} +exports.InMemoryTransport = InMemoryTransport; +//# sourceMappingURL=inMemory.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/inMemory.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/inMemory.js.map new file mode 100644 index 000000000..a45f3a89f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/inMemory.js.map @@ -0,0 +1 @@ +{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EAAE,QAAQ,EAAE,CAAC,CAAC;QAC7E,CAAC;aAAM,CAAC;YACJ,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;QACjG,CAAC;IACL,CAAC;CACJ;AAlDD,8CAkDC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/package.json b/node_modules/@modelcontextprotocol/sdk/dist/cjs/package.json new file mode 100644 index 000000000..b731bd61b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/clients.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/clients.d.ts new file mode 100644 index 000000000..be6899a19 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/clients.d.ts @@ -0,0 +1,19 @@ +import { OAuthClientInformationFull } from '../../shared/auth.js'; +/** + * Stores information about registered OAuth clients for this server. + */ +export interface OAuthRegisteredClientsStore { + /** + * Returns information about a registered client, based on its ID. + */ + getClient(clientId: string): OAuthClientInformationFull | undefined | Promise; + /** + * Registers a new client with the server. The client ID and secret will be automatically generated by the library. A modified version of the client information can be returned to reflect specific values enforced by the server. + * + * NOTE: Implementations should NOT delete expired client secrets in-place. Auth middleware provided by this library will automatically check the `client_secret_expires_at` field and reject requests with expired secrets. Any custom logic for authenticating clients should check the `client_secret_expires_at` field as well. + * + * If unimplemented, dynamic client registration is unsupported. + */ + registerClient?(client: Omit): OAuthClientInformationFull | Promise; +} +//# sourceMappingURL=clients.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/clients.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/clients.d.ts.map new file mode 100644 index 000000000..ab3851db3 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/clients.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clients.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/clients.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAElE;;GAEG;AACH,MAAM,WAAW,2BAA2B;IACxC;;OAEG;IACH,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,0BAA0B,GAAG,SAAS,GAAG,OAAO,CAAC,0BAA0B,GAAG,SAAS,CAAC,CAAC;IAEtH;;;;;;OAMG;IACH,cAAc,CAAC,CACX,MAAM,EAAE,IAAI,CAAC,0BAA0B,EAAE,WAAW,GAAG,qBAAqB,CAAC,GAC9E,0BAA0B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;CACvE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/clients.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/clients.js new file mode 100644 index 000000000..866b88b74 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/clients.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=clients.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/clients.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/clients.js.map new file mode 100644 index 000000000..021010442 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/clients.js.map @@ -0,0 +1 @@ +{"version":3,"file":"clients.js","sourceRoot":"","sources":["../../../../src/server/auth/clients.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/errors.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/errors.d.ts new file mode 100644 index 000000000..7fddf954c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/errors.d.ts @@ -0,0 +1,148 @@ +import { OAuthErrorResponse } from '../../shared/auth.js'; +/** + * Base class for all OAuth errors + */ +export declare class OAuthError extends Error { + readonly errorUri?: string | undefined; + static errorCode: string; + constructor(message: string, errorUri?: string | undefined); + /** + * Converts the error to a standard OAuth error response object + */ + toResponseObject(): OAuthErrorResponse; + get errorCode(): string; +} +/** + * Invalid request error - The request is missing a required parameter, + * includes an invalid parameter value, includes a parameter more than once, + * or is otherwise malformed. + */ +export declare class InvalidRequestError extends OAuthError { + static errorCode: string; +} +/** + * Invalid client error - Client authentication failed (e.g., unknown client, no client + * authentication included, or unsupported authentication method). + */ +export declare class InvalidClientError extends OAuthError { + static errorCode: string; +} +/** + * Invalid grant error - The provided authorization grant or refresh token is + * invalid, expired, revoked, does not match the redirection URI used in the + * authorization request, or was issued to another client. + */ +export declare class InvalidGrantError extends OAuthError { + static errorCode: string; +} +/** + * Unauthorized client error - The authenticated client is not authorized to use + * this authorization grant type. + */ +export declare class UnauthorizedClientError extends OAuthError { + static errorCode: string; +} +/** + * Unsupported grant type error - The authorization grant type is not supported + * by the authorization server. + */ +export declare class UnsupportedGrantTypeError extends OAuthError { + static errorCode: string; +} +/** + * Invalid scope error - The requested scope is invalid, unknown, malformed, or + * exceeds the scope granted by the resource owner. + */ +export declare class InvalidScopeError extends OAuthError { + static errorCode: string; +} +/** + * Access denied error - The resource owner or authorization server denied the request. + */ +export declare class AccessDeniedError extends OAuthError { + static errorCode: string; +} +/** + * Server error - The authorization server encountered an unexpected condition + * that prevented it from fulfilling the request. + */ +export declare class ServerError extends OAuthError { + static errorCode: string; +} +/** + * Temporarily unavailable error - The authorization server is currently unable to + * handle the request due to a temporary overloading or maintenance of the server. + */ +export declare class TemporarilyUnavailableError extends OAuthError { + static errorCode: string; +} +/** + * Unsupported response type error - The authorization server does not support + * obtaining an authorization code using this method. + */ +export declare class UnsupportedResponseTypeError extends OAuthError { + static errorCode: string; +} +/** + * Unsupported token type error - The authorization server does not support + * the requested token type. + */ +export declare class UnsupportedTokenTypeError extends OAuthError { + static errorCode: string; +} +/** + * Invalid token error - The access token provided is expired, revoked, malformed, + * or invalid for other reasons. + */ +export declare class InvalidTokenError extends OAuthError { + static errorCode: string; +} +/** + * Method not allowed error - The HTTP method used is not allowed for this endpoint. + * (Custom, non-standard error) + */ +export declare class MethodNotAllowedError extends OAuthError { + static errorCode: string; +} +/** + * Too many requests error - Rate limit exceeded. + * (Custom, non-standard error based on RFC 6585) + */ +export declare class TooManyRequestsError extends OAuthError { + static errorCode: string; +} +/** + * Invalid client metadata error - The client metadata is invalid. + * (Custom error for dynamic client registration - RFC 7591) + */ +export declare class InvalidClientMetadataError extends OAuthError { + static errorCode: string; +} +/** + * Insufficient scope error - The request requires higher privileges than provided by the access token. + */ +export declare class InsufficientScopeError extends OAuthError { + static errorCode: string; +} +/** + * Invalid target error - The requested resource is invalid, missing, unknown, or malformed. + * (Custom error for resource indicators - RFC 8707) + */ +export declare class InvalidTargetError extends OAuthError { + static errorCode: string; +} +/** + * A utility class for defining one-off error codes + */ +export declare class CustomOAuthError extends OAuthError { + private readonly customErrorCode; + constructor(customErrorCode: string, message: string, errorUri?: string); + get errorCode(): string; +} +/** + * A full list of all OAuthErrors, enabling parsing from error responses + */ +export declare const OAUTH_ERRORS: { + readonly [x: string]: typeof InvalidRequestError; +}; +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/errors.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/errors.d.ts.map new file mode 100644 index 000000000..5c0e99202 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAk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AAED;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,UAAU;IAC7C,MAAM,CAAC,SAAS,SAAmB;CACtC;AAED;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,UAAU;IACjD,MAAM,CAAC,SAAS,SAAwB;CAC3C;AAED;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,UAAU;IAChD,MAAM,CAAC,SAAS,SAAuB;CAC1C;AAED;;;GAGG;AACH,qBAAa,0BAA2B,SAAQ,UAAU;IACtD,MAAM,CAAC,SAAS,SAA6B;CAChD;AAED;;GAEG;AACH,qBAAa,sBAAuB,SAAQ,UAAU;IAClD,MAAM,CAAC,SAAS,SAAwB;CAC3C;AAED;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,UAAU;IAC9C,MAAM,CAAC,SAAS,SAAoB;CACvC;AAED;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,UAAU;IAExC,OAAO,CAAC,QAAQ,CAAC,eAAe;gBAAf,eAAe,EAAE,MAAM,EACxC,OAAO,EAAE,MAAM,EACf,QAAQ,CAAC,EAAE,MAAM;IAKrB,IAAI,SAAS,IAAI,MAAM,CAEtB;CACJ;AAED;;GAEG;AACH,eAAO,MAAM,YAAY;;CAkBf,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/errors.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/errors.js new file mode 100644 index 000000000..e67478c3c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/errors.js @@ -0,0 +1,202 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OAUTH_ERRORS = exports.CustomOAuthError = exports.InvalidTargetError = exports.InsufficientScopeError = exports.InvalidClientMetadataError = exports.TooManyRequestsError = exports.MethodNotAllowedError = exports.InvalidTokenError = exports.UnsupportedTokenTypeError = exports.UnsupportedResponseTypeError = exports.TemporarilyUnavailableError = exports.ServerError = exports.AccessDeniedError = exports.InvalidScopeError = exports.UnsupportedGrantTypeError = exports.UnauthorizedClientError = exports.InvalidGrantError = exports.InvalidClientError = exports.InvalidRequestError = exports.OAuthError = void 0; +/** + * Base class for all OAuth errors + */ +class OAuthError extends Error { + constructor(message, errorUri) { + super(message); + this.errorUri = errorUri; + this.name = this.constructor.name; + } + /** + * Converts the error to a standard OAuth error response object + */ + toResponseObject() { + const response = { + error: this.errorCode, + error_description: this.message + }; + if (this.errorUri) { + response.error_uri = this.errorUri; + } + return response; + } + get errorCode() { + return this.constructor.errorCode; + } +} +exports.OAuthError = OAuthError; +/** + * Invalid request error - The request is missing a required parameter, + * includes an invalid parameter value, includes a parameter more than once, + * or is otherwise malformed. + */ +class InvalidRequestError extends OAuthError { +} +exports.InvalidRequestError = InvalidRequestError; +InvalidRequestError.errorCode = 'invalid_request'; +/** + * Invalid client error - Client authentication failed (e.g., unknown client, no client + * authentication included, or unsupported authentication method). + */ +class InvalidClientError extends OAuthError { +} +exports.InvalidClientError = InvalidClientError; +InvalidClientError.errorCode = 'invalid_client'; +/** + * Invalid grant error - The provided authorization grant or refresh token is + * invalid, expired, revoked, does not match the redirection URI used in the + * authorization request, or was issued to another client. + */ +class InvalidGrantError extends OAuthError { +} +exports.InvalidGrantError = InvalidGrantError; +InvalidGrantError.errorCode = 'invalid_grant'; +/** + * Unauthorized client error - The authenticated client is not authorized to use + * this authorization grant type. + */ +class UnauthorizedClientError extends OAuthError { +} +exports.UnauthorizedClientError = UnauthorizedClientError; +UnauthorizedClientError.errorCode = 'unauthorized_client'; +/** + * Unsupported grant type error - The authorization grant type is not supported + * by the authorization server. + */ +class UnsupportedGrantTypeError extends OAuthError { +} +exports.UnsupportedGrantTypeError = UnsupportedGrantTypeError; +UnsupportedGrantTypeError.errorCode = 'unsupported_grant_type'; +/** + * Invalid scope error - The requested scope is invalid, unknown, malformed, or + * exceeds the scope granted by the resource owner. + */ +class InvalidScopeError extends OAuthError { +} +exports.InvalidScopeError = InvalidScopeError; +InvalidScopeError.errorCode = 'invalid_scope'; +/** + * Access denied error - The resource owner or authorization server denied the request. + */ +class AccessDeniedError extends OAuthError { +} +exports.AccessDeniedError = AccessDeniedError; +AccessDeniedError.errorCode = 'access_denied'; +/** + * Server error - The authorization server encountered an unexpected condition + * that prevented it from fulfilling the request. + */ +class ServerError extends OAuthError { +} +exports.ServerError = ServerError; +ServerError.errorCode = 'server_error'; +/** + * Temporarily unavailable error - The authorization server is currently unable to + * handle the request due to a temporary overloading or maintenance of the server. + */ +class TemporarilyUnavailableError extends OAuthError { +} +exports.TemporarilyUnavailableError = TemporarilyUnavailableError; +TemporarilyUnavailableError.errorCode = 'temporarily_unavailable'; +/** + * Unsupported response type error - The authorization server does not support + * obtaining an authorization code using this method. + */ +class UnsupportedResponseTypeError extends OAuthError { +} +exports.UnsupportedResponseTypeError = UnsupportedResponseTypeError; +UnsupportedResponseTypeError.errorCode = 'unsupported_response_type'; +/** + * Unsupported token type error - The authorization server does not support + * the requested token type. + */ +class UnsupportedTokenTypeError extends OAuthError { +} +exports.UnsupportedTokenTypeError = UnsupportedTokenTypeError; +UnsupportedTokenTypeError.errorCode = 'unsupported_token_type'; +/** + * Invalid token error - The access token provided is expired, revoked, malformed, + * or invalid for other reasons. + */ +class InvalidTokenError extends OAuthError { +} +exports.InvalidTokenError = InvalidTokenError; +InvalidTokenError.errorCode = 'invalid_token'; +/** + * Method not allowed error - The HTTP method used is not allowed for this endpoint. + * (Custom, non-standard error) + */ +class MethodNotAllowedError extends OAuthError { +} +exports.MethodNotAllowedError = MethodNotAllowedError; +MethodNotAllowedError.errorCode = 'method_not_allowed'; +/** + * Too many requests error - Rate limit exceeded. + * (Custom, non-standard error based on RFC 6585) + */ +class TooManyRequestsError extends OAuthError { +} +exports.TooManyRequestsError = TooManyRequestsError; +TooManyRequestsError.errorCode = 'too_many_requests'; +/** + * Invalid client metadata error - The client metadata is invalid. + * (Custom error for dynamic client registration - RFC 7591) + */ +class InvalidClientMetadataError extends OAuthError { +} +exports.InvalidClientMetadataError = InvalidClientMetadataError; +InvalidClientMetadataError.errorCode = 'invalid_client_metadata'; +/** + * Insufficient scope error - The request requires higher privileges than provided by the access token. + */ +class InsufficientScopeError extends OAuthError { +} +exports.InsufficientScopeError = InsufficientScopeError; +InsufficientScopeError.errorCode = 'insufficient_scope'; +/** + * Invalid target error - The requested resource is invalid, missing, unknown, or malformed. + * (Custom error for resource indicators - RFC 8707) + */ +class InvalidTargetError extends OAuthError { +} +exports.InvalidTargetError = InvalidTargetError; +InvalidTargetError.errorCode = 'invalid_target'; +/** + * A utility class for defining one-off error codes + */ +class CustomOAuthError extends OAuthError { + constructor(customErrorCode, message, errorUri) { + super(message, errorUri); + this.customErrorCode = customErrorCode; + } + get errorCode() { + return this.customErrorCode; + } +} +exports.CustomOAuthError = CustomOAuthError; +/** + * A full list of all OAuthErrors, enabling parsing from error responses + */ +exports.OAUTH_ERRORS = { + [InvalidRequestError.errorCode]: InvalidRequestError, + [InvalidClientError.errorCode]: InvalidClientError, + [InvalidGrantError.errorCode]: InvalidGrantError, + [UnauthorizedClientError.errorCode]: UnauthorizedClientError, + [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError, + [InvalidScopeError.errorCode]: InvalidScopeError, + [AccessDeniedError.errorCode]: AccessDeniedError, + [ServerError.errorCode]: ServerError, + [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError, + [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError, + [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError, + [InvalidTokenError.errorCode]: InvalidTokenError, + [MethodNotAllowedError.errorCode]: MethodNotAllowedError, + [TooManyRequestsError.errorCode]: TooManyRequestsError, + [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError, + [InsufficientScopeError.errorCode]: InsufficientScopeError, + [InvalidTargetError.errorCode]: InvalidTargetError +}; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/errors.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/errors.js.map new file mode 100644 index 000000000..f802594f8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../src/server/auth/errors.ts"],"names":[],"mappings":";;;AAEA;;GAEG;AACH,MAAa,UAAW,SAAQ,KAAK;IAGjC,YACI,OAAe,EACC,QAAiB;QAEjC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,aAAQ,GAAR,QAAQ,CAAS;QAGjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;IACtC,CAAC;IAED;;OAEG;IACH,gBAAgB;QACZ,MAAM,QAAQ,GAAuB;YACjC,KAAK,EAAE,IAAI,CAAC,SAAS;YACrB,iBAAiB,EAAE,IAAI,CAAC,OAAO;SAClC,CAAC;QAEF,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAChB,QAAQ,CAAC,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC;QACvC,CAAC;QAED,OAAO,QAAQ,CAAC;IACpB,CAAC;IAED,IAAI,SAAS;QACT,OAAQ,IAAI,CAAC,WAAiC,CAAC,SAAS,CAAC;IAC7D,CAAC;CACJ;AA9BD,gCA8BC;AAED;;;;GAIG;AACH,MAAa,mBAAoB,SAAQ,UAAU;;AAAnD,kDAEC;AADU,6BAAS,GAAG,iBAAiB,CAAC;AAGzC;;;GAGG;AACH,MAAa,kBAAmB,SAAQ,UAAU;;AAAlD,gDAEC;AADU,4BAAS,GAAG,gBAAgB,CAAC;AAGxC;;;;GAIG;AACH,MAAa,iBAAkB,SAAQ,UAAU;;AAAjD,8CAEC;AADU,2BAAS,GAAG,eAAe,CAAC;AAGvC;;;GAGG;AACH,MAAa,uBAAwB,SAAQ,UAAU;;AAAvD,0DAEC;AADU,iCAAS,GAAG,qBAAqB,CAAC;AAG7C;;;GAGG;AACH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protocol/sdk/dist/cjs/server/auth/handlers/authorize.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/authorize.d.ts new file mode 100644 index 000000000..38e9829bd --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/authorize.d.ts @@ -0,0 +1,13 @@ +import { RequestHandler } from 'express'; +import { OAuthServerProvider } from '../provider.js'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type AuthorizationHandlerOptions = { + provider: OAuthServerProvider; + /** + * Rate limiting configuration for the authorization endpoint. + * Set to false to disable rate limiting for this endpoint. + */ + rateLimit?: Partial | false; +}; +export declare function authorizationHandler({ provider, rateLimit: rateLimitConfig }: AuthorizationHandlerOptions): RequestHandler; +//# sourceMappingURL=authorize.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/authorize.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/authorize.d.ts.map new file mode 100644 index 000000000..b06798834 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/authorize.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/authorize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,2BAA2B,GAAG;IACtC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAqBF,wBAAgB,oBAAoB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,2BAA2B,GAAG,cAAc,CAgH1H"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/authorize.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/authorize.js new file mode 100644 index 000000000..902208219 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/authorize.js @@ -0,0 +1,167 @@ +"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.authorizationHandler = authorizationHandler; +const z = __importStar(require("zod/v4")); +const express_1 = __importDefault(require("express")); +const express_rate_limit_1 = require("express-rate-limit"); +const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); +const errors_js_1 = require("../errors.js"); +// Parameters that must be validated in order to issue redirects. +const ClientAuthorizationParamsSchema = z.object({ + client_id: z.string(), + redirect_uri: z + .string() + .optional() + .refine(value => value === undefined || URL.canParse(value), { message: 'redirect_uri must be a valid URL' }) +}); +// Parameters that must be validated for a successful authorization request. Failure can be reported to the redirect URI. +const RequestAuthorizationParamsSchema = z.object({ + response_type: z.literal('code'), + code_challenge: z.string(), + code_challenge_method: z.literal('S256'), + scope: z.string().optional(), + state: z.string().optional(), + resource: z.string().url().optional() +}); +function authorizationHandler({ provider, rateLimit: rateLimitConfig }) { + // Create a router to apply middleware + const router = express_1.default.Router(); + router.use((0, allowedMethods_js_1.allowedMethods)(['GET', 'POST'])); + router.use(express_1.default.urlencoded({ extended: false })); + // Apply rate limiting unless explicitly disabled + if (rateLimitConfig !== false) { + router.use((0, express_rate_limit_1.rateLimit)({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, // 100 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new errors_js_1.TooManyRequestsError('You have exceeded the rate limit for authorization requests').toResponseObject(), + ...rateLimitConfig + })); + } + router.all('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + // In the authorization flow, errors are split into two categories: + // 1. Pre-redirect errors (direct response with 400) + // 2. Post-redirect errors (redirect with error parameters) + // Phase 1: Validate client_id and redirect_uri. Any errors here must be direct responses. + let client_id, redirect_uri, client; + try { + const result = ClientAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); + if (!result.success) { + throw new errors_js_1.InvalidRequestError(result.error.message); + } + client_id = result.data.client_id; + redirect_uri = result.data.redirect_uri; + client = await provider.clientsStore.getClient(client_id); + if (!client) { + throw new errors_js_1.InvalidClientError('Invalid client_id'); + } + if (redirect_uri !== undefined) { + if (!client.redirect_uris.includes(redirect_uri)) { + throw new errors_js_1.InvalidRequestError('Unregistered redirect_uri'); + } + } + else if (client.redirect_uris.length === 1) { + redirect_uri = client.redirect_uris[0]; + } + else { + throw new errors_js_1.InvalidRequestError('redirect_uri must be specified when client has multiple registered URIs'); + } + } + catch (error) { + // Pre-redirect errors - return direct response + // + // These don't need to be JSON encoded, as they'll be displayed in a user + // agent, but OTOH they all represent exceptional situations (arguably, + // "programmer error"), so presenting a nice HTML page doesn't help the + // user anyway. + if (error instanceof errors_js_1.OAuthError) { + const status = error instanceof errors_js_1.ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + return; + } + // Phase 2: Validate other parameters. Any errors here should go into redirect responses. + let state; + try { + // Parse and validate authorization parameters + const parseResult = RequestAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); + if (!parseResult.success) { + throw new errors_js_1.InvalidRequestError(parseResult.error.message); + } + const { scope, code_challenge, resource } = parseResult.data; + state = parseResult.data.state; + // Validate scopes + let requestedScopes = []; + if (scope !== undefined) { + requestedScopes = scope.split(' '); + } + // All validation passed, proceed with authorization + await provider.authorize(client, { + state, + scopes: requestedScopes, + redirectUri: redirect_uri, + codeChallenge: code_challenge, + resource: resource ? new URL(resource) : undefined + }, res); + } + catch (error) { + // Post-redirect errors - redirect with error parameters + if (error instanceof errors_js_1.OAuthError) { + res.redirect(302, createErrorRedirect(redirect_uri, error, state)); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.redirect(302, createErrorRedirect(redirect_uri, serverError, state)); + } + } + }); + return router; +} +/** + * Helper function to create redirect URL with error parameters + */ +function createErrorRedirect(redirectUri, error, state) { + const errorUrl = new URL(redirectUri); + errorUrl.searchParams.set('error', error.errorCode); + errorUrl.searchParams.set('error_description', error.message); + if (error.errorUri) { + errorUrl.searchParams.set('error_uri', error.errorUri); + } + if (state) { + errorUrl.searchParams.set('state', state); + } + return errorUrl.href; +} +//# sourceMappingURL=authorize.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/authorize.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/authorize.js.map new file mode 100644 index 000000000..28e876271 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/authorize.js.map @@ -0,0 +1 @@ +{"version":3,"file":"authorize.js","sourceRoot":"","sources":["../../../../../src/server/auth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AAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;GAEG;AACH,SAAS,mBAAmB,CAAC,WAAmB,EAAE,KAAiB,EAAE,KAAc;IAC/E,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;IACtC,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IACpD,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,mBAAmB,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;IAC9D,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;QACjB,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,WAAW,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC3D,CAAC;IACD,IAAI,KAAK,EAAE,CAAC;QACR,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/metadata.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/metadata.d.ts new file mode 100644 index 000000000..4d0328617 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/metadata.d.ts @@ -0,0 +1,4 @@ +import { RequestHandler } from 'express'; +import { OAuthMetadata, OAuthProtectedResourceMetadata } from '../../../shared/auth.js'; +export declare function metadataHandler(metadata: OAuthMetadata | OAuthProtectedResourceMetadata): RequestHandler; +//# sourceMappingURL=metadata.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/metadata.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/metadata.d.ts.map new file mode 100644 index 000000000..55e3a50dc --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/metadata.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/metadata.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,8BAA8B,EAAE,MAAM,yBAAyB,CAAC;AAIxF,wBAAgB,eAAe,CAAC,QAAQ,EAAE,aAAa,GAAG,8BAA8B,GAAG,cAAc,CAaxG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/metadata.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/metadata.js new file mode 100644 index 000000000..4e00bc588 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/metadata.js @@ -0,0 +1,21 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.metadataHandler = metadataHandler; +const express_1 = __importDefault(require("express")); +const cors_1 = __importDefault(require("cors")); +const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); +function metadataHandler(metadata) { + // Nested router so we can configure middleware and restrict HTTP method + const router = express_1.default.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use((0, cors_1.default)()); + router.use((0, allowedMethods_js_1.allowedMethods)(['GET', 'OPTIONS'])); + router.get('/', (req, res) => { + res.status(200).json(metadata); + }); + return router; +} +//# sourceMappingURL=metadata.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/metadata.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/metadata.js.map new file mode 100644 index 000000000..9679c9fa5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/metadata.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/metadata.ts"],"names":[],"mappings":";;;;;AAKA,0CAaC;AAlBD,sDAAkD;AAElD,gDAAwB;AACxB,uEAAiE;AAEjE,SAAgB,eAAe,CAAC,QAAwD;IACpF,wEAAwE;IACxE,MAAM,MAAM,GAAG,iBAAO,CAAC,MAAM,EAAE,CAAC;IAEhC,kFAAkF;IAClF,MAAM,CAAC,GAAG,CAAC,IAAA,cAAI,GAAE,CAAC,CAAC;IAEnB,MAAM,CAAC,GAAG,CAAC,IAAA,kCAAc,EAAC,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;IAC/C,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;QACzB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACnC,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/register.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/register.d.ts new file mode 100644 index 000000000..e9add2845 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/register.d.ts @@ -0,0 +1,29 @@ +import { RequestHandler } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type ClientRegistrationHandlerOptions = { + /** + * A store used to save information about dynamically registered OAuth clients. + */ + clientsStore: OAuthRegisteredClientsStore; + /** + * The number of seconds after which to expire issued client secrets, or 0 to prevent expiration of client secrets (not recommended). + * + * If not set, defaults to 30 days. + */ + clientSecretExpirySeconds?: number; + /** + * Rate limiting configuration for the client registration endpoint. + * Set to false to disable rate limiting for this endpoint. + * Registration endpoints are particularly sensitive to abuse and should be rate limited. + */ + rateLimit?: Partial | false; + /** + * Whether to generate a client ID before calling the client registration endpoint. + * + * If not set, defaults to true. + */ + clientIdGeneration?: boolean; +}; +export declare function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds, rateLimit: rateLimitConfig, clientIdGeneration }: ClientRegistrationHandlerOptions): RequestHandler; +//# sourceMappingURL=register.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/register.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/register.d.ts.map new file mode 100644 index 000000000..a38ebdb89 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/register.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/register.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAIlD,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,gCAAgC,GAAG;IAC3C;;OAEG;IACH,YAAY,EAAE,2BAA2B,CAAC;IAE1C;;;;OAIG;IACH,yBAAyB,CAAC,EAAE,MAAM,CAAC;IAEnC;;;;OAIG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;IAE9C;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAChC,CAAC;AAIF,wBAAgB,yBAAyB,CAAC,EACtC,YAAY,EACZ,yBAAgE,EAChE,SAAS,EAAE,eAAe,EAC1B,kBAAyB,EAC5B,EAAE,gCAAgC,GAAG,cAAc,CA0EnD"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/register.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/register.js new file mode 100644 index 000000000..e40c5c904 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/register.js @@ -0,0 +1,77 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.clientRegistrationHandler = clientRegistrationHandler; +const express_1 = __importDefault(require("express")); +const auth_js_1 = require("../../../shared/auth.js"); +const node_crypto_1 = __importDefault(require("node:crypto")); +const cors_1 = __importDefault(require("cors")); +const express_rate_limit_1 = require("express-rate-limit"); +const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); +const errors_js_1 = require("../errors.js"); +const DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS = 30 * 24 * 60 * 60; // 30 days +function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds = DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS, rateLimit: rateLimitConfig, clientIdGeneration = true }) { + if (!clientsStore.registerClient) { + throw new Error('Client registration store does not support registering clients'); + } + // Nested router so we can configure middleware and restrict HTTP method + const router = express_1.default.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use((0, cors_1.default)()); + router.use((0, allowedMethods_js_1.allowedMethods)(['POST'])); + router.use(express_1.default.json()); + // Apply rate limiting unless explicitly disabled - stricter limits for registration + if (rateLimitConfig !== false) { + router.use((0, express_rate_limit_1.rateLimit)({ + windowMs: 60 * 60 * 1000, // 1 hour + max: 20, // 20 requests per hour - stricter as registration is sensitive + standardHeaders: true, + legacyHeaders: false, + message: new errors_js_1.TooManyRequestsError('You have exceeded the rate limit for client registration requests').toResponseObject(), + ...rateLimitConfig + })); + } + router.post('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + try { + const parseResult = auth_js_1.OAuthClientMetadataSchema.safeParse(req.body); + if (!parseResult.success) { + throw new errors_js_1.InvalidClientMetadataError(parseResult.error.message); + } + const clientMetadata = parseResult.data; + const isPublicClient = clientMetadata.token_endpoint_auth_method === 'none'; + // Generate client credentials + const clientSecret = isPublicClient ? undefined : node_crypto_1.default.randomBytes(32).toString('hex'); + const clientIdIssuedAt = Math.floor(Date.now() / 1000); + // Calculate client secret expiry time + const clientsDoExpire = clientSecretExpirySeconds > 0; + const secretExpiryTime = clientsDoExpire ? clientIdIssuedAt + clientSecretExpirySeconds : 0; + const clientSecretExpiresAt = isPublicClient ? undefined : secretExpiryTime; + let clientInfo = { + ...clientMetadata, + client_secret: clientSecret, + client_secret_expires_at: clientSecretExpiresAt + }; + if (clientIdGeneration) { + clientInfo.client_id = node_crypto_1.default.randomUUID(); + clientInfo.client_id_issued_at = clientIdIssuedAt; + } + clientInfo = await clientsStore.registerClient(clientInfo); + res.status(201).json(clientInfo); + } + catch (error) { + if (error instanceof errors_js_1.OAuthError) { + const status = error instanceof errors_js_1.ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }); + return router; +} +//# sourceMappingURL=register.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/register.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/register.js.map new file mode 100644 index 000000000..e116a474f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/register.js.map @@ -0,0 +1 @@ +{"version":3,"file":"register.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/register.ts"],"names":[],"mappings":";;;;;AAuCA,8DA+EC;AAtHD,sDAAkD;AAClD,qDAAgG;AAChG,8DAAiC;AACjC,gDAAwB;AAExB,2DAA4E;AAC5E,uEAAiE;AACjE,4CAAyG;AA8BzG,MAAM,oCAAoC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,UAAU;AAE1E,SAAgB,yBAAyB,CAAC,EACtC,Y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,CAAC,CAAC,GAAG,CAAC;gBACxD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,uBAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/revoke.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/revoke.d.ts new file mode 100644 index 000000000..2be32bb3c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/revoke.d.ts @@ -0,0 +1,13 @@ +import { OAuthServerProvider } from '../provider.js'; +import { RequestHandler } from 'express'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type RevocationHandlerOptions = { + provider: OAuthServerProvider; + /** + * Rate limiting configuration for the token revocation endpoint. + * Set to false to disable rate limiting for this endpoint. + */ + rateLimit?: Partial | false; +}; +export declare function revocationHandler({ provider, rateLimit: rateLimitConfig }: RevocationHandlerOptions): RequestHandler; +//# sourceMappingURL=revoke.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/revoke.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/revoke.d.ts.map new file mode 100644 index 000000000..fb13cf19f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/revoke.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"revoke.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/revoke.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAIlD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,wBAAwB,GAAG;IACnC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,wBAAwB,GAAG,cAAc,CA4DpH"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/revoke.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/revoke.js new file mode 100644 index 000000000..4fb1da738 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/revoke.js @@ -0,0 +1,65 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.revocationHandler = revocationHandler; +const express_1 = __importDefault(require("express")); +const cors_1 = __importDefault(require("cors")); +const clientAuth_js_1 = require("../middleware/clientAuth.js"); +const auth_js_1 = require("../../../shared/auth.js"); +const express_rate_limit_1 = require("express-rate-limit"); +const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); +const errors_js_1 = require("../errors.js"); +function revocationHandler({ provider, rateLimit: rateLimitConfig }) { + if (!provider.revokeToken) { + throw new Error('Auth provider does not support revoking tokens'); + } + // Nested router so we can configure middleware and restrict HTTP method + const router = express_1.default.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use((0, cors_1.default)()); + router.use((0, allowedMethods_js_1.allowedMethods)(['POST'])); + router.use(express_1.default.urlencoded({ extended: false })); + // Apply rate limiting unless explicitly disabled + if (rateLimitConfig !== false) { + router.use((0, express_rate_limit_1.rateLimit)({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 50, // 50 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new errors_js_1.TooManyRequestsError('You have exceeded the rate limit for token revocation requests').toResponseObject(), + ...rateLimitConfig + })); + } + // Authenticate and extract client details + router.use((0, clientAuth_js_1.authenticateClient)({ clientsStore: provider.clientsStore })); + router.post('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + try { + const parseResult = auth_js_1.OAuthTokenRevocationRequestSchema.safeParse(req.body); + if (!parseResult.success) { + throw new errors_js_1.InvalidRequestError(parseResult.error.message); + } + const client = req.client; + if (!client) { + // This should never happen + throw new errors_js_1.ServerError('Internal Server Error'); + } + await provider.revokeToken(client, parseResult.data); + res.status(200).json({}); + } + catch (error) { + if (error instanceof errors_js_1.OAuthError) { + const status = error instanceof errors_js_1.ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }); + return router; +} +//# sourceMappingURL=revoke.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/revoke.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/revoke.js.map new file mode 100644 index 000000000..ca01fee7f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/revoke.js.map @@ -0,0 +1 @@ +{"version":3,"file":"revoke.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/revoke.ts"],"names":[],"mappings":";;;;;AAkBA,8CA4DC;AA7ED,sDAAkD;AAClD,gDAAwB;AACxB,+DAAiE;AACjE,qDAA4E;AAC5E,2DAA4E;AAC5E,uEAAiE;AACjE,4CAAkG;AAWlG,SAAgB,iBAAiB,CAAC,EAAE,QAAQ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1E,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC;gBACvB,MAAM,IAAI,+BAAmB,CAAC,WAAW,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAC7D,CAAC;YAED,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;YAC1B,IAAI,CAAC,MAAM,EAAE,CAAC;gBACV,2BAA2B;gBAC3B,MAAM,IAAI,uBAAW,CAAC,uBAAuB,CAAC,CAAC;YACnD,CAAC;YAED,MAAM,QAAQ,CAAC,WAAY,CAAC,MAAM,EAAE,WAAW,CAAC,IAAI,CAAC,CAAC;YACtD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC7B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,sBAAU,EAAE,CAAC;gBAC9B,MAAM,MAAM,GAAG,KAAK,YAAY,uBAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;gBACxD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,uBAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/token.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/token.d.ts new file mode 100644 index 000000000..24d1c8783 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/token.d.ts @@ -0,0 +1,13 @@ +import { RequestHandler } from 'express'; +import { OAuthServerProvider } from '../provider.js'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type TokenHandlerOptions = { + provider: OAuthServerProvider; + /** + * Rate limiting configuration for the token endpoint. + * Set to false to disable rate limiting for this endpoint. + */ + rateLimit?: Partial | false; +}; +export declare function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHandlerOptions): RequestHandler; +//# sourceMappingURL=token.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/token.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/token.d.ts.map new file mode 100644 index 000000000..68189b0b2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/token.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/token.ts"],"names":[],"mappings":"AACA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAIrD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAW5E,MAAM,MAAM,mBAAmB,GAAG;IAC9B,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAmBF,wBAAgB,YAAY,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,mBAAmB,GAAG,cAAc,CA+G1G"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/token.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/token.js new file mode 100644 index 000000000..8318de6b0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/token.js @@ -0,0 +1,136 @@ +"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.tokenHandler = tokenHandler; +const z = __importStar(require("zod/v4")); +const express_1 = __importDefault(require("express")); +const cors_1 = __importDefault(require("cors")); +const pkce_challenge_1 = require("pkce-challenge"); +const clientAuth_js_1 = require("../middleware/clientAuth.js"); +const express_rate_limit_1 = require("express-rate-limit"); +const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); +const errors_js_1 = require("../errors.js"); +const TokenRequestSchema = z.object({ + grant_type: z.string() +}); +const AuthorizationCodeGrantSchema = z.object({ + code: z.string(), + code_verifier: z.string(), + redirect_uri: z.string().optional(), + resource: z.string().url().optional() +}); +const RefreshTokenGrantSchema = z.object({ + refresh_token: z.string(), + scope: z.string().optional(), + resource: z.string().url().optional() +}); +function tokenHandler({ provider, rateLimit: rateLimitConfig }) { + // Nested router so we can configure middleware and restrict HTTP method + const router = express_1.default.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use((0, cors_1.default)()); + router.use((0, allowedMethods_js_1.allowedMethods)(['POST'])); + router.use(express_1.default.urlencoded({ extended: false })); + // Apply rate limiting unless explicitly disabled + if (rateLimitConfig !== false) { + router.use((0, express_rate_limit_1.rateLimit)({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 50, // 50 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new errors_js_1.TooManyRequestsError('You have exceeded the rate limit for token requests').toResponseObject(), + ...rateLimitConfig + })); + } + // Authenticate and extract client details + router.use((0, clientAuth_js_1.authenticateClient)({ clientsStore: provider.clientsStore })); + router.post('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + try { + const parseResult = TokenRequestSchema.safeParse(req.body); + if (!parseResult.success) { + throw new errors_js_1.InvalidRequestError(parseResult.error.message); + } + const { grant_type } = parseResult.data; + const client = req.client; + if (!client) { + // This should never happen + throw new errors_js_1.ServerError('Internal Server Error'); + } + switch (grant_type) { + case 'authorization_code': { + const parseResult = AuthorizationCodeGrantSchema.safeParse(req.body); + if (!parseResult.success) { + throw new errors_js_1.InvalidRequestError(parseResult.error.message); + } + const { code, code_verifier, redirect_uri, resource } = parseResult.data; + const skipLocalPkceValidation = provider.skipLocalPkceValidation; + // Perform local PKCE validation unless explicitly skipped + // (e.g. to validate code_verifier in upstream server) + if (!skipLocalPkceValidation) { + const codeChallenge = await provider.challengeForAuthorizationCode(client, code); + if (!(await (0, pkce_challenge_1.verifyChallenge)(code_verifier, codeChallenge))) { + throw new errors_js_1.InvalidGrantError('code_verifier does not match the challenge'); + } + } + // Passes the code_verifier to the provider if PKCE validation didn't occur locally + const tokens = await provider.exchangeAuthorizationCode(client, code, skipLocalPkceValidation ? code_verifier : undefined, redirect_uri, resource ? new URL(resource) : undefined); + res.status(200).json(tokens); + break; + } + case 'refresh_token': { + const parseResult = RefreshTokenGrantSchema.safeParse(req.body); + if (!parseResult.success) { + throw new errors_js_1.InvalidRequestError(parseResult.error.message); + } + const { refresh_token, scope, resource } = parseResult.data; + const scopes = scope?.split(' '); + const tokens = await provider.exchangeRefreshToken(client, refresh_token, scopes, resource ? new URL(resource) : undefined); + res.status(200).json(tokens); + break; + } + // Additional auth methods will not be added on the server side of the SDK. + case 'client_credentials': + default: + throw new errors_js_1.UnsupportedGrantTypeError('The grant type is not supported by this authorization server.'); + } + } + catch (error) { + if (error instanceof errors_js_1.OAuthError) { + const status = error instanceof errors_js_1.ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }); + return router; +} +//# sourceMappingURL=token.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/token.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/token.js.map new file mode 100644 index 000000000..b6b640626 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/handlers/token.js.map @@ -0,0 +1 @@ +{"version":3,"file":"token.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/token.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,oCA+GC;AA1JD,0CAA4B;AAC5B,sDAAkD;AAElD,gDAAwB;AACxB,mDAAiD;AACjD,+DAAiE;AACjE,2DAA4E;AAC5E,uEAAiE;AACjE,4CAOsB;AAWtB,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;IAChC,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE;CACzB,CAAC,CAAC;AAEH,MAAM,4BAA4B,GAAG,CAAC,CAAC,MAAM,CAAC;IAC1C,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;IAChB,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE;IACzB,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IACnC,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAA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B,CAAC;gBAC1B;oBACI,MAAM,IAAI,qCAAyB,CAAC,+DAA+D,CAAC,CAAC;YAC7G,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,sBAAU,EAAE,CAAC;gBAC9B,MAAM,MAAM,GAAG,KAAK,YAAY,uBAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;gBACxD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,uBAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/allowedMethods.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/allowedMethods.d.ts new file mode 100644 index 000000000..ee6037e0d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/allowedMethods.d.ts @@ -0,0 +1,9 @@ +import { RequestHandler } from 'express'; +/** + * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. + * + * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) + * @returns Express middleware that returns a 405 error if method not in allowed list + */ +export declare function allowedMethods(allowedMethods: string[]): RequestHandler; +//# sourceMappingURL=allowedMethods.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/allowedMethods.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/allowedMethods.d.ts.map new file mode 100644 index 000000000..d3de93e24 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/allowedMethods.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"allowedMethods.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/allowedMethods.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzC;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,cAAc,EAAE,MAAM,EAAE,GAAG,cAAc,CAUvE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/allowedMethods.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/allowedMethods.js new file mode 100644 index 000000000..f44553745 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/allowedMethods.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.allowedMethods = allowedMethods; +const errors_js_1 = require("../errors.js"); +/** + * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. + * + * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) + * @returns Express middleware that returns a 405 error if method not in allowed list + */ +function allowedMethods(allowedMethods) { + return (req, res, next) => { + if (allowedMethods.includes(req.method)) { + next(); + return; + } + const error = new errors_js_1.MethodNotAllowedError(`The method ${req.method} is not allowed for this endpoint`); + res.status(405).set('Allow', allowedMethods.join(', ')).json(error.toResponseObject()); + }; +} +//# sourceMappingURL=allowedMethods.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/allowedMethods.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/allowedMethods.js.map new file mode 100644 index 000000000..be69f3377 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/allowedMethods.js.map @@ -0,0 +1 @@ +{"version":3,"file":"allowedMethods.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/allowedMethods.ts"],"names":[],"mappings":";;AASA,wCAUC;AAlBD,4CAAqD;AAErD;;;;;GAKG;AACH,SAAgB,cAAc,CAAC,cAAwB;IACnD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACtB,IAAI,cAAc,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YACtC,IAAI,EAAE,CAAC;YACP,OAAO;QACX,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,iCAAqB,CAAC,cAAc,GAAG,CAAC,MAAM,mCAAmC,CAAC,CAAC;QACrG,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;IAC3F,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/bearerAuth.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/bearerAuth.d.ts new file mode 100644 index 000000000..10730758b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/bearerAuth.d.ts @@ -0,0 +1,35 @@ +import { RequestHandler } from 'express'; +import { OAuthTokenVerifier } from '../provider.js'; +import { AuthInfo } from '../types.js'; +export type BearerAuthMiddlewareOptions = { + /** + * A provider used to verify tokens. + */ + verifier: OAuthTokenVerifier; + /** + * Optional scopes that the token must have. + */ + requiredScopes?: string[]; + /** + * Optional resource metadata URL to include in WWW-Authenticate header. + */ + resourceMetadataUrl?: string; +}; +declare module 'express-serve-static-core' { + interface Request { + /** + * Information about the validated access token, if the `requireBearerAuth` middleware was used. + */ + auth?: AuthInfo; + } +} +/** + * Middleware that requires a valid Bearer token in the Authorization header. + * + * This will validate the token with the auth provider and add the resulting auth info to the request object. + * + * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header + * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. + */ +export declare function requireBearerAuth({ verifier, requiredScopes, resourceMetadataUrl }: BearerAuthMiddlewareOptions): RequestHandler; +//# sourceMappingURL=bearerAuth.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/bearerAuth.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/bearerAuth.d.ts.map new file mode 100644 index 000000000..c9d939f3b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/bearerAuth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bearerAuth.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/bearerAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,MAAM,MAAM,2BAA2B,GAAG;IACtC;;OAEG;IACH,QAAQ,EAAE,kBAAkB,CAAC;IAE7B;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAE1B;;OAEG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF,OAAO,QAAQ,2BAA2B,CAAC;IACvC,UAAU,OAAO;QACb;;WAEG;QACH,IAAI,CAAC,EAAE,QAAQ,CAAC;KACnB;CACJ;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAmB,EAAE,mBAAmB,EAAE,EAAE,2BAA2B,GAAG,cAAc,CA8DrI"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/bearerAuth.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/bearerAuth.js new file mode 100644 index 000000000..dcfc50935 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/bearerAuth.js @@ -0,0 +1,75 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.requireBearerAuth = requireBearerAuth; +const errors_js_1 = require("../errors.js"); +/** + * Middleware that requires a valid Bearer token in the Authorization header. + * + * This will validate the token with the auth provider and add the resulting auth info to the request object. + * + * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header + * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. + */ +function requireBearerAuth({ verifier, requiredScopes = [], resourceMetadataUrl }) { + return async (req, res, next) => { + try { + const authHeader = req.headers.authorization; + if (!authHeader) { + throw new errors_js_1.InvalidTokenError('Missing Authorization header'); + } + const [type, token] = authHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !token) { + throw new errors_js_1.InvalidTokenError("Invalid Authorization header format, expected 'Bearer TOKEN'"); + } + const authInfo = await verifier.verifyAccessToken(token); + // Check if token has the required scopes (if any) + if (requiredScopes.length > 0) { + const hasAllScopes = requiredScopes.every(scope => authInfo.scopes.includes(scope)); + if (!hasAllScopes) { + throw new errors_js_1.InsufficientScopeError('Insufficient scope'); + } + } + // Check if the token is set to expire or if it is expired + if (typeof authInfo.expiresAt !== 'number' || isNaN(authInfo.expiresAt)) { + throw new errors_js_1.InvalidTokenError('Token has no expiration time'); + } + else if (authInfo.expiresAt < Date.now() / 1000) { + throw new errors_js_1.InvalidTokenError('Token has expired'); + } + req.auth = authInfo; + next(); + } + catch (error) { + // Build WWW-Authenticate header parts + const buildWwwAuthHeader = (errorCode, message) => { + let header = `Bearer error="${errorCode}", error_description="${message}"`; + if (requiredScopes.length > 0) { + header += `, scope="${requiredScopes.join(' ')}"`; + } + if (resourceMetadataUrl) { + header += `, resource_metadata="${resourceMetadataUrl}"`; + } + return header; + }; + if (error instanceof errors_js_1.InvalidTokenError) { + res.set('WWW-Authenticate', buildWwwAuthHeader(error.errorCode, error.message)); + res.status(401).json(error.toResponseObject()); + } + else if (error instanceof errors_js_1.InsufficientScopeError) { + res.set('WWW-Authenticate', buildWwwAuthHeader(error.errorCode, error.message)); + res.status(403).json(error.toResponseObject()); + } + else if (error instanceof errors_js_1.ServerError) { + res.status(500).json(error.toResponseObject()); + } + else if (error instanceof errors_js_1.OAuthError) { + res.status(400).json(error.toResponseObject()); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }; +} +//# sourceMappingURL=bearerAuth.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/bearerAuth.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/bearerAuth.js.map new file mode 100644 index 000000000..d111d36bf --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/bearerAuth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bearerAuth.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/bearerAuth.ts"],"names":[],"mappings":";;AAuCA,8CA8DC;AApGD,4CAAkG;AA8BlG;;;;;;;GAOG;AACH,SAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAc,GAAG,EAAE,EAAE,mBAAmB,EAA+B;IACjH,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC5B,IAAI,CAAC;YACD,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC;YAC7C,IAAI,CAAC,UAAU,EAAE,CAAC;gBACd,MAAM,IAAI,6BAAiB,CAAC,8BAA8B,CAAC,CAAC;YAChE,CAAC;YAED,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC5C,I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CAAC;QACL,CAAC;IACL,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/clientAuth.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/clientAuth.d.ts new file mode 100644 index 000000000..837f95fd2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/clientAuth.d.ts @@ -0,0 +1,19 @@ +import { RequestHandler } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { OAuthClientInformationFull } from '../../../shared/auth.js'; +export type ClientAuthenticationMiddlewareOptions = { + /** + * A store used to read information about registered OAuth clients. + */ + clientsStore: OAuthRegisteredClientsStore; +}; +declare module 'express-serve-static-core' { + interface Request { + /** + * The authenticated client for this request, if the `authenticateClient` middleware was used. + */ + client?: OAuthClientInformationFull; + } +} +export declare function authenticateClient({ clientsStore }: ClientAuthenticationMiddlewareOptions): RequestHandler; +//# sourceMappingURL=clientAuth.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/clientAuth.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/clientAuth.d.ts.map new file mode 100644 index 000000000..5455132c9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/clientAuth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clientAuth.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/clientAuth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AAGrE,MAAM,MAAM,qCAAqC,GAAG;IAChD;;OAEG;IACH,YAAY,EAAE,2BAA2B,CAAC;CAC7C,CAAC;AAOF,OAAO,QAAQ,2BAA2B,CAAC;IACvC,UAAU,OAAO;QACb;;WAEG;QACH,MAAM,CAAC,EAAE,0BAA0B,CAAC;KACvC;CACJ;AAED,wBAAgB,kBAAkB,CAAC,EAAE,YAAY,EAAE,EAAE,qCAAqC,GAAG,cAAc,CAoC1G"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/clientAuth.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/clientAuth.js new file mode 100644 index 000000000..e54dd10e8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/clientAuth.js @@ -0,0 +1,71 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.authenticateClient = authenticateClient; +const z = __importStar(require("zod/v4")); +const errors_js_1 = require("../errors.js"); +const ClientAuthenticatedRequestSchema = z.object({ + client_id: z.string(), + client_secret: z.string().optional() +}); +function authenticateClient({ clientsStore }) { + return async (req, res, next) => { + try { + const result = ClientAuthenticatedRequestSchema.safeParse(req.body); + if (!result.success) { + throw new errors_js_1.InvalidRequestError(String(result.error)); + } + const { client_id, client_secret } = result.data; + const client = await clientsStore.getClient(client_id); + if (!client) { + throw new errors_js_1.InvalidClientError('Invalid client_id'); + } + if (client.client_secret) { + if (!client_secret) { + throw new errors_js_1.InvalidClientError('Client secret is required'); + } + if (client.client_secret !== client_secret) { + throw new errors_js_1.InvalidClientError('Invalid client_secret'); + } + if (client.client_secret_expires_at && client.client_secret_expires_at < Math.floor(Date.now() / 1000)) { + throw new errors_js_1.InvalidClientError('Client secret has expired'); + } + } + req.client = client; + next(); + } + catch (error) { + if (error instanceof errors_js_1.OAuthError) { + const status = error instanceof errors_js_1.ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }; +} +//# sourceMappingURL=clientAuth.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/clientAuth.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/clientAuth.js.map new file mode 100644 index 000000000..63184f4b5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/middleware/clientAuth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"clientAuth.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/clientAuth.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,gDAoCC;AA/DD,0CAA4B;AAI5B,4CAAgG;AAShG,MAAM,gCAAgC,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9C,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACvC,CAAC,CAAC;AAWH,SAAgB,kBAAkB,CAAC,EAAE,YAAY,EAAyC;IACtF,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC5B,IAAI,CAAC;YACD,MAAM,MAAM,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CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,uBAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/provider.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/provider.d.ts new file mode 100644 index 000000000..3e4eca392 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/provider.d.ts @@ -0,0 +1,68 @@ +import { Response } from 'express'; +import { OAuthRegisteredClientsStore } from './clients.js'; +import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../shared/auth.js'; +import { AuthInfo } from './types.js'; +export type AuthorizationParams = { + state?: string; + scopes?: string[]; + codeChallenge: string; + redirectUri: string; + resource?: URL; +}; +/** + * Implements an end-to-end OAuth server. + */ +export interface OAuthServerProvider { + /** + * A store used to read information about registered OAuth clients. + */ + get clientsStore(): OAuthRegisteredClientsStore; + /** + * Begins the authorization flow, which can either be implemented by this server itself or via redirection to a separate authorization server. + * + * This server must eventually issue a redirect with an authorization response or an error response to the given redirect URI. Per OAuth 2.1: + * - In the successful case, the redirect MUST include the `code` and `state` (if present) query parameters. + * - In the error case, the redirect MUST include the `error` query parameter, and MAY include an optional `error_description` query parameter. + */ + authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; + /** + * Returns the `codeChallenge` that was used when the indicated authorization began. + */ + challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; + /** + * Exchanges an authorization code for an access token. + */ + exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; + /** + * Exchanges a refresh token for an access token. + */ + exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; + /** + * Verifies an access token and returns information about it. + */ + verifyAccessToken(token: string): Promise; + /** + * Revokes an access or refresh token. If unimplemented, token revocation is not supported (not recommended). + * + * If the given token is invalid or already revoked, this method should do nothing. + */ + revokeToken?(client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest): Promise; + /** + * Whether to skip local PKCE validation. + * + * If true, the server will not perform PKCE validation locally and will pass the code_verifier to the upstream server. + * + * NOTE: This should only be true if the upstream server is performing the actual PKCE validation. + */ + skipLocalPkceValidation?: boolean; +} +/** + * Slim implementation useful for token verification + */ +export interface OAuthTokenVerifier { + /** + * Verifies an access token and returns information about it. + */ + verifyAccessToken(token: string): Promise; +} +//# sourceMappingURL=provider.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/provider.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/provider.d.ts.map new file mode 100644 index 000000000..d1a4bfff0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,2BAA2B,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC5G,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,MAAM,MAAM,mBAAmB,GAAG;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,aAAa,EAAE,MAAM,CAA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at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/provider.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/provider.js new file mode 100644 index 000000000..0903bb2ef --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/provider.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=provider.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/provider.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/provider.js.map new file mode 100644 index 000000000..b968414aa --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../../src/server/auth/provider.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/providers/proxyProvider.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/providers/proxyProvider.d.ts new file mode 100644 index 000000000..ee6f35081 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/providers/proxyProvider.d.ts @@ -0,0 +1,49 @@ +import { Response } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../../shared/auth.js'; +import { AuthInfo } from '../types.js'; +import { AuthorizationParams, OAuthServerProvider } from '../provider.js'; +import { FetchLike } from '../../../shared/transport.js'; +export type ProxyEndpoints = { + authorizationUrl: string; + tokenUrl: string; + revocationUrl?: string; + registrationUrl?: string; +}; +export type ProxyOptions = { + /** + * Individual endpoint URLs for proxying specific OAuth operations + */ + endpoints: ProxyEndpoints; + /** + * Function to verify access tokens and return auth info + */ + verifyAccessToken: (token: string) => Promise; + /** + * Function to fetch client information from the upstream server + */ + getClient: (clientId: string) => Promise; + /** + * Custom fetch implementation used for all network requests. + */ + fetch?: FetchLike; +}; +/** + * Implements an OAuth server that proxies requests to another OAuth server. + */ +export declare class ProxyOAuthServerProvider implements OAuthServerProvider { + protected readonly _endpoints: ProxyEndpoints; + protected readonly _verifyAccessToken: (token: string) => Promise; + protected readonly _getClient: (clientId: string) => Promise; + protected readonly _fetch?: FetchLike; + skipLocalPkceValidation: boolean; + revokeToken?: (client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest) => Promise; + constructor(options: ProxyOptions); + get clientsStore(): OAuthRegisteredClientsStore; + authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; + challengeForAuthorizationCode(_client: OAuthClientInformationFull, _authorizationCode: string): Promise; + exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; + exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; + verifyAccessToken(token: string): Promise; +} +//# sourceMappingURL=proxyProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/providers/proxyProvider.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/providers/proxyProvider.d.ts.map new file mode 100644 index 000000000..124c105fa --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/providers/proxyProvider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"proxyProvider.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/providers/proxyProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EACH,0BAA0B,EAE1B,2BAA2B,EAC3B,WAAW,EAEd,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,mBAAm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M,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAoBxG,6BAA6B,CAAC,OAAO,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAM/G,yBAAyB,CAC3B,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EACzB,YAAY,CAAC,EAAE,MAAM,EACrB,WAAW,CAAC,EAAE,MAAM,EACpB,QAAQ,CAAC,EAAE,GAAG,GACf,OAAO,CAAC,WAAW,CAAC;IAwCjB,oBAAoB,CACtB,MAAM,EAAE,0BAA0B,EAClC,YAAY,EAAE,MAAM,EACpB,MAAM,CAAC,EAAE,MAAM,EAAE,EACjB,QAAQ,CAAC,EAAE,GAAG,GACf,OAAO,CAAC,WAAW,CAAC;IAoCjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAG5D"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/providers/proxyProvider.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/providers/proxyProvider.js new file mode 100644 index 000000000..17078949c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/providers/proxyProvider.js @@ -0,0 +1,159 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProxyOAuthServerProvider = void 0; +const auth_js_1 = require("../../../shared/auth.js"); +const errors_js_1 = require("../errors.js"); +/** + * Implements an OAuth server that proxies requests to another OAuth server. + */ +class ProxyOAuthServerProvider { + constructor(options) { + this.skipLocalPkceValidation = true; + this._endpoints = options.endpoints; + this._verifyAccessToken = options.verifyAccessToken; + this._getClient = options.getClient; + this._fetch = options.fetch; + if (options.endpoints?.revocationUrl) { + this.revokeToken = async (client, request) => { + const revocationUrl = this._endpoints.revocationUrl; + if (!revocationUrl) { + throw new Error('No revocation endpoint configured'); + } + const params = new URLSearchParams(); + params.set('token', request.token); + params.set('client_id', client.client_id); + if (client.client_secret) { + params.set('client_secret', client.client_secret); + } + if (request.token_type_hint) { + params.set('token_type_hint', request.token_type_hint); + } + const response = await (this._fetch ?? fetch)(revocationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: params.toString() + }); + await response.body?.cancel(); + if (!response.ok) { + throw new errors_js_1.ServerError(`Token revocation failed: ${response.status}`); + } + }; + } + } + get clientsStore() { + const registrationUrl = this._endpoints.registrationUrl; + return { + getClient: this._getClient, + ...(registrationUrl && { + registerClient: async (client) => { + const response = await (this._fetch ?? fetch)(registrationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(client) + }); + if (!response.ok) { + await response.body?.cancel(); + throw new errors_js_1.ServerError(`Client registration failed: ${response.status}`); + } + const data = await response.json(); + return auth_js_1.OAuthClientInformationFullSchema.parse(data); + } + }) + }; + } + async authorize(client, params, res) { + // Start with required OAuth parameters + const targetUrl = new URL(this._endpoints.authorizationUrl); + const searchParams = new URLSearchParams({ + client_id: client.client_id, + response_type: 'code', + redirect_uri: params.redirectUri, + code_challenge: params.codeChallenge, + code_challenge_method: 'S256' + }); + // Add optional standard OAuth parameters + if (params.state) + searchParams.set('state', params.state); + if (params.scopes?.length) + searchParams.set('scope', params.scopes.join(' ')); + if (params.resource) + searchParams.set('resource', params.resource.href); + targetUrl.search = searchParams.toString(); + res.redirect(targetUrl.toString()); + } + async challengeForAuthorizationCode(_client, _authorizationCode) { + // In a proxy setup, we don't store the code challenge ourselves + // Instead, we proxy the token request and let the upstream server validate it + return ''; + } + async exchangeAuthorizationCode(client, authorizationCode, codeVerifier, redirectUri, resource) { + const params = new URLSearchParams({ + grant_type: 'authorization_code', + client_id: client.client_id, + code: authorizationCode + }); + if (client.client_secret) { + params.append('client_secret', client.client_secret); + } + if (codeVerifier) { + params.append('code_verifier', codeVerifier); + } + if (redirectUri) { + params.append('redirect_uri', redirectUri); + } + if (resource) { + params.append('resource', resource.href); + } + const response = await (this._fetch ?? fetch)(this._endpoints.tokenUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: params.toString() + }); + if (!response.ok) { + await response.body?.cancel(); + throw new errors_js_1.ServerError(`Token exchange failed: ${response.status}`); + } + const data = await response.json(); + return auth_js_1.OAuthTokensSchema.parse(data); + } + async exchangeRefreshToken(client, refreshToken, scopes, resource) { + const params = new URLSearchParams({ + grant_type: 'refresh_token', + client_id: client.client_id, + refresh_token: refreshToken + }); + if (client.client_secret) { + params.set('client_secret', client.client_secret); + } + if (scopes?.length) { + params.set('scope', scopes.join(' ')); + } + if (resource) { + params.set('resource', resource.href); + } + const response = await (this._fetch ?? fetch)(this._endpoints.tokenUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: params.toString() + }); + if (!response.ok) { + await response.body?.cancel(); + throw new errors_js_1.ServerError(`Token refresh failed: ${response.status}`); + } + const data = await response.json(); + return auth_js_1.OAuthTokensSchema.parse(data); + } + async verifyAccessToken(token) { + return this._verifyAccessToken(token); + } +} +exports.ProxyOAuthServerProvider = ProxyOAuthServerProvider; +//# sourceMappingURL=proxyProvider.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/providers/proxyProvider.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/providers/proxyProvider.js.map new file mode 100644 index 000000000..7f16e7437 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/providers/proxyProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"proxyProvider.js","sourceRoot":"","sources":["../../../../../src/server/auth/providers/proxyProvider.ts"],"names":[],"mappings":";;;AAEA,qDAMiC;AAGjC,4CAA2C;AAgC3C;;GAEG;AACH,MAAa,wBAAwB;IAUjC,YAAY,OAAqB;QAJjC,4BAAuB,GAAG,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AM,EAAE,MAAM,EAAE,CAAC;YACjB,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QAC1C,CAAC;QAED,IAAI,QAAQ,EAAE,CAAC;YACX,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC1C,CAAC;QAED,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE;YACpE,MAAM,EAAE,MAAM;YACd,OAAO,EAAE;gBACL,cAAc,EAAE,mCAAmC;aACtD;YACD,IAAI,EAAE,MAAM,CAAC,QAAQ,EAAE;SAC1B,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACf,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC;YAC9B,MAAM,IAAI,uBAAW,CAAC,yBAAyB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;QACtE,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,OAAO,2BAAiB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,iBAAiB,CAAC,KAAa;QACjC,OAAO,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;CACJ;AA/LD,4DA+LC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/router.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/router.d.ts new file mode 100644 index 000000000..43dabde7d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/router.d.ts @@ -0,0 +1,101 @@ +import express, { RequestHandler } from 'express'; +import { ClientRegistrationHandlerOptions } from './handlers/register.js'; +import { TokenHandlerOptions } from './handlers/token.js'; +import { AuthorizationHandlerOptions } from './handlers/authorize.js'; +import { RevocationHandlerOptions } from './handlers/revoke.js'; +import { OAuthServerProvider } from './provider.js'; +import { OAuthMetadata } from '../../shared/auth.js'; +export type AuthRouterOptions = { + /** + * A provider implementing the actual authorization logic for this router. + */ + provider: OAuthServerProvider; + /** + * The authorization server's issuer identifier, which is a URL that uses the "https" scheme and has no query or fragment components. + */ + issuerUrl: URL; + /** + * The base URL of the authorization server to use for the metadata endpoints. + * + * If not provided, the issuer URL will be used as the base URL. + */ + baseUrl?: URL; + /** + * An optional URL of a page containing human-readable information that developers might want or need to know when using the authorization server. + */ + serviceDocumentationUrl?: URL; + /** + * An optional list of scopes supported by this authorization server + */ + scopesSupported?: string[]; + /** + * The resource name to be displayed in protected resource metadata + */ + resourceName?: string; + /** + * The URL of the protected resource (RS) whose metadata we advertise. + * If not provided, falls back to `baseUrl` and then to `issuerUrl` (AS=RS). + */ + resourceServerUrl?: URL; + authorizationOptions?: Omit; + clientRegistrationOptions?: Omit; + revocationOptions?: Omit; + tokenOptions?: Omit; +}; +export declare const createOAuthMetadata: (options: { + provider: OAuthServerProvider; + issuerUrl: URL; + baseUrl?: URL; + serviceDocumentationUrl?: URL; + scopesSupported?: string[]; +}) => OAuthMetadata; +/** + * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). + * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. + * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. + * + * By default, rate limiting is applied to all endpoints to prevent abuse. + * + * This router MUST be installed at the application root, like so: + * + * const app = express(); + * app.use(mcpAuthRouter(...)); + */ +export declare function mcpAuthRouter(options: AuthRouterOptions): RequestHandler; +export type AuthMetadataOptions = { + /** + * OAuth Metadata as would be returned from the authorization server + * this MCP server relies on + */ + oauthMetadata: OAuthMetadata; + /** + * The url of the MCP server, for use in protected resource metadata + */ + resourceServerUrl: URL; + /** + * The url for documentation for the MCP server + */ + serviceDocumentationUrl?: URL; + /** + * An optional list of scopes supported by this MCP server + */ + scopesSupported?: string[]; + /** + * An optional resource name to display in resource metadata + */ + resourceName?: string; +}; +export declare function mcpAuthMetadataRouter(options: AuthMetadataOptions): express.Router; +/** + * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL + * from a given server URL. This replaces the path with the standard metadata endpoint. + * + * @param serverUrl - The base URL of the protected resource server + * @returns The URL for the OAuth protected resource metadata endpoint + * + * @example + * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) + * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' + */ +export declare function getOAuthProtectedResourceMetadataUrl(serverUrl: URL): string; +//# sourceMappingURL=router.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/router.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/router.d.ts.map new file mode 100644 index 000000000..615cb964b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/router.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAA6B,gCAAgC,EAAE,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAgB,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAwB,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAC5F,OAAO,EAAqB,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,aAAa,EAAkC,MAAM,sBAAsB,CAAC;AAUrF,MAAM,MAAM,iBAAiB,GAAG;IAC5B;;OAEG;IACH,QAAQ,EAAE,mBAAmB,CAAC;IAE9B;;OAEG;IACH,SAAS,EAAE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AmB,GAAG,OAAO,CAAC,MAAM,CAuBlF;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,oCAAoC,CAAC,SAAS,EAAE,GAAG,GAAG,MAAM,CAI3E"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/router.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/router.js new file mode 100644 index 000000000..582711962 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/router.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 }); +exports.createOAuthMetadata = void 0; +exports.mcpAuthRouter = mcpAuthRouter; +exports.mcpAuthMetadataRouter = mcpAuthMetadataRouter; +exports.getOAuthProtectedResourceMetadataUrl = getOAuthProtectedResourceMetadataUrl; +const express_1 = __importDefault(require("express")); +const register_js_1 = require("./handlers/register.js"); +const token_js_1 = require("./handlers/token.js"); +const authorize_js_1 = require("./handlers/authorize.js"); +const revoke_js_1 = require("./handlers/revoke.js"); +const metadata_js_1 = require("./handlers/metadata.js"); +// Check for dev mode flag that allows HTTP issuer URLs (for development/testing only) +const allowInsecureIssuerUrl = process.env.MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL === 'true' || process.env.MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL === '1'; +if (allowInsecureIssuerUrl) { + // eslint-disable-next-line no-console + console.warn('MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL is enabled - HTTP issuer URLs are allowed. Do not use in production.'); +} +const checkIssuerUrl = (issuer) => { + // Technically RFC 8414 does not permit a localhost HTTPS exemption, but this will be necessary for ease of testing + if (issuer.protocol !== 'https:' && issuer.hostname !== 'localhost' && issuer.hostname !== '127.0.0.1' && !allowInsecureIssuerUrl) { + throw new Error('Issuer URL must be HTTPS'); + } + if (issuer.hash) { + throw new Error(`Issuer URL must not have a fragment: ${issuer}`); + } + if (issuer.search) { + throw new Error(`Issuer URL must not have a query string: ${issuer}`); + } +}; +const createOAuthMetadata = (options) => { + const issuer = options.issuerUrl; + const baseUrl = options.baseUrl; + checkIssuerUrl(issuer); + const authorization_endpoint = '/authorize'; + const token_endpoint = '/token'; + const registration_endpoint = options.provider.clientsStore.registerClient ? '/register' : undefined; + const revocation_endpoint = options.provider.revokeToken ? '/revoke' : undefined; + const metadata = { + issuer: issuer.href, + service_documentation: options.serviceDocumentationUrl?.href, + authorization_endpoint: new URL(authorization_endpoint, baseUrl || issuer).href, + response_types_supported: ['code'], + code_challenge_methods_supported: ['S256'], + token_endpoint: new URL(token_endpoint, baseUrl || issuer).href, + token_endpoint_auth_methods_supported: ['client_secret_post', 'none'], + grant_types_supported: ['authorization_code', 'refresh_token'], + scopes_supported: options.scopesSupported, + revocation_endpoint: revocation_endpoint ? new URL(revocation_endpoint, baseUrl || issuer).href : undefined, + revocation_endpoint_auth_methods_supported: revocation_endpoint ? ['client_secret_post'] : undefined, + registration_endpoint: registration_endpoint ? new URL(registration_endpoint, baseUrl || issuer).href : undefined + }; + return metadata; +}; +exports.createOAuthMetadata = createOAuthMetadata; +/** + * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). + * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. + * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. + * + * By default, rate limiting is applied to all endpoints to prevent abuse. + * + * This router MUST be installed at the application root, like so: + * + * const app = express(); + * app.use(mcpAuthRouter(...)); + */ +function mcpAuthRouter(options) { + const oauthMetadata = (0, exports.createOAuthMetadata)(options); + const router = express_1.default.Router(); + router.use(new URL(oauthMetadata.authorization_endpoint).pathname, (0, authorize_js_1.authorizationHandler)({ provider: options.provider, ...options.authorizationOptions })); + router.use(new URL(oauthMetadata.token_endpoint).pathname, (0, token_js_1.tokenHandler)({ provider: options.provider, ...options.tokenOptions })); + router.use(mcpAuthMetadataRouter({ + oauthMetadata, + // Prefer explicit RS; otherwise fall back to AS baseUrl, then to issuer (back-compat) + resourceServerUrl: options.resourceServerUrl ?? options.baseUrl ?? new URL(oauthMetadata.issuer), + serviceDocumentationUrl: options.serviceDocumentationUrl, + scopesSupported: options.scopesSupported, + resourceName: options.resourceName + })); + if (oauthMetadata.registration_endpoint) { + router.use(new URL(oauthMetadata.registration_endpoint).pathname, (0, register_js_1.clientRegistrationHandler)({ + clientsStore: options.provider.clientsStore, + ...options.clientRegistrationOptions + })); + } + if (oauthMetadata.revocation_endpoint) { + router.use(new URL(oauthMetadata.revocation_endpoint).pathname, (0, revoke_js_1.revocationHandler)({ provider: options.provider, ...options.revocationOptions })); + } + return router; +} +function mcpAuthMetadataRouter(options) { + checkIssuerUrl(new URL(options.oauthMetadata.issuer)); + const router = express_1.default.Router(); + const protectedResourceMetadata = { + resource: options.resourceServerUrl.href, + authorization_servers: [options.oauthMetadata.issuer], + scopes_supported: options.scopesSupported, + resource_name: options.resourceName, + resource_documentation: options.serviceDocumentationUrl?.href + }; + // Serve PRM at the path-specific URL per RFC 9728 + const rsPath = new URL(options.resourceServerUrl.href).pathname; + router.use(`/.well-known/oauth-protected-resource${rsPath === '/' ? '' : rsPath}`, (0, metadata_js_1.metadataHandler)(protectedResourceMetadata)); + // Always add this for OAuth Authorization Server metadata per RFC 8414 + router.use('/.well-known/oauth-authorization-server', (0, metadata_js_1.metadataHandler)(options.oauthMetadata)); + return router; +} +/** + * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL + * from a given server URL. This replaces the path with the standard metadata endpoint. + * + * @param serverUrl - The base URL of the protected resource server + * @returns The URL for the OAuth protected resource metadata endpoint + * + * @example + * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) + * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' + */ +function getOAuthProtectedResourceMetadataUrl(serverUrl) { + const u = new URL(serverUrl.href); + const rsPath = u.pathname && u.pathname !== '/' ? u.pathname : ''; + return new URL(`/.well-known/oauth-protected-resource${rsPath}`, u).href; +} +//# sourceMappingURL=router.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/router.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/router.js.map new file mode 100644 index 000000000..991898b46 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/router.js.map @@ -0,0 +1 @@ +{"version":3,"file":"router.js","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":";;;;;;AAgIA,sCAyCC;AA8BD,sDAuBC;AAaD,oFAIC;AA/OD,sDAAkD;AAClD,wDAAqG;AACrG,kDAAwE;AACxE,0DAA4F;AAC5F,oDAAmF;AACnF,wDAAyD;AAIzD,sFAAsF;AACtF,MAAM,sBAAsB,GACxB,OAAO,CAAC,GAAG,CAAC,yCAAyC,KAAK,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,yCAAyC,KAAK,GAAG,CAAC;AACtI,IAAI,sBAAsB,EAAE,CAAC;IACzB,sCAAsC;IACtC,OAAO,CAAC,IAAI,CAAC,gHAAgH,CAAC,CAAC;AACnI,CAAC;AAgDD,MAAM,cAAc,GAAG,CAAC,MAAW,EAAQ,EAAE;IACzC,mHAAmH;IACnH,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,KAAK,WAAW,IAAI,MAAM,CAAC,QAAQ,KAAK,WAAW,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAChI,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;IAChD,CAAC;IACD,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,CAAC,wCAAwC,MAAM,EAAE,CAAC,CAAC;IACtE,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,4CAA4C,MAAM,EAAE,CAAC,CA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EAAC,yBAAyB,CAAC,CAAC,CAAC;IAE/H,uEAAuE;IACvE,MAAM,CAAC,GAAG,CAAC,yCAAyC,EAAE,IAAA,6BAAe,EAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC;IAE9F,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,oCAAoC,CAAC,SAAc;IAC/D,MAAM,CAAC,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IAClC,MAAM,MAAM,GAAG,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,QAAQ,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;IAClE,OAAO,IAAI,GAAG,CAAC,wCAAwC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAC7E,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/types.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/types.d.ts new file mode 100644 index 000000000..05ec8485a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/types.d.ts @@ -0,0 +1,32 @@ +/** + * Information about a validated access token, provided to request handlers. + */ +export interface AuthInfo { + /** + * The access token. + */ + token: string; + /** + * The client ID associated with this token. + */ + clientId: string; + /** + * Scopes associated with this token. + */ + scopes: string[]; + /** + * When the token expires (in seconds since epoch). + */ + expiresAt?: number; + /** + * The RFC 8707 resource server identifier for which this token is valid. + * If set, this MUST match the MCP server's resource identifier (minus hash fragment). + */ + resource?: URL; + /** + * Additional data associated with the token. + * This field should be used for any additional data that needs to be attached to the auth info. + */ + extra?: Record; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/types.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/types.d.ts.map new file mode 100644 index 000000000..021e94740 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,QAAQ;IACrB;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,MAAM,EAAE,MAAM,EAAE,CAAC;IAEjB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,GAAG,CAAC;IAEf;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/types.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/types.js new file mode 100644 index 000000000..11e638d1e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/types.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/types.js.map new file mode 100644 index 000000000..0d8063dee --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/auth/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/server/auth/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/completable.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/completable.d.ts new file mode 100644 index 000000000..1b3159ac8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/completable.d.ts @@ -0,0 +1,38 @@ +import { AnySchema, SchemaInput } from './zod-compat.js'; +export declare const COMPLETABLE_SYMBOL: unique symbol; +export type CompleteCallback = (value: SchemaInput, context?: { + arguments?: Record; +}) => SchemaInput[] | Promise[]>; +export type CompletableMeta = { + complete: CompleteCallback; +}; +export type CompletableSchema = T & { + [COMPLETABLE_SYMBOL]: CompletableMeta; +}; +/** + * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. + * Works with both Zod v3 and v4 schemas. + */ +export declare function completable(schema: T, complete: CompleteCallback): CompletableSchema; +/** + * Checks if a schema is completable (has completion metadata). + */ +export declare function isCompletable(schema: unknown): schema is CompletableSchema; +/** + * Gets the completer callback from a completable schema, if it exists. + */ +export declare function getCompleter(schema: T): CompleteCallback | undefined; +/** + * Unwraps a completable schema to get the underlying schema. + * For backward compatibility with code that called `.unwrap()`. + */ +export declare function unwrapCompletable(schema: CompletableSchema): T; +export declare enum McpZodTypeKind { + Completable = "McpCompletable" +} +export interface CompletableDef { + type: T; + complete: CompleteCallback; + typeName: McpZodTypeKind.Completable; +} +//# sourceMappingURL=completable.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/completable.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/completable.d.ts.map new file mode 100644 index 000000000..83ea2f1e2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/completable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"completable.d.ts","sourceRoot":"","sources":["../../../src/server/completable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEzD,eAAO,MAAM,kBAAkB,EAAE,OAAO,MAAsC,CAAC;AAE/E,MAAM,MAAM,gBAAgB,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,IAAI,CAC5D,KAAK,EAAE,WAAW,C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W,CAAC;CACxC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/completable.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/completable.js new file mode 100644 index 000000000..58f187316 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/completable.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.McpZodTypeKind = exports.COMPLETABLE_SYMBOL = void 0; +exports.completable = completable; +exports.isCompletable = isCompletable; +exports.getCompleter = getCompleter; +exports.unwrapCompletable = unwrapCompletable; +exports.COMPLETABLE_SYMBOL = Symbol.for('mcp.completable'); +/** + * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. + * Works with both Zod v3 and v4 schemas. + */ +function completable(schema, complete) { + Object.defineProperty(schema, exports.COMPLETABLE_SYMBOL, { + value: { complete }, + enumerable: false, + writable: false, + configurable: false + }); + return schema; +} +/** + * Checks if a schema is completable (has completion metadata). + */ +function isCompletable(schema) { + return !!schema && typeof schema === 'object' && exports.COMPLETABLE_SYMBOL in schema; +} +/** + * Gets the completer callback from a completable schema, if it exists. + */ +function getCompleter(schema) { + const meta = schema[exports.COMPLETABLE_SYMBOL]; + return meta?.complete; +} +/** + * Unwraps a completable schema to get the underlying schema. + * For backward compatibility with code that called `.unwrap()`. + */ +function unwrapCompletable(schema) { + return schema; +} +// Legacy exports for backward compatibility +// These types are deprecated but kept for existing code +var McpZodTypeKind; +(function (McpZodTypeKind) { + McpZodTypeKind["Completable"] = "McpCompletable"; +})(McpZodTypeKind || (exports.McpZodTypeKind = McpZodTypeKind = {})); +//# sourceMappingURL=completable.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/completable.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/completable.js.map new file mode 100644 index 000000000..6b20bd6e6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/completable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"completable.js","sourceRoot":"","sources":["../../../src/server/completable.ts"],"names":[],"mappings":";;;AAuBA,kCAQC;AAKD,sCAEC;AAKD,oCAGC;AAMD,8CAEC;AApDY,QAAA,kBAAkB,GAAkB,MAAM,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;AAiB/E;;;GAGG;AACH,SAAgB,WAAW,CAAsB,MAAS,EAAE,QAA6B;IACrF,MAAM,CAAC,cAAc,CAAC,MAAgB,EAAE,0BAAkB,EAAE;QACxD,KAAK,EAAE,EAAE,QAAQ,EAAwB;QACzC,UAAU,EAAE,KAAK;QACjB,QAAQ,EAAE,KAAK;QACf,YAAY,EAAE,KAAK;KACtB,CAAC,CAAC;IACH,OAAO,MAA8B,CAAC;AAC1C,CAAC;AAED;;GAEG;AACH,SAAgB,aAAa,CAAC,MAAe;IACzC,OAAO,CAAC,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,0BAAkB,IAAK,MAAiB,CAAC;AAC9F,CAAC;AAED;;GAEG;AACH,SAAgB,YAAY,CAAsB,MAAS;IACvD,MAAM,IAAI,GAAI,MAAmE,CAAC,0BAAkB,CAAC,CAAC;IACtG,OAAO,IAAI,EAAE,QAA2C,CAAC;AAC7D,CAAC;AAED;;;GAGG;AACH,SAAgB,iBAAiB,CAAsB,MAA4B;IAC/E,OAAO,MAAM,CAAC;AAClB,CAAC;AAED,4CAA4C;AAC5C,wDAAwD;AACxD,IAAY,cAEX;AAFD,WAAY,cAAc;IACtB,gDAA8B,CAAA;AAClC,CAAC,EAFW,cAAc,8BAAd,cAAc,QAEzB"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.d.ts new file mode 100644 index 000000000..7746e823b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.d.ts @@ -0,0 +1,45 @@ +import { Express } from 'express'; +/** + * Options for creating an MCP Express application. + */ +export interface CreateMcpExpressAppOptions { + /** + * The hostname to bind to. Defaults to '127.0.0.1'. + * When set to '127.0.0.1', 'localhost', or '::1', DNS rebinding protection is automatically enabled. + */ + host?: string; + /** + * List of allowed hostnames for DNS rebinding protection. + * If provided, host header validation will be applied using this list. + * For IPv6, provide addresses with brackets (e.g., '[::1]'). + * + * This is useful when binding to '0.0.0.0' or '::' but still wanting + * to restrict which hostnames are allowed. + */ + allowedHosts?: string[]; +} +/** + * Creates an Express application pre-configured for MCP servers. + * + * When the host is '127.0.0.1', 'localhost', or '::1' (the default is '127.0.0.1'), + * DNS rebinding protection middleware is automatically applied to protect against + * DNS rebinding attacks on localhost servers. + * + * @param options - Configuration options + * @returns A configured Express application + * + * @example + * ```typescript + * // Basic usage - defaults to 127.0.0.1 with DNS rebinding protection + * const app = createMcpExpressApp(); + * + * // Custom host - DNS rebinding protection only applied for localhost hosts + * const app = createMcpExpressApp({ host: '0.0.0.0' }); // No automatic DNS rebinding protection + * const app = createMcpExpressApp({ host: 'localhost' }); // DNS rebinding protection enabled + * + * // Custom allowed hosts for non-localhost binding + * const app = createMcpExpressApp({ host: '0.0.0.0', allowedHosts: ['myapp.local', 'localhost'] }); + * ``` + */ +export declare function createMcpExpressApp(options?: CreateMcpExpressAppOptions): Express; +//# sourceMappingURL=express.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.d.ts.map new file mode 100644 index 000000000..5f607a9a9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"express.d.ts","sourceRoot":"","sources":["../../../src/server/express.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAG3C;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACvC;;;OAGG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd;;;;;;;OAOG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CAC3B;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,0BAA+B,GAAG,OAAO,CA0BrF"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.js new file mode 100644 index 000000000..1d37a8dac --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.js @@ -0,0 +1,56 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createMcpExpressApp = createMcpExpressApp; +const express_1 = __importDefault(require("express")); +const hostHeaderValidation_js_1 = require("./middleware/hostHeaderValidation.js"); +/** + * Creates an Express application pre-configured for MCP servers. + * + * When the host is '127.0.0.1', 'localhost', or '::1' (the default is '127.0.0.1'), + * DNS rebinding protection middleware is automatically applied to protect against + * DNS rebinding attacks on localhost servers. + * + * @param options - Configuration options + * @returns A configured Express application + * + * @example + * ```typescript + * // Basic usage - defaults to 127.0.0.1 with DNS rebinding protection + * const app = createMcpExpressApp(); + * + * // Custom host - DNS rebinding protection only applied for localhost hosts + * const app = createMcpExpressApp({ host: '0.0.0.0' }); // No automatic DNS rebinding protection + * const app = createMcpExpressApp({ host: 'localhost' }); // DNS rebinding protection enabled + * + * // Custom allowed hosts for non-localhost binding + * const app = createMcpExpressApp({ host: '0.0.0.0', allowedHosts: ['myapp.local', 'localhost'] }); + * ``` + */ +function createMcpExpressApp(options = {}) { + const { host = '127.0.0.1', allowedHosts } = options; + const app = (0, express_1.default)(); + app.use(express_1.default.json()); + // If allowedHosts is explicitly provided, use that for validation + if (allowedHosts) { + app.use((0, hostHeaderValidation_js_1.hostHeaderValidation)(allowedHosts)); + } + else { + // Apply DNS rebinding protection automatically for localhost hosts + const localhostHosts = ['127.0.0.1', 'localhost', '::1']; + if (localhostHosts.includes(host)) { + app.use((0, hostHeaderValidation_js_1.localhostHostValidation)()); + } + else if (host === '0.0.0.0' || host === '::') { + // Warn when binding to all interfaces without DNS rebinding protection + // eslint-disable-next-line no-console + console.warn(`Warning: Server is binding to ${host} without DNS rebinding protection. ` + + 'Consider using the allowedHosts option to restrict allowed hosts, ' + + 'or use authentication to protect your server.'); + } + } + return app; +} +//# sourceMappingURL=express.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.js.map new file mode 100644 index 000000000..f15b40d71 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.js.map @@ -0,0 +1 @@ +{"version":3,"file":"express.js","sourceRoot":"","sources":["../../../src/server/express.ts"],"names":[],"mappings":";;;;;AA+CA,kDA0BC;AAzED,sDAA2C;AAC3C,kFAAqG;AAuBrG;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,SAAgB,mBAAmB,CAAC,UAAsC,EAAE;IACxE,MAAM,EAAE,IAAI,GAAG,WAAW,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC;IAErD,MAAM,GAAG,GAAG,IAAA,iBAAO,GAAE,CAAC;IACtB,GAAG,CAAC,GAAG,CAAC,iBAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IAExB,kEAAkE;IAClE,IAAI,YAAY,EAAE,CAAC;QACf,GAAG,CAAC,GAAG,CAAC,IAAA,8CAAoB,EAAC,YAAY,CAAC,CAAC,CAAC;IAChD,CAAC;SAAM,CAAC;QACJ,mEAAmE;QACnE,MAAM,cAAc,GAAG,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC;QACzD,IAAI,cAAc,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YAChC,GAAG,CAAC,GAAG,CAAC,IAAA,iDAAuB,GAAE,CAAC,CAAC;QACvC,CAAC;aAAM,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YAC7C,uEAAuE;YACvE,sCAAsC;YACtC,OAAO,CAAC,IAAI,CACR,iCAAiC,IAAI,qCAAqC;gBACtE,oEAAoE;gBACpE,+CAA+C,CACtD,CAAC;QACN,CAAC;IACL,CAAC;IAED,OAAO,GAAG,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.d.ts new file mode 100644 index 000000000..cfa236eb0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.d.ts @@ -0,0 +1,196 @@ +import { Protocol, type NotificationOptions, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; +import { type ClientCapabilities, type CreateMessageRequest, type CreateMessageResult, type CreateMessageResultWithTools, type CreateMessageRequestParamsBase, type CreateMessageRequestParamsWithTools, type ElicitRequestFormParams, type ElicitRequestURLParams, type ElicitResult, type Implementation, type ListRootsRequest, type LoggingMessageNotification, type ResourceUpdatedNotification, type ServerCapabilities, type ServerNotification, type ServerRequest, type ServerResult, type Request, type Notification, type Result } from '../types.js'; +import type { jsonSchemaValidator } from '../validation/types.js'; +import { AnyObjectSchema, SchemaOutput } from './zod-compat.js'; +import { RequestHandlerExtra } from '../shared/protocol.js'; +import { ExperimentalServerTasks } from '../experimental/tasks/server.js'; +export type ServerOptions = ProtocolOptions & { + /** + * Capabilities to advertise as being supported by this server. + */ + capabilities?: ServerCapabilities; + /** + * Optional instructions describing how to use the server and its features. + */ + instructions?: string; + /** + * JSON Schema validator for elicitation response validation. + * + * The validator is used to validate user input returned from elicitation + * requests against the requested schema. + * + * @default AjvJsonSchemaValidator + * + * @example + * ```typescript + * // ajv (default) + * const server = new Server( + * { name: 'my-server', version: '1.0.0' }, + * { + * capabilities: {} + * jsonSchemaValidator: new AjvJsonSchemaValidator() + * } + * ); + * + * // @cfworker/json-schema + * const server = new Server( + * { name: 'my-server', version: '1.0.0' }, + * { + * capabilities: {}, + * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() + * } + * ); + * ``` + */ + jsonSchemaValidator?: jsonSchemaValidator; +}; +/** + * An MCP server on top of a pluggable transport. + * + * This server will automatically respond to the initialization flow as initiated from the client. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed server + * const server = new Server({ + * name: "CustomServer", + * version: "1.0.0" + * }) + * ``` + * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. + */ +export declare class Server extends Protocol { + private _serverInfo; + private _clientCapabilities?; + private _clientVersion?; + private _capabilities; + private _instructions?; + private _jsonSchemaValidator; + private _experimental?; + /** + * Callback for when initialization has fully completed (i.e., the client has sent an `initialized` notification). + */ + oninitialized?: () => void; + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo: Implementation, options?: ServerOptions); + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental(): { + tasks: ExperimentalServerTasks; + }; + private _loggingLevels; + private readonly LOG_LEVEL_SEVERITY; + private isMessageIgnored; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities: ServerCapabilities): void; + /** + * Override request handler registration to enforce server-side validation for tools/call. + */ + setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => ServerResult | ResultT | Promise): void; + protected assertCapabilityForMethod(method: RequestT['method']): void; + protected assertNotificationCapability(method: (ServerNotification | NotificationT)['method']): void; + protected assertRequestHandlerCapability(method: string): void; + protected assertTaskCapability(method: string): void; + protected assertTaskHandlerCapability(method: string): void; + private _oninitialize; + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + */ + getClientCapabilities(): ClientCapabilities | undefined; + /** + * After initialization has completed, this will be populated with information about the client's name and version. + */ + getClientVersion(): Implementation | undefined; + private getCapabilities; + ping(): Promise<{ + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + /** + * Request LLM sampling from the client (without tools). + * Returns single content block for backwards compatibility. + */ + createMessage(params: CreateMessageRequestParamsBase, options?: RequestOptions): Promise; + /** + * Request LLM sampling from the client with tool support. + * Returns content that may be a single block or array (for parallel tool calls). + */ + createMessage(params: CreateMessageRequestParamsWithTools, options?: RequestOptions): Promise; + /** + * Request LLM sampling from the client. + * When tools may or may not be present, returns the union type. + */ + createMessage(params: CreateMessageRequest['params'], options?: RequestOptions): Promise; + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + */ + elicitInput(params: ElicitRequestFormParams | ElicitRequestURLParams, options?: RequestOptions): Promise; + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId: string, options?: NotificationOptions): () => Promise; + listRoots(params?: ListRootsRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + roots: { + uri: string; + name?: string | undefined; + _meta?: Record | undefined; + }[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise; + sendResourceUpdated(params: ResourceUpdatedNotification['params']): Promise; + sendResourceListChanged(): Promise; + sendToolListChanged(): Promise; + sendPromptListChanged(): Promise; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.d.ts.map new file mode 100644 index 000000000..fe0fa6589 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,KAAK,mBAAmB,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACzI,OAAO,EACH,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EAExB,KAAK,4BAA4B,EAEjC,KAAK,8BAA8B,EACnC,KAAK,mCAAmC,EACxC,KAAK,uBAAuB,EAC5B,KAAK,sBAAsB,EAC3B,KAAK,YAAY,EAIjB,KAAK,cAAc,EAMnB,KAAK,gBAAgB,EAIrB,KAAK,0BAA0B,EAE/B,KAAK,2BAA2B,EAChC,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,YAAY,EAQjB,KAAK,OAAO,EACZ,KAAK,YAAY,EACjB,KAAK,MAAM,EACd,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EAAkB,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAClF,OAAO,EACH,eAAe,EAIf,YAAY,EAGf,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAA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EAAE,cAAc,GACzB,OAAO,CAAC,mBAAmB,GAAG,4BAA4B,CAAC;IAwD9D;;;;;;OAMG;IACG,WAAW,CAAC,MAAM,EAAE,uBAAuB,GAAG,sBAAsB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC;IAgD5H;;;;;;;OAOG;IACH,mCAAmC,CAAC,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC;IAiBxG,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;IAI7E;;;;;;OAMG;IACG,kBAAkB,CAAC,MAAM,EAAE,0BAA0B,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC,EAAE,MAAM;IAQnF,mBAAmB,CAAC,MAAM,EAAE,2BAA2B,CAAC,QAAQ,CAAC;IAOjE,uBAAuB;IAMvB,mBAAmB;IAInB,qBAAqB;CAG9B"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.js new file mode 100644 index 000000000..e183dd4df --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.js @@ -0,0 +1,444 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Server = void 0; +const protocol_js_1 = require("../shared/protocol.js"); +const types_js_1 = require("../types.js"); +const ajv_provider_js_1 = require("../validation/ajv-provider.js"); +const zod_compat_js_1 = require("./zod-compat.js"); +const server_js_1 = require("../experimental/tasks/server.js"); +const helpers_js_1 = require("../experimental/tasks/helpers.js"); +/** + * An MCP server on top of a pluggable transport. + * + * This server will automatically respond to the initialization flow as initiated from the client. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed server + * const server = new Server({ + * name: "CustomServer", + * version: "1.0.0" + * }) + * ``` + * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. + */ +class Server extends protocol_js_1.Protocol { + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + super(options); + this._serverInfo = _serverInfo; + // Map log levels by session id + this._loggingLevels = new Map(); + // Map LogLevelSchema to severity index + this.LOG_LEVEL_SEVERITY = new Map(types_js_1.LoggingLevelSchema.options.map((level, index) => [level, index])); + // Is a message with the given level ignored in the log level set for the given session id? + this.isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + this._capabilities = options?.capabilities ?? {}; + this._instructions = options?.instructions; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new ajv_provider_js_1.AjvJsonSchemaValidator(); + this.setRequestHandler(types_js_1.InitializeRequestSchema, request => this._oninitialize(request)); + this.setNotificationHandler(types_js_1.InitializedNotificationSchema, () => this.oninitialized?.()); + if (this._capabilities.logging) { + this.setRequestHandler(types_js_1.SetLevelRequestSchema, async (request, extra) => { + const transportSessionId = extra.sessionId || extra.requestInfo?.headers['mcp-session-id'] || undefined; + const { level } = request.params; + const parseResult = types_js_1.LoggingLevelSchema.safeParse(level); + if (parseResult.success) { + this._loggingLevels.set(transportSessionId, parseResult.data); + } + return {}; + }); + } + } + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental() { + if (!this._experimental) { + this._experimental = { + tasks: new server_js_1.ExperimentalServerTasks(this) + }; + } + return this._experimental; + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error('Cannot register capabilities after connecting to transport'); + } + this._capabilities = (0, protocol_js_1.mergeCapabilities)(this._capabilities, capabilities); + } + /** + * Override request handler registration to enforce server-side validation for tools/call. + */ + setRequestHandler(requestSchema, handler) { + const shape = (0, zod_compat_js_1.getObjectShape)(requestSchema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + // Extract literal value using type-safe property access + let methodValue; + if ((0, zod_compat_js_1.isZ4Schema)(methodSchema)) { + const v4Schema = methodSchema; + const v4Def = v4Schema._zod?.def; + methodValue = v4Def?.value ?? v4Schema.value; + } + else { + const v3Schema = methodSchema; + const legacyDef = v3Schema._def; + methodValue = legacyDef?.value ?? v3Schema.value; + } + if (typeof methodValue !== 'string') { + throw new Error('Schema method literal must be a string'); + } + const method = methodValue; + if (method === 'tools/call') { + const wrappedHandler = async (request, extra) => { + const validatedRequest = (0, zod_compat_js_1.safeParse)(types_js_1.CallToolRequestSchema, request); + if (!validatedRequest.success) { + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + const result = await Promise.resolve(handler(request, extra)); + // When task creation is requested, validate and return CreateTaskResult + if (params.task) { + const taskValidationResult = (0, zod_compat_js_1.safeParse)(types_js_1.CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error + ? taskValidationResult.error.message + : String(taskValidationResult.error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + // For non-task requests, validate against CallToolResultSchema + const validationResult = (0, zod_compat_js_1.safeParse)(types_js_1.CallToolResultSchema, result); + if (!validationResult.success) { + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`); + } + return validationResult.data; + }; + // Install the wrapped handler + return super.setRequestHandler(requestSchema, wrappedHandler); + } + // Other handlers use default behavior + return super.setRequestHandler(requestSchema, handler); + } + assertCapabilityForMethod(method) { + switch (method) { + case 'sampling/createMessage': + if (!this._clientCapabilities?.sampling) { + throw new Error(`Client does not support sampling (required for ${method})`); + } + break; + case 'elicitation/create': + if (!this._clientCapabilities?.elicitation) { + throw new Error(`Client does not support elicitation (required for ${method})`); + } + break; + case 'roots/list': + if (!this._clientCapabilities?.roots) { + throw new Error(`Client does not support listing roots (required for ${method})`); + } + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertNotificationCapability(method) { + switch (method) { + case 'notifications/message': + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'notifications/resources/updated': + case 'notifications/resources/list_changed': + if (!this._capabilities.resources) { + throw new Error(`Server does not support notifying about resources (required for ${method})`); + } + break; + case 'notifications/tools/list_changed': + if (!this._capabilities.tools) { + throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); + } + break; + case 'notifications/prompts/list_changed': + if (!this._capabilities.prompts) { + throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); + } + break; + case 'notifications/elicitation/complete': + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error(`Client does not support URL elicitation (required for ${method})`); + } + break; + case 'notifications/cancelled': + // Cancellation notifications are always allowed + break; + case 'notifications/progress': + // Progress notifications are always allowed + break; + } + } + assertRequestHandlerCapability(method) { + // Task handlers are registered in Protocol constructor before _capabilities is initialized + // Skip capability check for task methods during initialization + if (!this._capabilities) { + return; + } + switch (method) { + case 'completion/complete': + if (!this._capabilities.completions) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case 'logging/setLevel': + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'prompts/get': + case 'prompts/list': + if (!this._capabilities.prompts) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case 'resources/list': + case 'resources/templates/list': + case 'resources/read': + if (!this._capabilities.resources) { + throw new Error(`Server does not support resources (required for ${method})`); + } + break; + case 'tools/call': + case 'tools/list': + if (!this._capabilities.tools) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case 'tasks/get': + case 'tasks/list': + case 'tasks/result': + case 'tasks/cancel': + if (!this._capabilities.tasks) { + throw new Error(`Server does not support tasks capability (required for ${method})`); + } + break; + case 'ping': + case 'initialize': + // No specific capability required for these methods + break; + } + } + assertTaskCapability(method) { + (0, helpers_js_1.assertClientRequestTaskCapability)(this._clientCapabilities?.tasks?.requests, method, 'Client'); + } + assertTaskHandlerCapability(method) { + // Task handlers are registered in Protocol constructor before _capabilities is initialized + // Skip capability check for task methods during initialization + if (!this._capabilities) { + return; + } + (0, helpers_js_1.assertToolsCallTaskCapability)(this._capabilities.tasks?.requests, method, 'Server'); + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const protocolVersion = types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : types_js_1.LATEST_PROTOCOL_VERSION; + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...(this._instructions && { instructions: this._instructions }) + }; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + */ + getClientVersion() { + return this._clientVersion; + } + getCapabilities() { + return this._capabilities; + } + async ping() { + return this.request({ method: 'ping' }, types_js_1.EmptyResultSchema); + } + // Implementation + async createMessage(params, options) { + // Capability check - only required when tools/toolChoice are provided + if (params.tools || params.toolChoice) { + if (!this._clientCapabilities?.sampling?.tools) { + throw new Error('Client does not support sampling tools capability.'); + } + } + // Message structure validation - always validate tool_use/tool_result pairs. + // These may appear even without tools/toolChoice in the current request when + // a previous sampling request returned tool_use and this is a follow-up with results. + if (params.messages.length > 0) { + const lastMessage = params.messages[params.messages.length - 1]; + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some(c => c.type === 'tool_result'); + const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined; + const previousContent = previousMessage + ? Array.isArray(previousMessage.content) + ? previousMessage.content + : [previousMessage.content] + : []; + const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use'); + if (hasToolResults) { + if (lastContent.some(c => c.type !== 'tool_result')) { + throw new Error('The last message must contain only tool_result content if any is present'); + } + if (!hasPreviousToolUse) { + throw new Error('tool_result blocks are not matching any tool_use from the previous message'); + } + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id)); + const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) { + throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match'); + } + } + } + // Use different schemas based on whether tools are provided + if (params.tools) { + return this.request({ method: 'sampling/createMessage', params }, types_js_1.CreateMessageResultWithToolsSchema, options); + } + return this.request({ method: 'sampling/createMessage', params }, types_js_1.CreateMessageResultSchema, options); + } + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + */ + async elicitInput(params, options) { + const mode = (params.mode ?? 'form'); + switch (mode) { + case 'url': { + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error('Client does not support url elicitation.'); + } + const urlParams = params; + return this.request({ method: 'elicitation/create', params: urlParams }, types_js_1.ElicitResultSchema, options); + } + case 'form': { + if (!this._clientCapabilities?.elicitation?.form) { + throw new Error('Client does not support form elicitation.'); + } + const formParams = params.mode === 'form' ? params : { ...params, mode: 'form' }; + const result = await this.request({ method: 'elicitation/create', params: formParams }, types_js_1.ElicitResultSchema, options); + if (result.action === 'accept' && result.content && formParams.requestedSchema) { + try { + const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); + const validationResult = validator(result.content); + if (!validationResult.valid) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } + } + catch (error) { + if (error instanceof types_js_1.McpError) { + throw error; + } + throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); + } + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)'); + } + return () => this.notification({ + method: 'notifications/elicitation/complete', + params: { + elicitationId + } + }, options); + } + async listRoots(params, options) { + return this.request({ method: 'roots/list', params }, types_js_1.ListRootsResultSchema, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging) { + if (!this.isMessageIgnored(params.level, sessionId)) { + return this.notification({ method: 'notifications/message', params }); + } + } + } + async sendResourceUpdated(params) { + return this.notification({ + method: 'notifications/resources/updated', + params + }); + } + async sendResourceListChanged() { + return this.notification({ + method: 'notifications/resources/list_changed' + }); + } + async sendToolListChanged() { + return this.notification({ method: 'notifications/tools/list_changed' }); + } + async sendPromptListChanged() { + return this.notification({ method: 'notifications/prompts/list_changed' }); + } +} +exports.Server = Server; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.js.map new file mode 100644 index 000000000..32ed405e7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":";;;AAAA,uDAAyI;AACzI,0CA0CqB;AACrB,mEAAuE;AAEvE,mDAQyB;AAEzB,+DAA0E;AAC1E,iEAAoH;AA6CpH;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAa,MAIX,SAAQ,sBAA8F;IAapG;;OAEG;IACH,YACY,WAA2B,EACnC,OAAuB;QAEvB,KAAK,CAAC,OAAO,CAAC,CAAC;QAHP,gBAAW,GAAX,WAAW,CAAgB;QAyCvC,+BAA+B;QACvB,mBAAc,GAAG,IAAI,GAAG,EAAoC,CAAC;QAErE,uCAAuC;QACtB,uBAAkB,GAAG,IAAI,GAAG,CAAC,6BAAkB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;QAEhH,2FAA2F;QACnF,qBAAgB,GAAG,CAAC,KAAmB,EAAE,SAAkB,EAAW,EAAE;YAC5E,MAAM,YAAY,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;YACxD,OAAO,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,KAAK,CAAE,GAAG,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,YAAY,CAAE,CAAC,CAAC,CAAC,KAAK,CAAC;QACnH,CAAC,CAAC;QA/CE,IAAI,CAAC,aAAa,GAAG,OAAO,EAAE,YAAY,IAAI,EAAE,CAAC;QACjD,IA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CAAC;IACV,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,MAAmC,EAAE,OAAwB;QACzE,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,gCAAqB,EAAE,OAAO,CAAC,CAAC;IAC1F,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,kBAAkB,CAAC,MAA4C,EAAE,SAAkB;QACrF,IAAI,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;YAC7B,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,KAAK,EAAE,SAAS,CAAC,EAAE,CAAC;gBAClD,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,uBAAuB,EAAE,MAAM,EAAE,CAAC,CAAC;YAC1E,CAAC;QACL,CAAC;IACL,CAAC;IAED,KAAK,CAAC,mBAAmB,CAAC,MAA6C;QACnE,OAAO,IAAI,CAAC,YAAY,CAAC;YACrB,MAAM,EAAE,iCAAiC;YACzC,MAAM;SACT,CAAC,CAAC;IACP,CAAC;IAED,KAAK,CAAC,uBAAuB;QACzB,OAAO,IAAI,CAAC,YAAY,CAAC;YACrB,MAAM,EAAE,sCAAsC;SACjD,CAAC,CAAC;IACP,CAAC;IAED,KAAK,CAAC,mBAAmB;QACrB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC,CAAC;IAC7E,CAAC;IAED,KAAK,CAAC,qBAAqB;QACvB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,oCAAoC,EAAE,CAAC,CAAC;IAC/E,CAAC;CACJ;AA5hBD,wBA4hBC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.d.ts new file mode 100644 index 000000000..1bc0c6829 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.d.ts @@ -0,0 +1,364 @@ +import { Server, ServerOptions } from './index.js'; +import { AnySchema, AnyObjectSchema, ZodRawShapeCompat, SchemaOutput, ShapeOutput } from './zod-compat.js'; +import { Implementation, CallToolResult, Resource, ListResourcesResult, GetPromptResult, ReadResourceResult, ServerRequest, ServerNotification, ToolAnnotations, LoggingMessageNotification, Result, ToolExecution } from '../types.js'; +import { UriTemplate, Variables } from '../shared/uriTemplate.js'; +import { RequestHandlerExtra } from '../shared/protocol.js'; +import { Transport } from '../shared/transport.js'; +import { ExperimentalMcpServerTasks } from '../experimental/tasks/mcp-server.js'; +import type { ToolTaskHandler } from '../experimental/tasks/interfaces.js'; +/** + * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. + * For advanced usage (like sending notifications or setting custom request handlers), use the underlying + * Server instance available via the `server` property. + */ +export declare class McpServer { + /** + * The underlying Server instance, useful for advanced operations like sending notifications. + */ + readonly server: Server; + private _registeredResources; + private _registeredResourceTemplates; + private _registeredTools; + private _registeredPrompts; + private _experimental?; + constructor(serverInfo: Implementation, options?: ServerOptions); + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental(): { + tasks: ExperimentalMcpServerTasks; + }; + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + connect(transport: Transport): Promise; + /** + * Closes the connection. + */ + close(): Promise; + private _toolHandlersInitialized; + private setToolRequestHandlers; + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + private createToolError; + /** + * Validates tool input arguments against the tool's input schema. + */ + private validateToolInput; + /** + * Validates tool output against the tool's output schema. + */ + private validateToolOutput; + /** + * Executes a tool handler (either regular or task-based). + */ + private executeToolHandler; + /** + * Handles automatic task polling for tools with taskSupport 'optional'. + */ + private handleAutomaticTaskPolling; + private _completionHandlerInitialized; + private setCompletionRequestHandler; + private handlePromptCompletion; + private handleResourceCompletion; + private _resourceHandlersInitialized; + private setResourceRequestHandlers; + private _promptHandlersInitialized; + private setPromptRequestHandlers; + /** + * Registers a resource `name` at a fixed URI, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, uri: string, readCallback: ReadResourceCallback): RegisteredResource; + /** + * Registers a resource `name` at a fixed URI with metadata, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, uri: string, metadata: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; + /** + * Registers a resource `name` with a template pattern, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, template: ResourceTemplate, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; + /** + * Registers a resource `name` with a template pattern and metadata, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, template: ResourceTemplate, metadata: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; + /** + * Registers a resource with a config object and callback. + * For static resources, use a URI string. For dynamic resources, use a ResourceTemplate. + */ + registerResource(name: string, uriOrTemplate: string, config: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; + registerResource(name: string, uriOrTemplate: ResourceTemplate, config: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; + private _createRegisteredResource; + private _createRegisteredResourceTemplate; + private _createRegisteredPrompt; + private _createRegisteredTool; + /** + * Registers a zero-argument tool `name`, which will run the given function when the client calls it. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, cb: ToolCallback): RegisteredTool; + /** + * Registers a zero-argument tool `name` (with a description) which will run the given function when the client calls it. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, description: string, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool taking either a parameter schema for validation or annotations for additional metadata. + * This unified overload handles both `tool(name, paramsSchema, cb)` and `tool(name, annotations, cb)` cases. + * + * Note: We use a union type for the second parameter because TypeScript cannot reliably disambiguate + * between ToolAnnotations and ZodRawShapeCompat during overload resolution, as both are plain object types. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool `name` (with a description) taking either parameter schema or annotations. + * This unified overload handles both `tool(name, description, paramsSchema, cb)` and + * `tool(name, description, annotations, cb)` cases. + * + * Note: We use a union type for the third parameter because TypeScript cannot reliably disambiguate + * between ToolAnnotations and ZodRawShapeCompat during overload resolution, as both are plain object types. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, description: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool with both parameter schema and annotations. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool with description, parameter schema, and annotations. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, description: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool with a config object and callback. + */ + registerTool(name: string, config: { + title?: string; + description?: string; + inputSchema?: InputArgs; + outputSchema?: OutputArgs; + annotations?: ToolAnnotations; + _meta?: Record; + }, cb: ToolCallback): RegisteredTool; + /** + * Registers a zero-argument prompt `name`, which will run the given function when the client calls it. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a zero-argument prompt `name` (with a description) which will run the given function when the client calls it. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, description: string, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a prompt `name` accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a prompt `name` (with a description) accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, description: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a prompt with a config object and callback. + */ + registerPrompt(name: string, config: { + title?: string; + description?: string; + argsSchema?: Args; + }, cb: PromptCallback): RegisteredPrompt; + /** + * Checks if the server is connected to a transport. + * @returns True if the server is connected + */ + isConnected(): boolean; + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise; + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged(): void; + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged(): void; + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged(): void; +} +/** + * A callback to complete one variable within a resource template's URI template. + */ +export type CompleteResourceTemplateCallback = (value: string, context?: { + arguments?: Record; +}) => string[] | Promise; +/** + * A resource template combines a URI pattern with optional functionality to enumerate + * all resources matching that pattern. + */ +export declare class ResourceTemplate { + private _callbacks; + private _uriTemplate; + constructor(uriTemplate: string | UriTemplate, _callbacks: { + /** + * A callback to list all resources matching this template. This is required to specified, even if `undefined`, to avoid accidentally forgetting resource listing. + */ + list: ListResourcesCallback | undefined; + /** + * An optional callback to autocomplete variables within the URI template. Useful for clients and users to discover possible values. + */ + complete?: { + [variable: string]: CompleteResourceTemplateCallback; + }; + }); + /** + * Gets the URI template pattern. + */ + get uriTemplate(): UriTemplate; + /** + * Gets the list callback, if one was provided. + */ + get listCallback(): ListResourcesCallback | undefined; + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable: string): CompleteResourceTemplateCallback | undefined; +} +export type BaseToolCallback, Args extends undefined | ZodRawShapeCompat | AnySchema> = Args extends ZodRawShapeCompat ? (args: ShapeOutput, extra: Extra) => SendResultT | Promise : Args extends AnySchema ? (args: SchemaOutput, extra: Extra) => SendResultT | Promise : (extra: Extra) => SendResultT | Promise; +/** + * Callback for a tool handler registered with Server.tool(). + * + * Parameters will include tool arguments, if applicable, as well as other request handler context. + * + * The callback should return: + * - `structuredContent` if the tool has an outputSchema defined + * - `content` if the tool does not have an outputSchema + * - Both fields are optional but typically one should be provided + */ +export type ToolCallback = BaseToolCallback, Args>; +/** + * Supertype that can handle both regular tools (simple callback) and task-based tools (task handler object). + */ +export type AnyToolHandler = ToolCallback | ToolTaskHandler; +export type RegisteredTool = { + title?: string; + description?: string; + inputSchema?: AnySchema; + outputSchema?: AnySchema; + annotations?: ToolAnnotations; + execution?: ToolExecution; + _meta?: Record; + handler: AnyToolHandler; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string | null; + title?: string; + description?: string; + paramsSchema?: InputArgs; + outputSchema?: OutputArgs; + annotations?: ToolAnnotations; + _meta?: Record; + callback?: ToolCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +/** + * Additional, optional information for annotating a resource. + */ +export type ResourceMetadata = Omit; +/** + * Callback to list all resources matching a given template. + */ +export type ListResourcesCallback = (extra: RequestHandlerExtra) => ListResourcesResult | Promise; +/** + * Callback to read a resource at a given URI. + */ +export type ReadResourceCallback = (uri: URL, extra: RequestHandlerExtra) => ReadResourceResult | Promise; +export type RegisteredResource = { + name: string; + title?: string; + metadata?: ResourceMetadata; + readCallback: ReadResourceCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string; + title?: string; + uri?: string | null; + metadata?: ResourceMetadata; + callback?: ReadResourceCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +/** + * Callback to read a resource at a given URI, following a filled-in URI template. + */ +export type ReadResourceTemplateCallback = (uri: URL, variables: Variables, extra: RequestHandlerExtra) => ReadResourceResult | Promise; +export type RegisteredResourceTemplate = { + resourceTemplate: ResourceTemplate; + title?: string; + metadata?: ResourceMetadata; + readCallback: ReadResourceTemplateCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string | null; + title?: string; + template?: ResourceTemplate; + metadata?: ResourceMetadata; + callback?: ReadResourceTemplateCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +type PromptArgsRawShape = ZodRawShapeCompat; +export type PromptCallback = Args extends PromptArgsRawShape ? (args: ShapeOutput, extra: RequestHandlerExtra) => GetPromptResult | Promise : (extra: RequestHandlerExtra) => GetPromptResult | Promise; +export type RegisteredPrompt = { + title?: string; + description?: string; + argsSchema?: AnyObjectSchema; + callback: PromptCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string | null; + title?: string; + description?: string; + argsSchema?: Args; + callback?: PromptCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +export {}; +//# sourceMappingURL=mcp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.d.ts.map new file mode 100644 index 000000000..0b460bb2a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../../src/server/mcp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACH,SAAS,EACT,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,WAAW,EASd,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACH,cAAc,EAGd,cAAc,EAOd,QAAQ,EACR,mBAAmB,EAYnB,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,eAAe,EACf,0BAA0B,EAE1B,MAAM,EAMN,aAAa,EAChB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MA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QACf,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,UAAU,CAAC,EAAE,IAAI,CAAC;QAClB,QAAQ,CAAC,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;QAChC,OAAO,CAAC,EAAE,OAAO,CAAC;KACrB,GAAG,IAAI,CAAC;IACT,MAAM,IAAI,IAAI,CAAC;CAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.js new file mode 100644 index 000000000..e10bb3da3 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.js @@ -0,0 +1,918 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ResourceTemplate = exports.McpServer = void 0; +const index_js_1 = require("./index.js"); +const zod_compat_js_1 = require("./zod-compat.js"); +const zod_json_schema_compat_js_1 = require("./zod-json-schema-compat.js"); +const types_js_1 = require("../types.js"); +const completable_js_1 = require("./completable.js"); +const uriTemplate_js_1 = require("../shared/uriTemplate.js"); +const toolNameValidation_js_1 = require("../shared/toolNameValidation.js"); +const mcp_server_js_1 = require("../experimental/tasks/mcp-server.js"); +const zod_1 = require("zod"); +/** + * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. + * For advanced usage (like sending notifications or setting custom request handlers), use the underlying + * Server instance available via the `server` property. + */ +class McpServer { + constructor(serverInfo, options) { + this._registeredResources = {}; + this._registeredResourceTemplates = {}; + this._registeredTools = {}; + this._registeredPrompts = {}; + this._toolHandlersInitialized = false; + this._completionHandlerInitialized = false; + this._resourceHandlersInitialized = false; + this._promptHandlersInitialized = false; + this.server = new index_js_1.Server(serverInfo, options); + } + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental() { + if (!this._experimental) { + this._experimental = { + tasks: new mcp_server_js_1.ExperimentalMcpServerTasks(this) + }; + } + return this._experimental; + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport) { + return await this.server.connect(transport); + } + /** + * Closes the connection. + */ + async close() { + await this.server.close(); + } + setToolRequestHandlers() { + if (this._toolHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListToolsRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.CallToolRequestSchema)); + this.server.registerCapabilities({ + tools: { + listChanged: true + } + }); + this.server.setRequestHandler(types_js_1.ListToolsRequestSchema, () => ({ + tools: Object.entries(this._registeredTools) + .filter(([, tool]) => tool.enabled) + .map(([name, tool]) => { + const toolDefinition = { + name, + title: tool.title, + description: tool.description, + inputSchema: (() => { + const obj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.inputSchema); + return obj + ? (0, zod_json_schema_compat_js_1.toJsonSchemaCompat)(obj, { + strictUnions: true, + pipeStrategy: 'input' + }) + : EMPTY_OBJECT_JSON_SCHEMA; + })(), + annotations: tool.annotations, + execution: tool.execution, + _meta: tool._meta + }; + if (tool.outputSchema) { + const obj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.outputSchema); + if (obj) { + toolDefinition.outputSchema = (0, zod_json_schema_compat_js_1.toJsonSchemaCompat)(obj, { + strictUnions: true, + pipeStrategy: 'output' + }); + } + } + return toolDefinition; + }) + })); + this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => { + try { + const tool = this._registeredTools[request.params.name]; + if (!tool) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); + } + if (!tool.enabled) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); + } + const isTaskRequest = !!request.params.task; + const taskSupport = tool.execution?.taskSupport; + const isTaskHandler = 'createTask' in tool.handler; + // Validate task hint configuration + if ((taskSupport === 'required' || taskSupport === 'optional') && !isTaskHandler) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`); + } + // Handle taskSupport 'required' without task augmentation + if (taskSupport === 'required' && !isTaskRequest) { + throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`); + } + // Handle taskSupport 'optional' without task augmentation - automatic polling + if (taskSupport === 'optional' && !isTaskRequest && isTaskHandler) { + return await this.handleAutomaticTaskPolling(tool, request, extra); + } + // Normal execution path + const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); + const result = await this.executeToolHandler(tool, args, extra); + // Return CreateTaskResult immediately for task requests + if (isTaskRequest) { + return result; + } + // Validate output schema for non-task requests + await this.validateToolOutput(tool, result, request.params.name); + return result; + } + catch (error) { + if (error instanceof types_js_1.McpError) { + if (error.code === types_js_1.ErrorCode.UrlElicitationRequired) { + throw error; // Return the error to the caller without wrapping in CallToolResult + } + } + return this.createToolError(error instanceof Error ? error.message : String(error)); + } + }); + this._toolHandlersInitialized = true; + } + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + createToolError(errorMessage) { + return { + content: [ + { + type: 'text', + text: errorMessage + } + ], + isError: true + }; + } + /** + * Validates tool input arguments against the tool's input schema. + */ + async validateToolInput(tool, args, toolName) { + if (!tool.inputSchema) { + return undefined; + } + // Try to normalize to object schema first (for raw shapes and object schemas) + // If that fails, use the schema directly (for union/intersection/etc) + const inputObj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.inputSchema); + const schemaToParse = inputObj ?? tool.inputSchema; + const parseResult = await (0, zod_compat_js_1.safeParseAsync)(schemaToParse, args); + if (!parseResult.success) { + const error = 'error' in parseResult ? parseResult.error : 'Unknown error'; + const errorMessage = (0, zod_compat_js_1.getParseErrorMessage)(error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`); + } + return parseResult.data; + } + /** + * Validates tool output against the tool's output schema. + */ + async validateToolOutput(tool, result, toolName) { + if (!tool.outputSchema) { + return; + } + // Only validate CallToolResult, not CreateTaskResult + if (!('content' in result)) { + return; + } + if (result.isError) { + return; + } + if (!result.structuredContent) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); + } + // if the tool has an output schema, validate structured content + const outputObj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.outputSchema); + const parseResult = await (0, zod_compat_js_1.safeParseAsync)(outputObj, result.structuredContent); + if (!parseResult.success) { + const error = 'error' in parseResult ? parseResult.error : 'Unknown error'; + const errorMessage = (0, zod_compat_js_1.getParseErrorMessage)(error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`); + } + } + /** + * Executes a tool handler (either regular or task-based). + */ + async executeToolHandler(tool, args, extra) { + const handler = tool.handler; + const isTaskHandler = 'createTask' in handler; + if (isTaskHandler) { + if (!extra.taskStore) { + throw new Error('No task store provided.'); + } + const taskExtra = { ...extra, taskStore: extra.taskStore }; + if (tool.inputSchema) { + const typedHandler = handler; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return await Promise.resolve(typedHandler.createTask(args, taskExtra)); + } + else { + const typedHandler = handler; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return await Promise.resolve(typedHandler.createTask(taskExtra)); + } + } + if (tool.inputSchema) { + const typedHandler = handler; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return await Promise.resolve(typedHandler(args, extra)); + } + else { + const typedHandler = handler; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return await Promise.resolve(typedHandler(extra)); + } + } + /** + * Handles automatic task polling for tools with taskSupport 'optional'. + */ + async handleAutomaticTaskPolling(tool, request, extra) { + if (!extra.taskStore) { + throw new Error('No task store provided for task-capable tool.'); + } + // Validate input and create task + const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); + const handler = tool.handler; + const taskExtra = { ...extra, taskStore: extra.taskStore }; + const createTaskResult = args // undefined only if tool.inputSchema is undefined + ? await Promise.resolve(handler.createTask(args, taskExtra)) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + await Promise.resolve(handler.createTask(taskExtra)); + // Poll until completion + const taskId = createTaskResult.task.taskId; + let task = createTaskResult.task; + const pollInterval = task.pollInterval ?? 5000; + while (task.status !== 'completed' && task.status !== 'failed' && task.status !== 'cancelled') { + await new Promise(resolve => setTimeout(resolve, pollInterval)); + const updatedTask = await extra.taskStore.getTask(taskId); + if (!updatedTask) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, `Task ${taskId} not found during polling`); + } + task = updatedTask; + } + // Return the final result + return (await extra.taskStore.getTaskResult(taskId)); + } + setCompletionRequestHandler() { + if (this._completionHandlerInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.CompleteRequestSchema)); + this.server.registerCapabilities({ + completions: {} + }); + this.server.setRequestHandler(types_js_1.CompleteRequestSchema, async (request) => { + switch (request.params.ref.type) { + case 'ref/prompt': + (0, types_js_1.assertCompleteRequestPrompt)(request); + return this.handlePromptCompletion(request, request.params.ref); + case 'ref/resource': + (0, types_js_1.assertCompleteRequestResourceTemplate)(request); + return this.handleResourceCompletion(request, request.params.ref); + default: + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); + } + }); + this._completionHandlerInitialized = true; + } + async handlePromptCompletion(request, ref) { + const prompt = this._registeredPrompts[ref.name]; + if (!prompt) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); + } + if (!prompt.enabled) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); + } + if (!prompt.argsSchema) { + return EMPTY_COMPLETION_RESULT; + } + const promptShape = (0, zod_compat_js_1.getObjectShape)(prompt.argsSchema); + const field = promptShape?.[request.params.argument.name]; + if (!(0, completable_js_1.isCompletable)(field)) { + return EMPTY_COMPLETION_RESULT; + } + const completer = (0, completable_js_1.getCompleter)(field); + if (!completer) { + return EMPTY_COMPLETION_RESULT; + } + const suggestions = await completer(request.params.argument.value, request.params.context); + return createCompletionResult(suggestions); + } + async handleResourceCompletion(request, ref) { + const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri); + if (!template) { + if (this._registeredResources[ref.uri]) { + // Attempting to autocomplete a fixed resource URI is not an error in the spec (but probably should be). + return EMPTY_COMPLETION_RESULT; + } + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); + } + const completer = template.resourceTemplate.completeCallback(request.params.argument.name); + if (!completer) { + return EMPTY_COMPLETION_RESULT; + } + const suggestions = await completer(request.params.argument.value, request.params.context); + return createCompletionResult(suggestions); + } + setResourceRequestHandlers() { + if (this._resourceHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListResourcesRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListResourceTemplatesRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ReadResourceRequestSchema)); + this.server.registerCapabilities({ + resources: { + listChanged: true + } + }); + this.server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async (request, extra) => { + const resources = Object.entries(this._registeredResources) + .filter(([_, resource]) => resource.enabled) + .map(([uri, resource]) => ({ + uri, + name: resource.name, + ...resource.metadata + })); + const templateResources = []; + for (const template of Object.values(this._registeredResourceTemplates)) { + if (!template.resourceTemplate.listCallback) { + continue; + } + const result = await template.resourceTemplate.listCallback(extra); + for (const resource of result.resources) { + templateResources.push({ + ...template.metadata, + // the defined resource metadata should override the template metadata if present + ...resource + }); + } + } + return { resources: [...resources, ...templateResources] }; + }); + this.server.setRequestHandler(types_js_1.ListResourceTemplatesRequestSchema, async () => { + const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ + name, + uriTemplate: template.resourceTemplate.uriTemplate.toString(), + ...template.metadata + })); + return { resourceTemplates }; + }); + this.server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request, extra) => { + const uri = new URL(request.params.uri); + // First check for exact resource match + const resource = this._registeredResources[uri.toString()]; + if (resource) { + if (!resource.enabled) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource ${uri} disabled`); + } + return resource.readCallback(uri, extra); + } + // Then check templates + for (const template of Object.values(this._registeredResourceTemplates)) { + const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); + if (variables) { + return template.readCallback(uri, variables, extra); + } + } + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource ${uri} not found`); + }); + this._resourceHandlersInitialized = true; + } + setPromptRequestHandlers() { + if (this._promptHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListPromptsRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.GetPromptRequestSchema)); + this.server.registerCapabilities({ + prompts: { + listChanged: true + } + }); + this.server.setRequestHandler(types_js_1.ListPromptsRequestSchema, () => ({ + prompts: Object.entries(this._registeredPrompts) + .filter(([, prompt]) => prompt.enabled) + .map(([name, prompt]) => { + return { + name, + title: prompt.title, + description: prompt.description, + arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined + }; + }) + })); + this.server.setRequestHandler(types_js_1.GetPromptRequestSchema, async (request, extra) => { + const prompt = this._registeredPrompts[request.params.name]; + if (!prompt) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); + } + if (!prompt.enabled) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); + } + if (prompt.argsSchema) { + const argsObj = (0, zod_compat_js_1.normalizeObjectSchema)(prompt.argsSchema); + const parseResult = await (0, zod_compat_js_1.safeParseAsync)(argsObj, request.params.arguments); + if (!parseResult.success) { + const error = 'error' in parseResult ? parseResult.error : 'Unknown error'; + const errorMessage = (0, zod_compat_js_1.getParseErrorMessage)(error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`); + } + const args = parseResult.data; + const cb = prompt.callback; + return await Promise.resolve(cb(args, extra)); + } + else { + const cb = prompt.callback; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return await Promise.resolve(cb(extra)); + } + }); + this._promptHandlersInitialized = true; + } + resource(name, uriOrTemplate, ...rest) { + let metadata; + if (typeof rest[0] === 'object') { + metadata = rest.shift(); + } + const readCallback = rest[0]; + if (typeof uriOrTemplate === 'string') { + if (this._registeredResources[uriOrTemplate]) { + throw new Error(`Resource ${uriOrTemplate} is already registered`); + } + const registeredResource = this._createRegisteredResource(name, undefined, uriOrTemplate, metadata, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } + else { + if (this._registeredResourceTemplates[name]) { + throw new Error(`Resource template ${name} is already registered`); + } + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + registerResource(name, uriOrTemplate, config, readCallback) { + if (typeof uriOrTemplate === 'string') { + if (this._registeredResources[uriOrTemplate]) { + throw new Error(`Resource ${uriOrTemplate} is already registered`); + } + const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } + else { + if (this._registeredResourceTemplates[name]) { + throw new Error(`Resource template ${name} is already registered`); + } + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + _createRegisteredResource(name, title, uri, metadata, readCallback) { + const registeredResource = { + name, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResource.update({ enabled: false }), + enable: () => registeredResource.update({ enabled: true }), + remove: () => registeredResource.update({ uri: null }), + update: updates => { + if (typeof updates.uri !== 'undefined' && updates.uri !== uri) { + delete this._registeredResources[uri]; + if (updates.uri) + this._registeredResources[updates.uri] = registeredResource; + } + if (typeof updates.name !== 'undefined') + registeredResource.name = updates.name; + if (typeof updates.title !== 'undefined') + registeredResource.title = updates.title; + if (typeof updates.metadata !== 'undefined') + registeredResource.metadata = updates.metadata; + if (typeof updates.callback !== 'undefined') + registeredResource.readCallback = updates.callback; + if (typeof updates.enabled !== 'undefined') + registeredResource.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResources[uri] = registeredResource; + return registeredResource; + } + _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { + const registeredResourceTemplate = { + resourceTemplate: template, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResourceTemplate.update({ enabled: false }), + enable: () => registeredResourceTemplate.update({ enabled: true }), + remove: () => registeredResourceTemplate.update({ name: null }), + update: updates => { + if (typeof updates.name !== 'undefined' && updates.name !== name) { + delete this._registeredResourceTemplates[name]; + if (updates.name) + this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; + } + if (typeof updates.title !== 'undefined') + registeredResourceTemplate.title = updates.title; + if (typeof updates.template !== 'undefined') + registeredResourceTemplate.resourceTemplate = updates.template; + if (typeof updates.metadata !== 'undefined') + registeredResourceTemplate.metadata = updates.metadata; + if (typeof updates.callback !== 'undefined') + registeredResourceTemplate.readCallback = updates.callback; + if (typeof updates.enabled !== 'undefined') + registeredResourceTemplate.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResourceTemplates[name] = registeredResourceTemplate; + // If the resource template has any completion callbacks, enable completions capability + const variableNames = template.uriTemplate.variableNames; + const hasCompleter = Array.isArray(variableNames) && variableNames.some(v => !!template.completeCallback(v)); + if (hasCompleter) { + this.setCompletionRequestHandler(); + } + return registeredResourceTemplate; + } + _createRegisteredPrompt(name, title, description, argsSchema, callback) { + const registeredPrompt = { + title, + description, + argsSchema: argsSchema === undefined ? undefined : (0, zod_compat_js_1.objectFromShape)(argsSchema), + callback, + enabled: true, + disable: () => registeredPrompt.update({ enabled: false }), + enable: () => registeredPrompt.update({ enabled: true }), + remove: () => registeredPrompt.update({ name: null }), + update: updates => { + if (typeof updates.name !== 'undefined' && updates.name !== name) { + delete this._registeredPrompts[name]; + if (updates.name) + this._registeredPrompts[updates.name] = registeredPrompt; + } + if (typeof updates.title !== 'undefined') + registeredPrompt.title = updates.title; + if (typeof updates.description !== 'undefined') + registeredPrompt.description = updates.description; + if (typeof updates.argsSchema !== 'undefined') + registeredPrompt.argsSchema = (0, zod_compat_js_1.objectFromShape)(updates.argsSchema); + if (typeof updates.callback !== 'undefined') + registeredPrompt.callback = updates.callback; + if (typeof updates.enabled !== 'undefined') + registeredPrompt.enabled = updates.enabled; + this.sendPromptListChanged(); + } + }; + this._registeredPrompts[name] = registeredPrompt; + // If any argument uses a Completable schema, enable completions capability + if (argsSchema) { + const hasCompletable = Object.values(argsSchema).some(field => { + const inner = field instanceof zod_1.ZodOptional ? field._def?.innerType : field; + return (0, completable_js_1.isCompletable)(inner); + }); + if (hasCompletable) { + this.setCompletionRequestHandler(); + } + } + return registeredPrompt; + } + _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) { + // Validate tool name according to SEP specification + (0, toolNameValidation_js_1.validateAndWarnToolName)(name); + const registeredTool = { + title, + description, + inputSchema: getZodSchemaObject(inputSchema), + outputSchema: getZodSchemaObject(outputSchema), + annotations, + execution, + _meta, + handler: handler, + enabled: true, + disable: () => registeredTool.update({ enabled: false }), + enable: () => registeredTool.update({ enabled: true }), + remove: () => registeredTool.update({ name: null }), + update: updates => { + if (typeof updates.name !== 'undefined' && updates.name !== name) { + if (typeof updates.name === 'string') { + (0, toolNameValidation_js_1.validateAndWarnToolName)(updates.name); + } + delete this._registeredTools[name]; + if (updates.name) + this._registeredTools[updates.name] = registeredTool; + } + if (typeof updates.title !== 'undefined') + registeredTool.title = updates.title; + if (typeof updates.description !== 'undefined') + registeredTool.description = updates.description; + if (typeof updates.paramsSchema !== 'undefined') + registeredTool.inputSchema = (0, zod_compat_js_1.objectFromShape)(updates.paramsSchema); + if (typeof updates.outputSchema !== 'undefined') + registeredTool.outputSchema = (0, zod_compat_js_1.objectFromShape)(updates.outputSchema); + if (typeof updates.callback !== 'undefined') + registeredTool.handler = updates.callback; + if (typeof updates.annotations !== 'undefined') + registeredTool.annotations = updates.annotations; + if (typeof updates._meta !== 'undefined') + registeredTool._meta = updates._meta; + if (typeof updates.enabled !== 'undefined') + registeredTool.enabled = updates.enabled; + this.sendToolListChanged(); + } + }; + this._registeredTools[name] = registeredTool; + this.setToolRequestHandlers(); + this.sendToolListChanged(); + return registeredTool; + } + /** + * tool() implementation. Parses arguments passed to overrides defined above. + */ + tool(name, ...rest) { + if (this._registeredTools[name]) { + throw new Error(`Tool ${name} is already registered`); + } + let description; + let inputSchema; + let outputSchema; + let annotations; + // Tool properties are passed as separate arguments, with omissions allowed. + // Support for this style is frozen as of protocol version 2025-03-26. Future additions + // to tool definition should *NOT* be added. + if (typeof rest[0] === 'string') { + description = rest.shift(); + } + // Handle the different overload combinations + if (rest.length > 1) { + // We have at least one more arg before the callback + const firstArg = rest[0]; + if (isZodRawShapeCompat(firstArg)) { + // We have a params schema as the first arg + inputSchema = rest.shift(); + // Check if the next arg is potentially annotations + if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShapeCompat(rest[0])) { + // Case: tool(name, paramsSchema, annotations, cb) + // Or: tool(name, description, paramsSchema, annotations, cb) + annotations = rest.shift(); + } + } + else if (typeof firstArg === 'object' && firstArg !== null) { + // Not a ZodRawShapeCompat, so must be annotations in this position + // Case: tool(name, annotations, cb) + // Or: tool(name, description, annotations, cb) + annotations = rest.shift(); + } + } + const callback = rest[0]; + return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, undefined, callback); + } + /** + * Registers a tool with a config object and callback. + */ + registerTool(name, config, cb) { + if (this._registeredTools[name]) { + throw new Error(`Tool ${name} is already registered`); + } + const { title, description, inputSchema, outputSchema, annotations, _meta } = config; + return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, _meta, cb); + } + prompt(name, ...rest) { + if (this._registeredPrompts[name]) { + throw new Error(`Prompt ${name} is already registered`); + } + let description; + if (typeof rest[0] === 'string') { + description = rest.shift(); + } + let argsSchema; + if (rest.length > 1) { + argsSchema = rest.shift(); + } + const cb = rest[0]; + const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Registers a prompt with a config object and callback. + */ + registerPrompt(name, config, cb) { + if (this._registeredPrompts[name]) { + throw new Error(`Prompt ${name} is already registered`); + } + const { title, description, argsSchema } = config; + const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Checks if the server is connected to a transport. + * @returns True if the server is connected + */ + isConnected() { + return this.server.transport !== undefined; + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + async sendLoggingMessage(params, sessionId) { + return this.server.sendLoggingMessage(params, sessionId); + } + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged() { + if (this.isConnected()) { + this.server.sendResourceListChanged(); + } + } + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged() { + if (this.isConnected()) { + this.server.sendToolListChanged(); + } + } + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged() { + if (this.isConnected()) { + this.server.sendPromptListChanged(); + } + } +} +exports.McpServer = McpServer; +/** + * A resource template combines a URI pattern with optional functionality to enumerate + * all resources matching that pattern. + */ +class ResourceTemplate { + constructor(uriTemplate, _callbacks) { + this._callbacks = _callbacks; + this._uriTemplate = typeof uriTemplate === 'string' ? new uriTemplate_js_1.UriTemplate(uriTemplate) : uriTemplate; + } + /** + * Gets the URI template pattern. + */ + get uriTemplate() { + return this._uriTemplate; + } + /** + * Gets the list callback, if one was provided. + */ + get listCallback() { + return this._callbacks.list; + } + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable) { + return this._callbacks.complete?.[variable]; + } +} +exports.ResourceTemplate = ResourceTemplate; +const EMPTY_OBJECT_JSON_SCHEMA = { + type: 'object', + properties: {} +}; +/** + * Checks if a value looks like a Zod schema by checking for parse/safeParse methods. + */ +function isZodTypeLike(value) { + return (value !== null && + typeof value === 'object' && + 'parse' in value && + typeof value.parse === 'function' && + 'safeParse' in value && + typeof value.safeParse === 'function'); +} +/** + * Checks if an object is a Zod schema instance (v3 or v4). + * + * Zod schemas have internal markers: + * - v3: `_def` property + * - v4: `_zod` property + * + * This includes transformed schemas like z.preprocess(), z.transform(), z.pipe(). + */ +function isZodSchemaInstance(obj) { + return '_def' in obj || '_zod' in obj || isZodTypeLike(obj); +} +/** + * Checks if an object is a "raw shape" - a plain object where values are Zod schemas. + * + * Raw shapes are used as shorthand: `{ name: z.string() }` instead of `z.object({ name: z.string() })`. + * + * IMPORTANT: This must NOT match actual Zod schema instances (like z.preprocess, z.pipe), + * which have internal properties that could be mistaken for schema values. + */ +function isZodRawShapeCompat(obj) { + if (typeof obj !== 'object' || obj === null) { + return false; + } + // If it's already a Zod schema instance, it's NOT a raw shape + if (isZodSchemaInstance(obj)) { + return false; + } + // Empty objects are valid raw shapes (tools with no parameters) + if (Object.keys(obj).length === 0) { + return true; + } + // A raw shape has at least one property that is a Zod schema + return Object.values(obj).some(isZodTypeLike); +} +/** + * Converts a provided Zod schema to a Zod object if it is a ZodRawShapeCompat, + * otherwise returns the schema as is. + */ +function getZodSchemaObject(schema) { + if (!schema) { + return undefined; + } + if (isZodRawShapeCompat(schema)) { + return (0, zod_compat_js_1.objectFromShape)(schema); + } + return schema; +} +function promptArgumentsFromSchema(schema) { + const shape = (0, zod_compat_js_1.getObjectShape)(schema); + if (!shape) + return []; + return Object.entries(shape).map(([name, field]) => { + // Get description - works for both v3 and v4 + const description = (0, zod_compat_js_1.getSchemaDescription)(field); + // Check if optional - works for both v3 and v4 + const isOptional = (0, zod_compat_js_1.isSchemaOptional)(field); + return { + name, + description, + required: !isOptional + }; + }); +} +function getMethodValue(schema) { + const shape = (0, zod_compat_js_1.getObjectShape)(schema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + // Extract literal value - works for both v3 and v4 + const value = (0, zod_compat_js_1.getLiteralValue)(methodSchema); + if (typeof value === 'string') { + return value; + } + throw new Error('Schema method literal must be a string'); +} +function createCompletionResult(suggestions) { + return { + completion: { + values: suggestions.slice(0, 100), + total: suggestions.length, + hasMore: suggestions.length > 100 + } + }; +} +const EMPTY_COMPLETION_RESULT = { + completion: { + values: [], + hasMore: false + } +}; +//# sourceMappingURL=mcp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.js.map new file mode 100644 index 000000000..d31072a5a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mcp.js","sourceRoot":"","sources":["../../../src/server/mcp.ts"],"names":[],"mappings":";;;AAAA,yCAAmD;AACnD,mDAcyB;AACzB,2EAAiE;AACjE,0CAsCqB;AACrB,qDAA+D;AAC/D,6DAAkE;AAIlE,2EAA0E;AAC1E,uEAAiF;AAEjF,6BAAkC;AAElC;;;;GAIG;AACH,MAAa,SAAS;IAclB,YAAY,UAA0B,EAAE,OAAuB;QARvD,yBAAoB,GAA0C,EAAE,CAAC;QACjE,iC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,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC9D,CAAC;AAED,SAAS,sBAAsB,CAAC,WAAqB;IACjD,OAAO;QACH,UAAU,EAAE;YACR,MAAM,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC;YACjC,KAAK,EAAE,WAAW,CAAC,MAAM;YACzB,OAAO,EAAE,WAAW,CAAC,MAAM,GAAG,GAAG;SACpC;KACJ,CAAC;AACN,CAAC;AAED,MAAM,uBAAuB,GAAmB;IAC5C,UAAU,EAAE;QACR,MAAM,EAAE,EAAE;QACV,OAAO,EAAE,KAAK;KACjB;CACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/middleware/hostHeaderValidation.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/middleware/hostHeaderValidation.d.ts new file mode 100644 index 000000000..cb526d8fa --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/middleware/hostHeaderValidation.d.ts @@ -0,0 +1,32 @@ +import { RequestHandler } from 'express'; +/** + * Express middleware for DNS rebinding protection. + * Validates Host header hostname (port-agnostic) against an allowed list. + * + * This is particularly important for servers without authorization or HTTPS, + * such as localhost servers or development servers. DNS rebinding attacks can + * bypass same-origin policy by manipulating DNS to point a domain to a + * localhost address, allowing malicious websites to access your local server. + * + * @param allowedHostnames - List of allowed hostnames (without ports). + * For IPv6, provide the address with brackets (e.g., '[::1]'). + * @returns Express middleware function + * + * @example + * ```typescript + * const middleware = hostHeaderValidation(['localhost', '127.0.0.1', '[::1]']); + * app.use(middleware); + * ``` + */ +export declare function hostHeaderValidation(allowedHostnames: string[]): RequestHandler; +/** + * Convenience middleware for localhost DNS rebinding protection. + * Allows only localhost, 127.0.0.1, and [::1] (IPv6 localhost) hostnames. + * + * @example + * ```typescript + * app.use(localhostHostValidation()); + * ``` + */ +export declare function localhostHostValidation(): RequestHandler; +//# sourceMappingURL=hostHeaderValidation.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/middleware/hostHeaderValidation.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/middleware/hostHeaderValidation.d.ts.map new file mode 100644 index 000000000..c550324ec --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/middleware/hostHeaderValidation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hostHeaderValidation.d.ts","sourceRoot":"","sources":["../../../../src/server/middleware/hostHeaderValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmC,cAAc,EAAE,MAAM,SAAS,CAAC;AAE1E;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,oBAAoB,CAAC,gBAAgB,EAAE,MAAM,EAAE,GAAG,cAAc,CA4C/E;AAED;;;;;;;;GAQG;AACH,wBAAgB,uBAAuB,IAAI,cAAc,CAExD"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/middleware/hostHeaderValidation.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/middleware/hostHeaderValidation.js new file mode 100644 index 000000000..6d8c0ae75 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/middleware/hostHeaderValidation.js @@ -0,0 +1,80 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hostHeaderValidation = hostHeaderValidation; +exports.localhostHostValidation = localhostHostValidation; +/** + * Express middleware for DNS rebinding protection. + * Validates Host header hostname (port-agnostic) against an allowed list. + * + * This is particularly important for servers without authorization or HTTPS, + * such as localhost servers or development servers. DNS rebinding attacks can + * bypass same-origin policy by manipulating DNS to point a domain to a + * localhost address, allowing malicious websites to access your local server. + * + * @param allowedHostnames - List of allowed hostnames (without ports). + * For IPv6, provide the address with brackets (e.g., '[::1]'). + * @returns Express middleware function + * + * @example + * ```typescript + * const middleware = hostHeaderValidation(['localhost', '127.0.0.1', '[::1]']); + * app.use(middleware); + * ``` + */ +function hostHeaderValidation(allowedHostnames) { + return (req, res, next) => { + const hostHeader = req.headers.host; + if (!hostHeader) { + res.status(403).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Missing Host header' + }, + id: null + }); + return; + } + // Use URL API to parse hostname (handles IPv4, IPv6, and regular hostnames) + let hostname; + try { + hostname = new URL(`http://${hostHeader}`).hostname; + } + catch { + res.status(403).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: `Invalid Host header: ${hostHeader}` + }, + id: null + }); + return; + } + if (!allowedHostnames.includes(hostname)) { + res.status(403).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: `Invalid Host: ${hostname}` + }, + id: null + }); + return; + } + next(); + }; +} +/** + * Convenience middleware for localhost DNS rebinding protection. + * Allows only localhost, 127.0.0.1, and [::1] (IPv6 localhost) hostnames. + * + * @example + * ```typescript + * app.use(localhostHostValidation()); + * ``` + */ +function localhostHostValidation() { + return hostHeaderValidation(['localhost', '127.0.0.1', '[::1]']); +} +//# sourceMappingURL=hostHeaderValidation.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/middleware/hostHeaderValidation.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/middleware/hostHeaderValidation.js.map new file mode 100644 index 000000000..c97b55287 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/middleware/hostHeaderValidation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hostHeaderValidation.js","sourceRoot":"","sources":["../../../../src/server/middleware/hostHeaderValidation.ts"],"names":[],"mappings":";;AAqBA,oDA4CC;AAWD,0DAEC;AA5ED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,oBAAoB,CAAC,gBAA0B;IAC3D,OAAO,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;QACvD,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,IAAI,CAA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d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sse.d.ts new file mode 100644 index 000000000..7fa42a58f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sse.d.ts @@ -0,0 +1,82 @@ +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage, MessageExtraInfo } from '../types.js'; +import { AuthInfo } from './auth/types.js'; +/** + * Configuration options for SSEServerTransport. + */ +export interface SSEServerTransportOptions { + /** + * List of allowed host header values for DNS rebinding protection. + * If not specified, host validation is disabled. + * @deprecated Use the `hostHeaderValidation` middleware from `@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js` instead, + * or use `createMcpExpressApp` from `@modelcontextprotocol/sdk/server/express.js` which includes localhost protection by default. + */ + allowedHosts?: string[]; + /** + * List of allowed origin header values for DNS rebinding protection. + * If not specified, origin validation is disabled. + * @deprecated Use the `hostHeaderValidation` middleware from `@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js` instead, + * or use `createMcpExpressApp` from `@modelcontextprotocol/sdk/server/express.js` which includes localhost protection by default. + */ + allowedOrigins?: string[]; + /** + * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). + * Default is false for backwards compatibility. + * @deprecated Use the `hostHeaderValidation` middleware from `@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js` instead, + * or use `createMcpExpressApp` from `@modelcontextprotocol/sdk/server/express.js` which includes localhost protection by default. + */ + enableDnsRebindingProtection?: boolean; +} +/** + * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. + * + * This transport is only available in Node.js environments. + * @deprecated SSEServerTransport is deprecated. Use StreamableHTTPServerTransport instead. + */ +export declare class SSEServerTransport implements Transport { + private _endpoint; + private res; + private _sseResponse?; + private _sessionId; + private _options; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; + /** + * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. + */ + constructor(_endpoint: string, res: ServerResponse, options?: SSEServerTransportOptions); + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + private validateRequestHeaders; + /** + * Handles the initial SSE connection request. + * + * This should be called when a GET request is made to establish the SSE stream. + */ + start(): Promise; + /** + * Handles incoming POST messages. + * + * This should be called when a POST request is made to send a message to the server. + */ + handlePostMessage(req: IncomingMessage & { + auth?: AuthInfo; + }, res: ServerResponse, parsedBody?: unknown): Promise; + /** + * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. + */ + handleMessage(message: unknown, extra?: MessageExtraInfo): Promise; + close(): Promise; + send(message: JSONRPCMessage): Promise; + /** + * Returns the session ID for this transport. + * + * This can be used to route incoming POST requests. + */ + get sessionId(): string; +} +//# sourceMappingURL=sse.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sse.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sse.d.ts.map new file mode 100644 index 000000000..c94a521d2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sse.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../../src/server/sse.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAwB,gBAAgB,EAAe,MAAM,aAAa,CAAC;AAGlG,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAK3C;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACtC;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IAExB;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAE1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new file mode 100644 index 000000000..2829fd38c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sse.js @@ -0,0 +1,165 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SSEServerTransport = void 0; +const node_crypto_1 = require("node:crypto"); +const types_js_1 = require("../types.js"); +const raw_body_1 = __importDefault(require("raw-body")); +const content_type_1 = __importDefault(require("content-type")); +const node_url_1 = require("node:url"); +const MAXIMUM_MESSAGE_SIZE = '4mb'; +/** + * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. + * + * This transport is only available in Node.js environments. + * @deprecated SSEServerTransport is deprecated. Use StreamableHTTPServerTransport instead. + */ +class SSEServerTransport { + /** + * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. + */ + constructor(_endpoint, res, options) { + this._endpoint = _endpoint; + this.res = res; + this._sessionId = (0, node_crypto_1.randomUUID)(); + this._options = options || { enableDnsRebindingProtection: false }; + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + validateRequestHeaders(req) { + // Skip validation if protection is not enabled + if (!this._options.enableDnsRebindingProtection) { + return undefined; + } + // Validate Host header if allowedHosts is configured + if (this._options.allowedHosts && this._options.allowedHosts.length > 0) { + const hostHeader = req.headers.host; + if (!hostHeader || !this._options.allowedHosts.includes(hostHeader)) { + return `Invalid Host header: ${hostHeader}`; + } + } + // Validate Origin header if allowedOrigins is configured + if (this._options.allowedOrigins && this._options.allowedOrigins.length > 0) { + const originHeader = req.headers.origin; + if (originHeader && !this._options.allowedOrigins.includes(originHeader)) { + return `Invalid Origin header: ${originHeader}`; + } + } + return undefined; + } + /** + * Handles the initial SSE connection request. + * + * This should be called when a GET request is made to establish the SSE stream. + */ + async start() { + if (this._sseResponse) { + throw new Error('SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.'); + } + this.res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }); + // Send the endpoint event + // Use a dummy base URL because this._endpoint is relative. + // This allows using URL/URLSearchParams for robust parameter handling. + const dummyBase = 'http://localhost'; // Any valid base works + const endpointUrl = new node_url_1.URL(this._endpoint, dummyBase); + endpointUrl.searchParams.set('sessionId', this._sessionId); + // Reconstruct the relative URL string (pathname + search + hash) + const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash; + this.res.write(`event: endpoint\ndata: ${relativeUrlWithSession}\n\n`); + this._sseResponse = this.res; + this.res.on('close', () => { + this._sseResponse = undefined; + this.onclose?.(); + }); + } + /** + * Handles incoming POST messages. + * + * This should be called when a POST request is made to send a message to the server. + */ + async handlePostMessage(req, res, parsedBody) { + if (!this._sseResponse) { + const message = 'SSE connection not established'; + res.writeHead(500).end(message); + throw new Error(message); + } + // Validate request headers for DNS rebinding protection + const validationError = this.validateRequestHeaders(req); + if (validationError) { + res.writeHead(403).end(validationError); + this.onerror?.(new Error(validationError)); + return; + } + const authInfo = req.auth; + const requestInfo = { headers: req.headers }; + let body; + try { + const ct = content_type_1.default.parse(req.headers['content-type'] ?? ''); + if (ct.type !== 'application/json') { + throw new Error(`Unsupported content-type: ${ct.type}`); + } + body = + parsedBody ?? + (await (0, raw_body_1.default)(req, { + limit: MAXIMUM_MESSAGE_SIZE, + encoding: ct.parameters.charset ?? 'utf-8' + })); + } + catch (error) { + res.writeHead(400).end(String(error)); + this.onerror?.(error); + return; + } + try { + await this.handleMessage(typeof body === 'string' ? JSON.parse(body) : body, { requestInfo, authInfo }); + } + catch { + res.writeHead(400).end(`Invalid message: ${body}`); + return; + } + res.writeHead(202).end('Accepted'); + } + /** + * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. + */ + async handleMessage(message, extra) { + let parsedMessage; + try { + parsedMessage = types_js_1.JSONRPCMessageSchema.parse(message); + } + catch (error) { + this.onerror?.(error); + throw error; + } + this.onmessage?.(parsedMessage, extra); + } + async close() { + this._sseResponse?.end(); + this._sseResponse = undefined; + this.onclose?.(); + } + async send(message) { + if (!this._sseResponse) { + throw new Error('Not connected'); + } + this._sseResponse.write(`event: message\ndata: ${JSON.stringify(message)}\n\n`); + } + /** + * Returns the session ID for this transport. + * + * This can be used to route incoming POST requests. + */ + get sessionId() { + return this._sessionId; + } +} +exports.SSEServerTransport = SSEServerTransport; +//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sse.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sse.js.map new file mode 100644 index 000000000..f80cb8d1f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.js","sourceRoot":"","sources":["../../../src/server/sse.ts"],"names":[],"mappings":";;;;;;AAAA,6CAAyC;AAGzC,0CAAkG;AAClG,wDAAkC;AAClC,gEAAuC;AAEvC,uCAA+B;AAE/B,MAAM,oBAAoB,GAAG,KAAK,CAAC;AA+BnC;;;;;GAKG;AACH,MAAa,kBAAkB;IAQ3B;;OAEG;IACH,YACY,SAAiB,EACjB,GAAmB,EAC3B,OAAmC;QAF3B,cAAS,GAAT,SAAS,CAAQ;QACjB,QAAG,GAAH,GAAG,CAAgB;QAG3B,IAAI,CAAC,UAAU,GAAG,IAAA,wBAAU,GAAE,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAAG,OAAO,IAAI,EAAE,4BAA4B,EAAE,KAAK,EAAE,CAAC;IACvE,CAAC;IAED;;;OAGG;IACK,sBAAsB,CAAC,GAAoB;QAC/C,+CAA+C;QAC/C,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,4BAA4B,EAAE,CAAC;YAC9C,OAAO,SAAS,CAAC;QACrB,CAAC;QAED,qDAAqD;QACrD,IAAI,IAAI,CAAC,QAAQ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+BAAoB,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACxD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,CAAC,OAAO,EAAE,CAAC,KAAc,CAAC,CAAC;YAC/B,MAAM,KAAK,CAAC;QAChB,CAAC;QAED,IAAI,CAAC,SAAS,EAAE,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,KAAK;QACP,IAAI,CAAC,YAAY,EAAE,GAAG,EAAE,CAAC;QACzB,IAAI,CAAC,YAAY,GAAG,SAAS,CAAC;QAC9B,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,OAAuB;QAC9B,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;QACrC,CAAC;QAED,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,yBAAyB,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpF,CAAC;IAED;;;;OAIG;IACH,IAAI,SAAS;QACT,OAAO,IAAI,CAAC,UAAU,CAAC;IAC3B,CAAC;CACJ;AA7KD,gDA6KC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.d.ts new file mode 100644 index 000000000..83af57219 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.d.ts @@ -0,0 +1,28 @@ +import { Readable, Writable } from 'node:stream'; +import { JSONRPCMessage } from '../types.js'; +import { Transport } from '../shared/transport.js'; +/** + * Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout. + * + * This transport is only available in Node.js environments. + */ +export declare class StdioServerTransport implements Transport { + private _stdin; + private _stdout; + private _readBuffer; + private _started; + constructor(_stdin?: Readable, _stdout?: Writable); + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + _ondata: (chunk: Buffer) => void; + _onerror: (error: Error) => void; + /** + * Starts listening for messages on stdin. + */ + start(): Promise; + private processReadBuffer; + close(): Promise; + send(message: JSONRPCMessage): Promise; +} +//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.d.ts.map new file mode 100644 index 000000000..fdd2dfe48 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/server/stdio.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,SAAS;IAK9C,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IALnB,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,QAAQ,CAAS;gBAGb,MAAM,GAAE,QAAwB,EAChC,OAAO,GAAE,QAAyB;IAG9C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;IAG9C,OAAO,UAAW,MAAM,UAGtB;IACF,QAAQ,UAAW,KAAK,UAEtB;IAEF;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAY5B,OAAO,CAAC,iBAAiB;IAenB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAkB5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAU/C"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.js new file mode 100644 index 000000000..0edcbf325 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.js @@ -0,0 +1,82 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StdioServerTransport = void 0; +const node_process_1 = __importDefault(require("node:process")); +const stdio_js_1 = require("../shared/stdio.js"); +/** + * Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout. + * + * This transport is only available in Node.js environments. + */ +class StdioServerTransport { + constructor(_stdin = node_process_1.default.stdin, _stdout = node_process_1.default.stdout) { + this._stdin = _stdin; + this._stdout = _stdout; + this._readBuffer = new stdio_js_1.ReadBuffer(); + this._started = false; + // Arrow functions to bind `this` properly, while maintaining function identity. + this._ondata = (chunk) => { + this._readBuffer.append(chunk); + this.processReadBuffer(); + }; + this._onerror = (error) => { + this.onerror?.(error); + }; + } + /** + * Starts listening for messages on stdin. + */ + async start() { + if (this._started) { + throw new Error('StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.'); + } + this._started = true; + this._stdin.on('data', this._ondata); + this._stdin.on('error', this._onerror); + } + processReadBuffer() { + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + this.onmessage?.(message); + } + catch (error) { + this.onerror?.(error); + } + } + } + async close() { + // Remove our event listeners first + this._stdin.off('data', this._ondata); + this._stdin.off('error', this._onerror); + // Check if we were the only data listener + const remainingDataListeners = this._stdin.listenerCount('data'); + if (remainingDataListeners === 0) { + // Only pause stdin if we were the only listener + // This prevents interfering with other parts of the application that might be using stdin + this._stdin.pause(); + } + // Clear the buffer and notify closure + this._readBuffer.clear(); + this.onclose?.(); + } + send(message) { + return new Promise(resolve => { + const json = (0, stdio_js_1.serializeMessage)(message); + if (this._stdout.write(json)) { + resolve(); + } + else { + this._stdout.once('drain', resolve); + } + }); + } +} +exports.StdioServerTransport = StdioServerTransport; +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.js.map new file mode 100644 index 000000000..f5d54d451 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/server/stdio.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAmC;AAEnC,iDAAkE;AAIlE;;;;GAIG;AACH,MAAa,oBAAoB;IAI7B,YACY,SAAmB,sBAAO,CAAC,KAAK,EAChC,UAAoB,sBAAO,CAAC,MAAM;QADlC,WAAM,GAAN,MAAM,CAA0B;QAChC,YAAO,GAAP,OAAO,CAA2B;QALtC,gBAAW,GAAe,IAAI,qBAAU,EAAE,CAAC;QAC3C,aAAQ,GAAG,KAAK,CAAC;QAWzB,gFAAgF;QAChF,YAAO,GAAG,CAAC,KAAa,EAAE,EAAE;YACxB,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC/B,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAC7B,CAAC,CAAC;QACF,aAAQ,GAAG,CAAC,KAAY,EAAE,EAAE;YACxB,IAAI,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC;QAC1B,CAAC,CAAC;IAbC,CAAC;IAeJ;;OAEG;IACH,KAAK,CAAC,KAAK;QACP,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CACX,+GAA+G,CAClH,CAAC;QACN,CAAC;QAED,IAAI,CAAC,QAAQ,GAA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AA,2BAAgB,EAAC,OAAO,CAAC,CAAC;YACvC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC3B,OAAO,EAAE,CAAC;YACd,CAAC;iBAAM,CAAC;gBACJ,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAhFD,oDAgFC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/streamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/streamableHttp.d.ts new file mode 100644 index 000000000..5d5564bd1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/streamableHttp.d.ts @@ -0,0 +1,122 @@ +/** + * Node.js HTTP Streamable HTTP Server Transport + * + * This is a thin wrapper around `WebStandardStreamableHTTPServerTransport` that provides + * compatibility with Node.js HTTP server (IncomingMessage/ServerResponse). + * + * For web-standard environments (Cloudflare Workers, Deno, Bun), use `WebStandardStreamableHTTPServerTransport` directly. + */ +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Transport } from '../shared/transport.js'; +import { AuthInfo } from './auth/types.js'; +import { MessageExtraInfo, JSONRPCMessage, RequestId } from '../types.js'; +import { WebStandardStreamableHTTPServerTransportOptions, EventStore, StreamId, EventId } from './webStandardStreamableHttp.js'; +export type { EventStore, StreamId, EventId }; +/** + * Configuration options for StreamableHTTPServerTransport + * + * This is an alias for WebStandardStreamableHTTPServerTransportOptions for backward compatibility. + */ +export type StreamableHTTPServerTransportOptions = WebStandardStreamableHTTPServerTransportOptions; +/** + * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It supports both SSE streaming and direct HTTP responses. + * + * This is a wrapper around `WebStandardStreamableHTTPServerTransport` that provides Node.js HTTP compatibility. + * It uses the `@hono/node-server` library to convert between Node.js HTTP and Web Standard APIs. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: () => randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Using with pre-parsed request body + * app.post('/mcp', (req, res) => { + * transport.handleRequest(req, res, req.body); + * }); + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +export declare class StreamableHTTPServerTransport implements Transport { + private _webStandardTransport; + private _requestListener; + private _requestContext; + constructor(options?: StreamableHTTPServerTransportOptions); + /** + * Gets the session ID for this transport instance. + */ + get sessionId(): string | undefined; + /** + * Sets callback for when the transport is closed. + */ + set onclose(handler: (() => void) | undefined); + get onclose(): (() => void) | undefined; + /** + * Sets callback for transport errors. + */ + set onerror(handler: ((error: Error) => void) | undefined); + get onerror(): ((error: Error) => void) | undefined; + /** + * Sets callback for incoming messages. + */ + set onmessage(handler: ((message: JSONRPCMessage, extra?: MessageExtraInfo) => void) | undefined); + get onmessage(): ((message: JSONRPCMessage, extra?: MessageExtraInfo) => void) | undefined; + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + start(): Promise; + /** + * Closes the transport and all active connections. + */ + close(): Promise; + /** + * Sends a JSON-RPC message through the transport. + */ + send(message: JSONRPCMessage, options?: { + relatedRequestId?: RequestId; + }): Promise; + /** + * Handles an incoming HTTP request, whether GET or POST. + * + * This method converts Node.js HTTP objects to Web Standard Request/Response + * and delegates to the underlying WebStandardStreamableHTTPServerTransport. + * + * @param req - Node.js IncomingMessage, optionally with auth property from middleware + * @param res - Node.js ServerResponse + * @param parsedBody - Optional pre-parsed body from body-parser middleware + */ + handleRequest(req: IncomingMessage & { + auth?: AuthInfo; + }, res: ServerResponse, parsedBody?: unknown): Promise; + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId: RequestId): void; + /** + * Close the standalone GET SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream(): void; +} +//# sourceMappingURL=streamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/streamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/streamableHttp.d.ts.map new file mode 100644 index 000000000..f9e54b43e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/streamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.d.ts","sourceRoot":"","sources":["../../../src/server/streamableHttp.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE5D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC1E,OAAO,EAEH,+CAA+C,EAC/C,UAAU,EACV,QAAQ,EACR,OAAO,EACV,MAAM,gCAAgC,CAAC;AAGxC,YAAY,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;AAE9C;;;;GAIG;AACH,MAAM,MAAM,oCAAoC,GAAG,+CAA+C,CAAC;AAEnG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,qBAAa,6BAA8B,YAAW,SAAS;IAC3D,OAAO,CAAC,qBAAqB,CAA2C;IACxE,OAAO,CAAC,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;IACH,cAAc,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI;IAI1C;;;OAGG;IACH,wBAAwB,IAAI,IAAI;CAGnC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/streamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/streamableHttp.js new file mode 100644 index 000000000..a995355ab --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/streamableHttp.js @@ -0,0 +1,165 @@ +"use strict"; +/** + * Node.js HTTP Streamable HTTP Server Transport + * + * This is a thin wrapper around `WebStandardStreamableHTTPServerTransport` that provides + * compatibility with Node.js HTTP server (IncomingMessage/ServerResponse). + * + * For web-standard environments (Cloudflare Workers, Deno, Bun), use `WebStandardStreamableHTTPServerTransport` directly. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamableHTTPServerTransport = void 0; +const node_server_1 = require("@hono/node-server"); +const webStandardStreamableHttp_js_1 = require("./webStandardStreamableHttp.js"); +/** + * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It supports both SSE streaming and direct HTTP responses. + * + * This is a wrapper around `WebStandardStreamableHTTPServerTransport` that provides Node.js HTTP compatibility. + * It uses the `@hono/node-server` library to convert between Node.js HTTP and Web Standard APIs. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: () => randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Using with pre-parsed request body + * app.post('/mcp', (req, res) => { + * transport.handleRequest(req, res, req.body); + * }); + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +class StreamableHTTPServerTransport { + constructor(options = {}) { + // Store auth and parsedBody per request for passing through to handleRequest + this._requestContext = new WeakMap(); + this._webStandardTransport = new webStandardStreamableHttp_js_1.WebStandardStreamableHTTPServerTransport(options); + // Create a request listener that wraps the web standard transport + // getRequestListener converts Node.js HTTP to Web Standard and properly handles SSE streaming + // overrideGlobalObjects: false prevents Hono from overwriting global Response, which would + // break frameworks like Next.js whose response classes extend the native Response + this._requestListener = (0, node_server_1.getRequestListener)(async (webRequest) => { + // Get context if available (set during handleRequest) + const context = this._requestContext.get(webRequest); + return this._webStandardTransport.handleRequest(webRequest, { + authInfo: context?.authInfo, + parsedBody: context?.parsedBody + }); + }, { overrideGlobalObjects: false }); + } + /** + * Gets the session ID for this transport instance. + */ + get sessionId() { + return this._webStandardTransport.sessionId; + } + /** + * Sets callback for when the transport is closed. + */ + set onclose(handler) { + this._webStandardTransport.onclose = handler; + } + get onclose() { + return this._webStandardTransport.onclose; + } + /** + * Sets callback for transport errors. + */ + set onerror(handler) { + this._webStandardTransport.onerror = handler; + } + get onerror() { + return this._webStandardTransport.onerror; + } + /** + * Sets callback for incoming messages. + */ + set onmessage(handler) { + this._webStandardTransport.onmessage = handler; + } + get onmessage() { + return this._webStandardTransport.onmessage; + } + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start() { + return this._webStandardTransport.start(); + } + /** + * Closes the transport and all active connections. + */ + async close() { + return this._webStandardTransport.close(); + } + /** + * Sends a JSON-RPC message through the transport. + */ + async send(message, options) { + return this._webStandardTransport.send(message, options); + } + /** + * Handles an incoming HTTP request, whether GET or POST. + * + * This method converts Node.js HTTP objects to Web Standard Request/Response + * and delegates to the underlying WebStandardStreamableHTTPServerTransport. + * + * @param req - Node.js IncomingMessage, optionally with auth property from middleware + * @param res - Node.js ServerResponse + * @param parsedBody - Optional pre-parsed body from body-parser middleware + */ + async handleRequest(req, res, parsedBody) { + // Store context for this request to pass through auth and parsedBody + // We need to intercept the request creation to attach this context + const authInfo = req.auth; + // Create a custom handler that includes our context + // overrideGlobalObjects: false prevents Hono from overwriting global Response, which would + // break frameworks like Next.js whose response classes extend the native Response + const handler = (0, node_server_1.getRequestListener)(async (webRequest) => { + return this._webStandardTransport.handleRequest(webRequest, { + authInfo, + parsedBody + }); + }, { overrideGlobalObjects: false }); + // Delegate to the request listener which handles all the Node.js <-> Web Standard conversion + // including proper SSE streaming support + await handler(req, res); + } + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId) { + this._webStandardTransport.closeSSEStream(requestId); + } + /** + * Close the standalone GET SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream() { + this._webStandardTransport.closeStandaloneSSEStream(); + } +} +exports.StreamableHTTPServerTransport = StreamableHTTPServerTransport; +//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/streamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/streamableHttp.js.map new file mode 100644 index 000000000..d30634fdd --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/streamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.js","sourceRoot":"","sources":["../../../src/server/streamableHttp.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAGH,mDAAuD;AAIvD,iFAMwC;AAYxC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,MAAa,6BAA6B;IAMtC,YAAY,UAAgD,EAAE;QAH9D,6EAA6E;QACrE,oBAAe,GAAoE,IAAI,OAAO,EAAE,CAAC;QAGrG,IAAI,CAAC,qBAAqB,GAAG,IAAI,uEAAwC,CAAC,OAAO,CAAC,CAAC;QAEnF,kEAAkE;QAClE,8FAA8F;QAC9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K;QACP,OAAO,IAAI,CAAC,qBAAqB,CAAC,KAAK,EAAE,CAAC;IAC9C,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,IAAI,CAAC,OAAuB,EAAE,OAA0C;QAC1E,OAAO,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC7D,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,aAAa,CAAC,GAA0C,EAAE,GAAmB,EAAE,UAAoB;QACrG,qEAAqE;QACrE,mEAAmE;QACnE,MAAM,QAAQ,GAAG,GAAG,CAAC,IAAI,CAAC;QAE1B,oDAAoD;QACpD,2FAA2F;QAC3F,kFAAkF;QAClF,MAAM,OAAO,GAAG,IAAA,gCAAkB,EAC9B,KAAK,EAAE,UAAmB,EAAE,EAAE;YAC1B,OAAO,IAAI,CAAC,qBAAqB,CAAC,aAAa,CAAC,UAAU,EAAE;gBACxD,QAAQ;gBACR,UAAU;aACb,CAAC,CAAC;QACP,CAAC,EACD,EAAE,qBAAqB,EAAE,KAAK,EAAE,CACnC,CAAC;QAEF,6FAA6F;QAC7F,yCAAyC;QACzC,MAAM,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IAC5B,CAAC;IAED;;;;OAIG;IACH,cAAc,CAAC,SAAoB;QAC/B,IAAI,CAAC,qBAAqB,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;IACzD,CAAC;IAED;;;OAGG;IACH,wBAAwB;QACpB,IAAI,CAAC,qBAAqB,CAAC,wBAAwB,EAAE,CAAC;IAC1D,CAAC;CACJ;AAzID,sEAyIC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.d.ts new file mode 100644 index 000000000..d8f3ca64b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.d.ts @@ -0,0 +1,267 @@ +/** + * Web Standards Streamable HTTP Server Transport + * + * This is the core transport implementation using Web Standard APIs (Request, Response, ReadableStream). + * It can run on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. + * + * For Node.js Express/HTTP compatibility, use `StreamableHTTPServerTransport` which wraps this transport. + */ +import { Transport } from '../shared/transport.js'; +import { AuthInfo } from './auth/types.js'; +import { MessageExtraInfo, JSONRPCMessage, RequestId } from '../types.js'; +export type StreamId = string; +export type EventId = string; +/** + * Interface for resumability support via event storage + */ +export interface EventStore { + /** + * Stores an event for later retrieval + * @param streamId ID of the stream the event belongs to + * @param message The JSON-RPC message to store + * @returns The generated event ID for the stored event + */ + storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise; + /** + * Get the stream ID associated with a given event ID. + * @param eventId The event ID to look up + * @returns The stream ID, or undefined if not found + * + * Optional: If not provided, the SDK will use the streamId returned by + * replayEventsAfter for stream mapping. + */ + getStreamIdForEventId?(eventId: EventId): Promise; + replayEventsAfter(lastEventId: EventId, { send }: { + send: (eventId: EventId, message: JSONRPCMessage) => Promise; + }): Promise; +} +/** + * Configuration options for WebStandardStreamableHTTPServerTransport + */ +export interface WebStandardStreamableHTTPServerTransportOptions { + /** + * Function that generates a session ID for the transport. + * The session ID SHOULD be globally unique and cryptographically secure (e.g., a securely generated UUID, a JWT, or a cryptographic hash) + * + * If not provided, session management is disabled (stateless mode). + */ + sessionIdGenerator?: () => string; + /** + * A callback for session initialization events + * This is called when the server initializes a new session. + * Useful in cases when you need to register multiple mcp sessions + * and need to keep track of them. + * @param sessionId The generated session ID + */ + onsessioninitialized?: (sessionId: string) => void | Promise; + /** + * A callback for session close events + * This is called when the server closes a session due to a DELETE request. + * Useful in cases when you need to clean up resources associated with the session. + * Note that this is different from the transport closing, if you are handling + * HTTP requests from multiple nodes you might want to close each + * WebStandardStreamableHTTPServerTransport after a request is completed while still keeping the + * session open/running. + * @param sessionId The session ID that was closed + */ + onsessionclosed?: (sessionId: string) => void | Promise; + /** + * If true, the server will return JSON responses instead of starting an SSE stream. + * This can be useful for simple request/response scenarios without streaming. + * Default is false (SSE streams are preferred). + */ + enableJsonResponse?: boolean; + /** + * Event store for resumability support + * If provided, resumability will be enabled, allowing clients to reconnect and resume messages + */ + eventStore?: EventStore; + /** + * List of allowed host header values for DNS rebinding protection. + * If not specified, host validation is disabled. + * @deprecated Use external middleware for host validation instead. + */ + allowedHosts?: string[]; + /** + * List of allowed origin header values for DNS rebinding protection. + * If not specified, origin validation is disabled. + * @deprecated Use external middleware for origin validation instead. + */ + allowedOrigins?: string[]; + /** + * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). + * Default is false for backwards compatibility. + * @deprecated Use external middleware for DNS rebinding protection instead. + */ + enableDnsRebindingProtection?: boolean; + /** + * Retry interval in milliseconds to suggest to clients in SSE retry field. + * When set, the server will send a retry field in SSE priming events to control + * client reconnection timing for polling behavior. + */ + retryInterval?: number; +} +/** + * Options for handling a request + */ +export interface HandleRequestOptions { + /** + * Pre-parsed request body. If provided, the transport will use this instead of parsing req.json(). + * Useful when using body-parser middleware that has already parsed the body. + */ + parsedBody?: unknown; + /** + * Authentication info from middleware. If provided, will be passed to message handlers. + */ + authInfo?: AuthInfo; +} +/** + * Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification + * using Web Standard APIs (Request, Response, ReadableStream). + * + * This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new WebStandardStreamableHTTPServerTransport({ + * sessionIdGenerator: () => crypto.randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new WebStandardStreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Hono.js usage + * app.all('/mcp', async (c) => { + * return transport.handleRequest(c.req.raw); + * }); + * + * // Cloudflare Workers usage + * export default { + * async fetch(request: Request): Promise { + * return transport.handleRequest(request); + * } + * }; + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +export declare class WebStandardStreamableHTTPServerTransport implements Transport { + private sessionIdGenerator; + private _started; + private _streamMapping; + private _requestToStreamMapping; + private _requestResponseMap; + private _initialized; + private _enableJsonResponse; + private _standaloneSseStreamId; + private _eventStore?; + private _onsessioninitialized?; + private _onsessionclosed?; + private _allowedHosts?; + private _allowedOrigins?; + private _enableDnsRebindingProtection; + private _retryInterval?; + sessionId?: string; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; + constructor(options?: WebStandardStreamableHTTPServerTransportOptions); + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + start(): Promise; + /** + * Helper to create a JSON error response + */ + private createJsonErrorResponse; + /** + * Validates request headers for DNS rebinding protection. + * @returns Error response if validation fails, undefined if validation passes. + */ + private validateRequestHeaders; + /** + * Handles an incoming HTTP request, whether GET, POST, or DELETE + * Returns a Response object (Web Standard) + */ + handleRequest(req: Request, options?: HandleRequestOptions): Promise; + /** + * Writes a priming event to establish resumption capability. + * Only sends if eventStore is configured (opt-in for resumability) and + * the client's protocol version supports empty SSE data (>= 2025-11-25). + */ + private writePrimingEvent; + /** + * Handles GET requests for SSE stream + */ + private handleGetRequest; + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + private replayEvents; + /** + * Writes an event to an SSE stream via controller with proper formatting + */ + private writeSSEEvent; + /** + * Handles unsupported requests (PUT, PATCH, etc.) + */ + private handleUnsupportedRequest; + /** + * Handles POST requests containing JSON-RPC messages + */ + private handlePostRequest; + /** + * Handles DELETE requests to terminate sessions + */ + private handleDeleteRequest; + /** + * Validates session ID for non-initialization requests. + * Returns Response error if invalid, undefined otherwise + */ + private validateSession; + /** + * Validates the MCP-Protocol-Version header on incoming requests. + * + * For initialization: Version negotiation handles unknown versions gracefully + * (server responds with its supported version). + * + * For subsequent requests with MCP-Protocol-Version header: + * - Accept if in supported list + * - 400 if unsupported + * + * For HTTP requests without the MCP-Protocol-Version header: + * - Accept and default to the version negotiated at initialization + */ + private validateProtocolVersion; + close(): Promise; + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId: RequestId): void; + /** + * Close the standalone GET SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream(): void; + send(message: JSONRPCMessage, options?: { + relatedRequestId?: RequestId; + }): Promise; +} +//# sourceMappingURL=webStandardStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.d.ts.map new file mode 100644 index 000000000..49c1aed78 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webStandardStreamableHttp.d.ts","sourceRoot":"","sources":["../../../src/server/webStandardStreamableHttp.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EACH,gBAAgB,EAMhB,cAAc,EAEd,SAAS,EAGZ,MAAM,aAAa,CAAC;AAErB,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC;AAC9B,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC;AAE7B;;GAEG;AACH,MAAM,WAAW,UA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9B;;;OAGG;YACW,YAAY;IAgF1B;;OAEG;IACH,OAAO,CAAC,aAAa;IAoBrB;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAoBhC;;OAEG;YACW,iBAAiB;IA8M/B;;OAEG;YACW,mBAAmB;IAejC;;;OAGG;IACH,OAAO,CAAC,eAAe;IA0BvB;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,uBAAuB;IAazB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAY5B;;;;OAIG;IACH,cAAc,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI;IAU1C;;;OAGG;IACH,wBAAwB,IAAI,IAAI;IAO1B,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAiGjG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.js new file mode 100644 index 000000000..1bc5843d2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.js @@ -0,0 +1,729 @@ +"use strict"; +/** + * Web Standards Streamable HTTP Server Transport + * + * This is the core transport implementation using Web Standard APIs (Request, Response, ReadableStream). + * It can run on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. + * + * For Node.js Express/HTTP compatibility, use `StreamableHTTPServerTransport` which wraps this transport. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebStandardStreamableHTTPServerTransport = void 0; +const types_js_1 = require("../types.js"); +/** + * Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification + * using Web Standard APIs (Request, Response, ReadableStream). + * + * This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new WebStandardStreamableHTTPServerTransport({ + * sessionIdGenerator: () => crypto.randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new WebStandardStreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Hono.js usage + * app.all('/mcp', async (c) => { + * return transport.handleRequest(c.req.raw); + * }); + * + * // Cloudflare Workers usage + * export default { + * async fetch(request: Request): Promise { + * return transport.handleRequest(request); + * } + * }; + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +class WebStandardStreamableHTTPServerTransport { + constructor(options = {}) { + this._started = false; + this._streamMapping = new Map(); + this._requestToStreamMapping = new Map(); + this._requestResponseMap = new Map(); + this._initialized = false; + this._enableJsonResponse = false; + this._standaloneSseStreamId = '_GET_stream'; + this.sessionIdGenerator = options.sessionIdGenerator; + this._enableJsonResponse = options.enableJsonResponse ?? false; + this._eventStore = options.eventStore; + this._onsessioninitialized = options.onsessioninitialized; + this._onsessionclosed = options.onsessionclosed; + this._allowedHosts = options.allowedHosts; + this._allowedOrigins = options.allowedOrigins; + this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; + this._retryInterval = options.retryInterval; + } + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start() { + if (this._started) { + throw new Error('Transport already started'); + } + this._started = true; + } + /** + * Helper to create a JSON error response + */ + createJsonErrorResponse(status, code, message, options) { + const error = { code, message }; + if (options?.data !== undefined) { + error.data = options.data; + } + return new Response(JSON.stringify({ + jsonrpc: '2.0', + error, + id: null + }), { + status, + headers: { + 'Content-Type': 'application/json', + ...options?.headers + } + }); + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error response if validation fails, undefined if validation passes. + */ + validateRequestHeaders(req) { + // Skip validation if protection is not enabled + if (!this._enableDnsRebindingProtection) { + return undefined; + } + // Validate Host header if allowedHosts is configured + if (this._allowedHosts && this._allowedHosts.length > 0) { + const hostHeader = req.headers.get('host'); + if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { + const error = `Invalid Host header: ${hostHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32000, error); + } + } + // Validate Origin header if allowedOrigins is configured + if (this._allowedOrigins && this._allowedOrigins.length > 0) { + const originHeader = req.headers.get('origin'); + if (originHeader && !this._allowedOrigins.includes(originHeader)) { + const error = `Invalid Origin header: ${originHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32000, error); + } + } + return undefined; + } + /** + * Handles an incoming HTTP request, whether GET, POST, or DELETE + * Returns a Response object (Web Standard) + */ + async handleRequest(req, options) { + // Validate request headers for DNS rebinding protection + const validationError = this.validateRequestHeaders(req); + if (validationError) { + return validationError; + } + switch (req.method) { + case 'POST': + return this.handlePostRequest(req, options); + case 'GET': + return this.handleGetRequest(req); + case 'DELETE': + return this.handleDeleteRequest(req); + default: + return this.handleUnsupportedRequest(); + } + } + /** + * Writes a priming event to establish resumption capability. + * Only sends if eventStore is configured (opt-in for resumability) and + * the client's protocol version supports empty SSE data (>= 2025-11-25). + */ + async writePrimingEvent(controller, encoder, streamId, protocolVersion) { + if (!this._eventStore) { + return; + } + // Priming events have empty data which older clients cannot handle. + // Only send priming events to clients with protocol version >= 2025-11-25 + // which includes the fix for handling empty SSE data. + if (protocolVersion < '2025-11-25') { + return; + } + const primingEventId = await this._eventStore.storeEvent(streamId, {}); + let primingEvent = `id: ${primingEventId}\ndata: \n\n`; + if (this._retryInterval !== undefined) { + primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; + } + controller.enqueue(encoder.encode(primingEvent)); + } + /** + * Handles GET requests for SSE stream + */ + async handleGetRequest(req) { + // The client MUST include an Accept header, listing text/event-stream as a supported content type. + const acceptHeader = req.headers.get('accept'); + if (!acceptHeader?.includes('text/event-stream')) { + return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept text/event-stream'); + } + // If an Mcp-Session-Id is returned by the server during initialization, + // clients using the Streamable HTTP transport MUST include it + // in the Mcp-Session-Id header on all of their subsequent HTTP requests. + const sessionError = this.validateSession(req); + if (sessionError) { + return sessionError; + } + const protocolError = this.validateProtocolVersion(req); + if (protocolError) { + return protocolError; + } + // Handle resumability: check for Last-Event-ID header + if (this._eventStore) { + const lastEventId = req.headers.get('last-event-id'); + if (lastEventId) { + return this.replayEvents(lastEventId); + } + } + // Check if there's already an active standalone SSE stream for this session + if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) { + // Only one GET SSE stream is allowed per session + return this.createJsonErrorResponse(409, -32000, 'Conflict: Only one SSE stream is allowed per session'); + } + const encoder = new TextEncoder(); + let streamController; + // Create a ReadableStream with a controller we can use to push SSE events + const readable = new ReadableStream({ + start: controller => { + streamController = controller; + }, + cancel: () => { + // Stream was cancelled by client + this._streamMapping.delete(this._standaloneSseStreamId); + } + }); + const headers = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }; + // After initialization, always include the session ID if we have one + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + // Store the stream mapping with the controller for pushing data + this._streamMapping.set(this._standaloneSseStreamId, { + controller: streamController, + encoder, + cleanup: () => { + this._streamMapping.delete(this._standaloneSseStreamId); + try { + streamController.close(); + } + catch { + // Controller might already be closed + } + } + }); + return new Response(readable, { headers }); + } + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + async replayEvents(lastEventId) { + if (!this._eventStore) { + return this.createJsonErrorResponse(400, -32000, 'Event store not configured'); + } + try { + // If getStreamIdForEventId is available, use it for conflict checking + let streamId; + if (this._eventStore.getStreamIdForEventId) { + streamId = await this._eventStore.getStreamIdForEventId(lastEventId); + if (!streamId) { + return this.createJsonErrorResponse(400, -32000, 'Invalid event ID format'); + } + // Check conflict with the SAME streamId we'll use for mapping + if (this._streamMapping.get(streamId) !== undefined) { + return this.createJsonErrorResponse(409, -32000, 'Conflict: Stream already has an active connection'); + } + } + const headers = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }; + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + // Create a ReadableStream with controller for SSE + const encoder = new TextEncoder(); + let streamController; + const readable = new ReadableStream({ + start: controller => { + streamController = controller; + }, + cancel: () => { + // Stream was cancelled by client + // Cleanup will be handled by the mapping + } + }); + // Replay events - returns the streamId for backwards compatibility + const replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { + send: async (eventId, message) => { + const success = this.writeSSEEvent(streamController, encoder, message, eventId); + if (!success) { + this.onerror?.(new Error('Failed replay events')); + try { + streamController.close(); + } + catch { + // Controller might already be closed + } + } + } + }); + this._streamMapping.set(replayedStreamId, { + controller: streamController, + encoder, + cleanup: () => { + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } + catch { + // Controller might already be closed + } + } + }); + return new Response(readable, { headers }); + } + catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(500, -32000, 'Error replaying events'); + } + } + /** + * Writes an event to an SSE stream via controller with proper formatting + */ + writeSSEEvent(controller, encoder, message, eventId) { + try { + let eventData = `event: message\n`; + // Include event ID if provided - this is important for resumability + if (eventId) { + eventData += `id: ${eventId}\n`; + } + eventData += `data: ${JSON.stringify(message)}\n\n`; + controller.enqueue(encoder.encode(eventData)); + return true; + } + catch { + return false; + } + } + /** + * Handles unsupported requests (PUT, PATCH, etc.) + */ + handleUnsupportedRequest() { + return new Response(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + }), { + status: 405, + headers: { + Allow: 'GET, POST, DELETE', + 'Content-Type': 'application/json' + } + }); + } + /** + * Handles POST requests containing JSON-RPC messages + */ + async handlePostRequest(req, options) { + try { + // Validate the Accept header + const acceptHeader = req.headers.get('accept'); + // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types. + if (!acceptHeader?.includes('application/json') || !acceptHeader.includes('text/event-stream')) { + return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept both application/json and text/event-stream'); + } + const ct = req.headers.get('content-type'); + if (!ct || !ct.includes('application/json')) { + return this.createJsonErrorResponse(415, -32000, 'Unsupported Media Type: Content-Type must be application/json'); + } + // Build request info from headers + const requestInfo = { + headers: Object.fromEntries(req.headers.entries()) + }; + let rawMessage; + if (options?.parsedBody !== undefined) { + rawMessage = options.parsedBody; + } + else { + try { + rawMessage = await req.json(); + } + catch { + return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON'); + } + } + let messages; + // handle batch and single messages + try { + if (Array.isArray(rawMessage)) { + messages = rawMessage.map(msg => types_js_1.JSONRPCMessageSchema.parse(msg)); + } + else { + messages = [types_js_1.JSONRPCMessageSchema.parse(rawMessage)]; + } + } + catch { + return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON-RPC message'); + } + // Check if this is an initialization request + // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/ + const isInitializationRequest = messages.some(types_js_1.isInitializeRequest); + if (isInitializationRequest) { + // If it's a server with session management and the session ID is already set we should reject the request + // to avoid re-initialization. + if (this._initialized && this.sessionId !== undefined) { + return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Server already initialized'); + } + if (messages.length > 1) { + return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Only one initialization request is allowed'); + } + this.sessionId = this.sessionIdGenerator?.(); + this._initialized = true; + // If we have a session ID and an onsessioninitialized handler, call it immediately + // This is needed in cases where the server needs to keep track of multiple sessions + if (this.sessionId && this._onsessioninitialized) { + await Promise.resolve(this._onsessioninitialized(this.sessionId)); + } + } + if (!isInitializationRequest) { + // If an Mcp-Session-Id is returned by the server during initialization, + // clients using the Streamable HTTP transport MUST include it + // in the Mcp-Session-Id header on all of their subsequent HTTP requests. + const sessionError = this.validateSession(req); + if (sessionError) { + return sessionError; + } + // Mcp-Protocol-Version header is required for all requests after initialization. + const protocolError = this.validateProtocolVersion(req); + if (protocolError) { + return protocolError; + } + } + // check if it contains requests + const hasRequests = messages.some(types_js_1.isJSONRPCRequest); + if (!hasRequests) { + // if it only contains notifications or responses, return 202 + for (const message of messages) { + this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo }); + } + return new Response(null, { status: 202 }); + } + // The default behavior is to use SSE streaming + // but in some cases server will return JSON responses + const streamId = crypto.randomUUID(); + // Extract protocol version for priming event decision. + // For initialize requests, get from request params. + // For other requests, get from header (already validated). + const initRequest = messages.find(m => (0, types_js_1.isInitializeRequest)(m)); + const clientProtocolVersion = initRequest + ? initRequest.params.protocolVersion + : (req.headers.get('mcp-protocol-version') ?? types_js_1.DEFAULT_NEGOTIATED_PROTOCOL_VERSION); + if (this._enableJsonResponse) { + // For JSON response mode, return a Promise that resolves when all responses are ready + return new Promise(resolve => { + this._streamMapping.set(streamId, { + resolveJson: resolve, + cleanup: () => { + this._streamMapping.delete(streamId); + } + }); + for (const message of messages) { + if ((0, types_js_1.isJSONRPCRequest)(message)) { + this._requestToStreamMapping.set(message.id, streamId); + } + } + for (const message of messages) { + this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo }); + } + }); + } + // SSE streaming mode - use ReadableStream with controller for more reliable data pushing + const encoder = new TextEncoder(); + let streamController; + const readable = new ReadableStream({ + start: controller => { + streamController = controller; + }, + cancel: () => { + // Stream was cancelled by client + this._streamMapping.delete(streamId); + } + }); + const headers = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive' + }; + // After initialization, always include the session ID if we have one + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + // Store the response for this request to send messages back through this connection + // We need to track by request ID to maintain the connection + for (const message of messages) { + if ((0, types_js_1.isJSONRPCRequest)(message)) { + this._streamMapping.set(streamId, { + controller: streamController, + encoder, + cleanup: () => { + this._streamMapping.delete(streamId); + try { + streamController.close(); + } + catch { + // Controller might already be closed + } + } + }); + this._requestToStreamMapping.set(message.id, streamId); + } + } + // Write priming event if event store is configured (after mapping is set up) + await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); + // handle each message + for (const message of messages) { + // Build closeSSEStream callback for requests when eventStore is configured + // AND client supports resumability (protocol version >= 2025-11-25). + // Old clients can't resume if the stream is closed early because they + // didn't receive a priming event with an event ID. + let closeSSEStream; + let closeStandaloneSSEStream; + if ((0, types_js_1.isJSONRPCRequest)(message) && this._eventStore && clientProtocolVersion >= '2025-11-25') { + closeSSEStream = () => { + this.closeSSEStream(message.id); + }; + closeStandaloneSSEStream = () => { + this.closeStandaloneSSEStream(); + }; + } + this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo, closeSSEStream, closeStandaloneSSEStream }); + } + // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses + // This will be handled by the send() method when responses are ready + return new Response(readable, { status: 200, headers }); + } + catch (error) { + // return JSON-RPC formatted error + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, 'Parse error', { data: String(error) }); + } + } + /** + * Handles DELETE requests to terminate sessions + */ + async handleDeleteRequest(req) { + const sessionError = this.validateSession(req); + if (sessionError) { + return sessionError; + } + const protocolError = this.validateProtocolVersion(req); + if (protocolError) { + return protocolError; + } + await Promise.resolve(this._onsessionclosed?.(this.sessionId)); + await this.close(); + return new Response(null, { status: 200 }); + } + /** + * Validates session ID for non-initialization requests. + * Returns Response error if invalid, undefined otherwise + */ + validateSession(req) { + if (this.sessionIdGenerator === undefined) { + // If the sessionIdGenerator ID is not set, the session management is disabled + // and we don't need to validate the session ID + return undefined; + } + if (!this._initialized) { + // If the server has not been initialized yet, reject all requests + return this.createJsonErrorResponse(400, -32000, 'Bad Request: Server not initialized'); + } + const sessionId = req.headers.get('mcp-session-id'); + if (!sessionId) { + // Non-initialization requests without a session ID should return 400 Bad Request + return this.createJsonErrorResponse(400, -32000, 'Bad Request: Mcp-Session-Id header is required'); + } + if (sessionId !== this.sessionId) { + // Reject requests with invalid session ID with 404 Not Found + return this.createJsonErrorResponse(404, -32001, 'Session not found'); + } + return undefined; + } + /** + * Validates the MCP-Protocol-Version header on incoming requests. + * + * For initialization: Version negotiation handles unknown versions gracefully + * (server responds with its supported version). + * + * For subsequent requests with MCP-Protocol-Version header: + * - Accept if in supported list + * - 400 if unsupported + * + * For HTTP requests without the MCP-Protocol-Version header: + * - Accept and default to the version negotiated at initialization + */ + validateProtocolVersion(req) { + const protocolVersion = req.headers.get('mcp-protocol-version'); + if (protocolVersion !== null && !types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) { + return this.createJsonErrorResponse(400, -32000, `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${types_js_1.SUPPORTED_PROTOCOL_VERSIONS.join(', ')})`); + } + return undefined; + } + async close() { + // Close all SSE connections + this._streamMapping.forEach(({ cleanup }) => { + cleanup(); + }); + this._streamMapping.clear(); + // Clear any pending responses + this._requestResponseMap.clear(); + this.onclose?.(); + } + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId) { + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) + return; + const stream = this._streamMapping.get(streamId); + if (stream) { + stream.cleanup(); + } + } + /** + * Close the standalone GET SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream() { + const stream = this._streamMapping.get(this._standaloneSseStreamId); + if (stream) { + stream.cleanup(); + } + } + async send(message, options) { + let requestId = options?.relatedRequestId; + if ((0, types_js_1.isJSONRPCResultResponse)(message) || (0, types_js_1.isJSONRPCErrorResponse)(message)) { + // If the message is a response, use the request ID from the message + requestId = message.id; + } + // Check if this message should be sent on the standalone SSE stream (no request ID) + // Ignore notifications from tools (which have relatedRequestId set) + // Those will be sent via dedicated response SSE streams + if (requestId === undefined) { + // For standalone SSE streams, we can only send requests and notifications + if ((0, types_js_1.isJSONRPCResultResponse)(message) || (0, types_js_1.isJSONRPCErrorResponse)(message)) { + throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request'); + } + // Generate and store event ID if event store is provided + // Store even if stream is disconnected so events can be replayed on reconnect + let eventId; + if (this._eventStore) { + // Stores the event and gets the generated event ID + eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); + } + const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); + if (standaloneSse === undefined) { + // Stream is disconnected - event is stored for replay, nothing more to do + return; + } + // Send the message to the standalone SSE stream + if (standaloneSse.controller && standaloneSse.encoder) { + this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); + } + return; + } + // Get the response for this request + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) { + throw new Error(`No connection established for request ID: ${String(requestId)}`); + } + const stream = this._streamMapping.get(streamId); + if (!this._enableJsonResponse && stream?.controller && stream?.encoder) { + // For SSE responses, generate event ID if event store is provided + let eventId; + if (this._eventStore) { + eventId = await this._eventStore.storeEvent(streamId, message); + } + // Write the event to the response stream + this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); + } + if ((0, types_js_1.isJSONRPCResultResponse)(message) || (0, types_js_1.isJSONRPCErrorResponse)(message)) { + this._requestResponseMap.set(requestId, message); + const relatedIds = Array.from(this._requestToStreamMapping.entries()) + .filter(([_, sid]) => sid === streamId) + .map(([id]) => id); + // Check if we have responses for all requests using this connection + const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id)); + if (allResponsesReady) { + if (!stream) { + throw new Error(`No connection established for request ID: ${String(requestId)}`); + } + if (this._enableJsonResponse && stream.resolveJson) { + // All responses ready, send as JSON + const headers = { + 'Content-Type': 'application/json' + }; + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + const responses = relatedIds.map(id => this._requestResponseMap.get(id)); + if (responses.length === 1) { + stream.resolveJson(new Response(JSON.stringify(responses[0]), { status: 200, headers })); + } + else { + stream.resolveJson(new Response(JSON.stringify(responses), { status: 200, headers })); + } + } + else { + // End the SSE stream + stream.cleanup(); + } + // Clean up + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + } + } + } +} +exports.WebStandardStreamableHTTPServerTransport = WebStandardStreamableHTTPServerTransport; +//# sourceMappingURL=webStandardStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.js.map new file mode 100644 index 000000000..79bd4214c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webStandardStreamableHttp.js","sourceRoot":"","sources":["../../../src/server/webStandardStreamableHttp.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAIH,0CAYqB;AA8IrB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAa,wCAAwC;IAuBjD,YAAY,UAA2D,EAAE;QApBjE,aAAQ,GAAY,KAAK,CAAC;QAC1B,mBAAc,GAA+B,IAAI,GAAG,EAAE,CAAC;QACvD,4BAAuB,GAA2B,IAAI,GAAG,EAAE,CAAC;QAC5D,wBAAmB,GAAmC,IAAI,GAAG,EAAE,CAAC;QAChE,iBAAY,GAAY,KAAK,CAAC;QAC9B,wBAAmB,GAAY,KAAK,CAAC;QACrC,2BAAsB,GAAW,aAAa,CAAC;QAenD,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;QACrD,IAAI,CAAC,mBAAmB,GAAG,OAAO,CAAC,kBAAkB,IAAI,KAAK,CAAC;QAC/D,IAAI,CAAC,WAAW,GAAG,OAAO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AC;oBAC1B,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;oBACpC,IAAI,CAAC,uBAAuB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAC5C,CAAC;YACL,CAAC;QACL,CAAC;IACL,CAAC;CACJ;AApxBD,4FAoxBC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.d.ts new file mode 100644 index 000000000..c3a5b60ee --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.d.ts @@ -0,0 +1,84 @@ +import type * as z3 from 'zod/v3'; +import type * as z4 from 'zod/v4/core'; +export type AnySchema = z3.ZodTypeAny | z4.$ZodType; +export type AnyObjectSchema = z3.AnyZodObject | z4.$ZodObject | AnySchema; +export type ZodRawShapeCompat = Record; +export interface ZodV3Internal { + _def?: { + typeName?: string; + value?: unknown; + values?: unknown[]; + shape?: Record | (() => Record); + description?: string; + }; + shape?: Record | (() => Record); + value?: unknown; +} +export interface ZodV4Internal { + _zod?: { + def?: { + type?: string; + value?: unknown; + values?: unknown[]; + shape?: Record | (() => Record); + }; + }; + value?: unknown; +} +export type SchemaOutput = S extends z3.ZodTypeAny ? z3.infer : S extends z4.$ZodType ? z4.output : never; +export type SchemaInput = S extends z3.ZodTypeAny ? z3.input : S extends z4.$ZodType ? z4.input : never; +/** + * Infers the output type from a ZodRawShapeCompat (raw shape object). + * Maps over each key in the shape and infers the output type from each schema. + */ +export type ShapeOutput = { + [K in keyof Shape]: SchemaOutput; +}; +export declare function isZ4Schema(s: AnySchema): s is z4.$ZodType; +export declare function objectFromShape(shape: ZodRawShapeCompat): AnyObjectSchema; +export declare function safeParse(schema: S, data: unknown): { + success: true; + data: SchemaOutput; +} | { + success: false; + error: unknown; +}; +export declare function safeParseAsync(schema: S, data: unknown): Promise<{ + success: true; + data: SchemaOutput; +} | { + success: false; + error: unknown; +}>; +export declare function getObjectShape(schema: AnyObjectSchema | undefined): Record | undefined; +/** + * Normalizes a schema to an object schema. Handles both: + * - Already-constructed object schemas (v3 or v4) + * - Raw shapes that need to be wrapped into object schemas + */ +export declare function normalizeObjectSchema(schema: AnySchema | ZodRawShapeCompat | undefined): AnyObjectSchema | undefined; +/** + * Safely extracts an error message from a parse result error. + * Zod errors can have different structures, so we handle various cases. + */ +export declare function getParseErrorMessage(error: unknown): string; +/** + * Gets the description from a schema, if available. + * Works with both Zod v3 and v4. + * + * Both versions expose a `.description` getter that returns the description + * from their respective internal storage (v3: _def, v4: globalRegistry). + */ +export declare function getSchemaDescription(schema: AnySchema): string | undefined; +/** + * Checks if a schema is optional. + * Works with both Zod v3 and v4. + */ +export declare function isSchemaOptional(schema: AnySchema): boolean; +/** + * Gets the literal value from a schema, if it's a literal schema. + * Works with both Zod v3 and v4. + * Returns undefined if the schema is not a literal or the value cannot be determined. + */ +export declare function getLiteralValue(schema: AnySchema): unknown; +//# sourceMappingURL=zod-compat.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.d.ts.map new file mode 100644 index 000000000..a2ccd51c7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-compat.d.ts","sourceRoot":"","sources":["../../../src/server/zod-compat.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,KAAK,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAMvC,MAAM,MAAM,SAAS,GAAG,EAAE,CAAC,UAAU,GAAG,EAAE,CAAC,QAAQ,CAAC;AACpD,MAAM,MAAM,eAAe,GAAG,EAAE,CAAC,YAAY,GAAG,EAAE,CAAC,UAAU,GAAG,SAAS,CAAC;AAC1E,M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AAGD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAoB3D;AAGD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,GAAG,SAAS,CAE1E;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAW3D;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAwB1D"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.js new file mode 100644 index 000000000..2e75c80c6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.js @@ -0,0 +1,244 @@ +"use strict"; +// zod-compat.ts +// ---------------------------------------------------- +// Unified types + helpers to accept Zod v3 and v4 (Mini) +// ---------------------------------------------------- +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isZ4Schema = isZ4Schema; +exports.objectFromShape = objectFromShape; +exports.safeParse = safeParse; +exports.safeParseAsync = safeParseAsync; +exports.getObjectShape = getObjectShape; +exports.normalizeObjectSchema = normalizeObjectSchema; +exports.getParseErrorMessage = getParseErrorMessage; +exports.getSchemaDescription = getSchemaDescription; +exports.isSchemaOptional = isSchemaOptional; +exports.getLiteralValue = getLiteralValue; +const z3rt = __importStar(require("zod/v3")); +const z4mini = __importStar(require("zod/v4-mini")); +// --- Runtime detection --- +function isZ4Schema(s) { + // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3 + const schema = s; + return !!schema._zod; +} +// --- Schema construction --- +function objectFromShape(shape) { + const values = Object.values(shape); + if (values.length === 0) + return z4mini.object({}); // default to v4 Mini + const allV4 = values.every(isZ4Schema); + const allV3 = values.every(s => !isZ4Schema(s)); + if (allV4) + return z4mini.object(shape); + if (allV3) + return z3rt.object(shape); + throw new Error('Mixed Zod versions detected in object shape.'); +} +// --- Unified parsing --- +function safeParse(schema, data) { + if (isZ4Schema(schema)) { + // Mini exposes top-level safeParse + const result = z4mini.safeParse(schema, data); + return result; + } + const v3Schema = schema; + const result = v3Schema.safeParse(data); + return result; +} +async function safeParseAsync(schema, data) { + if (isZ4Schema(schema)) { + // Mini exposes top-level safeParseAsync + const result = await z4mini.safeParseAsync(schema, data); + return result; + } + const v3Schema = schema; + const result = await v3Schema.safeParseAsync(data); + return result; +} +// --- Shape extraction --- +function getObjectShape(schema) { + if (!schema) + return undefined; + // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape` + let rawShape; + if (isZ4Schema(schema)) { + const v4Schema = schema; + rawShape = v4Schema._zod?.def?.shape; + } + else { + const v3Schema = schema; + rawShape = v3Schema.shape; + } + if (!rawShape) + return undefined; + if (typeof rawShape === 'function') { + try { + return rawShape(); + } + catch { + return undefined; + } + } + return rawShape; +} +// --- Schema normalization --- +/** + * Normalizes a schema to an object schema. Handles both: + * - Already-constructed object schemas (v3 or v4) + * - Raw shapes that need to be wrapped into object schemas + */ +function normalizeObjectSchema(schema) { + if (!schema) + return undefined; + // First check if it's a raw shape (Record) + // Raw shapes don't have _def or _zod properties and aren't schemas themselves + if (typeof schema === 'object') { + // Check if it's actually a ZodRawShapeCompat (not a schema instance) + // by checking if it lacks schema-like internal properties + const asV3 = schema; + const asV4 = schema; + // If it's not a schema instance (no _def or _zod), it might be a raw shape + if (!asV3._def && !asV4._zod) { + // Check if all values are schemas (heuristic to confirm it's a raw shape) + const values = Object.values(schema); + if (values.length > 0 && + values.every(v => typeof v === 'object' && + v !== null && + (v._def !== undefined || + v._zod !== undefined || + typeof v.parse === 'function'))) { + return objectFromShape(schema); + } + } + } + // If we get here, it should be an AnySchema (not a raw shape) + // Check if it's already an object schema + if (isZ4Schema(schema)) { + // Check if it's a v4 object + const v4Schema = schema; + const def = v4Schema._zod?.def; + if (def && (def.type === 'object' || def.shape !== undefined)) { + return schema; + } + } + else { + // Check if it's a v3 object + const v3Schema = schema; + if (v3Schema.shape !== undefined) { + return schema; + } + } + return undefined; +} +// --- Error message extraction --- +/** + * Safely extracts an error message from a parse result error. + * Zod errors can have different structures, so we handle various cases. + */ +function getParseErrorMessage(error) { + if (error && typeof error === 'object') { + // Try common error structures + if ('message' in error && typeof error.message === 'string') { + return error.message; + } + if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) { + const firstIssue = error.issues[0]; + if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) { + return String(firstIssue.message); + } + } + // Fallback: try to stringify the error + try { + return JSON.stringify(error); + } + catch { + return String(error); + } + } + return String(error); +} +// --- Schema metadata access --- +/** + * Gets the description from a schema, if available. + * Works with both Zod v3 and v4. + * + * Both versions expose a `.description` getter that returns the description + * from their respective internal storage (v3: _def, v4: globalRegistry). + */ +function getSchemaDescription(schema) { + return schema.description; +} +/** + * Checks if a schema is optional. + * Works with both Zod v3 and v4. + */ +function isSchemaOptional(schema) { + if (isZ4Schema(schema)) { + const v4Schema = schema; + return v4Schema._zod?.def?.type === 'optional'; + } + const v3Schema = schema; + // v3 has isOptional() method + if (typeof schema.isOptional === 'function') { + return schema.isOptional(); + } + return v3Schema._def?.typeName === 'ZodOptional'; +} +/** + * Gets the literal value from a schema, if it's a literal schema. + * Works with both Zod v3 and v4. + * Returns undefined if the schema is not a literal or the value cannot be determined. + */ +function getLiteralValue(schema) { + if (isZ4Schema(schema)) { + const v4Schema = schema; + const def = v4Schema._zod?.def; + if (def) { + // Try various ways to get the literal value + if (def.value !== undefined) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + } + const v3Schema = schema; + const def = v3Schema._def; + if (def) { + if (def.value !== undefined) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + // Fallback: check for direct value property (some Zod versions) + const directValue = schema.value; + if (directValue !== undefined) + return directValue; + return undefined; +} +//# sourceMappingURL=zod-compat.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.js.map new file mode 100644 index 000000000..d36391a97 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-compat.js","sourceRoot":"","sources":["../../../src/server/zod-compat.ts"],"names":[],"mappings":";AAAA,gBAAgB;AAChB,uDAAuD;AACvD,yDAAyD;AACzD,uDAAuD;;;;;;;;;;;;;;;;;;;;;;;;;AAqDvD,gCAIC;AAGD,0CAWC;AAGD,8BAYC;AAED,wCAYC;AAGD,wCAyBC;AAQD,sDAiDC;AAOD,oDAoBC;AAUD,oDAEC;AAMD,4CAWC;AAOD,0CAwBC;AA3QD,6CAA+B;AAC/B,oDAAsC;AA8CtC,4BAA4B;AAC5B,SAAgB,UAAU,CAAC,CAAY;IACnC,6DAA6D;IAC7D,MAAM,MAAM,GAAG,CAA6B,CAAC;IAC7C,OAAO,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;AACzB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AC;AAED;;;;GAIG;AACH,SAAgB,eAAe,CAAC,MAAiB;IAC7C,IAAI,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;QACrB,MAAM,QAAQ,GAAG,MAAkC,CAAC;QACpD,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,GAAG,CAAC;QAC/B,IAAI,GAAG,EAAE,CAAC;YACN,4CAA4C;YAC5C,IAAI,GAAG,CAAC,KAAK,KAAK,SAAS;gBAAE,OAAO,GAAG,CAAC,KAAK,CAAC;YAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACrD,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACzB,CAAC;QACL,CAAC;IACL,CAAC;IACD,MAAM,QAAQ,GAAG,MAAkC,CAAC;IACpD,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC;IAC1B,IAAI,GAAG,EAAE,CAAC;QACN,IAAI,GAAG,CAAC,KAAK,KAAK,SAAS;YAAE,OAAO,GAAG,CAAC,KAAK,CAAC;QAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrD,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QACzB,CAAC;IACL,CAAC;IACD,gEAAgE;IAChE,MAAM,WAAW,GAAI,MAA8B,CAAC,KAAK,CAAC;IAC1D,IAAI,WAAW,KAAK,SAAS;QAAE,OAAO,WAAW,CAAC;IAClD,OAAO,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-json-schema-compat.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-json-schema-compat.d.ts new file mode 100644 index 000000000..3a04452b4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-json-schema-compat.d.ts @@ -0,0 +1,12 @@ +import { AnySchema, AnyObjectSchema } from './zod-compat.js'; +type JsonSchema = Record; +type CommonOpts = { + strictUnions?: boolean; + pipeStrategy?: 'input' | 'output'; + target?: 'jsonSchema7' | 'draft-7' | 'jsonSchema2019-09' | 'draft-2020-12'; +}; +export declare function toJsonSchemaCompat(schema: AnyObjectSchema, opts?: CommonOpts): JsonSchema; +export declare function getMethodLiteral(schema: AnyObjectSchema): string; +export declare function parseWithCompat(schema: AnySchema, data: unknown): unknown; +export {}; +//# sourceMappingURL=zod-json-schema-compat.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-json-schema-compat.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-json-schema-compat.d.ts.map new file mode 100644 index 000000000..0b851bf50 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-json-schema-compat.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-json-schema-compat.d.ts","sourceRoot":"","sources":["../../../src/server/zod-json-schema-compat.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,SAAS,EAAE,eAAe,EAA0D,MAAM,iBAAiB,CAAC;AAGrH,KAAK,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAG1C,KAAK,UAAU,GAAG;IACd,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;IAClC,MAAM,CAAC,EAAE,aAAa,GAAG,SAAS,GAAG,mBAAmB,GAAG,eAAe,CAAC;CAC9E,CAAC;AASF,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAczF;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,eAAe,GAAG,MAAM,CAahE;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAMzE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-json-schema-compat.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-json-schema-compat.js new file mode 100644 index 000000000..bc067dad0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-json-schema-compat.js @@ -0,0 +1,79 @@ +"use strict"; +// zod-json-schema-compat.ts +// ---------------------------------------------------- +// JSON Schema conversion for both Zod v3 and Zod v4 (Mini) +// v3 uses your vendored converter; v4 uses Mini's toJSONSchema +// ---------------------------------------------------- +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toJsonSchemaCompat = toJsonSchemaCompat; +exports.getMethodLiteral = getMethodLiteral; +exports.parseWithCompat = parseWithCompat; +const z4mini = __importStar(require("zod/v4-mini")); +const zod_compat_js_1 = require("./zod-compat.js"); +const zod_to_json_schema_1 = require("zod-to-json-schema"); +function mapMiniTarget(t) { + if (!t) + return 'draft-7'; + if (t === 'jsonSchema7' || t === 'draft-7') + return 'draft-7'; + if (t === 'jsonSchema2019-09' || t === 'draft-2020-12') + return 'draft-2020-12'; + return 'draft-7'; // fallback +} +function toJsonSchemaCompat(schema, opts) { + if ((0, zod_compat_js_1.isZ4Schema)(schema)) { + // v4 branch — use Mini's built-in toJSONSchema + return z4mini.toJSONSchema(schema, { + target: mapMiniTarget(opts?.target), + io: opts?.pipeStrategy ?? 'input' + }); + } + // v3 branch — use vendored converter + return (0, zod_to_json_schema_1.zodToJsonSchema)(schema, { + strictUnions: opts?.strictUnions ?? true, + pipeStrategy: opts?.pipeStrategy ?? 'input' + }); +} +function getMethodLiteral(schema) { + const shape = (0, zod_compat_js_1.getObjectShape)(schema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + const value = (0, zod_compat_js_1.getLiteralValue)(methodSchema); + if (typeof value !== 'string') { + throw new Error('Schema method literal must be a string'); + } + return value; +} +function parseWithCompat(schema, data) { + const result = (0, zod_compat_js_1.safeParse)(schema, data); + if (!result.success) { + throw result.error; + } + return result.data; +} +//# sourceMappingURL=zod-json-schema-compat.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-json-schema-compat.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-json-schema-compat.js.map new file mode 100644 index 000000000..627929d8c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-json-schema-compat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-json-schema-compat.js","sourceRoot":"","sources":["../../../src/server/zod-json-schema-compat.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,uDAAuD;AACvD,2DAA2D;AAC3D,+DAA+D;AAC/D,uDAAuD;;;;;;;;;;;;;;;;;;;;;;;;;AA0BvD,gDAcC;AAED,4CAaC;AAED,0CAMC;AA1DD,oDAAsC;AAEtC,mDAAqH;AACrH,2DAAqD;AAWrD,SAAS,aAAa,C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AAC,MAAiB,EAAE,IAAa;IAC5D,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACvC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QAClB,MAAM,MAAM,CAAC,KAAK,CAAC;IACvB,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC;AACvB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth-utils.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth-utils.d.ts new file mode 100644 index 000000000..c966e30e7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth-utils.d.ts @@ -0,0 +1,23 @@ +/** + * Utilities for handling OAuth resource URIs. + */ +/** + * Converts a server URL to a resource URL by removing the fragment. + * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". + * Keeps everything else unchanged (scheme, domain, port, path, query). + */ +export declare function resourceUrlFromServerUrl(url: URL | string): URL; +/** + * Checks if a requested resource URL matches a configured resource URL. + * A requested resource matches if it has the same scheme, domain, port, + * and its path starts with the configured resource's path. + * + * @param requestedResource The resource URL being requested + * @param configuredResource The resource URL that has been configured + * @returns true if the requested resource matches the configured resource, false otherwise + */ +export declare function checkResourceAllowed({ requestedResource, configuredResource }: { + requestedResource: URL | string; + configuredResource: URL | string; +}): boolean; +//# sourceMappingURL=auth-utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth-utils.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth-utils.d.ts.map new file mode 100644 index 000000000..30873de55 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth-utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-utils.d.ts","sourceRoot":"","sources":["../../../src/shared/auth-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,GAAG,GAAG,CAI/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,EACjC,iBAAiB,EACjB,kBAAkB,EACrB,EAAE;IACC,iBAAiB,EAAE,GAAG,GAAG,MAAM,CAAC;IAChC,kBAAkB,EAAE,GAAG,GAAG,MAAM,CAAC;CACpC,GAAG,OAAO,CAwBV"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth-utils.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth-utils.js new file mode 100644 index 000000000..f2fe61734 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth-utils.js @@ -0,0 +1,48 @@ +"use strict"; +/** + * Utilities for handling OAuth resource URIs. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resourceUrlFromServerUrl = resourceUrlFromServerUrl; +exports.checkResourceAllowed = checkResourceAllowed; +/** + * Converts a server URL to a resource URL by removing the fragment. + * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". + * Keeps everything else unchanged (scheme, domain, port, path, query). + */ +function resourceUrlFromServerUrl(url) { + const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href); + resourceURL.hash = ''; // Remove fragment + return resourceURL; +} +/** + * Checks if a requested resource URL matches a configured resource URL. + * A requested resource matches if it has the same scheme, domain, port, + * and its path starts with the configured resource's path. + * + * @param requestedResource The resource URL being requested + * @param configuredResource The resource URL that has been configured + * @returns true if the requested resource matches the configured resource, false otherwise + */ +function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href); + // Compare the origin (scheme, domain, and port) + if (requested.origin !== configured.origin) { + return false; + } + // Handle cases like requested=/foo and configured=/foo/ + if (requested.pathname.length < configured.pathname.length) { + return false; + } + // Check if the requested path starts with the configured path + // Ensure both paths end with / for proper comparison + // This ensures that if we have paths like "/api" and "/api/users", + // we properly detect that "/api/users" is a subpath of "/api" + // By adding a trailing slash if missing, we avoid false positives + // where paths like "/api123" would incorrectly match "/api" + const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/'; + const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/'; + return requestedPath.startsWith(configuredPath); +} +//# sourceMappingURL=auth-utils.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth-utils.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth-utils.js.map new file mode 100644 index 000000000..4a71b257b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-utils.js","sourceRoot":"","sources":["../../../src/shared/auth-utils.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAOH,4DAIC;AAWD,oDA8BC;AAlDD;;;;GAIG;AACH,SAAgB,wBAAwB,CAAC,GAAiB;IACtD,MAAM,WAAW,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC/E,WAAW,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,kBAAkB;IACzC,OAAO,WAAW,CAAC;AACvB,CAAC;AAED;;;;;;;;GAQG;AACH,SAAgB,oBAAoB,CAAC,EACjC,iBAAiB,EACjB,kBAAkB,EAIrB;IACG,MAAM,SAAS,GAAG,OAAO,iBAAiB,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACvH,MAAM,UAAU,GAAG,OAAO,kBAAkB,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IAE3H,gDAAgD;IAChD,IAAI,SAAS,CAAC,MAAM,KAAK,UAAU,CAAC,MAAM,EAAE,CAAC;QACzC,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,wDAAwD;IACxD,IAAI,SAAS,CAAC,QAAQ,CAAC,MAAM,GAAG,UAAU,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QACzD,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,8DAA8D;IAC9D,qDAAqD;IACrD,mEAAmE;IACnE,8DAA8D;IAC9D,kEAAkE;IAClE,4DAA4D;IAC5D,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,GAAG,GAAG,CAAC;IACvG,MAAM,cAAc,GAAG,UAAU,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,GAAG,GAAG,CAAC;IAE3G,OAAO,aAAa,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;AACpD,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth.d.ts new file mode 100644 index 000000000..4e47be12b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth.d.ts @@ -0,0 +1,240 @@ +import * as z from 'zod/v4'; +/** + * Reusable URL validation that disallows javascript: scheme + */ +export declare const SafeUrlSchema: z.ZodURL; +/** + * RFC 9728 OAuth Protected Resource Metadata + */ +export declare const OAuthProtectedResourceMetadataSchema: z.ZodObject<{ + resource: z.ZodString; + authorization_servers: z.ZodOptional>; + jwks_uri: z.ZodOptional; + scopes_supported: z.ZodOptional>; + bearer_methods_supported: z.ZodOptional>; + resource_signing_alg_values_supported: z.ZodOptional>; + resource_name: z.ZodOptional; + resource_documentation: z.ZodOptional; + resource_policy_uri: z.ZodOptional; + resource_tos_uri: z.ZodOptional; + tls_client_certificate_bound_access_tokens: z.ZodOptional; + authorization_details_types_supported: z.ZodOptional>; + dpop_signing_alg_values_supported: z.ZodOptional>; + dpop_bound_access_tokens_required: z.ZodOptional; +}, z.core.$loose>; +/** + * RFC 8414 OAuth 2.0 Authorization Server Metadata + */ +export declare const OAuthMetadataSchema: z.ZodObject<{ + issuer: z.ZodString; + authorization_endpoint: z.ZodURL; + token_endpoint: z.ZodURL; + registration_endpoint: z.ZodOptional; + scopes_supported: z.ZodOptional>; + response_types_supported: z.ZodArray; + response_modes_supported: z.ZodOptional>; + grant_types_supported: z.ZodOptional>; + token_endpoint_auth_methods_supported: z.ZodOptional>; + token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + service_documentation: z.ZodOptional; + revocation_endpoint: z.ZodOptional; + revocation_endpoint_auth_methods_supported: z.ZodOptional>; + revocation_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + introspection_endpoint: z.ZodOptional; + introspection_endpoint_auth_methods_supported: z.ZodOptional>; + introspection_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + code_challenge_methods_supported: z.ZodOptional>; + client_id_metadata_document_supported: z.ZodOptional; +}, z.core.$loose>; +/** + * OpenID Connect Discovery 1.0 Provider Metadata + * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +export declare const OpenIdProviderMetadataSchema: z.ZodObject<{ + issuer: z.ZodString; + authorization_endpoint: z.ZodURL; + token_endpoint: z.ZodURL; + userinfo_endpoint: z.ZodOptional; + jwks_uri: z.ZodURL; + registration_endpoint: z.ZodOptional; + scopes_supported: z.ZodOptional>; + response_types_supported: z.ZodArray; + response_modes_supported: z.ZodOptional>; + grant_types_supported: z.ZodOptional>; + acr_values_supported: z.ZodOptional>; + subject_types_supported: z.ZodArray; + id_token_signing_alg_values_supported: z.ZodArray; + id_token_encryption_alg_values_supported: z.ZodOptional>; + id_token_encryption_enc_values_supported: z.ZodOptional>; + userinfo_signing_alg_values_supported: z.ZodOptional>; + userinfo_encryption_alg_values_supported: z.ZodOptional>; + userinfo_encryption_enc_values_supported: z.ZodOptional>; + request_object_signing_alg_values_supported: z.ZodOptional>; + request_object_encryption_alg_values_supported: z.ZodOptional>; + request_object_encryption_enc_values_supported: z.ZodOptional>; + token_endpoint_auth_methods_supported: z.ZodOptional>; + token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + display_values_supported: z.ZodOptional>; + claim_types_supported: z.ZodOptional>; + claims_supported: z.ZodOptional>; + service_documentation: z.ZodOptional; + claims_locales_supported: z.ZodOptional>; + ui_locales_supported: z.ZodOptional>; + claims_parameter_supported: z.ZodOptional; + request_parameter_supported: z.ZodOptional; + request_uri_parameter_supported: z.ZodOptional; + require_request_uri_registration: z.ZodOptional; + op_policy_uri: z.ZodOptional; + op_tos_uri: z.ZodOptional; + client_id_metadata_document_supported: z.ZodOptional; +}, z.core.$loose>; +/** + * OpenID Connect Discovery metadata that may include OAuth 2.0 fields + * This schema represents the real-world scenario where OIDC providers + * return a mix of OpenID Connect and OAuth 2.0 metadata fields + */ +export declare const OpenIdProviderDiscoveryMetadataSchema: z.ZodObject<{ + code_challenge_methods_supported: z.ZodOptional>; + issuer: z.ZodString; + authorization_endpoint: z.ZodURL; + token_endpoint: z.ZodURL; + userinfo_endpoint: z.ZodOptional; + jwks_uri: z.ZodURL; + registration_endpoint: z.ZodOptional; + scopes_supported: z.ZodOptional>; + response_types_supported: z.ZodArray; + response_modes_supported: z.ZodOptional>; + grant_types_supported: z.ZodOptional>; + acr_values_supported: z.ZodOptional>; + subject_types_supported: z.ZodArray; + id_token_signing_alg_values_supported: z.ZodArray; + id_token_encryption_alg_values_supported: z.ZodOptional>; + id_token_encryption_enc_values_supported: z.ZodOptional>; + userinfo_signing_alg_values_supported: z.ZodOptional>; + userinfo_encryption_alg_values_supported: z.ZodOptional>; + userinfo_encryption_enc_values_supported: z.ZodOptional>; + request_object_signing_alg_values_supported: z.ZodOptional>; + request_object_encryption_alg_values_supported: z.ZodOptional>; + request_object_encryption_enc_values_supported: z.ZodOptional>; + token_endpoint_auth_methods_supported: z.ZodOptional>; + token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + display_values_supported: z.ZodOptional>; + claim_types_supported: z.ZodOptional>; + claims_supported: z.ZodOptional>; + service_documentation: z.ZodOptional; + claims_locales_supported: z.ZodOptional>; + ui_locales_supported: z.ZodOptional>; + claims_parameter_supported: z.ZodOptional; + request_parameter_supported: z.ZodOptional; + request_uri_parameter_supported: z.ZodOptional; + require_request_uri_registration: z.ZodOptional; + op_policy_uri: z.ZodOptional; + op_tos_uri: z.ZodOptional; + client_id_metadata_document_supported: z.ZodOptional; +}, z.core.$strip>; +/** + * OAuth 2.1 token response + */ +export declare const OAuthTokensSchema: z.ZodObject<{ + access_token: z.ZodString; + id_token: z.ZodOptional; + token_type: z.ZodString; + expires_in: z.ZodOptional>; + scope: z.ZodOptional; + refresh_token: z.ZodOptional; +}, z.core.$strip>; +/** + * OAuth 2.1 error response + */ +export declare const OAuthErrorResponseSchema: z.ZodObject<{ + error: z.ZodString; + error_description: z.ZodOptional; + error_uri: z.ZodOptional; +}, z.core.$strip>; +/** + * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri + */ +export declare const OptionalSafeUrlSchema: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata + */ +export declare const OAuthClientMetadataSchema: z.ZodObject<{ + redirect_uris: z.ZodArray; + token_endpoint_auth_method: z.ZodOptional; + grant_types: z.ZodOptional>; + response_types: z.ZodOptional>; + client_name: z.ZodOptional; + client_uri: z.ZodOptional; + logo_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + scope: z.ZodOptional; + contacts: z.ZodOptional>; + tos_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + policy_uri: z.ZodOptional; + jwks_uri: z.ZodOptional; + jwks: z.ZodOptional; + software_id: z.ZodOptional; + software_version: z.ZodOptional; + software_statement: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration client information + */ +export declare const OAuthClientInformationSchema: z.ZodObject<{ + client_id: z.ZodString; + client_secret: z.ZodOptional; + client_id_issued_at: z.ZodOptional; + client_secret_expires_at: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) + */ +export declare const OAuthClientInformationFullSchema: z.ZodObject<{ + redirect_uris: z.ZodArray; + token_endpoint_auth_method: z.ZodOptional; + grant_types: z.ZodOptional>; + response_types: z.ZodOptional>; + client_name: z.ZodOptional; + client_uri: z.ZodOptional; + logo_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + scope: z.ZodOptional; + contacts: z.ZodOptional>; + tos_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + policy_uri: z.ZodOptional; + jwks_uri: z.ZodOptional; + jwks: z.ZodOptional; + software_id: z.ZodOptional; + software_version: z.ZodOptional; + software_statement: z.ZodOptional; + client_id: z.ZodString; + client_secret: z.ZodOptional; + client_id_issued_at: z.ZodOptional; + client_secret_expires_at: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration error response + */ +export declare const OAuthClientRegistrationErrorSchema: z.ZodObject<{ + error: z.ZodString; + error_description: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7009 OAuth 2.0 Token Revocation request + */ +export declare const OAuthTokenRevocationRequestSchema: z.ZodObject<{ + token: z.ZodString; + token_type_hint: z.ZodOptional; +}, z.core.$strip>; +export type OAuthMetadata = z.infer; +export type OpenIdProviderMetadata = z.infer; +export type OpenIdProviderDiscoveryMetadata = z.infer; +export type OAuthTokens = z.infer; +export type OAuthErrorResponse = z.infer; +export type OAuthClientMetadata = z.infer; +export type OAuthClientInformation = z.infer; +export type OAuthClientInformationFull = z.infer; +export type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull; +export type OAuthClientRegistrationError = z.infer; +export type OAuthTokenRevocationRequest = z.infer; +export type OAuthProtectedResourceMetadata = z.infer; +export type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscoveryMetadata; +//# sourceMappingURL=auth.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth.d.ts.map new file mode 100644 index 000000000..031a88fb9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/shared/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B;;GAEG;AACH,eAAO,MAAM,aAAa,UAmBrB,CAAC;AAEN;;GAEG;AACH,eAAO,MAAM,oCAAoC;;;;;;;;;;;;;;;iBAe/C,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;iBAoB9B,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqCvC,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,qCAAqC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAKhD,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;iBASlB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kC,CAAC,CAAC;AAC9F,MAAM,MAAM,2BAA2B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iCAAiC,CAAC,CAAC;AAC5F,MAAM,MAAM,8BAA8B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oCAAoC,CAAC,CAAC;AAGlG,MAAM,MAAM,2BAA2B,GAAG,aAAa,GAAG,+BAA+B,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth.js new file mode 100644 index 000000000..97217c9c8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth.js @@ -0,0 +1,224 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OAuthTokenRevocationRequestSchema = exports.OAuthClientRegistrationErrorSchema = exports.OAuthClientInformationFullSchema = exports.OAuthClientInformationSchema = exports.OAuthClientMetadataSchema = exports.OptionalSafeUrlSchema = exports.OAuthErrorResponseSchema = exports.OAuthTokensSchema = exports.OpenIdProviderDiscoveryMetadataSchema = exports.OpenIdProviderMetadataSchema = exports.OAuthMetadataSchema = exports.OAuthProtectedResourceMetadataSchema = exports.SafeUrlSchema = void 0; +const z = __importStar(require("zod/v4")); +/** + * Reusable URL validation that disallows javascript: scheme + */ +exports.SafeUrlSchema = z + .url() + .superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'URL must be parseable', + fatal: true + }); + return z.NEVER; + } +}) + .refine(url => { + const u = new URL(url); + return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:'; +}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' }); +/** + * RFC 9728 OAuth Protected Resource Metadata + */ +exports.OAuthProtectedResourceMetadataSchema = z.looseObject({ + resource: z.string().url(), + authorization_servers: z.array(exports.SafeUrlSchema).optional(), + jwks_uri: z.string().url().optional(), + scopes_supported: z.array(z.string()).optional(), + bearer_methods_supported: z.array(z.string()).optional(), + resource_signing_alg_values_supported: z.array(z.string()).optional(), + resource_name: z.string().optional(), + resource_documentation: z.string().optional(), + resource_policy_uri: z.string().url().optional(), + resource_tos_uri: z.string().url().optional(), + tls_client_certificate_bound_access_tokens: z.boolean().optional(), + authorization_details_types_supported: z.array(z.string()).optional(), + dpop_signing_alg_values_supported: z.array(z.string()).optional(), + dpop_bound_access_tokens_required: z.boolean().optional() +}); +/** + * RFC 8414 OAuth 2.0 Authorization Server Metadata + */ +exports.OAuthMetadataSchema = z.looseObject({ + issuer: z.string(), + authorization_endpoint: exports.SafeUrlSchema, + token_endpoint: exports.SafeUrlSchema, + registration_endpoint: exports.SafeUrlSchema.optional(), + scopes_supported: z.array(z.string()).optional(), + response_types_supported: z.array(z.string()), + response_modes_supported: z.array(z.string()).optional(), + grant_types_supported: z.array(z.string()).optional(), + token_endpoint_auth_methods_supported: z.array(z.string()).optional(), + token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + service_documentation: exports.SafeUrlSchema.optional(), + revocation_endpoint: exports.SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + introspection_endpoint: z.string().optional(), + introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + code_challenge_methods_supported: z.array(z.string()).optional(), + client_id_metadata_document_supported: z.boolean().optional() +}); +/** + * OpenID Connect Discovery 1.0 Provider Metadata + * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +exports.OpenIdProviderMetadataSchema = z.looseObject({ + issuer: z.string(), + authorization_endpoint: exports.SafeUrlSchema, + token_endpoint: exports.SafeUrlSchema, + userinfo_endpoint: exports.SafeUrlSchema.optional(), + jwks_uri: exports.SafeUrlSchema, + registration_endpoint: exports.SafeUrlSchema.optional(), + scopes_supported: z.array(z.string()).optional(), + response_types_supported: z.array(z.string()), + response_modes_supported: z.array(z.string()).optional(), + grant_types_supported: z.array(z.string()).optional(), + acr_values_supported: z.array(z.string()).optional(), + subject_types_supported: z.array(z.string()), + id_token_signing_alg_values_supported: z.array(z.string()), + id_token_encryption_alg_values_supported: z.array(z.string()).optional(), + id_token_encryption_enc_values_supported: z.array(z.string()).optional(), + userinfo_signing_alg_values_supported: z.array(z.string()).optional(), + userinfo_encryption_alg_values_supported: z.array(z.string()).optional(), + userinfo_encryption_enc_values_supported: z.array(z.string()).optional(), + request_object_signing_alg_values_supported: z.array(z.string()).optional(), + request_object_encryption_alg_values_supported: z.array(z.string()).optional(), + request_object_encryption_enc_values_supported: z.array(z.string()).optional(), + token_endpoint_auth_methods_supported: z.array(z.string()).optional(), + token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + display_values_supported: z.array(z.string()).optional(), + claim_types_supported: z.array(z.string()).optional(), + claims_supported: z.array(z.string()).optional(), + service_documentation: z.string().optional(), + claims_locales_supported: z.array(z.string()).optional(), + ui_locales_supported: z.array(z.string()).optional(), + claims_parameter_supported: z.boolean().optional(), + request_parameter_supported: z.boolean().optional(), + request_uri_parameter_supported: z.boolean().optional(), + require_request_uri_registration: z.boolean().optional(), + op_policy_uri: exports.SafeUrlSchema.optional(), + op_tos_uri: exports.SafeUrlSchema.optional(), + client_id_metadata_document_supported: z.boolean().optional() +}); +/** + * OpenID Connect Discovery metadata that may include OAuth 2.0 fields + * This schema represents the real-world scenario where OIDC providers + * return a mix of OpenID Connect and OAuth 2.0 metadata fields + */ +exports.OpenIdProviderDiscoveryMetadataSchema = z.object({ + ...exports.OpenIdProviderMetadataSchema.shape, + ...exports.OAuthMetadataSchema.pick({ + code_challenge_methods_supported: true + }).shape +}); +/** + * OAuth 2.1 token response + */ +exports.OAuthTokensSchema = z + .object({ + access_token: z.string(), + id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect + token_type: z.string(), + expires_in: z.coerce.number().optional(), + scope: z.string().optional(), + refresh_token: z.string().optional() +}) + .strip(); +/** + * OAuth 2.1 error response + */ +exports.OAuthErrorResponseSchema = z.object({ + error: z.string(), + error_description: z.string().optional(), + error_uri: z.string().optional() +}); +/** + * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri + */ +exports.OptionalSafeUrlSchema = exports.SafeUrlSchema.optional().or(z.literal('').transform(() => undefined)); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata + */ +exports.OAuthClientMetadataSchema = z + .object({ + redirect_uris: z.array(exports.SafeUrlSchema), + token_endpoint_auth_method: z.string().optional(), + grant_types: z.array(z.string()).optional(), + response_types: z.array(z.string()).optional(), + client_name: z.string().optional(), + client_uri: exports.SafeUrlSchema.optional(), + logo_uri: exports.OptionalSafeUrlSchema, + scope: z.string().optional(), + contacts: z.array(z.string()).optional(), + tos_uri: exports.OptionalSafeUrlSchema, + policy_uri: z.string().optional(), + jwks_uri: exports.SafeUrlSchema.optional(), + jwks: z.any().optional(), + software_id: z.string().optional(), + software_version: z.string().optional(), + software_statement: z.string().optional() +}) + .strip(); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration client information + */ +exports.OAuthClientInformationSchema = z + .object({ + client_id: z.string(), + client_secret: z.string().optional(), + client_id_issued_at: z.number().optional(), + client_secret_expires_at: z.number().optional() +}) + .strip(); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) + */ +exports.OAuthClientInformationFullSchema = exports.OAuthClientMetadataSchema.merge(exports.OAuthClientInformationSchema); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration error response + */ +exports.OAuthClientRegistrationErrorSchema = z + .object({ + error: z.string(), + error_description: z.string().optional() +}) + .strip(); +/** + * RFC 7009 OAuth 2.0 Token Revocation request + */ +exports.OAuthTokenRevocationRequestSchema = z + .object({ + token: z.string(), + token_type_hint: z.string().optional() +}) + .strip(); +//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth.js.map new file mode 100644 index 000000000..310255ae1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/auth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/shared/auth.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAA4B;AAE5B;;GAEG;AACU,QAAA,aAAa,GAAG,CAAC;KACzB,GAAG,EAAE;KACL,WAAW,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;IACtB,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,GAAG,CAAC,QAAQ,CAAC;YACT,IAAI,EAAE,CAAC,CAAC,YAAY,CAAC,MAAM;YAC3B,OAAO,EAAE,uBAAuB;YAChC,KAAK,EAAE,IAAI;SACd,CAAC,CAAC;QAEH,OAAO,CAAC,CAAC,KAAK,CAAC;IACnB,CAAC;AACL,CAAC,CAAC;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ACjB,eAAe,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACzC,CAAC;KACD,KAAK,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/metadataUtils.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/metadataUtils.d.ts new file mode 100644 index 000000000..9dff76dae --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/metadataUtils.d.ts @@ -0,0 +1,16 @@ +import { BaseMetadata } from '../types.js'; +/** + * Utilities for working with BaseMetadata objects. + */ +/** + * Gets the display name for an object with BaseMetadata. + * For tools, the precedence is: title → annotations.title → name + * For other objects: title → name + * This implements the spec requirement: "if no title is provided, name should be used for display purposes" + */ +export declare function getDisplayName(metadata: BaseMetadata | (BaseMetadata & { + annotations?: { + title?: string; + }; +})): string; +//# sourceMappingURL=metadataUtils.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/metadataUtils.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/metadataUtils.d.ts.map new file mode 100644 index 000000000..9d9929c54 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/metadataUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metadataUtils.d.ts","sourceRoot":"","sources":["../../../src/shared/metadataUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C;;GAEG;AAEH;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,YAAY,GAAG,CAAC,YAAY,GAAG;IAAE,WAAW,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAAC,GAAG,MAAM,CAarH"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/metadataUtils.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/metadataUtils.js new file mode 100644 index 000000000..2e50da63f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/metadataUtils.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getDisplayName = getDisplayName; +/** + * Utilities for working with BaseMetadata objects. + */ +/** + * Gets the display name for an object with BaseMetadata. + * For tools, the precedence is: title → annotations.title → name + * For other objects: title → name + * This implements the spec requirement: "if no title is provided, name should be used for display purposes" + */ +function getDisplayName(metadata) { + // First check for title (not undefined and not empty string) + if (metadata.title !== undefined && metadata.title !== '') { + return metadata.title; + } + // Then check for annotations.title (only present in Tool objects) + if ('annotations' in metadata && metadata.annotations?.title) { + return metadata.annotations.title; + } + // Finally fall back to name + return metadata.name; +} +//# sourceMappingURL=metadataUtils.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/metadataUtils.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/metadataUtils.js.map new file mode 100644 index 000000000..a334dbdbd --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/metadataUtils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metadataUtils.js","sourceRoot":"","sources":["../../../src/shared/metadataUtils.ts"],"names":[],"mappings":";;AAYA,wCAaC;AAvBD;;GAEG;AAEH;;;;;GAKG;AACH,SAAgB,cAAc,CAAC,QAA8E;IACzG,6DAA6D;IAC7D,IAAI,QAAQ,CAAC,KAAK,KAAK,SAAS,IAAI,QAAQ,CAAC,KAAK,KAAK,EAAE,EAAE,CAAC;QACxD,OAAO,QAAQ,CAAC,KAAK,CAAC;IAC1B,CAAC;IAED,kEAAkE;IAClE,IAAI,aAAa,IAAI,QAAQ,IAAI,QAAQ,CAAC,WAAW,EAAE,KAAK,EAAE,CAAC;QAC3D,OAAO,QAAQ,CAAC,WAAW,CAAC,KAAK,CAAC;IACtC,CAAC;IAED,4BAA4B;IAC5B,OAAO,QAAQ,CAAC,IAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/protocol.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/protocol.d.ts new file mode 100644 index 000000000..808bfedf7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/protocol.d.ts @@ -0,0 +1,443 @@ +import { AnySchema, AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js'; +import { ClientCapabilities, GetTaskRequest, GetTaskPayloadRequest, ListTasksResultSchema, CancelTaskResultSchema, JSONRPCRequest, Progress, RequestId, Result, ServerCapabilities, RequestMeta, RequestInfo, GetTaskResult, TaskCreationParams, RelatedTaskMetadata, Task, Request, Notification } from '../types.js'; +import { Transport, TransportSendOptions } from './transport.js'; +import { AuthInfo } from '../server/auth/types.js'; +import { TaskStore, TaskMessageQueue, CreateTaskOptions } from '../experimental/tasks/interfaces.js'; +import { ResponseMessage } from './responseMessage.js'; +/** + * Callback for progress notifications. + */ +export type ProgressCallback = (progress: Progress) => void; +/** + * Additional initialization options. + */ +export type ProtocolOptions = { + /** + * Whether to restrict emitted requests to only those that the remote side has indicated that they can handle, through their advertised capabilities. + * + * Note that this DOES NOT affect checking of _local_ side capabilities, as it is considered a logic error to mis-specify those. + * + * Currently this defaults to false, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to true. + */ + enforceStrictCapabilities?: boolean; + /** + * An array of notification method names that should be automatically debounced. + * Any notifications with a method in this list will be coalesced if they + * occur in the same tick of the event loop. + * e.g., ['notifications/tools/list_changed'] + */ + debouncedNotificationMethods?: string[]; + /** + * Optional task storage implementation. If provided, enables task-related request handlers + * and provides task storage capabilities to request handlers. + */ + taskStore?: TaskStore; + /** + * Optional task message queue implementation for managing server-initiated messages + * that will be delivered through the tasks/result response stream. + */ + taskMessageQueue?: TaskMessageQueue; + /** + * Default polling interval (in milliseconds) for task status checks when no pollInterval + * is provided by the server. Defaults to 5000ms if not specified. + */ + defaultTaskPollInterval?: number; + /** + * Maximum number of messages that can be queued per task for side-channel delivery. + * If undefined, the queue size is unbounded. + * When the limit is exceeded, the TaskMessageQueue implementation's enqueue() method + * will throw an error. It's the implementation's responsibility to handle overflow + * appropriately (e.g., by failing the task, dropping messages, etc.). + */ + maxTaskQueueSize?: number; +}; +/** + * The default request timeout, in miliseconds. + */ +export declare const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; +/** + * Options that can be given per request. + */ +export type RequestOptions = { + /** + * If set, requests progress notifications from the remote end (if supported). When progress notifications are received, this callback will be invoked. + * + * For task-augmented requests: progress notifications continue after CreateTaskResult is returned and stop automatically when the task reaches a terminal status. + */ + onprogress?: ProgressCallback; + /** + * Can be used to cancel an in-flight request. This will cause an AbortError to be raised from request(). + */ + signal?: AbortSignal; + /** + * A timeout (in milliseconds) for this request. If exceeded, an McpError with code `RequestTimeout` will be raised from request(). + * + * If not specified, `DEFAULT_REQUEST_TIMEOUT_MSEC` will be used as the timeout. + */ + timeout?: number; + /** + * If true, receiving a progress notification will reset the request timeout. + * This is useful for long-running operations that send periodic progress updates. + * Default: false + */ + resetTimeoutOnProgress?: boolean; + /** + * Maximum total time (in milliseconds) to wait for a response. + * If exceeded, an McpError with code `RequestTimeout` will be raised, regardless of progress notifications. + * If not specified, there is no maximum total timeout. + */ + maxTotalTimeout?: number; + /** + * If provided, augments the request with task creation parameters to enable call-now, fetch-later execution patterns. + */ + task?: TaskCreationParams; + /** + * If provided, associates this request with a related task. + */ + relatedTask?: RelatedTaskMetadata; +} & TransportSendOptions; +/** + * Options that can be given per notification. + */ +export type NotificationOptions = { + /** + * May be used to indicate to the transport which incoming request to associate this outgoing notification with. + */ + relatedRequestId?: RequestId; + /** + * If provided, associates this notification with a related task. + */ + relatedTask?: RelatedTaskMetadata; +}; +/** + * Options that can be given per request. + */ +export type TaskRequestOptions = Omit; +/** + * Request-scoped TaskStore interface. + */ +export interface RequestTaskStore { + /** + * Creates a new task with the given creation parameters. + * The implementation generates a unique taskId and createdAt timestamp. + * + * @param taskParams - The task creation parameters from the request + * @returns The created task object + */ + createTask(taskParams: CreateTaskOptions): Promise; + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @returns The task object + * @throws If the task does not exist + */ + getTask(taskId: string): Promise; + /** + * Stores the result of a task and sets its final status. + * + * @param taskId - The task identifier + * @param status - The final status: 'completed' for success, 'failed' for errors + * @param result - The result to store + */ + storeTaskResult(taskId: string, status: 'completed' | 'failed', result: Result): Promise; + /** + * Retrieves the stored result of a task. + * + * @param taskId - The task identifier + * @returns The stored result + */ + getTaskResult(taskId: string): Promise; + /** + * Updates a task's status (e.g., to 'cancelled', 'failed', 'completed'). + * + * @param taskId - The task identifier + * @param status - The new status + * @param statusMessage - Optional diagnostic message for failed tasks or other status information + */ + updateTaskStatus(taskId: string, status: Task['status'], statusMessage?: string): Promise; + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @param cursor - Optional cursor for pagination + * @returns An object containing the tasks array and an optional nextCursor + */ + listTasks(cursor?: string): Promise<{ + tasks: Task[]; + nextCursor?: string; + }>; +} +/** + * Extra data given to request handlers. + */ +export type RequestHandlerExtra = { + /** + * An abort signal used to communicate if the request was cancelled from the sender's side. + */ + signal: AbortSignal; + /** + * Information about a validated access token, provided to request handlers. + */ + authInfo?: AuthInfo; + /** + * The session ID from the transport, if available. + */ + sessionId?: string; + /** + * Metadata from the original request. + */ + _meta?: RequestMeta; + /** + * The JSON-RPC ID of the request being handled. + * This can be useful for tracking or logging purposes. + */ + requestId: RequestId; + taskId?: string; + taskStore?: RequestTaskStore; + taskRequestedTtl?: number | null; + /** + * The original HTTP request. + */ + requestInfo?: RequestInfo; + /** + * Sends a notification that relates to the current request being handled. + * + * This is used by certain transports to correctly associate related messages. + */ + sendNotification: (notification: SendNotificationT) => Promise; + /** + * Sends a request that relates to the current request being handled. + * + * This is used by certain transports to correctly associate related messages. + */ + sendRequest: (request: SendRequestT, resultSchema: U, options?: TaskRequestOptions) => Promise>; + /** + * Closes the SSE stream for this request, triggering client reconnection. + * Only available when using StreamableHTTPServerTransport with eventStore configured. + * Use this to implement polling behavior during long-running operations. + */ + closeSSEStream?: () => void; + /** + * Closes the standalone GET SSE stream, triggering client reconnection. + * Only available when using StreamableHTTPServerTransport with eventStore configured. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream?: () => void; +}; +/** + * Implements MCP protocol framing on top of a pluggable transport, including + * features like request/response linking, notifications, and progress. + */ +export declare abstract class Protocol { + private _options?; + private _transport?; + private _requestMessageId; + private _requestHandlers; + private _requestHandlerAbortControllers; + private _notificationHandlers; + private _responseHandlers; + private _progressHandlers; + private _timeoutInfo; + private _pendingDebouncedNotifications; + private _taskProgressTokens; + private _taskStore?; + private _taskMessageQueue?; + private _requestResolvers; + /** + * Callback for when the connection is closed for any reason. + * + * This is invoked when close() is called as well. + */ + onclose?: () => void; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror?: (error: Error) => void; + /** + * A handler to invoke for any request types that do not have their own handler installed. + */ + fallbackRequestHandler?: (request: JSONRPCRequest, extra: RequestHandlerExtra) => Promise; + /** + * A handler to invoke for any notification types that do not have their own handler installed. + */ + fallbackNotificationHandler?: (notification: Notification) => Promise; + constructor(_options?: ProtocolOptions | undefined); + private _oncancel; + private _setupTimeout; + private _resetTimeout; + private _cleanupTimeout; + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + connect(transport: Transport): Promise; + private _onclose; + private _onerror; + private _onnotification; + private _onrequest; + private _onprogress; + private _onresponse; + get transport(): Transport | undefined; + /** + * Closes the connection. + */ + close(): Promise; + /** + * A method to check if a capability is supported by the remote side, for the given method to be called. + * + * This should be implemented by subclasses. + */ + protected abstract assertCapabilityForMethod(method: SendRequestT['method']): void; + /** + * A method to check if a notification is supported by the local side, for the given method to be sent. + * + * This should be implemented by subclasses. + */ + protected abstract assertNotificationCapability(method: SendNotificationT['method']): void; + /** + * A method to check if a request handler is supported by the local side, for the given method to be handled. + * + * This should be implemented by subclasses. + */ + protected abstract assertRequestHandlerCapability(method: string): void; + /** + * A method to check if task creation is supported for the given request method. + * + * This should be implemented by subclasses. + */ + protected abstract assertTaskCapability(method: string): void; + /** + * A method to check if task handler is supported by the local side, for the given method to be handled. + * + * This should be implemented by subclasses. + */ + protected abstract assertTaskHandlerCapability(method: string): void; + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * @example + * ```typescript + * const stream = protocol.requestStream(request, resultSchema, options); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @experimental Use `client.experimental.tasks.requestStream()` to access this method. + */ + protected requestStream(request: SendRequestT, resultSchema: T, options?: RequestOptions): AsyncGenerator>, void, void>; + /** + * Sends a request and waits for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request: SendRequestT, resultSchema: T, options?: RequestOptions): Promise>; + /** + * Gets the current status of a task. + * + * @experimental Use `client.experimental.tasks.getTask()` to access this method. + */ + protected getTask(params: GetTaskRequest['params'], options?: RequestOptions): Promise; + /** + * Retrieves the result of a completed task. + * + * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. + */ + protected getTaskResult(params: GetTaskPayloadRequest['params'], resultSchema: T, options?: RequestOptions): Promise>; + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @experimental Use `client.experimental.tasks.listTasks()` to access this method. + */ + protected listTasks(params?: { + cursor?: string; + }, options?: RequestOptions): Promise>; + /** + * Cancels a specific task. + * + * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. + */ + protected cancelTask(params: { + taskId: string; + }, options?: RequestOptions): Promise>; + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + notification(notification: SendNotificationT, options?: NotificationOptions): Promise; + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => SendResultT | Promise): void; + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method: string): void; + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method: string): void; + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema: T, handler: (notification: SchemaOutput) => void | Promise): void; + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method: string): void; + /** + * Cleans up the progress handler associated with a task. + * This should be called when a task reaches a terminal status. + */ + private _cleanupTaskProgressHandler; + /** + * Enqueues a task-related message for side-channel delivery via tasks/result. + * @param taskId The task ID to associate the message with + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) + * + * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle + * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer + * simply propagates the error. + */ + private _enqueueTaskMessage; + /** + * Clears the message queue for a task and rejects any pending request resolvers. + * @param taskId The task ID whose queue should be cleared + * @param sessionId Optional session ID for binding the operation to a specific session + */ + private _clearTaskQueue; + /** + * Waits for a task update (new messages or status change) with abort signal support. + * Uses polling to check for updates at the task's configured poll interval. + * @param taskId The task ID to wait for + * @param signal Abort signal to cancel the wait + * @returns Promise that resolves when an update occurs or rejects if aborted + */ + private _waitForTaskUpdate; + private requestTaskStore; +} +export declare function mergeCapabilities(base: ServerCapabilities, additional: Partial): ServerCapabilities; +export declare function mergeCapabilities(base: ClientCapabilities, additional: Partial): ClientCapabilities; +//# sourceMappingURL=protocol.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/protocol.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/protocol.d.ts.map new file mode 100644 index 000000000..b669a018a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/protocol.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../../src/shared/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,YAAY,EAAa,MAAM,yBAAyB,CAAC;AAC9F,OAAO,EAEH,kBAAkB,EAGlB,cAAc,EAGd,qBAAqB,EAGrB,qBAAqB,EAErB,sBAAsB,EAOtB,cAAc,EAId,QAAQ,EAIR,SAAS,EACT,MAAM,EACN,kBAAkB,EAClB,WAAW,EAEX,WAAW,EACX,aAAa,EACb,kBAAkB,EAClB,mBAAmB,EAEnB,IAAI,EAGJ,OAAO,EACP,YAAY,EAGf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAc,SAAS,EAAE,gBAAgB,EAAiB,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAEhI,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEvD;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;AAE5D;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG;IAC1B;;;;;;OAMG;IACH,yBAAyB,CAAC,EAAE,OAAO,CAAC;IACpC;;;;;OAKG;IACH,4BAA4B,CAAC,EAAE,MAAM,EAAE,CAAC;IACxC;;;OAGG;IACH,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB;;;O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,MAAM,EAAE,MAAM,GAAG,IAAI;IAMhD;;;;OAIG;IACH,sBAAsB,CAAC,CAAC,SAAS,eAAe,EAC5C,kBAAkB,EAAE,CAAC,EACrB,OAAO,EAAE,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GACjE,IAAI;IAQP;;OAEG;IACH,yBAAyB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI/C;;;OAGG;IACH,OAAO,CAAC,2BAA2B;IAQnC;;;;;;;;;;OAUG;YACW,mBAAmB;IAUjC;;;;OAIG;YACW,eAAe;IAqB7B;;;;;;OAMG;YACW,kBAAkB;IAiChC,OAAO,CAAC,gBAAgB;CAwF3B;AAMD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,kBAAkB,CAAC;AACzH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,kBAAkB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/protocol.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/protocol.js new file mode 100644 index 000000000..198ffe1c1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/protocol.js @@ -0,0 +1,1091 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Protocol = exports.DEFAULT_REQUEST_TIMEOUT_MSEC = void 0; +exports.mergeCapabilities = mergeCapabilities; +const zod_compat_js_1 = require("../server/zod-compat.js"); +const types_js_1 = require("../types.js"); +const interfaces_js_1 = require("../experimental/tasks/interfaces.js"); +const zod_json_schema_compat_js_1 = require("../server/zod-json-schema-compat.js"); +/** + * The default request timeout, in miliseconds. + */ +exports.DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; +/** + * Implements MCP protocol framing on top of a pluggable transport, including + * features like request/response linking, notifications, and progress. + */ +class Protocol { + constructor(_options) { + this._options = _options; + this._requestMessageId = 0; + this._requestHandlers = new Map(); + this._requestHandlerAbortControllers = new Map(); + this._notificationHandlers = new Map(); + this._responseHandlers = new Map(); + this._progressHandlers = new Map(); + this._timeoutInfo = new Map(); + this._pendingDebouncedNotifications = new Set(); + // Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult + this._taskProgressTokens = new Map(); + this._requestResolvers = new Map(); + this.setNotificationHandler(types_js_1.CancelledNotificationSchema, notification => { + this._oncancel(notification); + }); + this.setNotificationHandler(types_js_1.ProgressNotificationSchema, notification => { + this._onprogress(notification); + }); + this.setRequestHandler(types_js_1.PingRequestSchema, + // Automatic pong by default. + _request => ({})); + // Install task handlers if TaskStore is provided + this._taskStore = _options?.taskStore; + this._taskMessageQueue = _options?.taskMessageQueue; + if (this._taskStore) { + this.setRequestHandler(types_js_1.GetTaskRequestSchema, async (request, extra) => { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found'); + } + // Per spec: tasks/get responses SHALL NOT include related-task metadata + // as the taskId parameter is the source of truth + // @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else + return { + ...task + }; + }); + this.setRequestHandler(types_js_1.GetTaskPayloadRequestSchema, async (request, extra) => { + const handleTaskResult = async () => { + const taskId = request.params.taskId; + // Deliver queued messages + if (this._taskMessageQueue) { + let queuedMessage; + while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) { + // Handle response and error messages by routing them to the appropriate resolver + if (queuedMessage.type === 'response' || queuedMessage.type === 'error') { + const message = queuedMessage.message; + const requestId = message.id; + // Lookup resolver in _requestResolvers map + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + // Remove resolver from map after invocation + this._requestResolvers.delete(requestId); + // Invoke resolver with response or error + if (queuedMessage.type === 'response') { + resolver(message); + } + else { + // Convert JSONRPCError to McpError + const errorMessage = message; + const error = new types_js_1.McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data); + resolver(error); + } + } + else { + // Handle missing resolver gracefully with error logging + const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error'; + this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); + } + // Continue to next message + continue; + } + // Send the message on the response stream by passing the relatedRequestId + // This tells the transport to write the message to the tasks/result response stream + await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); + } + } + // Now check task status + const task = await this._taskStore.getTask(taskId, extra.sessionId); + if (!task) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Task not found: ${taskId}`); + } + // Block if task is not terminal (we've already delivered all queued messages above) + if (!(0, interfaces_js_1.isTerminal)(task.status)) { + // Wait for status change or new messages + await this._waitForTaskUpdate(taskId, extra.signal); + // After waking up, recursively call to deliver any new messages or result + return await handleTaskResult(); + } + // If task is terminal, return the result + if ((0, interfaces_js_1.isTerminal)(task.status)) { + const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); + this._clearTaskQueue(taskId); + return { + ...result, + _meta: { + ...result._meta, + [types_js_1.RELATED_TASK_META_KEY]: { + taskId: taskId + } + } + }; + } + return await handleTaskResult(); + }; + return await handleTaskResult(); + }); + this.setRequestHandler(types_js_1.ListTasksRequestSchema, async (request, extra) => { + try { + const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); + // @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else + return { + tasks, + nextCursor, + _meta: {} + }; + } + catch (error) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`); + } + }); + this.setRequestHandler(types_js_1.CancelTaskRequestSchema, async (request, extra) => { + try { + // Get the current task to check if it's in a terminal state, in case the implementation is not atomic + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); + } + // Reject cancellation of terminal tasks + if ((0, interfaces_js_1.isTerminal)(task.status)) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); + } + await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId); + this._clearTaskQueue(request.params.taskId); + const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!cancelledTask) { + // Task was deleted during cancellation (e.g., cleanup happened) + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); + } + return { + _meta: {}, + ...cancelledTask + }; + } + catch (error) { + // Re-throw McpError as-is + if (error instanceof types_js_1.McpError) { + throw error; + } + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`); + } + }); + } + } + async _oncancel(notification) { + if (!notification.params.requestId) { + return; + } + // Handle request cancellation + const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); + controller?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) + return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw types_js_1.McpError.fromError(types_js_1.ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport) { + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + _onclose?.(); + this._onclose(); + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error) => { + _onerror?.(error); + this._onerror(error); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if ((0, types_js_1.isJSONRPCResultResponse)(message) || (0, types_js_1.isJSONRPCErrorResponse)(message)) { + this._onresponse(message); + } + else if ((0, types_js_1.isJSONRPCRequest)(message)) { + this._onrequest(message, extra); + } + else if ((0, types_js_1.isJSONRPCNotification)(message)) { + this._onnotification(message); + } + else { + this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); + } + }; + await this._transport.start(); + } + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = new Map(); + this._progressHandlers.clear(); + this._taskProgressTokens.clear(); + this._pendingDebouncedNotifications.clear(); + const error = types_js_1.McpError.fromError(types_js_1.ErrorCode.ConnectionClosed, 'Connection closed'); + this._transport = undefined; + this.onclose?.(); + for (const handler of responseHandlers.values()) { + handler(error); + } + } + _onerror(error) { + this.onerror?.(error); + } + _onnotification(notification) { + const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; + // Ignore notifications not being subscribed to. + if (handler === undefined) { + return; + } + // Starting with Promise.resolve() puts any synchronous errors into the monad as well. + Promise.resolve() + .then(() => handler(notification)) + .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`))); + } + _onrequest(request, extra) { + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + // Capture the current transport at request time to ensure responses go to the correct client + const capturedTransport = this._transport; + // Extract taskId from request metadata if present (needed early for method not found case) + const relatedTaskId = request.params?._meta?.[types_js_1.RELATED_TASK_META_KEY]?.taskId; + if (handler === undefined) { + const errorResponse = { + jsonrpc: '2.0', + id: request.id, + error: { + code: types_js_1.ErrorCode.MethodNotFound, + message: 'Method not found' + } + }; + // Queue or send the error response based on whether this is a task-related request + if (relatedTaskId && this._taskMessageQueue) { + this._enqueueTaskMessage(relatedTaskId, { + type: 'error', + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`))); + } + else { + capturedTransport + ?.send(errorResponse) + .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`))); + } + return; + } + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const taskCreationParams = (0, types_js_1.isTaskAugmentedRequestParams)(request.params) ? request.params.task : undefined; + const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined; + const fullExtra = { + signal: abortController.signal, + sessionId: capturedTransport?.sessionId, + _meta: request.params?._meta, + sendNotification: async (notification) => { + // Include related-task metadata if this request is part of a task + const notificationOptions = { relatedRequestId: request.id }; + if (relatedTaskId) { + notificationOptions.relatedTask = { taskId: relatedTaskId }; + } + await this.notification(notification, notificationOptions); + }, + sendRequest: async (r, resultSchema, options) => { + // Include related-task metadata if this request is part of a task + const requestOptions = { ...options, relatedRequestId: request.id }; + if (relatedTaskId && !requestOptions.relatedTask) { + requestOptions.relatedTask = { taskId: relatedTaskId }; + } + // Set task status to input_required when sending a request within a task context + // Use the taskId from options (explicit) or fall back to relatedTaskId (inherited) + const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; + if (effectiveTaskId && taskStore) { + await taskStore.updateTaskStatus(effectiveTaskId, 'input_required'); + } + return await this.request(r, resultSchema, requestOptions); + }, + authInfo: extra?.authInfo, + requestId: request.id, + requestInfo: extra?.requestInfo, + taskId: relatedTaskId, + taskStore: taskStore, + taskRequestedTtl: taskCreationParams?.ttl, + closeSSEStream: extra?.closeSSEStream, + closeStandaloneSSEStream: extra?.closeStandaloneSSEStream + }; + // Starting with Promise.resolve() puts any synchronous errors into the monad as well. + Promise.resolve() + .then(() => { + // If this request asked for task creation, check capability first + if (taskCreationParams) { + // Check if the request method supports task creation + this.assertTaskHandlerCapability(request.method); + } + }) + .then(() => handler(request, fullExtra)) + .then(async (result) => { + if (abortController.signal.aborted) { + // Request was cancelled + return; + } + const response = { + result, + jsonrpc: '2.0', + id: request.id + }; + // Queue or send the response based on whether this is a task-related request + if (relatedTaskId && this._taskMessageQueue) { + await this._enqueueTaskMessage(relatedTaskId, { + type: 'response', + message: response, + timestamp: Date.now() + }, capturedTransport?.sessionId); + } + else { + await capturedTransport?.send(response); + } + }, async (error) => { + if (abortController.signal.aborted) { + // Request was cancelled + return; + } + const errorResponse = { + jsonrpc: '2.0', + id: request.id, + error: { + code: Number.isSafeInteger(error['code']) ? error['code'] : types_js_1.ErrorCode.InternalError, + message: error.message ?? 'Internal error', + ...(error['data'] !== undefined && { data: error['data'] }) + } + }; + // Queue or send the error response based on whether this is a task-related request + if (relatedTaskId && this._taskMessageQueue) { + await this._enqueueTaskMessage(relatedTaskId, { + type: 'error', + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId); + } + else { + await capturedTransport?.send(errorResponse); + } + }) + .catch(error => this._onerror(new Error(`Failed to send response: ${error}`))) + .finally(() => { + this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { + try { + this._resetTimeout(messageId); + } + catch (error) { + // Clean up if maxTotalTimeout was exceeded + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error); + return; + } + } + handler(params); + } + _onresponse(response) { + const messageId = Number(response.id); + // Check if this is a response to a queued request + const resolver = this._requestResolvers.get(messageId); + if (resolver) { + this._requestResolvers.delete(messageId); + if ((0, types_js_1.isJSONRPCResultResponse)(response)) { + resolver(response); + } + else { + const error = new types_js_1.McpError(response.error.code, response.error.message, response.error.data); + resolver(error); + } + return; + } + const handler = this._responseHandlers.get(messageId); + if (handler === undefined) { + this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + // Keep progress handler alive for CreateTaskResult responses + let isTaskResponse = false; + if ((0, types_js_1.isJSONRPCResultResponse)(response) && response.result && typeof response.result === 'object') { + const result = response.result; + if (result.task && typeof result.task === 'object') { + const task = result.task; + if (typeof task.taskId === 'string') { + isTaskResponse = true; + this._taskProgressTokens.set(task.taskId, messageId); + } + } + } + if (!isTaskResponse) { + this._progressHandlers.delete(messageId); + } + if ((0, types_js_1.isJSONRPCResultResponse)(response)) { + handler(response); + } + else { + const error = types_js_1.McpError.fromError(response.error.code, response.error.message, response.error.data); + handler(error); + } + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * @example + * ```typescript + * const stream = protocol.requestStream(request, resultSchema, options); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @experimental Use `client.experimental.tasks.requestStream()` to access this method. + */ + async *requestStream(request, resultSchema, options) { + const { task } = options ?? {}; + // For non-task requests, just yield the result + if (!task) { + try { + const result = await this.request(request, resultSchema, options); + yield { type: 'result', result }; + } + catch (error) { + yield { + type: 'error', + error: error instanceof types_js_1.McpError ? error : new types_js_1.McpError(types_js_1.ErrorCode.InternalError, String(error)) + }; + } + return; + } + // For task-augmented requests, we need to poll for status + // First, make the request to create the task + let taskId; + try { + // Send the request and get the CreateTaskResult + const createResult = await this.request(request, types_js_1.CreateTaskResultSchema, options); + // Extract taskId from the result + if (createResult.task) { + taskId = createResult.task.taskId; + yield { type: 'taskCreated', task: createResult.task }; + } + else { + throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, 'Task creation did not return a task'); + } + // Poll for task completion + while (true) { + // Get current task status + const task = await this.getTask({ taskId }, options); + yield { type: 'taskStatus', task }; + // Check if task is terminal + if ((0, interfaces_js_1.isTerminal)(task.status)) { + if (task.status === 'completed') { + // Get the final result + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: 'result', result }; + } + else if (task.status === 'failed') { + yield { + type: 'error', + error: new types_js_1.McpError(types_js_1.ErrorCode.InternalError, `Task ${taskId} failed`) + }; + } + else if (task.status === 'cancelled') { + yield { + type: 'error', + error: new types_js_1.McpError(types_js_1.ErrorCode.InternalError, `Task ${taskId} was cancelled`) + }; + } + return; + } + // When input_required, call tasks/result to deliver queued messages + // (elicitation, sampling) via SSE and block until terminal + if (task.status === 'input_required') { + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: 'result', result }; + return; + } + // Wait before polling again + const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000; + await new Promise(resolve => setTimeout(resolve, pollInterval)); + // Check if cancelled + options?.signal?.throwIfAborted(); + } + } + catch (error) { + yield { + type: 'error', + error: error instanceof types_js_1.McpError ? error : new types_js_1.McpError(types_js_1.ErrorCode.InternalError, String(error)) + }; + } + } + /** + * Sends a request and waits for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; + // Send the request + return new Promise((resolve, reject) => { + const earlyReject = (error) => { + reject(error); + }; + if (!this._transport) { + earlyReject(new Error('Not connected')); + return; + } + if (this._options?.enforceStrictCapabilities === true) { + try { + this.assertCapabilityForMethod(request.method); + // If task creation is requested, also check task capabilities + if (task) { + this.assertTaskCapability(request.method); + } + } + catch (e) { + earlyReject(e); + return; + } + } + options?.signal?.throwIfAborted(); + const messageId = this._requestMessageId++; + const jsonrpcRequest = { + ...request, + jsonrpc: '2.0', + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...(request.params?._meta || {}), + progressToken: messageId + } + }; + } + // Augment with task creation parameters if provided + if (task) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + task: task + }; + } + // Augment with related task metadata if relatedTask is provided + if (relatedTask) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + _meta: { + ...(jsonrpcRequest.params?._meta || {}), + [types_js_1.RELATED_TASK_META_KEY]: relatedTask + } + }; + } + const cancel = (reason) => { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._transport + ?.send({ + jsonrpc: '2.0', + method: 'notifications/cancelled', + params: { + requestId: messageId, + reason: String(reason) + } + }, { relatedRequestId, resumptionToken, onresumptiontoken }) + .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`))); + // Wrap the reason in an McpError if it isn't already + const error = reason instanceof types_js_1.McpError ? reason : new types_js_1.McpError(types_js_1.ErrorCode.RequestTimeout, String(reason)); + reject(error); + }; + this._responseHandlers.set(messageId, response => { + if (options?.signal?.aborted) { + return; + } + if (response instanceof Error) { + return reject(response); + } + try { + const parseResult = (0, zod_compat_js_1.safeParse)(resultSchema, response.result); + if (!parseResult.success) { + // Type guard: if success is false, error is guaranteed to exist + reject(parseResult.error); + } + else { + resolve(parseResult.data); + } + } + catch (error) { + reject(error); + } + }); + options?.signal?.addEventListener('abort', () => { + cancel(options?.signal?.reason); + }); + const timeout = options?.timeout ?? exports.DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(types_js_1.McpError.fromError(types_js_1.ErrorCode.RequestTimeout, 'Request timed out', { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + // Queue request if related to a task + const relatedTaskId = relatedTask?.taskId; + if (relatedTaskId) { + // Store the response resolver for this request so responses can be routed back + const responseResolver = (response) => { + const handler = this._responseHandlers.get(messageId); + if (handler) { + handler(response); + } + else { + // Log error when resolver is missing, but don't fail + this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); + } + }; + this._requestResolvers.set(messageId, responseResolver); + this._enqueueTaskMessage(relatedTaskId, { + type: 'request', + message: jsonrpcRequest, + timestamp: Date.now() + }).catch(error => { + this._cleanupTimeout(messageId); + reject(error); + }); + // Don't send through transport - queued messages are delivered via tasks/result only + // This prevents duplicate delivery for bidirectional transports + } + else { + // No related task - send through transport normally + this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => { + this._cleanupTimeout(messageId); + reject(error); + }); + } + }); + } + /** + * Gets the current status of a task. + * + * @experimental Use `client.experimental.tasks.getTask()` to access this method. + */ + async getTask(params, options) { + // @ts-expect-error SendRequestT cannot directly contain GetTaskRequest, but we ensure all type instantiations contain it anyways + return this.request({ method: 'tasks/get', params }, types_js_1.GetTaskResultSchema, options); + } + /** + * Retrieves the result of a completed task. + * + * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. + */ + async getTaskResult(params, resultSchema, options) { + // @ts-expect-error SendRequestT cannot directly contain GetTaskPayloadRequest, but we ensure all type instantiations contain it anyways + return this.request({ method: 'tasks/result', params }, resultSchema, options); + } + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @experimental Use `client.experimental.tasks.listTasks()` to access this method. + */ + async listTasks(params, options) { + // @ts-expect-error SendRequestT cannot directly contain ListTasksRequest, but we ensure all type instantiations contain it anyways + return this.request({ method: 'tasks/list', params }, types_js_1.ListTasksResultSchema, options); + } + /** + * Cancels a specific task. + * + * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. + */ + async cancelTask(params, options) { + // @ts-expect-error SendRequestT cannot directly contain CancelTaskRequest, but we ensure all type instantiations contain it anyways + return this.request({ method: 'tasks/cancel', params }, types_js_1.CancelTaskResultSchema, options); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + if (!this._transport) { + throw new Error('Not connected'); + } + this.assertNotificationCapability(notification.method); + // Queue notification if related to a task + const relatedTaskId = options?.relatedTask?.taskId; + if (relatedTaskId) { + // Build the JSONRPC notification with metadata + const jsonrpcNotification = { + ...notification, + jsonrpc: '2.0', + params: { + ...notification.params, + _meta: { + ...(notification.params?._meta || {}), + [types_js_1.RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + await this._enqueueTaskMessage(relatedTaskId, { + type: 'notification', + message: jsonrpcNotification, + timestamp: Date.now() + }); + // Don't send through transport - queued messages are delivered via tasks/result only + // This prevents duplicate delivery for bidirectional transports + return; + } + const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; + // A notification can only be debounced if it's in the list AND it's "simple" + // (i.e., has no parameters and no related request ID or related task that could be lost). + const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask; + if (canDebounce) { + // If a notification of this type is already scheduled, do nothing. + if (this._pendingDebouncedNotifications.has(notification.method)) { + return; + } + // Mark this notification type as pending. + this._pendingDebouncedNotifications.add(notification.method); + // Schedule the actual send to happen in the next microtask. + // This allows all synchronous calls in the current event loop tick to be coalesced. + Promise.resolve().then(() => { + // Un-mark the notification so the next one can be scheduled. + this._pendingDebouncedNotifications.delete(notification.method); + // SAFETY CHECK: If the connection was closed while this was pending, abort. + if (!this._transport) { + return; + } + let jsonrpcNotification = { + ...notification, + jsonrpc: '2.0' + }; + // Augment with related task metadata if relatedTask is provided + if (options?.relatedTask) { + jsonrpcNotification = { + ...jsonrpcNotification, + params: { + ...jsonrpcNotification.params, + _meta: { + ...(jsonrpcNotification.params?._meta || {}), + [types_js_1.RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + // Send the notification, but don't await it here to avoid blocking. + // Handle potential errors with a .catch(). + this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error)); + }); + // Return immediately. + return; + } + let jsonrpcNotification = { + ...notification, + jsonrpc: '2.0' + }; + // Augment with related task metadata if relatedTask is provided + if (options?.relatedTask) { + jsonrpcNotification = { + ...jsonrpcNotification, + params: { + ...jsonrpcNotification.params, + _meta: { + ...(jsonrpcNotification.params?._meta || {}), + [types_js_1.RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + await this._transport.send(jsonrpcNotification, options); + } + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema, handler) { + const method = (0, zod_json_schema_compat_js_1.getMethodLiteral)(requestSchema); + this.assertRequestHandlerCapability(method); + this._requestHandlers.set(method, (request, extra) => { + const parsed = (0, zod_json_schema_compat_js_1.parseWithCompat)(requestSchema, request); + return Promise.resolve(handler(parsed, extra)); + }); + } + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) { + throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + } + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema, handler) { + const method = (0, zod_json_schema_compat_js_1.getMethodLiteral)(notificationSchema); + this._notificationHandlers.set(method, notification => { + const parsed = (0, zod_json_schema_compat_js_1.parseWithCompat)(notificationSchema, notification); + return Promise.resolve(handler(parsed)); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } + /** + * Cleans up the progress handler associated with a task. + * This should be called when a task reaches a terminal status. + */ + _cleanupTaskProgressHandler(taskId) { + const progressToken = this._taskProgressTokens.get(taskId); + if (progressToken !== undefined) { + this._progressHandlers.delete(progressToken); + this._taskProgressTokens.delete(taskId); + } + } + /** + * Enqueues a task-related message for side-channel delivery via tasks/result. + * @param taskId The task ID to associate the message with + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) + * + * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle + * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer + * simply propagates the error. + */ + async _enqueueTaskMessage(taskId, message, sessionId) { + // Task message queues are only used when taskStore is configured + if (!this._taskStore || !this._taskMessageQueue) { + throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured'); + } + const maxQueueSize = this._options?.maxTaskQueueSize; + await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize); + } + /** + * Clears the message queue for a task and rejects any pending request resolvers. + * @param taskId The task ID whose queue should be cleared + * @param sessionId Optional session ID for binding the operation to a specific session + */ + async _clearTaskQueue(taskId, sessionId) { + if (this._taskMessageQueue) { + // Reject any pending request resolvers + const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); + for (const message of messages) { + if (message.type === 'request' && (0, types_js_1.isJSONRPCRequest)(message.message)) { + // Extract request ID from the message + const requestId = message.message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + resolver(new types_js_1.McpError(types_js_1.ErrorCode.InternalError, 'Task cancelled or completed')); + this._requestResolvers.delete(requestId); + } + else { + // Log error when resolver is missing during cleanup for better observability + this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); + } + } + } + } + } + /** + * Waits for a task update (new messages or status change) with abort signal support. + * Uses polling to check for updates at the task's configured poll interval. + * @param taskId The task ID to wait for + * @param signal Abort signal to cancel the wait + * @returns Promise that resolves when an update occurs or rejects if aborted + */ + async _waitForTaskUpdate(taskId, signal) { + // Get the task's poll interval, falling back to default + let interval = this._options?.defaultTaskPollInterval ?? 1000; + try { + const task = await this._taskStore?.getTask(taskId); + if (task?.pollInterval) { + interval = task.pollInterval; + } + } + catch { + // Use default interval if task lookup fails + } + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, 'Request cancelled')); + return; + } + // Wait for the poll interval, then resolve so caller can check for updates + const timeoutId = setTimeout(resolve, interval); + // Clean up timeout and reject if aborted + signal.addEventListener('abort', () => { + clearTimeout(timeoutId); + reject(new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, 'Request cancelled')); + }, { once: true }); + }); + } + requestTaskStore(request, sessionId) { + const taskStore = this._taskStore; + if (!taskStore) { + throw new Error('No task store configured'); + } + return { + createTask: async (taskParams) => { + if (!request) { + throw new Error('No request provided'); + } + return await taskStore.createTask(taskParams, request.id, { + method: request.method, + params: request.params + }, sessionId); + }, + getTask: async (taskId) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found'); + } + return task; + }, + storeTaskResult: async (taskId, status, result) => { + await taskStore.storeTaskResult(taskId, status, result, sessionId); + // Get updated task state and send notification + const task = await taskStore.getTask(taskId, sessionId); + if (task) { + const notification = types_js_1.TaskStatusNotificationSchema.parse({ + method: 'notifications/tasks/status', + params: task + }); + await this.notification(notification); + if ((0, interfaces_js_1.isTerminal)(task.status)) { + this._cleanupTaskProgressHandler(taskId); + // Don't clear queue here - it will be cleared after delivery via tasks/result + } + } + }, + getTaskResult: taskId => { + return taskStore.getTaskResult(taskId, sessionId); + }, + updateTaskStatus: async (taskId, status, statusMessage) => { + // Check if task exists + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); + } + // Don't allow transitions from terminal states + if ((0, interfaces_js_1.isTerminal)(task.status)) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); + } + await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); + // Get updated task state and send notification + const updatedTask = await taskStore.getTask(taskId, sessionId); + if (updatedTask) { + const notification = types_js_1.TaskStatusNotificationSchema.parse({ + method: 'notifications/tasks/status', + params: updatedTask + }); + await this.notification(notification); + if ((0, interfaces_js_1.isTerminal)(updatedTask.status)) { + this._cleanupTaskProgressHandler(taskId); + // Don't clear queue here - it will be cleared after delivery via tasks/result + } + } + }, + listTasks: cursor => { + return taskStore.listTasks(cursor, sessionId); + } + }; + } +} +exports.Protocol = Protocol; +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === undefined) + continue; + const baseValue = result[k]; + if (isPlainObject(baseValue) && isPlainObject(addValue)) { + result[k] = { ...baseValue, ...addValue }; + } + else { + result[k] = addValue; + } + } + return result; +} +//# sourceMappingURL=protocol.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/protocol.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/protocol.js.map new file mode 100644 index 000000000..ed43a14a5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/protocol.js.map @@ -0,0 +1 @@ +{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../../src/shared/protocol.ts"],"names":[],"mappings":";;;AA0mDA,8CAcC;AAxnDD,2DAA8F;AAC9F,0CA6CqB;AAGrB,uEAAgI;AAChI,mFAAwF;AAoDxF;;GAEG;AACU,QAAA,4BAA4B,GAAG,KAAK,CAAC;AAkNlD;;;GAGG;AACH,MAAsB,QAAQ;IA8C1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,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;QAC3B,MAAM,CAAC,GAAG,GAAc,CAAC;QACzB,MAAM,QAAQ,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;QAC/B,IAAI,QAAQ,KAAK,SAAS;YAAE,SAAS;QACrC,MAAM,SAAS,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;QAC5B,IAAI,aAAa,CAAC,SAAS,CAAC,IAAI,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC;YACtD,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,GAAI,SAAqC,EAAE,GAAI,QAAoC,EAAiB,CAAC;QACvH,CAAC;aAAM,CAAC;YACJ,MAAM,CAAC,CAAC,CAAC,GAAG,QAAuB,CAAC;QACxC,CAAC;IACL,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/responseMessage.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/responseMessage.d.ts new file mode 100644 index 000000000..84354bdb7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/responseMessage.d.ts @@ -0,0 +1,45 @@ +import { Result, Task, McpError } from '../types.js'; +/** + * Base message type + */ +export interface BaseResponseMessage { + type: string; +} +/** + * Task status update message + */ +export interface TaskStatusMessage extends BaseResponseMessage { + type: 'taskStatus'; + task: Task; +} +/** + * Task created message (first message for task-augmented requests) + */ +export interface TaskCreatedMessage extends BaseResponseMessage { + type: 'taskCreated'; + task: Task; +} +/** + * Final result message (terminal) + */ +export interface ResultMessage extends BaseResponseMessage { + type: 'result'; + result: T; +} +/** + * Error message (terminal) + */ +export interface ErrorMessage extends BaseResponseMessage { + type: 'error'; + error: McpError; +} +/** + * Union type representing all possible messages that can be yielded during request processing. + * Note: Progress notifications are handled through the existing onprogress callback mechanism. + * Side-channeled messages (server requests/notifications) are handled through registered handlers. + */ +export type ResponseMessage = TaskStatusMessage | TaskCreatedMessage | ResultMessage | ErrorMessage; +export type AsyncGeneratorValue = T extends AsyncGenerator ? U : never; +export declare function toArrayAsync>(it: T): Promise[]>; +export declare function takeResult>>(it: U): Promise; +//# sourceMappingURL=responseMessage.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/responseMessage.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/responseMessage.d.ts.map new file mode 100644 index 000000000..65d93bb50 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/responseMessage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"responseMessage.d.ts","sourceRoot":"","sources":["../../../src/shared/responseMessage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAErD;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAChC,IAAI,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAkB,SAAQ,mBAAmB;IAC1D,IAAI,EAAE,YAAY,CAAC;IACnB,IAAI,EAAE,IAAI,CAAC;CACd;AAED;;GAEG;AACH,MAAM,WAAW,kBAAmB,SAAQ,mBAAmB;IAC3D,IAAI,EAAE,aAAa,CAAC;IACpB,IAAI,EAAE,IAAI,CAAC;CACd;AAED;;GAEG;AACH,MAAM,WAAW,aAAa,CAAC,CAAC,SAAS,MAAM,CAAE,SAAQ,mBAAmB;IACxE,IAAI,EAAE,QAAQ,CAAC;IACf,MAAM,EAAE,CAAC,CAAC;CACb;AAED;;GAEG;AACH,MAAM,WAAW,YAAa,SAAQ,mBAAmB;IACrD,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EAAE,QAAQ,CAAC;CACnB;AAED;;;;GAIG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,MAAM,IAAI,iBAAiB,GAAG,kBAAkB,GAAG,aAAa,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC;AAEzH,MAAM,MAAM,mBAAmB,CAAC,CAAC,IAAI,CAAC,SAAS,cAAc,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAEnF,wBAAsB,YAAY,CAAC,CAAC,SAAS,cAAc,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC,CAAC,EAAE,CAAC,CAO9G;AAED,wBAAsB,UAAU,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,cAAc,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAUlH"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/responseMessage.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/responseMessage.js new file mode 100644 index 000000000..6c223fcbc --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/responseMessage.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toArrayAsync = toArrayAsync; +exports.takeResult = takeResult; +async function toArrayAsync(it) { + const arr = []; + for await (const o of it) { + arr.push(o); + } + return arr; +} +async function takeResult(it) { + for await (const o of it) { + if (o.type === 'result') { + return o.result; + } + else if (o.type === 'error') { + throw o.error; + } + } + throw new Error('No result in stream.'); +} +//# sourceMappingURL=responseMessage.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/responseMessage.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/responseMessage.js.map new file mode 100644 index 000000000..18bd904ed --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/responseMessage.js.map @@ -0,0 +1 @@ +{"version":3,"file":"responseMessage.js","sourceRoot":"","sources":["../../../src/shared/responseMessage.ts"],"names":[],"mappings":";;AAkDA,oCAOC;AAED,gCAUC;AAnBM,KAAK,UAAU,YAAY,CAAoC,EAAK;IACvE,MAAM,GAAG,GAA6B,EAAE,CAAC;IACzC,IAAI,KAAK,EAAE,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;QACvB,GAAG,CAAC,IAAI,CAAC,CAA2B,CAAC,CAAC;IAC1C,CAAC;IAED,OAAO,GAAG,CAAC;AACf,CAAC;AAEM,KAAK,UAAU,UAAU,CAAiE,EAAK;IAClG,IAAI,KAAK,EAAE,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;QACvB,IAAI,CAAC,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACtB,OAAO,CAAC,CAAC,MAAM,CAAC;QACpB,CAAC;aAAM,IAAI,CAAC,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;YAC5B,MAAM,CAAC,CAAC,KAAK,CAAC;QAClB,CAAC;IACL,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;AAC5C,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.d.ts new file mode 100644 index 000000000..0830a48bc --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.d.ts @@ -0,0 +1,13 @@ +import { JSONRPCMessage } from '../types.js'; +/** + * Buffers a continuous stdio stream into discrete JSON-RPC messages. + */ +export declare class ReadBuffer { + private _buffer?; + append(chunk: Buffer): void; + readMessage(): JSONRPCMessage | null; + clear(): void; +} +export declare function deserializeMessage(line: string): JSONRPCMessage; +export declare function serializeMessage(message: JSONRPCMessage): string; +//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.d.ts.map new file mode 100644 index 000000000..8f97f2ab1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/shared/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAEnE;;GAEG;AACH,qBAAa,UAAU;IACnB,OAAO,CAAC,OAAO,CAAC,CAAS;IAEzB,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAI3B,WAAW,IAAI,cAAc,GAAG,IAAI;IAepC,KAAK,IAAI,IAAI;CAGhB;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,CAE/D;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM,CAEhE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.js new file mode 100644 index 000000000..540ee5682 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReadBuffer = void 0; +exports.deserializeMessage = deserializeMessage; +exports.serializeMessage = serializeMessage; +const types_js_1 = require("../types.js"); +/** + * Buffers a continuous stdio stream into discrete JSON-RPC messages. + */ +class ReadBuffer { + append(chunk) { + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + if (!this._buffer) { + return null; + } + const index = this._buffer.indexOf('\n'); + if (index === -1) { + return null; + } + const line = this._buffer.toString('utf8', 0, index).replace(/\r$/, ''); + this._buffer = this._buffer.subarray(index + 1); + return deserializeMessage(line); + } + clear() { + this._buffer = undefined; + } +} +exports.ReadBuffer = ReadBuffer; +function deserializeMessage(line) { + return types_js_1.JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message) { + return JSON.stringify(message) + '\n'; +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.js.map new file mode 100644 index 000000000..89fbc1a66 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/shared/stdio.ts"],"names":[],"mappings":";;;AAgCA,gDAEC;AAED,4CAEC;AAtCD,0CAAmE;AAEnE;;GAEG;AACH,MAAa,UAAU;IAGnB,MAAM,CAAC,KAAa;QAChB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC/E,CAAC;IAED,WAAW;QACP,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAChB,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACzC,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE,CAAC;YACf,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACxE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QAChD,OAAO,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;IAED,KAAK;QACD,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;IAC7B,CAAC;CACJ;AAzBD,gCAyBC;AAED,SAAgB,kBAAkB,CAAC,IAAY;IAC3C,OAAO,+BAAoB,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,SAAgB,gBAAgB,CAAC,OAAuB;IACpD,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/toolNameValidation.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/toolNameValidation.d.ts new file mode 100644 index 000000000..3cf94bf78 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/toolNameValidation.d.ts @@ -0,0 +1,31 @@ +/** + * Tool name validation utilities according to SEP: Specify Format for Tool Names + * + * Tool names SHOULD be between 1 and 128 characters in length (inclusive). + * Tool names are case-sensitive. + * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits + * (0-9), underscore (_), dash (-), and dot (.). + * Tool names SHOULD NOT contain spaces, commas, or other special characters. + */ +/** + * Validates a tool name according to the SEP specification + * @param name - The tool name to validate + * @returns An object containing validation result and any warnings + */ +export declare function validateToolName(name: string): { + isValid: boolean; + warnings: string[]; +}; +/** + * Issues warnings for non-conforming tool names + * @param name - The tool name that triggered the warnings + * @param warnings - Array of warning messages + */ +export declare function issueToolNameWarning(name: string, warnings: string[]): void; +/** + * Validates a tool name and issues warnings for non-conforming names + * @param name - The tool name to validate + * @returns true if the name is valid, false otherwise + */ +export declare function validateAndWarnToolName(name: string): boolean; +//# sourceMappingURL=toolNameValidation.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/toolNameValidation.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/toolNameValidation.d.ts.map new file mode 100644 index 000000000..d81f0156e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/toolNameValidation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"toolNameValidation.d.ts","sourceRoot":"","sources":["../../../src/shared/toolNameValidation.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAOH;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG;IAC5C,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACtB,CA0DA;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAY3E;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAO7D"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/toolNameValidation.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/toolNameValidation.js new file mode 100644 index 000000000..cd9d93078 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/toolNameValidation.js @@ -0,0 +1,97 @@ +"use strict"; +/** + * Tool name validation utilities according to SEP: Specify Format for Tool Names + * + * Tool names SHOULD be between 1 and 128 characters in length (inclusive). + * Tool names are case-sensitive. + * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits + * (0-9), underscore (_), dash (-), and dot (.). + * Tool names SHOULD NOT contain spaces, commas, or other special characters. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateToolName = validateToolName; +exports.issueToolNameWarning = issueToolNameWarning; +exports.validateAndWarnToolName = validateAndWarnToolName; +/** + * Regular expression for valid tool names according to SEP-986 specification + */ +const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; +/** + * Validates a tool name according to the SEP specification + * @param name - The tool name to validate + * @returns An object containing validation result and any warnings + */ +function validateToolName(name) { + const warnings = []; + // Check length + if (name.length === 0) { + return { + isValid: false, + warnings: ['Tool name cannot be empty'] + }; + } + if (name.length > 128) { + return { + isValid: false, + warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] + }; + } + // Check for specific problematic patterns (these are warnings, not validation failures) + if (name.includes(' ')) { + warnings.push('Tool name contains spaces, which may cause parsing issues'); + } + if (name.includes(',')) { + warnings.push('Tool name contains commas, which may cause parsing issues'); + } + // Check for potentially confusing patterns (leading/trailing dashes, dots, slashes) + if (name.startsWith('-') || name.endsWith('-')) { + warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts'); + } + if (name.startsWith('.') || name.endsWith('.')) { + warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts'); + } + // Check for invalid characters + if (!TOOL_NAME_REGEX.test(name)) { + const invalidChars = name + .split('') + .filter(char => !/[A-Za-z0-9._-]/.test(char)) + .filter((char, index, arr) => arr.indexOf(char) === index); // Remove duplicates + warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c => `"${c}"`).join(', ')}`, 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)'); + return { + isValid: false, + warnings + }; + } + return { + isValid: true, + warnings + }; +} +/** + * Issues warnings for non-conforming tool names + * @param name - The tool name that triggered the warnings + * @param warnings - Array of warning messages + */ +function issueToolNameWarning(name, warnings) { + if (warnings.length > 0) { + console.warn(`Tool name validation warning for "${name}":`); + for (const warning of warnings) { + console.warn(` - ${warning}`); + } + console.warn('Tool registration will proceed, but this may cause compatibility issues.'); + console.warn('Consider updating the tool name to conform to the MCP tool naming standard.'); + console.warn('See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.'); + } +} +/** + * Validates a tool name and issues warnings for non-conforming names + * @param name - The tool name to validate + * @returns true if the name is valid, false otherwise + */ +function validateAndWarnToolName(name) { + const result = validateToolName(name); + // Always issue warnings for any validation issues (both invalid names and warnings) + issueToolNameWarning(name, result.warnings); + return result.isValid; +} +//# sourceMappingURL=toolNameValidation.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/toolNameValidation.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/toolNameValidation.js.map new file mode 100644 index 000000000..ad136cc30 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/toolNameValidation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"toolNameValidation.js","sourceRoot":"","sources":["../../../src/shared/toolNameValidation.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;AAYH,4CA6DC;AAOD,oDAYC;AAOD,0DAOC;AAxGD;;GAEG;AACH,MAAM,eAAe,GAAG,yBAAyB,CAAC;AAElD;;;;GAIG;AACH,SAAgB,gBAAgB,CAAC,IAAY;IAIzC,MAAM,QAAQ,GAAa,EAAE,CAAC;IAE9B,eAAe;IACf,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpB,OAAO;YACH,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE,CAAC,2BAA2B,CAAC;SAC1C,CAAC;IACN,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;QACpB,OAAO;YACH,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE,CAAC,gEAAgE,IAAI,CAAC,MAAM,GAAG,CAAC;SAC7F,CAAC;IACN,CAAC;IAED,wFAAwF;IACxF,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,QAAQ,CAAC,IAAI,CAAC,2DAA2D,CAAC,CAAC;IAC/E,CAAC;IAED,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,QAAQ,CAAC,IAAI,CAAC,2DAA2D,CAAC,CAAC;IAC/E,CAAC;IAED,oFAAoF;IACpF,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QAC7C,QAAQ,CAAC,IAAI,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EAA0E,CAAC,CAAC;QACzF,OAAO,CAAC,IAAI,CAAC,6EAA6E,CAAC,CAAC;QAC5F,OAAO,CAAC,IAAI,CACR,oIAAoI,CACvI,CAAC;IACN,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,SAAgB,uBAAuB,CAAC,IAAY;IAChD,MAAM,MAAM,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAEtC,oFAAoF;IACpF,oBAAoB,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;IAE5C,OAAO,MAAM,CAAC,OAAO,CAAC;AAC1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/transport.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/transport.d.ts new file mode 100644 index 000000000..1bd95efb4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/transport.d.ts @@ -0,0 +1,89 @@ +import { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types.js'; +export type FetchLike = (url: string | URL, init?: RequestInit) => Promise; +/** + * Normalizes HeadersInit to a plain Record for manipulation. + * Handles Headers objects, arrays of tuples, and plain objects. + */ +export declare function normalizeHeaders(headers: HeadersInit | undefined): Record; +/** + * Creates a fetch function that includes base RequestInit options. + * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. + * + * @param baseFetch - The base fetch function to wrap (defaults to global fetch) + * @param baseInit - The base RequestInit to merge with each request + * @returns A wrapped fetch function that merges base options with call-specific options + */ +export declare function createFetchWithInit(baseFetch?: FetchLike, baseInit?: RequestInit): FetchLike; +/** + * Options for sending a JSON-RPC message. + */ +export type TransportSendOptions = { + /** + * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. + */ + relatedRequestId?: RequestId; + /** + * The resumption token used to continue long-running requests that were interrupted. + * + * This allows clients to reconnect and continue from where they left off, if supported by the transport. + */ + resumptionToken?: string; + /** + * A callback that is invoked when the resumption token changes, if supported by the transport. + * + * This allows clients to persist the latest token for potential reconnection. + */ + onresumptiontoken?: (token: string) => void; +}; +/** + * Describes the minimal contract for an MCP transport that a client or server can communicate over. + */ +export interface Transport { + /** + * Starts processing messages on the transport, including any connection steps that might need to be taken. + * + * This method should only be called after callbacks are installed, or else messages may be lost. + * + * NOTE: This method should not be called explicitly when using Client, Server, or Protocol classes, as they will implicitly call start(). + */ + start(): Promise; + /** + * Sends a JSON-RPC message (request or response). + * + * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. + */ + send(message: JSONRPCMessage, options?: TransportSendOptions): Promise; + /** + * Closes the connection. + */ + close(): Promise; + /** + * Callback for when the connection is closed for any reason. + * + * This should be invoked when close() is called as well. + */ + onclose?: () => void; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror?: (error: Error) => void; + /** + * Callback for when a message (request or response) is received over the connection. + * + * Includes the requestInfo and authInfo if the transport is authenticated. + * + * The requestInfo can be used to get the original request information (headers, etc.) + */ + onmessage?: (message: T, extra?: MessageExtraInfo) => void; + /** + * The session ID generated for this connection. + */ + sessionId?: string; + /** + * Sets the protocol version used for the connection (called when the initialize response is received). + */ + setProtocolVersion?: (version: string) => void; +} +//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/transport.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/transport.d.ts.map new file mode 100644 index 000000000..7a3d837df --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/transport.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../src/shared/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE1E,MAAM,MAAM,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,GAA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I,CAAC;CAClD"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/transport.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/transport.js new file mode 100644 index 000000000..38cfcc7e7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/transport.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.normalizeHeaders = normalizeHeaders; +exports.createFetchWithInit = createFetchWithInit; +/** + * Normalizes HeadersInit to a plain Record for manipulation. + * Handles Headers objects, arrays of tuples, and plain objects. + */ +function normalizeHeaders(headers) { + if (!headers) + return {}; + if (headers instanceof Headers) { + return Object.fromEntries(headers.entries()); + } + if (Array.isArray(headers)) { + return Object.fromEntries(headers); + } + return { ...headers }; +} +/** + * Creates a fetch function that includes base RequestInit options. + * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. + * + * @param baseFetch - The base fetch function to wrap (defaults to global fetch) + * @param baseInit - The base RequestInit to merge with each request + * @returns A wrapped fetch function that merges base options with call-specific options + */ +function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) { + return baseFetch; + } + // Return a wrapped fetch that merges base RequestInit with call-specific init + return async (url, init) => { + const mergedInit = { + ...baseInit, + ...init, + // Headers need special handling - merge instead of replace + headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers + }; + return baseFetch(url, mergedInit); + }; +} +//# sourceMappingURL=transport.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/transport.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/transport.js.map new file mode 100644 index 000000000..7ddf2f94d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/transport.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../src/shared/transport.ts"],"names":[],"mappings":";;AAQA,4CAYC;AAUD,kDAeC;AAzCD;;;GAGG;AACH,SAAgB,gBAAgB,CAAC,OAAgC;IAC7D,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC;IAExB,IAAI,OAAO,YAAY,OAAO,EAAE,CAAC;QAC7B,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IACjD,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,EAAE,GAAI,OAAkC,EAAE,CAAC;AACtD,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,mBAAmB,CAAC,YAAuB,KAAK,EAAE,QAAsB;IACpF,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,8EAA8E;IAC9E,OAAO,KAAK,EAAE,GAAiB,EAAE,IAAkB,EAAqB,EAAE;QACtE,MAAM,UAAU,GAAgB;YAC5B,GAAG,QAAQ;YACX,GAAG,IAAI;YACP,2DAA2D;YAC3D,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,gBAAgB,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO;SAC3H,CAAC;QACF,OAAO,SAAS,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;IACtC,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/uriTemplate.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/uriTemplate.d.ts new file mode 100644 index 000000000..175e329b6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/uriTemplate.d.ts @@ -0,0 +1,25 @@ +export type Variables = Record; +export declare class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like {foo} or {?bar}. + */ + static isTemplate(str: string): boolean; + private static validateLength; + private readonly template; + private readonly parts; + get variableNames(): string[]; + constructor(template: string); + toString(): string; + private parse; + private getOperator; + private getNames; + private encodeValue; + private expandPart; + expand(variables: Variables): string; + private escapeRegExp; + private partToRegExp; + match(uri: string): Variables | null; +} +//# sourceMappingURL=uriTemplate.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/uriTemplate.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/uriTemplate.d.ts.map new file mode 100644 index 000000000..052e91851 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/uriTemplate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"uriTemplate.d.ts","sourceRoot":"","sources":["../../../src/shared/uriTemplate.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;AAO1D,qBAAa,WAAW;IACpB;;;;OAIG;IACH,MAAM,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAMvC,OAAO,CAAC,MAAM,CAAC,cAAc;IAK7B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAyF;IAE/G,IAAI,aAAa,IAAI,MAAM,EAAE,CAE5B;gBAEW,QAAQ,EAAE,MAAM;IAM5B,QAAQ,IAAI,MAAM;IAIlB,OAAO,CAAC,KAAK;IA8Cb,OAAO,CAAC,WAAW;IAKnB,OAAO,CAAC,QAAQ;IAShB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,UAAU;IAsDlB,MAAM,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM;IA4BpC,OAAO,CAAC,YAAY;IAIpB,OAAO,CAAC,YAAY;IAkDpB,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;CAuCvC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/uriTemplate.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/uriTemplate.js new file mode 100644 index 000000000..8f8c74a84 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/uriTemplate.js @@ -0,0 +1,243 @@ +"use strict"; +// Claude-authored implementation of RFC 6570 URI Templates +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UriTemplate = void 0; +const MAX_TEMPLATE_LENGTH = 1000000; // 1MB +const MAX_VARIABLE_LENGTH = 1000000; // 1MB +const MAX_TEMPLATE_EXPRESSIONS = 10000; +const MAX_REGEX_LENGTH = 1000000; // 1MB +class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like {foo} or {?bar}. + */ + static isTemplate(str) { + // Look for any sequence of characters between curly braces + // that isn't just whitespace + return /\{[^}\s]+\}/.test(str); + } + static validateLength(str, max, context) { + if (str.length > max) { + throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); + } + } + get variableNames() { + return this.parts.flatMap(part => (typeof part === 'string' ? [] : part.names)); + } + constructor(template) { + UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, 'Template'); + this.template = template; + this.parts = this.parse(template); + } + toString() { + return this.template; + } + parse(template) { + const parts = []; + let currentText = ''; + let i = 0; + let expressionCount = 0; + while (i < template.length) { + if (template[i] === '{') { + if (currentText) { + parts.push(currentText); + currentText = ''; + } + const end = template.indexOf('}', i); + if (end === -1) + throw new Error('Unclosed template expression'); + expressionCount++; + if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) { + throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); + } + const expr = template.slice(i + 1, end); + const operator = this.getOperator(expr); + const exploded = expr.includes('*'); + const names = this.getNames(expr); + const name = names[0]; + // Validate variable name length + for (const name of names) { + UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); + } + parts.push({ name, operator, names, exploded }); + i = end + 1; + } + else { + currentText += template[i]; + i++; + } + } + if (currentText) { + parts.push(currentText); + } + return parts; + } + getOperator(expr) { + const operators = ['+', '#', '.', '/', '?', '&']; + return operators.find(op => expr.startsWith(op)) || ''; + } + getNames(expr) { + const operator = this.getOperator(expr); + return expr + .slice(operator.length) + .split(',') + .map(name => name.replace('*', '').trim()) + .filter(name => name.length > 0); + } + encodeValue(value, operator) { + UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, 'Variable value'); + if (operator === '+' || operator === '#') { + return encodeURI(value); + } + return encodeURIComponent(value); + } + expandPart(part, variables) { + if (part.operator === '?' || part.operator === '&') { + const pairs = part.names + .map(name => { + const value = variables[name]; + if (value === undefined) + return ''; + const encoded = Array.isArray(value) + ? value.map(v => this.encodeValue(v, part.operator)).join(',') + : this.encodeValue(value.toString(), part.operator); + return `${name}=${encoded}`; + }) + .filter(pair => pair.length > 0); + if (pairs.length === 0) + return ''; + const separator = part.operator === '?' ? '?' : '&'; + return separator + pairs.join('&'); + } + if (part.names.length > 1) { + const values = part.names.map(name => variables[name]).filter(v => v !== undefined); + if (values.length === 0) + return ''; + return values.map(v => (Array.isArray(v) ? v[0] : v)).join(','); + } + const value = variables[part.name]; + if (value === undefined) + return ''; + const values = Array.isArray(value) ? value : [value]; + const encoded = values.map(v => this.encodeValue(v, part.operator)); + switch (part.operator) { + case '': + return encoded.join(','); + case '+': + return encoded.join(','); + case '#': + return '#' + encoded.join(','); + case '.': + return '.' + encoded.join('.'); + case '/': + return '/' + encoded.join('/'); + default: + return encoded.join(','); + } + } + expand(variables) { + let result = ''; + let hasQueryParam = false; + for (const part of this.parts) { + if (typeof part === 'string') { + result += part; + continue; + } + const expanded = this.expandPart(part, variables); + if (!expanded) + continue; + // Convert ? to & if we already have a query parameter + if ((part.operator === '?' || part.operator === '&') && hasQueryParam) { + result += expanded.replace('?', '&'); + } + else { + result += expanded; + } + if (part.operator === '?' || part.operator === '&') { + hasQueryParam = true; + } + } + return result; + } + escapeRegExp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + } + partToRegExp(part) { + const patterns = []; + // Validate variable name length for matching + for (const name of part.names) { + UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); + } + if (part.operator === '?' || part.operator === '&') { + for (let i = 0; i < part.names.length; i++) { + const name = part.names[i]; + const prefix = i === 0 ? '\\' + part.operator : '&'; + patterns.push({ + pattern: prefix + this.escapeRegExp(name) + '=([^&]+)', + name + }); + } + return patterns; + } + let pattern; + const name = part.name; + switch (part.operator) { + case '': + pattern = part.exploded ? '([^/,]+(?:,[^/,]+)*)' : '([^/,]+)'; + break; + case '+': + case '#': + pattern = '(.+)'; + break; + case '.': + pattern = '\\.([^/,]+)'; + break; + case '/': + pattern = '/' + (part.exploded ? '([^/,]+(?:,[^/,]+)*)' : '([^/,]+)'); + break; + default: + pattern = '([^/]+)'; + } + patterns.push({ pattern, name }); + return patterns; + } + match(uri) { + UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, 'URI'); + let pattern = '^'; + const names = []; + for (const part of this.parts) { + if (typeof part === 'string') { + pattern += this.escapeRegExp(part); + } + else { + const patterns = this.partToRegExp(part); + for (const { pattern: partPattern, name } of patterns) { + pattern += partPattern; + names.push({ name, exploded: part.exploded }); + } + } + } + pattern += '$'; + UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, 'Generated regex pattern'); + const regex = new RegExp(pattern); + const match = uri.match(regex); + if (!match) + return null; + const result = {}; + for (let i = 0; i < names.length; i++) { + const { name, exploded } = names[i]; + const value = match[i + 1]; + const cleanName = name.replace('*', ''); + if (exploded && value.includes(',')) { + result[cleanName] = value.split(','); + } + else { + result[cleanName] = value; + } + } + return result; + } +} +exports.UriTemplate = UriTemplate; +//# sourceMappingURL=uriTemplate.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/uriTemplate.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/uriTemplate.js.map new file mode 100644 index 000000000..6181393dc --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/uriTemplate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uriTemplate.js","sourceRoot":"","sources":["../../../src/shared/uriTemplate.ts"],"names":[],"mappings":";AAAA,2DAA2D;;;AAI3D,MAAM,mBAAmB,GAAG,OAAO,CAAC,CAAC,MAAM;AAC3C,MAAM,mBAAmB,GAAG,OAAO,CAAC,CAAC,MAAM;AAC3C,MAAM,wBAAwB,GAAG,KAAK,CAAC;AACvC,MAAM,gBAAgB,GAAG,OAAO,CAAC,CAAC,MAAM;AAExC,MAAa,WAAW;IACpB;;;;OAIG;IACH,MAAM,CAAC,UAAU,CAAC,GAAW;QACzB,2DAA2D;QAC3D,6BAA6B;QAC7B,OAAO,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACnC,CAAC;IAEO,MAAM,CAAC,cAAc,CAAC,GAAW,EAAE,GAAW,EAAE,OAAe;QACnE,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,GAAG,OAAO,8BAA8B,GAAG,oBAAoB,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC;QAClG,CAAC;IACL,CAAC;IAID,IAAI,aAAa;QACb,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IACpF,CAAC;IAED,YAAY,QAAgB;QACxB,WAAW,CAAC,cAAc,CAAC,QAAQ,EAAE,mBAAmB,EAAE,UAAU,CAAC,CAAC;Q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MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAE/B,IAAI,CAAC,KAAK;YAAE,OAAO,IAAI,CAAC;QAExB,MAAM,MAAM,GAAc,EAAE,CAAC;QAC7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACpC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YACpC,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YAC3B,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YAExC,IAAI,QAAQ,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;gBAClC,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YACzC,CAAC;iBAAM,CAAC;gBACJ,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC;YAC9B,CAAC;QACL,CAAC;QAED,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AArRD,kCAqRC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/spec.types.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/spec.types.d.ts new file mode 100644 index 000000000..f94e3cf8f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/spec.types.d.ts @@ -0,0 +1,2299 @@ +/** + * This file is automatically generated from the Model Context Protocol specification. + * + * Source: https://github.com/modelcontextprotocol/modelcontextprotocol + * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts + * Last updated from commit: 35fa160caf287a9c48696e3ae452c0645c713669 + * + * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. + * To update this file, run: npm run fetch:spec-types + */ +/** + * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. + * + * @category JSON-RPC + */ +export type JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResponse; +/** @internal */ +export declare const LATEST_PROTOCOL_VERSION = "DRAFT-2026-v1"; +/** @internal */ +export declare const JSONRPC_VERSION = "2.0"; +/** + * A progress token, used to associate progress notifications with the original request. + * + * @category Common Types + */ +export type ProgressToken = string | number; +/** + * An opaque token used to represent a cursor for pagination. + * + * @category Common Types + */ +export type Cursor = string; +/** + * Common params for any task-augmented request. + * + * @internal + */ +export interface TaskAugmentedRequestParams extends RequestParams { + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task?: TaskMetadata; +} +/** + * Common params for any request. + * + * @internal + */ +export interface RequestParams { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken?: ProgressToken; + [key: string]: unknown; + }; +} +/** @internal */ +export interface Request { + method: string; + params?: { + [key: string]: any; + }; +} +/** @internal */ +export interface NotificationParams { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** @internal */ +export interface Notification { + method: string; + params?: { + [key: string]: any; + }; +} +/** + * @category Common Types + */ +export interface Result { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; + [key: string]: unknown; +} +/** + * @category Common Types + */ +export interface Error { + /** + * The error type that occurred. + */ + code: number; + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string; + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data?: unknown; +} +/** + * A uniquely identifying ID for a request in JSON-RPC. + * + * @category Common Types + */ +export type RequestId = string | number; +/** + * A request that expects a response. + * + * @category JSON-RPC + */ +export interface JSONRPCRequest extends Request { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; +} +/** + * A notification which does not expect a response. + * + * @category JSON-RPC + */ +export interface JSONRPCNotification extends Notification { + jsonrpc: typeof JSONRPC_VERSION; +} +/** + * A successful (non-error) response to a request. + * + * @category JSON-RPC + */ +export interface JSONRPCResultResponse { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + result: Result; +} +/** + * A response to a request that indicates an error occurred. + * + * @category JSON-RPC + */ +export interface JSONRPCErrorResponse { + jsonrpc: typeof JSONRPC_VERSION; + id?: RequestId; + error: Error; +} +/** + * A response to a request, containing either the result or error. + */ +export type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse; +export declare const PARSE_ERROR = -32700; +export declare const INVALID_REQUEST = -32600; +export declare const METHOD_NOT_FOUND = -32601; +export declare const INVALID_PARAMS = -32602; +export declare const INTERNAL_ERROR = -32603; +/** @internal */ +export declare const URL_ELICITATION_REQUIRED = -32042; +/** + * An error response that indicates that the server requires the client to provide additional information via an elicitation request. + * + * @internal + */ +export interface URLElicitationRequiredError extends Omit { + error: Error & { + code: typeof URL_ELICITATION_REQUIRED; + data: { + elicitations: ElicitRequestURLParams[]; + [key: string]: unknown; + }; + }; +} +/** + * A response that indicates success but carries no data. + * + * @category Common Types + */ +export type EmptyResult = Result; +/** + * Parameters for a `notifications/cancelled` notification. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotificationParams extends NotificationParams { + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + * This MUST be provided for cancelling non-task requests. + * This MUST NOT be used for cancelling tasks (use the `tasks/cancel` request instead). + */ + requestId?: RequestId; + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; +} +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + * + * For task cancellation, use the `tasks/cancel` request instead of this notification. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotification extends JSONRPCNotification { + method: "notifications/cancelled"; + params: CancelledNotificationParams; +} +/** + * Parameters for an `initialize` request. + * + * @category `initialize` + */ +export interface InitializeRequestParams extends RequestParams { + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string; + capabilities: ClientCapabilities; + clientInfo: Implementation; +} +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + * + * @category `initialize` + */ +export interface InitializeRequest extends JSONRPCRequest { + method: "initialize"; + params: InitializeRequestParams; +} +/** + * After receiving an initialize request from the client, the server sends this response. + * + * @category `initialize` + */ +export interface InitializeResult extends Result { + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string; + capabilities: ServerCapabilities; + serverInfo: Implementation; + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions?: string; +} +/** + * This notification is sent from the client to the server after initialization has finished. + * + * @category `notifications/initialized` + */ +export interface InitializedNotification extends JSONRPCNotification { + method: "notifications/initialized"; + params?: NotificationParams; +} +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + * + * @category `initialize` + */ +export interface ClientCapabilities { + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental?: { + [key: string]: object; + }; + /** + * Present if the client supports listing roots. + */ + roots?: { + /** + * Whether the client supports notifications for changes to the roots list. + */ + listChanged?: boolean; + }; + /** + * Present if the client supports sampling from an LLM. + */ + sampling?: { + /** + * Whether the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context?: object; + /** + * Whether the client supports tool use via tools and toolChoice parameters. + */ + tools?: object; + }; + /** + * Present if the client supports elicitation from the server. + */ + elicitation?: { + form?: object; + url?: object; + }; + /** + * Present if the client supports task-augmented requests. + */ + tasks?: { + /** + * Whether this client supports tasks/list. + */ + list?: object; + /** + * Whether this client supports tasks/cancel. + */ + cancel?: object; + /** + * Specifies which request types can be augmented with tasks. + */ + requests?: { + /** + * Task support for sampling-related requests. + */ + sampling?: { + /** + * Whether the client supports task-augmented sampling/createMessage requests. + */ + createMessage?: object; + }; + /** + * Task support for elicitation-related requests. + */ + elicitation?: { + /** + * Whether the client supports task-augmented elicitation/create requests. + */ + create?: object; + }; + }; + }; +} +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + * + * @category `initialize` + */ +export interface ServerCapabilities { + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental?: { + [key: string]: object; + }; + /** + * Present if the server supports sending log messages to the client. + */ + logging?: object; + /** + * Present if the server supports argument autocompletion suggestions. + */ + completions?: object; + /** + * Present if the server offers any prompt templates. + */ + prompts?: { + /** + * Whether this server supports notifications for changes to the prompt list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any resources to read. + */ + resources?: { + /** + * Whether this server supports subscribing to resource updates. + */ + subscribe?: boolean; + /** + * Whether this server supports notifications for changes to the resource list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any tools to call. + */ + tools?: { + /** + * Whether this server supports notifications for changes to the tool list. + */ + listChanged?: boolean; + }; + /** + * Present if the server supports task-augmented requests. + */ + tasks?: { + /** + * Whether this server supports tasks/list. + */ + list?: object; + /** + * Whether this server supports tasks/cancel. + */ + cancel?: object; + /** + * Specifies which request types can be augmented with tasks. + */ + requests?: { + /** + * Task support for tool-related requests. + */ + tools?: { + /** + * Whether the server supports task-augmented tools/call requests. + */ + call?: object; + }; + }; + }; +} +/** + * An optionally-sized icon that can be displayed in a user interface. + * + * @category Common Types + */ +export interface Icon { + /** + * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a + * `data:` URI with Base64-encoded image data. + * + * Consumers SHOULD takes steps to ensure URLs serving icons are from the + * same domain as the client/server or a trusted domain. + * + * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain + * executable JavaScript. + * + * @format uri + */ + src: string; + /** + * Optional MIME type override if the source MIME type is missing or generic. + * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. + */ + mimeType?: string; + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes?: string[]; + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme?: "light" | "dark"; +} +/** + * Base interface to add `icons` property. + * + * @internal + */ +export interface Icons { + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons?: Icon[]; +} +/** + * Base interface for metadata with name (identifier) and title (display name) properties. + * + * @internal + */ +export interface BaseMetadata { + /** + * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). + */ + name: string; + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title?: string; +} +/** + * Describes the MCP implementation. + * + * @category `initialize` + */ +export interface Implementation extends BaseMetadata, Icons { + version: string; + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description?: string; + /** + * An optional URL of the website for this implementation. + * + * @format uri + */ + websiteUrl?: string; +} +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + * + * @category `ping` + */ +export interface PingRequest extends JSONRPCRequest { + method: "ping"; + params?: RequestParams; +} +/** + * Parameters for a `notifications/progress` notification. + * + * @category `notifications/progress` + */ +export interface ProgressNotificationParams extends NotificationParams { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; +} +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category `notifications/progress` + */ +export interface ProgressNotification extends JSONRPCNotification { + method: "notifications/progress"; + params: ProgressNotificationParams; +} +/** + * Common parameters for paginated requests. + * + * @internal + */ +export interface PaginatedRequestParams extends RequestParams { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; +} +/** @internal */ +export interface PaginatedRequest extends JSONRPCRequest { + params?: PaginatedRequestParams; +} +/** @internal */ +export interface PaginatedResult extends Result { + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor?: Cursor; +} +/** + * Sent from the client to request a list of resources the server has. + * + * @category `resources/list` + */ +export interface ListResourcesRequest extends PaginatedRequest { + method: "resources/list"; +} +/** + * The server's response to a resources/list request from the client. + * + * @category `resources/list` + */ +export interface ListResourcesResult extends PaginatedResult { + resources: Resource[]; +} +/** + * Sent from the client to request a list of resource templates the server has. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesRequest extends PaginatedRequest { + method: "resources/templates/list"; +} +/** + * The server's response to a resources/templates/list request from the client. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesResult extends PaginatedResult { + resourceTemplates: ResourceTemplate[]; +} +/** + * Common parameters when working with resources. + * + * @internal + */ +export interface ResourceRequestParams extends RequestParams { + /** + * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; +} +/** + * Parameters for a `resources/read` request. + * + * @category `resources/read` + */ +export interface ReadResourceRequestParams extends ResourceRequestParams { +} +/** + * Sent from the client to the server, to read a specific resource URI. + * + * @category `resources/read` + */ +export interface ReadResourceRequest extends JSONRPCRequest { + method: "resources/read"; + params: ReadResourceRequestParams; +} +/** + * The server's response to a resources/read request from the client. + * + * @category `resources/read` + */ +export interface ReadResourceResult extends Result { + contents: (TextResourceContents | BlobResourceContents)[]; +} +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/resources/list_changed` + */ +export interface ResourceListChangedNotification extends JSONRPCNotification { + method: "notifications/resources/list_changed"; + params?: NotificationParams; +} +/** + * Parameters for a `resources/subscribe` request. + * + * @category `resources/subscribe` + */ +export interface SubscribeRequestParams extends ResourceRequestParams { +} +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + * + * @category `resources/subscribe` + */ +export interface SubscribeRequest extends JSONRPCRequest { + method: "resources/subscribe"; + params: SubscribeRequestParams; +} +/** + * Parameters for a `resources/unsubscribe` request. + * + * @category `resources/unsubscribe` + */ +export interface UnsubscribeRequestParams extends ResourceRequestParams { +} +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + * + * @category `resources/unsubscribe` + */ +export interface UnsubscribeRequest extends JSONRPCRequest { + method: "resources/unsubscribe"; + params: UnsubscribeRequestParams; +} +/** + * Parameters for a `notifications/resources/updated` notification. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotificationParams extends NotificationParams { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; +} +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotification extends JSONRPCNotification { + method: "notifications/resources/updated"; + params: ResourceUpdatedNotificationParams; +} +/** + * A known resource that the server is capable of reading. + * + * @category `resources/list` + */ +export interface Resource extends BaseMetadata, Icons { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size?: number; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * A template description for resources available on the server. + * + * @category `resources/templates/list` + */ +export interface ResourceTemplate extends BaseMetadata, Icons { + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * + * @format uri-template + */ + uriTemplate: string; + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType?: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The contents of a specific resource or sub-resource. + * + * @internal + */ +export interface ResourceContents { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * @category Content + */ +export interface TextResourceContents extends ResourceContents { + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string; +} +/** + * @category Content + */ +export interface BlobResourceContents extends ResourceContents { + /** + * A base64-encoded string representing the binary data of the item. + * + * @format byte + */ + blob: string; +} +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + * + * @category `prompts/list` + */ +export interface ListPromptsRequest extends PaginatedRequest { + method: "prompts/list"; +} +/** + * The server's response to a prompts/list request from the client. + * + * @category `prompts/list` + */ +export interface ListPromptsResult extends PaginatedResult { + prompts: Prompt[]; +} +/** + * Parameters for a `prompts/get` request. + * + * @category `prompts/get` + */ +export interface GetPromptRequestParams extends RequestParams { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { + [key: string]: string; + }; +} +/** + * Used by the client to get a prompt provided by the server. + * + * @category `prompts/get` + */ +export interface GetPromptRequest extends JSONRPCRequest { + method: "prompts/get"; + params: GetPromptRequestParams; +} +/** + * The server's response to a prompts/get request from the client. + * + * @category `prompts/get` + */ +export interface GetPromptResult extends Result { + /** + * An optional description for the prompt. + */ + description?: string; + messages: PromptMessage[]; +} +/** + * A prompt or prompt template that the server offers. + * + * @category `prompts/list` + */ +export interface Prompt extends BaseMetadata, Icons { + /** + * An optional description of what this prompt provides + */ + description?: string; + /** + * A list of arguments to use for templating the prompt. + */ + arguments?: PromptArgument[]; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * Describes an argument that a prompt can accept. + * + * @category `prompts/list` + */ +export interface PromptArgument extends BaseMetadata { + /** + * A human-readable description of the argument. + */ + description?: string; + /** + * Whether this argument must be provided. + */ + required?: boolean; +} +/** + * The sender or recipient of messages and data in a conversation. + * + * @category Common Types + */ +export type Role = "user" | "assistant"; +/** + * Describes a message returned as part of a prompt. + * + * This is similar to `SamplingMessage`, but also supports the embedding of + * resources from the MCP server. + * + * @category `prompts/get` + */ +export interface PromptMessage { + role: Role; + content: ContentBlock; +} +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + * + * @category Content + */ +export interface ResourceLink extends Resource { + type: "resource_link"; +} +/** + * The contents of a resource, embedded into a prompt or tool call result. + * + * It is up to the client how best to render embedded resources for the benefit + * of the LLM and/or the user. + * + * @category Content + */ +export interface EmbeddedResource { + type: "resource"; + resource: TextResourceContents | BlobResourceContents; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/prompts/list_changed` + */ +export interface PromptListChangedNotification extends JSONRPCNotification { + method: "notifications/prompts/list_changed"; + params?: NotificationParams; +} +/** + * Sent from the client to request a list of tools the server has. + * + * @category `tools/list` + */ +export interface ListToolsRequest extends PaginatedRequest { + method: "tools/list"; +} +/** + * The server's response to a tools/list request from the client. + * + * @category `tools/list` + */ +export interface ListToolsResult extends PaginatedResult { + tools: Tool[]; +} +/** + * The server's response to a tool call. + * + * @category `tools/call` + */ +export interface CallToolResult extends Result { + /** + * A list of content objects that represent the unstructured result of the tool call. + */ + content: ContentBlock[]; + /** + * An optional JSON object that represents the structured result of the tool call. + */ + structuredContent?: { + [key: string]: unknown; + }; + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError?: boolean; +} +/** + * Parameters for a `tools/call` request. + * + * @category `tools/call` + */ +export interface CallToolRequestParams extends TaskAugmentedRequestParams { + /** + * The name of the tool. + */ + name: string; + /** + * Arguments to use for the tool call. + */ + arguments?: { + [key: string]: unknown; + }; +} +/** + * Used by the client to invoke a tool provided by the server. + * + * @category `tools/call` + */ +export interface CallToolRequest extends JSONRPCRequest { + method: "tools/call"; + params: CallToolRequestParams; +} +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/tools/list_changed` + */ +export interface ToolListChangedNotification extends JSONRPCNotification { + method: "notifications/tools/list_changed"; + params?: NotificationParams; +} +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + * + * @category `tools/list` + */ +export interface ToolAnnotations { + /** + * A human-readable title for the tool. + */ + title?: string; + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint?: boolean; + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint?: boolean; + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint?: boolean; + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint?: boolean; +} +/** + * Execution-related properties for a tool. + * + * @category `tools/list` + */ +export interface ToolExecution { + /** + * Indicates whether this tool supports task-augmented execution. + * This allows clients to handle long-running operations through polling + * the task system. + * + * - "forbidden": Tool does not support task-augmented execution (default when absent) + * - "optional": Tool may support task-augmented execution + * - "required": Tool requires task-augmented execution + * + * Default: "forbidden" + */ + taskSupport?: "forbidden" | "optional" | "required"; +} +/** + * Definition for a tool the client can call. + * + * @category `tools/list` + */ +export interface Tool extends BaseMetadata, Icons { + /** + * A human-readable description of the tool. + * + * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. + */ + description?: string; + /** + * A JSON Schema object defining the expected parameters for the tool. + */ + inputSchema: { + $schema?: string; + type: "object"; + properties?: { + [key: string]: object; + }; + required?: string[]; + }; + /** + * Execution-related properties for this tool. + */ + execution?: ToolExecution; + /** + * An optional JSON Schema object defining the structure of the tool's output returned in + * the structuredContent field of a CallToolResult. + * + * Defaults to JSON Schema 2020-12 when no explicit $schema is provided. + * Currently restricted to type: "object" at the root level. + */ + outputSchema?: { + $schema?: string; + type: "object"; + properties?: { + [key: string]: object; + }; + required?: string[]; + }; + /** + * Optional additional tool information. + * + * Display name precedence order is: title, annotations.title, then name. + */ + annotations?: ToolAnnotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The status of a task. + * + * @category `tasks` + */ +export type TaskStatus = "working" | "input_required" | "completed" | "failed" | "cancelled"; +/** + * Metadata for augmenting a request with task execution. + * Include this in the `task` field of the request parameters. + * + * @category `tasks` + */ +export interface TaskMetadata { + /** + * Requested duration in milliseconds to retain task from creation. + */ + ttl?: number; +} +/** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @category `tasks` + */ +export interface RelatedTaskMetadata { + /** + * The task identifier this message is associated with. + */ + taskId: string; +} +/** + * Data associated with a task. + * + * @category `tasks` + */ +export interface Task { + /** + * The task identifier. + */ + taskId: string; + /** + * Current task state. + */ + status: TaskStatus; + /** + * Optional human-readable message describing the current task state. + * This can provide context for any status, including: + * - Reasons for "cancelled" status + * - Summaries for "completed" status + * - Diagnostic information for "failed" status (e.g., error details, what went wrong) + */ + statusMessage?: string; + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: string; + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: string; + /** + * Actual retention duration from creation in milliseconds, null for unlimited. + */ + ttl: number | null; + /** + * Suggested polling interval in milliseconds. + */ + pollInterval?: number; +} +/** + * A response to a task-augmented request. + * + * @category `tasks` + */ +export interface CreateTaskResult extends Result { + task: Task; +} +/** + * A request to retrieve the state of a task. + * + * @category `tasks/get` + */ +export interface GetTaskRequest extends JSONRPCRequest { + method: "tasks/get"; + params: { + /** + * The task identifier to query. + */ + taskId: string; + }; +} +/** + * The response to a tasks/get request. + * + * @category `tasks/get` + */ +export type GetTaskResult = Result & Task; +/** + * A request to retrieve the result of a completed task. + * + * @category `tasks/result` + */ +export interface GetTaskPayloadRequest extends JSONRPCRequest { + method: "tasks/result"; + params: { + /** + * The task identifier to retrieve results for. + */ + taskId: string; + }; +} +/** + * The response to a tasks/result request. + * The structure matches the result type of the original request. + * For example, a tools/call task would return the CallToolResult structure. + * + * @category `tasks/result` + */ +export interface GetTaskPayloadResult extends Result { + [key: string]: unknown; +} +/** + * A request to cancel a task. + * + * @category `tasks/cancel` + */ +export interface CancelTaskRequest extends JSONRPCRequest { + method: "tasks/cancel"; + params: { + /** + * The task identifier to cancel. + */ + taskId: string; + }; +} +/** + * The response to a tasks/cancel request. + * + * @category `tasks/cancel` + */ +export type CancelTaskResult = Result & Task; +/** + * A request to retrieve a list of tasks. + * + * @category `tasks/list` + */ +export interface ListTasksRequest extends PaginatedRequest { + method: "tasks/list"; +} +/** + * The response to a tasks/list request. + * + * @category `tasks/list` + */ +export interface ListTasksResult extends PaginatedResult { + tasks: Task[]; +} +/** + * Parameters for a `notifications/tasks/status` notification. + * + * @category `notifications/tasks/status` + */ +export type TaskStatusNotificationParams = NotificationParams & Task; +/** + * An optional notification from the receiver to the requestor, informing them that a task's status has changed. Receivers are not required to send these notifications. + * + * @category `notifications/tasks/status` + */ +export interface TaskStatusNotification extends JSONRPCNotification { + method: "notifications/tasks/status"; + params: TaskStatusNotificationParams; +} +/** + * Parameters for a `logging/setLevel` request. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequestParams extends RequestParams { + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/message. + */ + level: LoggingLevel; +} +/** + * A request from the client to the server, to enable or adjust logging. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequest extends JSONRPCRequest { + method: "logging/setLevel"; + params: SetLevelRequestParams; +} +/** + * Parameters for a `notifications/message` notification. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotificationParams extends NotificationParams { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; +} +/** + * JSONRPCNotification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotification extends JSONRPCNotification { + method: "notifications/message"; + params: LoggingMessageNotificationParams; +} +/** + * The severity of a log message. + * + * These map to syslog message severities, as specified in RFC-5424: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + * + * @category Common Types + */ +export type LoggingLevel = "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency"; +/** + * Parameters for a `sampling/createMessage` request. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequestParams extends TaskAugmentedRequestParams { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext?: "none" | "thisServer" | "allServers"; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: object; + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools?: Tool[]; + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice?: ToolChoice; +} +/** + * Controls tool selection behavior for sampling requests. + * + * @category `sampling/createMessage` + */ +export interface ToolChoice { + /** + * Controls the tool use ability of the model: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode?: "auto" | "required" | "none"; +} +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequest extends JSONRPCRequest { + method: "sampling/createMessage"; + params: CreateMessageRequestParams; +} +/** + * The client's response to a sampling/createMessage request from the server. + * The client should inform the user before returning the sampled message, to allow them + * to inspect the response (human in the loop) and decide whether to allow the server to see it. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageResult extends Result, SamplingMessage { + /** + * The name of the model that generated the message. + */ + model: string; + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason?: "endTurn" | "stopSequence" | "maxTokens" | "toolUse" | string; +} +/** + * Describes a message issued to or received from an LLM API. + * + * @category `sampling/createMessage` + */ +export interface SamplingMessage { + role: Role; + content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +export type SamplingMessageContentBlock = TextContent | ImageContent | AudioContent | ToolUseContent | ToolResultContent; +/** + * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed + * + * @category Common Types + */ +export interface Annotations { + /** + * Describes who the intended audience of this object or data is. + * + * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). + */ + audience?: Role[]; + /** + * Describes how important this data is for operating the server. + * + * A value of 1 means "most important," and indicates that the data is + * effectively required, while 0 means "least important," and indicates that + * the data is entirely optional. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + priority?: number; + /** + * The moment the resource was last modified, as an ISO 8601 formatted string. + * + * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). + * + * Examples: last activity timestamp in an open file, timestamp when the resource + * was attached, etc. + */ + lastModified?: string; +} +/** + * @category Content + */ +export type ContentBlock = TextContent | ImageContent | AudioContent | ResourceLink | EmbeddedResource; +/** + * Text provided to or from an LLM. + * + * @category Content + */ +export interface TextContent { + type: "text"; + /** + * The text content of the message. + */ + text: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * An image provided to or from an LLM. + * + * @category Content + */ +export interface ImageContent { + type: "image"; + /** + * The base64-encoded image data. + * + * @format byte + */ + data: string; + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * Audio provided to or from an LLM. + * + * @category Content + */ +export interface AudioContent { + type: "audio"; + /** + * The base64-encoded audio data. + * + * @format byte + */ + data: string; + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * A request from the assistant to call a tool. + * + * @category `sampling/createMessage` + */ +export interface ToolUseContent { + type: "tool_use"; + /** + * A unique identifier for this tool use. + * + * This ID is used to match tool results to their corresponding tool uses. + */ + id: string; + /** + * The name of the tool to call. + */ + name: string; + /** + * The arguments to pass to the tool, conforming to the tool's input schema. + */ + input: { + [key: string]: unknown; + }; + /** + * Optional metadata about the tool use. Clients SHOULD preserve this field when + * including tool uses in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The result of a tool use, provided by the user back to the assistant. + * + * @category `sampling/createMessage` + */ +export interface ToolResultContent { + type: "tool_result"; + /** + * The ID of the tool use this result corresponds to. + * + * This MUST match the ID from a previous ToolUseContent. + */ + toolUseId: string; + /** + * The unstructured result content of the tool use. + * + * This has the same format as CallToolResult.content and can include text, images, + * audio, resource links, and embedded resources. + */ + content: ContentBlock[]; + /** + * An optional structured result object. + * + * If the tool defined an outputSchema, this SHOULD conform to that schema. + */ + structuredContent?: { + [key: string]: unknown; + }; + /** + * Whether the tool use resulted in an error. + * + * If true, the content typically describes the error that occurred. + * Default: false + */ + isError?: boolean; + /** + * Optional metadata about the tool result. Clients SHOULD preserve this field when + * including tool results in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The server's preferences for model selection, requested of the client during sampling. + * + * Because LLMs can vary along multiple dimensions, choosing the "best" model is + * rarely straightforward. Different models excel in different areas—some are + * faster but less capable, others are more capable but more expensive, and so + * on. This interface allows servers to express their priorities across multiple + * dimensions to help clients make an appropriate selection for their use case. + * + * These preferences are always advisory. The client MAY ignore them. It is also + * up to the client to decide how to interpret these preferences and how to + * balance them against other considerations. + * + * @category `sampling/createMessage` + */ +export interface ModelPreferences { + /** + * Optional hints to use for model selection. + * + * If multiple hints are specified, the client MUST evaluate them in order + * (such that the first match is taken). + * + * The client SHOULD prioritize these hints over the numeric priorities, but + * MAY still use the priorities to select from ambiguous matches. + */ + hints?: ModelHint[]; + /** + * How much to prioritize cost when selecting a model. A value of 0 means cost + * is not important, while a value of 1 means cost is the most important + * factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + costPriority?: number; + /** + * How much to prioritize sampling speed (latency) when selecting a model. A + * value of 0 means speed is not important, while a value of 1 means speed is + * the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + speedPriority?: number; + /** + * How much to prioritize intelligence and capabilities when selecting a + * model. A value of 0 means intelligence is not important, while a value of 1 + * means intelligence is the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + intelligencePriority?: number; +} +/** + * Hints to use for model selection. + * + * Keys not declared here are currently left unspecified by the spec and are up + * to the client to interpret. + * + * @category `sampling/createMessage` + */ +export interface ModelHint { + /** + * A hint for a model name. + * + * The client SHOULD treat this as a substring of a model name; for example: + * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` + * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. + * - `claude` should match any Claude model + * + * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: + * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` + */ + name?: string; +} +/** + * Parameters for a `completion/complete` request. + * + * @category `completion/complete` + */ +export interface CompleteRequestParams extends RequestParams { + ref: PromptReference | ResourceTemplateReference; + /** + * The argument's information + */ + argument: { + /** + * The name of the argument + */ + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + /** + * Additional, optional context for completions + */ + context?: { + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments?: { + [key: string]: string; + }; + }; +} +/** + * A request from the client to the server, to ask for completion options. + * + * @category `completion/complete` + */ +export interface CompleteRequest extends JSONRPCRequest { + method: "completion/complete"; + params: CompleteRequestParams; +} +/** + * The server's response to a completion/complete request + * + * @category `completion/complete` + */ +export interface CompleteResult extends Result { + completion: { + /** + * An array of completion values. Must not exceed 100 items. + */ + values: string[]; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total?: number; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore?: boolean; + }; +} +/** + * A reference to a resource or resource template definition. + * + * @category `completion/complete` + */ +export interface ResourceTemplateReference { + type: "ref/resource"; + /** + * The URI or URI template of the resource. + * + * @format uri-template + */ + uri: string; +} +/** + * Identifies a prompt. + * + * @category `completion/complete` + */ +export interface PromptReference extends BaseMetadata { + type: "ref/prompt"; +} +/** + * Sent from the server to request a list of root URIs from the client. Roots allow + * servers to ask for specific directories or files to operate on. A common example + * for roots is providing a set of repositories or directories a server should operate + * on. + * + * This request is typically used when the server needs to understand the file system + * structure or access specific locations that the client has permission to read from. + * + * @category `roots/list` + */ +export interface ListRootsRequest extends JSONRPCRequest { + method: "roots/list"; + params?: RequestParams; +} +/** + * The client's response to a roots/list request from the server. + * This result contains an array of Root objects, each representing a root directory + * or file that the server can operate on. + * + * @category `roots/list` + */ +export interface ListRootsResult extends Result { + roots: Root[]; +} +/** + * Represents a root directory or file that the server can operate on. + * + * @category `roots/list` + */ +export interface Root { + /** + * The URI identifying the root. This *must* start with file:// for now. + * This restriction may be relaxed in future versions of the protocol to allow + * other URI schemes. + * + * @format uri + */ + uri: string; + /** + * An optional name for the root. This can be used to provide a human-readable + * identifier for the root, which may be useful for display purposes or for + * referencing the root in other parts of the application. + */ + name?: string; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * A notification from the client to the server, informing it that the list of roots has changed. + * This notification should be sent whenever the client adds, removes, or modifies any root. + * The server should then request an updated list of roots using the ListRootsRequest. + * + * @category `notifications/roots/list_changed` + */ +export interface RootsListChangedNotification extends JSONRPCNotification { + method: "notifications/roots/list_changed"; + params?: NotificationParams; +} +/** + * The parameters for a request to elicit non-sensitive information from the user via a form in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestFormParams extends TaskAugmentedRequestParams { + /** + * The elicitation mode. + */ + mode?: "form"; + /** + * The message to present to the user describing what information is being requested. + */ + message: string; + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: { + $schema?: string; + type: "object"; + properties: { + [key: string]: PrimitiveSchemaDefinition; + }; + required?: string[]; + }; +} +/** + * The parameters for a request to elicit information from the user via a URL in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestURLParams extends TaskAugmentedRequestParams { + /** + * The elicitation mode. + */ + mode: "url"; + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string; + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string; + /** + * The URL that the user should navigate to. + * + * @format uri + */ + url: string; +} +/** + * The parameters for a request to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export type ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLParams; +/** + * A request from the server to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequest extends JSONRPCRequest { + method: "elicitation/create"; + params: ElicitRequestParams; +} +/** + * Restricted schema definitions that only allow primitive types + * without nested objects or arrays. + * + * @category `elicitation/create` + */ +export type PrimitiveSchemaDefinition = StringSchema | NumberSchema | BooleanSchema | EnumSchema; +/** + * @category `elicitation/create` + */ +export interface StringSchema { + type: "string"; + title?: string; + description?: string; + minLength?: number; + maxLength?: number; + format?: "email" | "uri" | "date" | "date-time"; + default?: string; +} +/** + * @category `elicitation/create` + */ +export interface NumberSchema { + type: "number" | "integer"; + title?: string; + description?: string; + minimum?: number; + maximum?: number; + default?: number; +} +/** + * @category `elicitation/create` + */ +export interface BooleanSchema { + type: "boolean"; + title?: string; + description?: string; + default?: boolean; +} +/** + * Schema for single-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum values to choose from. + */ + enum: string[]; + /** + * Optional default value. + */ + default?: string; +} +/** + * Schema for single-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum options with values and display labels. + */ + oneOf: Array<{ + /** + * The enum value. + */ + const: string; + /** + * Display label for this option. + */ + title: string; + }>; + /** + * Optional default value. + */ + default?: string; +} +/** + * @category `elicitation/create` + */ +export type SingleSelectEnumSchema = UntitledSingleSelectEnumSchema | TitledSingleSelectEnumSchema; +/** + * Schema for multiple-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for the array items. + */ + items: { + type: "string"; + /** + * Array of enum values to choose from. + */ + enum: string[]; + }; + /** + * Optional default value. + */ + default?: string[]; +} +/** + * Schema for multiple-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for array items with enum options and display labels. + */ + items: { + /** + * Array of enum options with values and display labels. + */ + anyOf: Array<{ + /** + * The constant enum value. + */ + const: string; + /** + * Display title for this option. + */ + title: string; + }>; + }; + /** + * Optional default value. + */ + default?: string[]; +} +/** + * @category `elicitation/create` + */ +export type MultiSelectEnumSchema = UntitledMultiSelectEnumSchema | TitledMultiSelectEnumSchema; +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + * + * @category `elicitation/create` + */ +export interface LegacyTitledEnumSchema { + type: "string"; + title?: string; + description?: string; + enum: string[]; + /** + * (Legacy) Display names for enum values. + * Non-standard according to JSON schema 2020-12. + */ + enumNames?: string[]; + default?: string; +} +/** + * @category `elicitation/create` + */ +export type EnumSchema = SingleSelectEnumSchema | MultiSelectEnumSchema | LegacyTitledEnumSchema; +/** + * The client's response to an elicitation request. + * + * @category `elicitation/create` + */ +export interface ElicitResult extends Result { + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: "accept" | "decline" | "cancel"; + /** + * The submitted form data, only present when action is "accept" and mode was "form". + * Contains values matching the requested schema. + * Omitted for out-of-band mode responses. + */ + content?: { + [key: string]: string | number | boolean | string[]; + }; +} +/** + * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. + * + * @category `notifications/elicitation/complete` + */ +export interface ElicitationCompleteNotification extends JSONRPCNotification { + method: "notifications/elicitation/complete"; + params: { + /** + * The ID of the elicitation that completed. + */ + elicitationId: string; + }; +} +/** @internal */ +export type ClientRequest = PingRequest | InitializeRequest | CompleteRequest | SetLevelRequest | GetPromptRequest | ListPromptsRequest | ListResourcesRequest | ListResourceTemplatesRequest | ReadResourceRequest | SubscribeRequest | UnsubscribeRequest | CallToolRequest | ListToolsRequest | GetTaskRequest | GetTaskPayloadRequest | ListTasksRequest | CancelTaskRequest; +/** @internal */ +export type ClientNotification = CancelledNotification | ProgressNotification | InitializedNotification | RootsListChangedNotification | TaskStatusNotification; +/** @internal */ +export type ClientResult = EmptyResult | CreateMessageResult | ListRootsResult | ElicitResult | GetTaskResult | GetTaskPayloadResult | ListTasksResult | CancelTaskResult; +/** @internal */ +export type ServerRequest = PingRequest | CreateMessageRequest | ListRootsRequest | ElicitRequest | GetTaskRequest | GetTaskPayloadRequest | ListTasksRequest | CancelTaskRequest; +/** @internal */ +export type ServerNotification = CancelledNotification | ProgressNotification | LoggingMessageNotification | ResourceUpdatedNotification | ResourceListChangedNotification | ToolListChangedNotification | PromptListChangedNotification | ElicitationCompleteNotification | TaskStatusNotification; +/** @internal */ +export type ServerResult = EmptyResult | InitializeResult | CompleteResult | GetPromptResult | ListPromptsResult | ListResourceTemplatesResult | ListResourcesResult | ReadResourceResult | CallToolResult | ListToolsResult | GetTaskResult | GetTaskPayloadResult | ListTasksResult | CancelTaskResult; +//# sourceMappingURL=spec.types.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/spec.types.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/spec.types.d.ts.map new file mode 100644 index 000000000..7e4fb0e57 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/spec.types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"spec.types.d.ts","sourceRoot":"","sources":["../../src/spec.types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH;;;;GAIG;AACH,MAAM,MAAM,cAAc,GACtB,cAAc,GACd,mBAAmB,GACnB,eAAe,CAAC;AAEpB,gBAAgB;AAChB,eAAO,MAAM,uBAAuB,kBAAkB,CAAC;AACvD,gBAAgB;AAChB,eAAO,MAAM,eAAe,QAAQ,CAAC;AAErC;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,CAAC;AAE5C;;;;GAIG;AACH,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC;AAE5B;;;;GAIG;AACH,MAAM,WAAW,0BAA2B,SAAQ,aAAa;IAC/D;;;;;;;OAOG;IACH,IAAI,CAAC,EAAE,YAAY,CAAC;CAC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AkB,GAC1B,qBAAqB,GACrB,oBAAoB,GACpB,0BAA0B,GAC1B,2BAA2B,GAC3B,+BAA+B,GAC/B,2BAA2B,GAC3B,6BAA6B,GAC7B,+BAA+B,GAC/B,sBAAsB,CAAC;AAE3B,gBAAgB;AAChB,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,gBAAgB,GAChB,cAAc,GACd,eAAe,GACf,iBAAiB,GACjB,2BAA2B,GAC3B,mBAAmB,GACnB,kBAAkB,GAClB,cAAc,GACd,eAAe,GACf,aAAa,GACb,oBAAoB,GACpB,eAAe,GACf,gBAAgB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/spec.types.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/spec.types.js new file mode 100644 index 000000000..6924e5157 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/spec.types.js @@ -0,0 +1,27 @@ +"use strict"; +/** + * This file is automatically generated from the Model Context Protocol specification. + * + * Source: https://github.com/modelcontextprotocol/modelcontextprotocol + * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts + * Last updated from commit: 35fa160caf287a9c48696e3ae452c0645c713669 + * + * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. + * To update this file, run: npm run fetch:spec-types + */ /* JSON-RPC types */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.URL_ELICITATION_REQUIRED = exports.INTERNAL_ERROR = exports.INVALID_PARAMS = exports.METHOD_NOT_FOUND = exports.INVALID_REQUEST = exports.PARSE_ERROR = exports.JSONRPC_VERSION = exports.LATEST_PROTOCOL_VERSION = void 0; +/** @internal */ +exports.LATEST_PROTOCOL_VERSION = "DRAFT-2026-v1"; +/** @internal */ +exports.JSONRPC_VERSION = "2.0"; +// Standard JSON-RPC error codes +exports.PARSE_ERROR = -32700; +exports.INVALID_REQUEST = -32600; +exports.METHOD_NOT_FOUND = -32601; +exports.INVALID_PARAMS = -32602; +exports.INTERNAL_ERROR = -32603; +// Implementation-specific JSON-RPC error codes [-32000, -32099] +/** @internal */ +exports.URL_ELICITATION_REQUIRED = -32042; +//# sourceMappingURL=spec.types.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/spec.types.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/spec.types.js.map new file mode 100644 index 000000000..b04ea1a9d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/spec.types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spec.types.js","sourceRoot":"","sources":["../../src/spec.types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG,CAAA,oBAAoB;;;AAYvB,gBAAgB;AACH,QAAA,uBAAuB,GAAG,eAAe,CAAC;AACvD,gBAAgB;AACH,QAAA,eAAe,GAAG,KAAK,CAAC;AA4JrC,gCAAgC;AACnB,QAAA,WAAW,GAAG,CAAC,KAAK,CAAC;AACrB,QAAA,eAAe,GAAG,CAAC,KAAK,CAAC;AACzB,QAAA,gBAAgB,GAAG,CAAC,KAAK,CAAC;AAC1B,QAAA,cAAc,GAAG,CAAC,KAAK,CAAC;AACxB,QAAA,cAAc,GAAG,CAAC,KAAK,CAAC;AAErC,gEAAgE;AAChE,gBAAgB;AACH,QAAA,wBAAwB,GAAG,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/types.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/types.d.ts new file mode 100644 index 000000000..55f087ef8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/types.d.ts @@ -0,0 +1,8133 @@ +import * as z from 'zod/v4'; +import { AuthInfo } from './server/auth/types.js'; +export declare const LATEST_PROTOCOL_VERSION = "2025-11-25"; +export declare const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; +export declare const SUPPORTED_PROTOCOL_VERSIONS: string[]; +export declare const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; +export declare const JSONRPC_VERSION = "2.0"; +/** + * Utility types + */ +type ExpandRecursively = T extends object ? (T extends infer O ? { + [K in keyof O]: ExpandRecursively; +} : never) : T; +/** + * A progress token, used to associate progress notifications with the original request. + */ +export declare const ProgressTokenSchema: z.ZodUnion; +/** + * An opaque token used to represent a cursor for pagination. + */ +export declare const CursorSchema: z.ZodString; +/** + * Task creation parameters, used to ask that the server create a task to represent a request. + */ +export declare const TaskCreationParamsSchema: z.ZodObject<{ + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: z.ZodOptional>; + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval: z.ZodOptional; +}, z.core.$loose>; +export declare const TaskMetadataSchema: z.ZodObject<{ + ttl: z.ZodOptional; +}, z.core.$strip>; +/** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + */ +export declare const RelatedTaskMetadataSchema: z.ZodObject<{ + taskId: z.ZodString; +}, z.core.$strip>; +declare const RequestMetaSchema: z.ZodObject<{ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; +}, z.core.$loose>; +/** + * Common params for any request. + */ +declare const BaseRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strip>; +/** + * Common params for any task-augmented request. + */ +export declare const TaskAugmentedRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * Checks if a value is a valid TaskAugmentedRequestParams. + * @param value - The value to check. + * + * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise. + */ +export declare const isTaskAugmentedRequestParams: (value: unknown) => value is TaskAugmentedRequestParams; +export declare const RequestSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$strip>; +declare const NotificationsParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strip>; +export declare const NotificationSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$strip>; +export declare const ResultSchema: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$loose>; +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +export declare const RequestIdSchema: z.ZodUnion; +/** + * A request that expects a response. + */ +export declare const JSONRPCRequestSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; +}, z.core.$strict>; +export declare const isJSONRPCRequest: (value: unknown) => value is JSONRPCRequest; +/** + * A notification which does not expect a response. + */ +export declare const JSONRPCNotificationSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; +}, z.core.$strict>; +export declare const isJSONRPCNotification: (value: unknown) => value is JSONRPCNotification; +/** + * A successful (non-error) response to a request. + */ +export declare const JSONRPCResultResponseSchema: z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; + result: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>; +}, z.core.$strict>; +/** + * Checks if a value is a valid JSONRPCResultResponse. + * @param value - The value to check. + * + * @returns True if the value is a valid JSONRPCResultResponse, false otherwise. + */ +export declare const isJSONRPCResultResponse: (value: unknown) => value is JSONRPCResultResponse; +/** + * @deprecated Use {@link isJSONRPCResultResponse} instead. + * + * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse}) + */ +export declare const isJSONRPCResponse: (value: unknown) => value is JSONRPCResultResponse; +/** + * Error codes defined by the JSON-RPC specification. + */ +export declare enum ErrorCode { + ConnectionClosed = -32000, + RequestTimeout = -32001, + ParseError = -32700, + InvalidRequest = -32600, + MethodNotFound = -32601, + InvalidParams = -32602, + InternalError = -32603, + UrlElicitationRequired = -32042 +} +/** + * A response to a request that indicates an error occurred. + */ +export declare const JSONRPCErrorResponseSchema: z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodOptional>; + error: z.ZodObject<{ + code: z.ZodNumber; + message: z.ZodString; + data: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strict>; +/** + * @deprecated Use {@link JSONRPCErrorResponseSchema} instead. + */ +export declare const JSONRPCErrorSchema: z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodOptional>; + error: z.ZodObject<{ + code: z.ZodNumber; + message: z.ZodString; + data: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strict>; +/** + * Checks if a value is a valid JSONRPCErrorResponse. + * @param value - The value to check. + * + * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise. + */ +export declare const isJSONRPCErrorResponse: (value: unknown) => value is JSONRPCErrorResponse; +/** + * @deprecated Use {@link isJSONRPCErrorResponse} instead. + */ +export declare const isJSONRPCError: (value: unknown) => value is JSONRPCErrorResponse; +export declare const JSONRPCMessageSchema: z.ZodUnion>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; +}, z.core.$strict>, z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; +}, z.core.$strict>, z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; + result: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>; +}, z.core.$strict>, z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodOptional>; + error: z.ZodObject<{ + code: z.ZodNumber; + message: z.ZodString; + data: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strict>]>; +export declare const JSONRPCResponseSchema: z.ZodUnion; + id: z.ZodUnion; + result: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>; +}, z.core.$strict>, z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodOptional>; + error: z.ZodObject<{ + code: z.ZodNumber; + message: z.ZodString; + data: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strict>]>; +/** + * A response that indicates success but carries no data. + */ +export declare const EmptyResultSchema: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strict>; +export declare const CancelledNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + requestId: z.ZodOptional>; + reason: z.ZodOptional; +}, z.core.$strip>; +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + */ +export declare const CancelledNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/cancelled">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + requestId: z.ZodOptional>; + reason: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Icon schema for use in tools, prompts, resources, and implementations. + */ +export declare const IconSchema: z.ZodObject<{ + src: z.ZodString; + mimeType: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; +}, z.core.$strip>; +/** + * Base schema to add `icons` property. + * + */ +export declare const IconsSchema: z.ZodObject<{ + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; +}, z.core.$strip>; +/** + * Base metadata interface for common properties across resources, tools, prompts, and implementations. + */ +export declare const BaseMetadataSchema: z.ZodObject<{ + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Describes the name and version of an MCP implementation. + */ +export declare const ImplementationSchema: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + description: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Task capabilities for clients, indicating which request types support task creation. + */ +export declare const ClientTasksCapabilitySchema: z.ZodObject<{ + /** + * Present if the client supports listing tasks. + */ + list: z.ZodOptional>; + /** + * Present if the client supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + /** + * Task support for elicitation requests. + */ + elicitation: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$loose>; +/** + * Task capabilities for servers, indicating which request types support task creation. + */ +export declare const ServerTasksCapabilitySchema: z.ZodObject<{ + /** + * Present if the server supports listing tasks. + */ + list: z.ZodOptional>; + /** + * Present if the server supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$loose>; +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ +export declare const ClientCapabilitiesSchema: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the client supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + /** + * Task support for elicitation requests. + */ + elicitation: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$strip>; +export declare const InitializeRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the client supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + /** + * Task support for elicitation requests. + */ + elicitation: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$strip>; + clientInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + description: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ +export declare const InitializeRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"initialize">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the client supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + /** + * Task support for elicitation requests. + */ + elicitation: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$strip>; + clientInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + description: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + }, z.core.$strip>; +}, z.core.$strip>; +export declare const isInitializeRequest: (value: unknown) => value is InitializeRequest; +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ +export declare const ServerCapabilitiesSchema: z.ZodObject<{ + experimental: z.ZodOptional>>; + logging: z.ZodOptional>; + completions: z.ZodOptional>; + prompts: z.ZodOptional; + }, z.core.$strip>>; + resources: z.ZodOptional; + listChanged: z.ZodOptional; + }, z.core.$strip>>; + tools: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the server supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$strip>; +/** + * After receiving an initialize request from the client, the server sends this response. + */ +export declare const InitializeResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + logging: z.ZodOptional>; + completions: z.ZodOptional>; + prompts: z.ZodOptional; + }, z.core.$strip>>; + resources: z.ZodOptional; + listChanged: z.ZodOptional; + }, z.core.$strip>>; + tools: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the server supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$strip>; + serverInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + description: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + instructions: z.ZodOptional; +}, z.core.$loose>; +/** + * This notification is sent from the client to the server after initialization has finished. + */ +export declare const InitializedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/initialized">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +export declare const isInitializedNotification: (value: unknown) => value is InitializedNotification; +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +export declare const PingRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"ping">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +export declare const ProgressSchema: z.ZodObject<{ + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; +}, z.core.$strip>; +export declare const ProgressNotificationParamsSchema: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strip>; +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ +export declare const ProgressNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/progress">; + params: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>; +}, z.core.$strip>; +export declare const PaginatedRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; +}, z.core.$strip>; +export declare const PaginatedRequestSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$strip>; +export declare const PaginatedResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; +}, z.core.$loose>; +/** + * The status of a task. + * */ +export declare const TaskStatusSchema: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; +}>; +/** + * A pollable state object associated with a request. + */ +export declare const TaskSchema: z.ZodObject<{ + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; +}, z.core.$strip>; +/** + * Result returned when a task is created, containing the task data wrapped in a task field. + */ +export declare const CreateTaskResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodObject<{ + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$loose>; +/** + * Parameters for task status notification. + */ +export declare const TaskStatusNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; +}, z.core.$strip>; +/** + * A notification sent when a task's status changes. + */ +export declare const TaskStatusNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/tasks/status">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * A request to get the state of a specific task. + */ +export declare const GetTaskRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"tasks/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * The response to a tasks/get request. + */ +export declare const GetTaskResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; +}, z.core.$strip>; +/** + * A request to get the result of a specific task. + */ +export declare const GetTaskPayloadRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"tasks/result">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * The response to a tasks/result request. + * The structure matches the result type of the original request. + * For example, a tools/call task would return the CallToolResult structure. + * + */ +export declare const GetTaskPayloadResultSchema: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$loose>; +/** + * A request to list tasks. + */ +export declare const ListTasksRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"tasks/list">; +}, z.core.$strip>; +/** + * The response to a tasks/list request. + */ +export declare const ListTasksResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + tasks: z.ZodArray; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * A request to cancel a specific task. + */ +export declare const CancelTaskRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"tasks/cancel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * The response to a tasks/cancel request. + */ +export declare const CancelTaskResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; +}, z.core.$strip>; +/** + * The contents of a specific resource or sub-resource. + */ +export declare const ResourceContentsSchema: z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>; +export declare const TextResourceContentsSchema: z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + text: z.ZodString; +}, z.core.$strip>; +export declare const BlobResourceContentsSchema: z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; +}, z.core.$strip>; +/** + * The sender or recipient of messages and data in a conversation. + */ +export declare const RoleSchema: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; +}>; +/** + * Optional annotations providing clients additional context about a resource. + */ +export declare const AnnotationsSchema: z.ZodObject<{ + audience: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; +}, z.core.$strip>; +/** + * A known resource that the server is capable of reading. + */ +export declare const ResourceSchema: z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * A template description for resources available on the server. + */ +export declare const ResourceTemplateSchema: z.ZodObject<{ + uriTemplate: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Sent from the client to request a list of resources the server has. + */ +export declare const ListResourcesRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"resources/list">; +}, z.core.$strip>; +/** + * The server's response to a resources/list request from the client. + */ +export declare const ListResourcesResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + resources: z.ZodArray; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * Sent from the client to request a list of resource templates the server has. + */ +export declare const ListResourceTemplatesRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"resources/templates/list">; +}, z.core.$strip>; +/** + * The server's response to a resources/templates/list request from the client. + */ +export declare const ListResourceTemplatesResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + resourceTemplates: z.ZodArray; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +export declare const ResourceRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$strip>; +/** + * Parameters for a `resources/read` request. + */ +export declare const ReadResourceRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$strip>; +/** + * Sent from the client to the server, to read a specific resource URI. + */ +export declare const ReadResourceRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"resources/read">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * The server's response to a resources/read request from the client. + */ +export declare const ReadResourceResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + contents: z.ZodArray; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>>; +}, z.core.$loose>; +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ +export declare const ResourceListChangedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/resources/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +export declare const SubscribeRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$strip>; +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + */ +export declare const SubscribeRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"resources/subscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +export declare const UnsubscribeRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$strip>; +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + */ +export declare const UnsubscribeRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"resources/unsubscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Parameters for a `notifications/resources/updated` notification. + */ +export declare const ResourceUpdatedNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$strip>; +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + */ +export declare const ResourceUpdatedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/resources/updated">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Describes an argument that a prompt can accept. + */ +export declare const PromptArgumentSchema: z.ZodObject<{ + name: z.ZodString; + description: z.ZodOptional; + required: z.ZodOptional; +}, z.core.$strip>; +/** + * A prompt or prompt template that the server offers. + */ +export declare const PromptSchema: z.ZodObject<{ + description: z.ZodOptional; + arguments: z.ZodOptional; + required: z.ZodOptional; + }, z.core.$strip>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ +export declare const ListPromptsRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"prompts/list">; +}, z.core.$strip>; +/** + * The server's response to a prompts/list request from the client. + */ +export declare const ListPromptsResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + prompts: z.ZodArray; + arguments: z.ZodOptional; + required: z.ZodOptional; + }, z.core.$strip>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * Parameters for a `prompts/get` request. + */ +export declare const GetPromptRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; +}, z.core.$strip>; +/** + * Used by the client to get a prompt provided by the server. + */ +export declare const GetPromptRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"prompts/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Text provided to or from an LLM. + */ +export declare const TextContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * An image provided to or from an LLM. + */ +export declare const ImageContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * An Audio provided to or from an LLM. + */ +export declare const AudioContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + */ +export declare const ToolUseContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * The contents of a resource, embedded into a prompt or tool call result. + */ +export declare const EmbeddedResourceSchema: z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + */ +export declare const ResourceLinkSchema: z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; +}, z.core.$strip>; +/** + * A content block that can be used in prompts and tool results. + */ +export declare const ContentBlockSchema: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Describes a message returned as part of a prompt. + */ +export declare const PromptMessageSchema: z.ZodObject<{ + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; +}, z.core.$strip>; +/** + * The server's response to a prompts/get request from the client. + */ +export declare const GetPromptResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + description: z.ZodOptional; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export declare const PromptListChangedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/prompts/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + */ +export declare const ToolAnnotationsSchema: z.ZodObject<{ + title: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; +}, z.core.$strip>; +/** + * Execution-related properties for a tool. + */ +export declare const ToolExecutionSchema: z.ZodObject<{ + taskSupport: z.ZodOptional>; +}, z.core.$strip>; +/** + * Definition for a tool the client can call. + */ +export declare const ToolSchema: z.ZodObject<{ + description: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + execution: z.ZodOptional>; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Sent from the client to request a list of tools the server has. + */ +export declare const ListToolsRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"tools/list">; +}, z.core.$strip>; +/** + * The server's response to a tools/list request from the client. + */ +export declare const ListToolsResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + tools: z.ZodArray; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + execution: z.ZodOptional>; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * The server's response to a tool call. + */ +export declare const CallToolResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; +}, z.core.$loose>; +/** + * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. + */ +export declare const CompatibilityCallToolResultSchema: z.ZodUnion<[z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + toolResult: z.ZodUnknown; +}, z.core.$loose>]>; +/** + * Parameters for a `tools/call` request. + */ +export declare const CallToolRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + name: z.ZodString; + arguments: z.ZodOptional>; +}, z.core.$strip>; +/** + * Used by the client to invoke a tool provided by the server. + */ +export declare const CallToolRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"tools/call">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export declare const ToolListChangedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/tools/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * Callback type for list changed notifications. + */ +export type ListChangedCallback = (error: Error | null, items: T[] | null) => void; +/** + * Base schema for list changed subscription options (without callback). + * Used internally for Zod validation of autoRefresh and debounceMs. + */ +export declare const ListChangedOptionsBaseSchema: z.ZodObject<{ + autoRefresh: z.ZodDefault; + debounceMs: z.ZodDefault; +}, z.core.$strip>; +/** + * Options for subscribing to list changed notifications. + * + * @typeParam T - The type of items in the list (Tool, Prompt, or Resource) + */ +export type ListChangedOptions = { + /** + * If true, the list will be refreshed automatically when a list changed notification is received. + * @default true + */ + autoRefresh?: boolean; + /** + * Debounce time in milliseconds. Set to 0 to disable. + * @default 300 + */ + debounceMs?: number; + /** + * Callback invoked when the list changes. + * + * If autoRefresh is true, items contains the updated list. + * If autoRefresh is false, items is null (caller should refresh manually). + */ + onChanged: ListChangedCallback; +}; +/** + * Configuration for list changed notification handlers. + * + * Use this to configure handlers for tools, prompts, and resources list changes + * when creating a client. + * + * Note: Handlers are only activated if the server advertises the corresponding + * `listChanged` capability (e.g., `tools.listChanged: true`). If the server + * doesn't advertise this capability, the handler will not be set up. + */ +export type ListChangedHandlers = { + /** + * Handler for tool list changes. + */ + tools?: ListChangedOptions; + /** + * Handler for prompt list changes. + */ + prompts?: ListChangedOptions; + /** + * Handler for resource list changes. + */ + resources?: ListChangedOptions; +}; +/** + * The severity of a log message. + */ +export declare const LoggingLevelSchema: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; +}>; +/** + * Parameters for a `logging/setLevel` request. + */ +export declare const SetLevelRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; +}, z.core.$strip>; +/** + * A request from the client to the server, to enable or adjust logging. + */ +export declare const SetLevelRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"logging/setLevel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Parameters for a `notifications/message` notification. + */ +export declare const LoggingMessageNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + logger: z.ZodOptional; + data: z.ZodUnknown; +}, z.core.$strip>; +/** + * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + */ +export declare const LoggingMessageNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/message">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + logger: z.ZodOptional; + data: z.ZodUnknown; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Hints to use for model selection. + */ +export declare const ModelHintSchema: z.ZodObject<{ + name: z.ZodOptional; +}, z.core.$strip>; +/** + * The server's preferences for model selection, requested of the client during sampling. + */ +export declare const ModelPreferencesSchema: z.ZodObject<{ + hints: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; +}, z.core.$strip>; +/** + * Controls tool usage behavior in sampling requests. + */ +export declare const ToolChoiceSchema: z.ZodObject<{ + mode: z.ZodOptional>; +}, z.core.$strip>; +/** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via ToolUseContent. + */ +export declare const ToolResultContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible CreateMessageResult when tools are not used. + */ +export declare const SamplingContentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + */ +export declare const SamplingMessageContentBlockSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Describes a message issued to or received from an LLM API. + */ +export declare const SamplingMessageSchema: z.ZodObject<{ + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>, z.ZodArray; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>]>; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * Parameters for a `sampling/createMessage` request. + */ +export declare const CreateMessageRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>, z.ZodArray; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>>; + modelPreferences: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; + }, z.core.$strip>>; + systemPrompt: z.ZodOptional; + includeContext: z.ZodOptional>; + temperature: z.ZodOptional; + maxTokens: z.ZodNumber; + stopSequences: z.ZodOptional>; + metadata: z.ZodOptional>; + tools: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + execution: z.ZodOptional>; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>>; + toolChoice: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + */ +export declare const CreateMessageRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"sampling/createMessage">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>, z.ZodArray; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>>; + modelPreferences: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; + }, z.core.$strip>>; + systemPrompt: z.ZodOptional; + includeContext: z.ZodOptional>; + temperature: z.ZodOptional; + maxTokens: z.ZodNumber; + stopSequences: z.ZodOptional>; + metadata: z.ZodOptional>; + tools: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + execution: z.ZodOptional>; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>>; + toolChoice: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * The client's response to a sampling/create_message request from the server. + * This is the backwards-compatible version that returns single content (no arrays). + * Used when the request does not include tools. + */ +export declare const CreateMessageResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + model: z.ZodString; + stopReason: z.ZodOptional, z.ZodString]>>; + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodDiscriminatedUnion<[z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; +}, z.core.$loose>; +/** + * The client's response to a sampling/create_message request when tools were provided. + * This version supports array content for tool use flows. + */ +export declare const CreateMessageResultWithToolsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + model: z.ZodString; + stopReason: z.ZodOptional, z.ZodString]>>; + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>, z.ZodArray; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>]>; +}, z.core.$loose>; +/** + * Primitive schema definition for boolean fields. + */ +export declare const BooleanSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Primitive schema definition for string fields. + */ +export declare const StringSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Primitive schema definition for number fields. + */ +export declare const NumberSchemaSchema: z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Schema for single-selection enumeration without display titles for options. + */ +export declare const UntitledSingleSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Schema for single-selection enumeration with display titles for each option. + */ +export declare const TitledSingleSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + */ +export declare const LegacyTitledEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>; +export declare const SingleSelectEnumSchemaSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>]>; +/** + * Schema for multiple-selection enumeration without display titles for options. + */ +export declare const UntitledMultiSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>; +/** + * Schema for multiple-selection enumeration with display titles for each option. + */ +export declare const TitledMultiSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>; +/** + * Combined schema for multiple-selection enumeration + */ +export declare const MultiSelectEnumSchemaSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Primitive schema definition for enum fields. + */ +export declare const EnumSchemaSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>]>]>; +/** + * Union of all primitive schema definitions. + */ +export declare const PrimitiveSchemaDefinitionSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>]>; +/** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ +export declare const ElicitRequestFormParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodOptional>; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Parameters for an `elicitation/create` request for URL-based elicitation. + */ +export declare const ElicitRequestURLParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; +}, z.core.$strip>; +/** + * The parameters for a request to elicit additional information from the user via the client. + */ +export declare const ElicitRequestParamsSchema: z.ZodUnion>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodOptional>; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; +}, z.core.$strip>]>; +/** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ +export declare const ElicitRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"elicitation/create">; + params: z.ZodUnion>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodOptional>; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; + }, z.core.$strip>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; + }, z.core.$strip>]>; +}, z.core.$strip>; +/** + * Parameters for a `notifications/elicitation/complete` notification. + * + * @category notifications/elicitation/complete + */ +export declare const ElicitationCompleteNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + elicitationId: z.ZodString; +}, z.core.$strip>; +/** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ +export declare const ElicitationCompleteNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/elicitation/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + elicitationId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * The client's response to an elicitation/create request from the server. + */ +export declare const ElicitResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + action: z.ZodEnum<{ + cancel: "cancel"; + accept: "accept"; + decline: "decline"; + }>; + content: z.ZodPipe, z.ZodOptional]>>>>; +}, z.core.$loose>; +/** + * A reference to a resource or resource template definition. + */ +export declare const ResourceTemplateReferenceSchema: z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; +}, z.core.$strip>; +/** + * @deprecated Use ResourceTemplateReferenceSchema instead + */ +export declare const ResourceReferenceSchema: z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; +}, z.core.$strip>; +/** + * Identifies a prompt. + */ +export declare const PromptReferenceSchema: z.ZodObject<{ + type: z.ZodLiteral<"ref/prompt">; + name: z.ZodString; +}, z.core.$strip>; +/** + * Parameters for a `completion/complete` request. + */ +export declare const CompleteRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + ref: z.ZodUnion; + name: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; + }, z.core.$strip>]>; + argument: z.ZodObject<{ + name: z.ZodString; + value: z.ZodString; + }, z.core.$strip>; + context: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * A request from the client to the server, to ask for completion options. + */ +export declare const CompleteRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"completion/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + ref: z.ZodUnion; + name: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; + }, z.core.$strip>]>; + argument: z.ZodObject<{ + name: z.ZodString; + value: z.ZodString; + }, z.core.$strip>; + context: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$strip>; +}, z.core.$strip>; +export declare function assertCompleteRequestPrompt(request: CompleteRequest): asserts request is CompleteRequestPrompt; +export declare function assertCompleteRequestResourceTemplate(request: CompleteRequest): asserts request is CompleteRequestResourceTemplate; +/** + * The server's response to a completion/complete request + */ +export declare const CompleteResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + completion: z.ZodObject<{ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.ZodArray; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.ZodOptional; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$loose>; +/** + * Represents a root directory or file that the server can operate on. + */ +export declare const RootSchema: z.ZodObject<{ + uri: z.ZodString; + name: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * Sent from the server to request a list of root URIs from the client. + */ +export declare const ListRootsRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"roots/list">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * The client's response to a roots/list request from the server. + */ +export declare const ListRootsResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + roots: z.ZodArray; + _meta: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * A notification from the client to the server, informing it that the list of roots has changed. + */ +export declare const RootsListChangedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/roots/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +export declare const ClientRequestSchema: z.ZodUnion; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"initialize">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the client supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + /** + * Task support for elicitation requests. + */ + elicitation: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$strip>; + clientInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + description: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"completion/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + ref: z.ZodUnion; + name: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; + }, z.core.$strip>]>; + argument: z.ZodObject<{ + name: z.ZodString; + value: z.ZodString; + }, z.core.$strip>; + context: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"logging/setLevel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"prompts/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"prompts/list">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"resources/list">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"resources/templates/list">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"resources/read">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"resources/subscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"resources/unsubscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tools/call">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"tools/list">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tasks/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tasks/result">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"tasks/list">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tasks/cancel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>]>; +export declare const ClientNotificationSchema: z.ZodUnion; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + requestId: z.ZodOptional>; + reason: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/progress">; + params: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/initialized">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/roots/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/tasks/status">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>]>; +export declare const ClientResultSchema: z.ZodUnion>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strict>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + model: z.ZodString; + stopReason: z.ZodOptional, z.ZodString]>>; + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodDiscriminatedUnion<[z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + model: z.ZodString; + stopReason: z.ZodOptional, z.ZodString]>>; + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>, z.ZodArray; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>]>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + action: z.ZodEnum<{ + cancel: "cancel"; + accept: "accept"; + decline: "decline"; + }>; + content: z.ZodPipe, z.ZodOptional]>>>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + roots: z.ZodArray; + _meta: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + tasks: z.ZodArray; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodObject<{ + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$loose>]>; +export declare const ServerRequestSchema: z.ZodUnion; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"sampling/createMessage">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>, z.ZodArray; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>>; + modelPreferences: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; + }, z.core.$strip>>; + systemPrompt: z.ZodOptional; + includeContext: z.ZodOptional>; + temperature: z.ZodOptional; + maxTokens: z.ZodNumber; + stopSequences: z.ZodOptional>; + metadata: z.ZodOptional>; + tools: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + execution: z.ZodOptional>; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>>; + toolChoice: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"elicitation/create">; + params: z.ZodUnion>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodOptional>; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; + }, z.core.$strip>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; + }, z.core.$strip>]>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"roots/list">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tasks/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tasks/result">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"tasks/list">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tasks/cancel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>]>; +export declare const ServerNotificationSchema: z.ZodUnion; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + requestId: z.ZodOptional>; + reason: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/progress">; + params: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/message">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + logger: z.ZodOptional; + data: z.ZodUnknown; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/resources/updated">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/resources/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/tools/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/prompts/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/tasks/status">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/elicitation/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + elicitationId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>]>; +export declare const ServerResultSchema: z.ZodUnion>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strict>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + logging: z.ZodOptional>; + completions: z.ZodOptional>; + prompts: z.ZodOptional; + }, z.core.$strip>>; + resources: z.ZodOptional; + listChanged: z.ZodOptional; + }, z.core.$strip>>; + tools: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the server supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$strip>; + serverInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + description: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + instructions: z.ZodOptional; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + completion: z.ZodObject<{ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.ZodArray; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.ZodOptional; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + description: z.ZodOptional; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + prompts: z.ZodArray; + arguments: z.ZodOptional; + required: z.ZodOptional; + }, z.core.$strip>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + resources: z.ZodArray; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + resourceTemplates: z.ZodArray; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + contents: z.ZodArray; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + tools: z.ZodArray; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + execution: z.ZodOptional>; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + tasks: z.ZodArray; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodObject<{ + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$loose>]>; +export declare class McpError extends Error { + readonly code: number; + readonly data?: unknown; + constructor(code: number, message: string, data?: unknown); + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code: number, message: string, data?: unknown): McpError; +} +/** + * Specialized error type when a tool requires a URL mode elicitation. + * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. + */ +export declare class UrlElicitationRequiredError extends McpError { + constructor(elicitations: ElicitRequestURLParams[], message?: string); + get elicitations(): ElicitRequestURLParams[]; +} +type Primitive = string | number | boolean | bigint | null | undefined; +type Flatten = T extends Primitive ? T : T extends Array ? Array> : T extends Set ? Set> : T extends Map ? Map, Flatten> : T extends object ? { + [K in keyof T]: Flatten; +} : T; +type Infer = Flatten>; +/** + * Headers that are compatible with both Node.js and the browser. + */ +export type IsomorphicHeaders = Record; +/** + * Information about the incoming request. + */ +export interface RequestInfo { + /** + * The headers of the request. + */ + headers: IsomorphicHeaders; +} +/** + * Extra information about a message. + */ +export interface MessageExtraInfo { + /** + * The request information. + */ + requestInfo?: RequestInfo; + /** + * The authentication information. + */ + authInfo?: AuthInfo; + /** + * Callback to close the SSE stream for this request, triggering client reconnection. + * Only available when using StreamableHTTPServerTransport with eventStore configured. + */ + closeSSEStream?: () => void; + /** + * Callback to close the standalone GET SSE stream, triggering client reconnection. + * Only available when using StreamableHTTPServerTransport with eventStore configured. + */ + closeStandaloneSSEStream?: () => void; +} +export type ProgressToken = Infer; +export type Cursor = Infer; +export type Request = Infer; +export type TaskAugmentedRequestParams = Infer; +export type RequestMeta = Infer; +export type Notification = Infer; +export type Result = Infer; +export type RequestId = Infer; +export type JSONRPCRequest = Infer; +export type JSONRPCNotification = Infer; +export type JSONRPCResponse = Infer; +export type JSONRPCErrorResponse = Infer; +/** + * @deprecated Use {@link JSONRPCErrorResponse} instead. + * + * Please note that spec types have renamed {@link JSONRPCError} to {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCError}) and future versions will remove {@link JSONRPCError}. + */ +export type JSONRPCError = JSONRPCErrorResponse; +export type JSONRPCResultResponse = Infer; +export type JSONRPCMessage = Infer; +export type RequestParams = Infer; +export type NotificationParams = Infer; +export type EmptyResult = Infer; +export type CancelledNotificationParams = Infer; +export type CancelledNotification = Infer; +export type Icon = Infer; +export type Icons = Infer; +export type BaseMetadata = Infer; +export type Annotations = Infer; +export type Role = Infer; +export type Implementation = Infer; +export type ClientCapabilities = Infer; +export type InitializeRequestParams = Infer; +export type InitializeRequest = Infer; +export type ServerCapabilities = Infer; +export type InitializeResult = Infer; +export type InitializedNotification = Infer; +export type PingRequest = Infer; +export type Progress = Infer; +export type ProgressNotificationParams = Infer; +export type ProgressNotification = Infer; +export type Task = Infer; +export type TaskStatus = Infer; +export type TaskCreationParams = Infer; +export type TaskMetadata = Infer; +export type RelatedTaskMetadata = Infer; +export type CreateTaskResult = Infer; +export type TaskStatusNotificationParams = Infer; +export type TaskStatusNotification = Infer; +export type GetTaskRequest = Infer; +export type GetTaskResult = Infer; +export type GetTaskPayloadRequest = Infer; +export type ListTasksRequest = Infer; +export type ListTasksResult = Infer; +export type CancelTaskRequest = Infer; +export type CancelTaskResult = Infer; +export type GetTaskPayloadResult = Infer; +export type PaginatedRequestParams = Infer; +export type PaginatedRequest = Infer; +export type PaginatedResult = Infer; +export type ResourceContents = Infer; +export type TextResourceContents = Infer; +export type BlobResourceContents = Infer; +export type Resource = Infer; +export type ResourceTemplate = Infer; +export type ListResourcesRequest = Infer; +export type ListResourcesResult = Infer; +export type ListResourceTemplatesRequest = Infer; +export type ListResourceTemplatesResult = Infer; +export type ResourceRequestParams = Infer; +export type ReadResourceRequestParams = Infer; +export type ReadResourceRequest = Infer; +export type ReadResourceResult = Infer; +export type ResourceListChangedNotification = Infer; +export type SubscribeRequestParams = Infer; +export type SubscribeRequest = Infer; +export type UnsubscribeRequestParams = Infer; +export type UnsubscribeRequest = Infer; +export type ResourceUpdatedNotificationParams = Infer; +export type ResourceUpdatedNotification = Infer; +export type PromptArgument = Infer; +export type Prompt = Infer; +export type ListPromptsRequest = Infer; +export type ListPromptsResult = Infer; +export type GetPromptRequestParams = Infer; +export type GetPromptRequest = Infer; +export type TextContent = Infer; +export type ImageContent = Infer; +export type AudioContent = Infer; +export type ToolUseContent = Infer; +export type ToolResultContent = Infer; +export type EmbeddedResource = Infer; +export type ResourceLink = Infer; +export type ContentBlock = Infer; +export type PromptMessage = Infer; +export type GetPromptResult = Infer; +export type PromptListChangedNotification = Infer; +export type ToolAnnotations = Infer; +export type ToolExecution = Infer; +export type Tool = Infer; +export type ListToolsRequest = Infer; +export type ListToolsResult = Infer; +export type CallToolRequestParams = Infer; +export type CallToolResult = Infer; +export type CompatibilityCallToolResult = Infer; +export type CallToolRequest = Infer; +export type ToolListChangedNotification = Infer; +export type LoggingLevel = Infer; +export type SetLevelRequestParams = Infer; +export type SetLevelRequest = Infer; +export type LoggingMessageNotificationParams = Infer; +export type LoggingMessageNotification = Infer; +export type ToolChoice = Infer; +export type ModelHint = Infer; +export type ModelPreferences = Infer; +export type SamplingContent = Infer; +export type SamplingMessageContentBlock = Infer; +export type SamplingMessage = Infer; +export type CreateMessageRequestParams = Infer; +export type CreateMessageRequest = Infer; +export type CreateMessageResult = Infer; +export type CreateMessageResultWithTools = Infer; +/** + * CreateMessageRequestParams without tools - for backwards-compatible overload. + * Excludes tools/toolChoice to indicate they should not be provided. + */ +export type CreateMessageRequestParamsBase = Omit; +/** + * CreateMessageRequestParams with required tools - for tool-enabled overload. + */ +export interface CreateMessageRequestParamsWithTools extends CreateMessageRequestParams { + tools: Tool[]; +} +export type BooleanSchema = Infer; +export type StringSchema = Infer; +export type NumberSchema = Infer; +export type EnumSchema = Infer; +export type UntitledSingleSelectEnumSchema = Infer; +export type TitledSingleSelectEnumSchema = Infer; +export type LegacyTitledEnumSchema = Infer; +export type UntitledMultiSelectEnumSchema = Infer; +export type TitledMultiSelectEnumSchema = Infer; +export type SingleSelectEnumSchema = Infer; +export type MultiSelectEnumSchema = Infer; +export type PrimitiveSchemaDefinition = Infer; +export type ElicitRequestParams = Infer; +export type ElicitRequestFormParams = Infer; +export type ElicitRequestURLParams = Infer; +export type ElicitRequest = Infer; +export type ElicitationCompleteNotificationParams = Infer; +export type ElicitationCompleteNotification = Infer; +export type ElicitResult = Infer; +export type ResourceTemplateReference = Infer; +/** + * @deprecated Use ResourceTemplateReference instead + */ +export type ResourceReference = ResourceTemplateReference; +export type PromptReference = Infer; +export type CompleteRequestParams = Infer; +export type CompleteRequest = Infer; +export type CompleteRequestResourceTemplate = ExpandRecursively; +export type CompleteRequestPrompt = ExpandRecursively; +export type CompleteResult = Infer; +export type Root = Infer; +export type ListRootsRequest = Infer; +export type ListRootsResult = Infer; +export type RootsListChangedNotification = Infer; +export type ClientRequest = Infer; +export type ClientNotification = Infer; +export type ClientResult = Infer; +export type ServerRequest = Infer; +export type ServerNotification = Infer; +export type ServerResult = Infer; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/types.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/types.d.ts.map new file mode 100644 index 000000000..4745081a5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAElD,eAAO,MAAM,uBAAuB,eAAe,CAAC;AACpD,eAAO,MAAM,mCAAmC,eAAe,CAAC;AAChE,eAAO,MAAM,2BAA2B,UAAoF,CAAC;AAE7H,eAAO,MAAM,qBAAqB,yCAAyC,CAAC;AAG5E,eAAO,MAAM,eAAe,QAAQ,CAAC;AAErC;;GAEG;AACH,KAAK,iBAAiB,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;AAO7H;;GAEG;AACH,eAAO,MAAM,mBAAmB,iDAA0C,CAAC;AAE3E;;GAEG;AACH,eAAO,MAAM,YAAY,aAAa,CAAC;AAEvC;;GAEG;AACH,eAAO,MAAM,wBAAwB;IACjC;;;OAGG;;IAGH;;OAEG;;iBAEL,CAAC;AAEH,eAAO,MAAM,kBAAkB;;iBAE7B,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,yBAAyB;;iBAEpC,CAAC;AAEH,QAAA,MAAM,iBAAiB;IACnB;;OAEG;;IAEH;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sdk/dist/cjs/types.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/types.js new file mode 100644 index 000000000..1f4553e7d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/types.js @@ -0,0 +1,2092 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProgressNotificationParamsSchema = exports.ProgressSchema = exports.PingRequestSchema = exports.isInitializedNotification = exports.InitializedNotificationSchema = exports.InitializeResultSchema = exports.ServerCapabilitiesSchema = exports.isInitializeRequest = exports.InitializeRequestSchema = exports.InitializeRequestParamsSchema = exports.ClientCapabilitiesSchema = exports.ServerTasksCapabilitySchema = exports.ClientTasksCapabilitySchema = exports.ImplementationSchema = exports.BaseMetadataSchema = exports.IconsSchema = exports.IconSchema = exports.CancelledNotificationSchema = exports.CancelledNotificationParamsSchema = exports.EmptyResultSchema = exports.JSONRPCResponseSchema = exports.JSONRPCMessageSchema = exports.isJSONRPCError = exports.isJSONRPCErrorResponse = exports.JSONRPCErrorSchema = exports.JSONRPCErrorResponseSchema = exports.ErrorCode = exports.isJSONRPCResponse = exports.isJSONRPCResultResponse = exports.JSONRPCResultResponseSchema = exports.isJSONRPCNotification = exports.JSONRPCNotificationSchema = exports.isJSONRPCRequest = exports.JSONRPCRequestSchema = exports.RequestIdSchema = exports.ResultSchema = exports.NotificationSchema = exports.RequestSchema = exports.isTaskAugmentedRequestParams = exports.TaskAugmentedRequestParamsSchema = exports.RelatedTaskMetadataSchema = exports.TaskMetadataSchema = exports.TaskCreationParamsSchema = exports.CursorSchema = exports.ProgressTokenSchema = exports.JSONRPC_VERSION = exports.RELATED_TASK_META_KEY = exports.SUPPORTED_PROTOCOL_VERSIONS = exports.DEFAULT_NEGOTIATED_PROTOCOL_VERSION = exports.LATEST_PROTOCOL_VERSION = void 0; +exports.EmbeddedResourceSchema = exports.ToolUseContentSchema = exports.AudioContentSchema = exports.ImageContentSchema = exports.TextContentSchema = exports.GetPromptRequestSchema = exports.GetPromptRequestParamsSchema = exports.ListPromptsResultSchema = exports.ListPromptsRequestSchema = exports.PromptSchema = exports.PromptArgumentSchema = exports.ResourceUpdatedNotificationSchema = exports.ResourceUpdatedNotificationParamsSchema = exports.UnsubscribeRequestSchema = exports.UnsubscribeRequestParamsSchema = exports.SubscribeRequestSchema = exports.SubscribeRequestParamsSchema = exports.ResourceListChangedNotificationSchema = exports.ReadResourceResultSchema = exports.ReadResourceRequestSchema = exports.ReadResourceRequestParamsSchema = exports.ResourceRequestParamsSchema = exports.ListResourceTemplatesResultSchema = exports.ListResourceTemplatesRequestSchema = exports.ListResourcesResultSchema = exports.ListResourcesRequestSchema = exports.ResourceTemplateSchema = exports.ResourceSchema = exports.AnnotationsSchema = exports.RoleSchema = exports.BlobResourceContentsSchema = exports.TextResourceContentsSchema = exports.ResourceContentsSchema = exports.CancelTaskResultSchema = exports.CancelTaskRequestSchema = exports.ListTasksResultSchema = exports.ListTasksRequestSchema = exports.GetTaskPayloadResultSchema = exports.GetTaskPayloadRequestSchema = exports.GetTaskResultSchema = exports.GetTaskRequestSchema = exports.TaskStatusNotificationSchema = exports.TaskStatusNotificationParamsSchema = exports.CreateTaskResultSchema = exports.TaskSchema = exports.TaskStatusSchema = exports.PaginatedResultSchema = exports.PaginatedRequestSchema = exports.PaginatedRequestParamsSchema = exports.ProgressNotificationSchema = void 0; +exports.ElicitationCompleteNotificationSchema = exports.ElicitationCompleteNotificationParamsSchema = exports.ElicitRequestSchema = exports.ElicitRequestParamsSchema = exports.ElicitRequestURLParamsSchema = exports.ElicitRequestFormParamsSchema = exports.PrimitiveSchemaDefinitionSchema = exports.EnumSchemaSchema = exports.MultiSelectEnumSchemaSchema = exports.TitledMultiSelectEnumSchemaSchema = exports.UntitledMultiSelectEnumSchemaSchema = exports.SingleSelectEnumSchemaSchema = exports.LegacyTitledEnumSchemaSchema = exports.TitledSingleSelectEnumSchemaSchema = exports.UntitledSingleSelectEnumSchemaSchema = exports.NumberSchemaSchema = exports.StringSchemaSchema = exports.BooleanSchemaSchema = exports.CreateMessageResultWithToolsSchema = exports.CreateMessageResultSchema = exports.CreateMessageRequestSchema = exports.CreateMessageRequestParamsSchema = exports.SamplingMessageSchema = exports.SamplingMessageContentBlockSchema = exports.SamplingContentSchema = exports.ToolResultContentSchema = exports.ToolChoiceSchema = exports.ModelPreferencesSchema = exports.ModelHintSchema = exports.LoggingMessageNotificationSchema = exports.LoggingMessageNotificationParamsSchema = exports.SetLevelRequestSchema = exports.SetLevelRequestParamsSchema = exports.LoggingLevelSchema = exports.ListChangedOptionsBaseSchema = exports.ToolListChangedNotificationSchema = exports.CallToolRequestSchema = exports.CallToolRequestParamsSchema = exports.CompatibilityCallToolResultSchema = exports.CallToolResultSchema = exports.ListToolsResultSchema = exports.ListToolsRequestSchema = exports.ToolSchema = exports.ToolExecutionSchema = exports.ToolAnnotationsSchema = exports.PromptListChangedNotificationSchema = exports.GetPromptResultSchema = exports.PromptMessageSchema = exports.ContentBlockSchema = exports.ResourceLinkSchema = void 0; +exports.UrlElicitationRequiredError = exports.McpError = exports.ServerResultSchema = exports.ServerNotificationSchema = exports.ServerRequestSchema = exports.ClientResultSchema = exports.ClientNotificationSchema = exports.ClientRequestSchema = exports.RootsListChangedNotificationSchema = exports.ListRootsResultSchema = exports.ListRootsRequestSchema = exports.RootSchema = exports.CompleteResultSchema = exports.CompleteRequestSchema = exports.CompleteRequestParamsSchema = exports.PromptReferenceSchema = exports.ResourceReferenceSchema = exports.ResourceTemplateReferenceSchema = exports.ElicitResultSchema = void 0; +exports.assertCompleteRequestPrompt = assertCompleteRequestPrompt; +exports.assertCompleteRequestResourceTemplate = assertCompleteRequestResourceTemplate; +const z = __importStar(require("zod/v4")); +exports.LATEST_PROTOCOL_VERSION = '2025-11-25'; +exports.DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; +exports.SUPPORTED_PROTOCOL_VERSIONS = [exports.LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07']; +exports.RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task'; +/* JSON-RPC types */ +exports.JSONRPC_VERSION = '2.0'; +/** + * Assert 'object' type schema. + * + * @internal + */ +const AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function')); +/** + * A progress token, used to associate progress notifications with the original request. + */ +exports.ProgressTokenSchema = z.union([z.string(), z.number().int()]); +/** + * An opaque token used to represent a cursor for pagination. + */ +exports.CursorSchema = z.string(); +/** + * Task creation parameters, used to ask that the server create a task to represent a request. + */ +exports.TaskCreationParamsSchema = z.looseObject({ + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: z.union([z.number(), z.null()]).optional(), + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval: z.number().optional() +}); +exports.TaskMetadataSchema = z.object({ + ttl: z.number().optional() +}); +/** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + */ +exports.RelatedTaskMetadataSchema = z.object({ + taskId: z.string() +}); +const RequestMetaSchema = z.looseObject({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: exports.ProgressTokenSchema.optional(), + /** + * If specified, this request is related to the provided task. + */ + [exports.RELATED_TASK_META_KEY]: exports.RelatedTaskMetadataSchema.optional() +}); +/** + * Common params for any request. + */ +const BaseRequestParamsSchema = z.object({ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta: RequestMetaSchema.optional() +}); +/** + * Common params for any task-augmented request. + */ +exports.TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task: exports.TaskMetadataSchema.optional() +}); +/** + * Checks if a value is a valid TaskAugmentedRequestParams. + * @param value - The value to check. + * + * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise. + */ +const isTaskAugmentedRequestParams = (value) => exports.TaskAugmentedRequestParamsSchema.safeParse(value).success; +exports.isTaskAugmentedRequestParams = isTaskAugmentedRequestParams; +exports.RequestSchema = z.object({ + method: z.string(), + params: BaseRequestParamsSchema.loose().optional() +}); +const NotificationsParamsSchema = z.object({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() +}); +exports.NotificationSchema = z.object({ + method: z.string(), + params: NotificationsParamsSchema.loose().optional() +}); +exports.ResultSchema = z.looseObject({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() +}); +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +exports.RequestIdSchema = z.union([z.string(), z.number().int()]); +/** + * A request that expects a response. + */ +exports.JSONRPCRequestSchema = z + .object({ + jsonrpc: z.literal(exports.JSONRPC_VERSION), + id: exports.RequestIdSchema, + ...exports.RequestSchema.shape +}) + .strict(); +const isJSONRPCRequest = (value) => exports.JSONRPCRequestSchema.safeParse(value).success; +exports.isJSONRPCRequest = isJSONRPCRequest; +/** + * A notification which does not expect a response. + */ +exports.JSONRPCNotificationSchema = z + .object({ + jsonrpc: z.literal(exports.JSONRPC_VERSION), + ...exports.NotificationSchema.shape +}) + .strict(); +const isJSONRPCNotification = (value) => exports.JSONRPCNotificationSchema.safeParse(value).success; +exports.isJSONRPCNotification = isJSONRPCNotification; +/** + * A successful (non-error) response to a request. + */ +exports.JSONRPCResultResponseSchema = z + .object({ + jsonrpc: z.literal(exports.JSONRPC_VERSION), + id: exports.RequestIdSchema, + result: exports.ResultSchema +}) + .strict(); +/** + * Checks if a value is a valid JSONRPCResultResponse. + * @param value - The value to check. + * + * @returns True if the value is a valid JSONRPCResultResponse, false otherwise. + */ +const isJSONRPCResultResponse = (value) => exports.JSONRPCResultResponseSchema.safeParse(value).success; +exports.isJSONRPCResultResponse = isJSONRPCResultResponse; +/** + * @deprecated Use {@link isJSONRPCResultResponse} instead. + * + * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse}) + */ +exports.isJSONRPCResponse = exports.isJSONRPCResultResponse; +/** + * Error codes defined by the JSON-RPC specification. + */ +var ErrorCode; +(function (ErrorCode) { + // SDK error codes + ErrorCode[ErrorCode["ConnectionClosed"] = -32000] = "ConnectionClosed"; + ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout"; + // Standard JSON-RPC error codes + ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError"; + ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest"; + ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound"; + ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams"; + ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError"; + // MCP-specific error codes + ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; +})(ErrorCode || (exports.ErrorCode = ErrorCode = {})); +/** + * A response to a request that indicates an error occurred. + */ +exports.JSONRPCErrorResponseSchema = z + .object({ + jsonrpc: z.literal(exports.JSONRPC_VERSION), + id: exports.RequestIdSchema.optional(), + error: z.object({ + /** + * The error type that occurred. + */ + code: z.number().int(), + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: z.string(), + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data: z.unknown().optional() + }) +}) + .strict(); +/** + * @deprecated Use {@link JSONRPCErrorResponseSchema} instead. + */ +exports.JSONRPCErrorSchema = exports.JSONRPCErrorResponseSchema; +/** + * Checks if a value is a valid JSONRPCErrorResponse. + * @param value - The value to check. + * + * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise. + */ +const isJSONRPCErrorResponse = (value) => exports.JSONRPCErrorResponseSchema.safeParse(value).success; +exports.isJSONRPCErrorResponse = isJSONRPCErrorResponse; +/** + * @deprecated Use {@link isJSONRPCErrorResponse} instead. + */ +exports.isJSONRPCError = exports.isJSONRPCErrorResponse; +exports.JSONRPCMessageSchema = z.union([ + exports.JSONRPCRequestSchema, + exports.JSONRPCNotificationSchema, + exports.JSONRPCResultResponseSchema, + exports.JSONRPCErrorResponseSchema +]); +exports.JSONRPCResponseSchema = z.union([exports.JSONRPCResultResponseSchema, exports.JSONRPCErrorResponseSchema]); +/* Empty result */ +/** + * A response that indicates success but carries no data. + */ +exports.EmptyResultSchema = exports.ResultSchema.strict(); +exports.CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: exports.RequestIdSchema.optional(), + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason: z.string().optional() +}); +/* Cancellation */ +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + */ +exports.CancelledNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/cancelled'), + params: exports.CancelledNotificationParamsSchema +}); +/* Base Metadata */ +/** + * Icon schema for use in tools, prompts, resources, and implementations. + */ +exports.IconSchema = z.object({ + /** + * URL or data URI for the icon. + */ + src: z.string(), + /** + * Optional MIME type for the icon. + */ + mimeType: z.string().optional(), + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes: z.array(z.string()).optional(), + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme: z.enum(['light', 'dark']).optional() +}); +/** + * Base schema to add `icons` property. + * + */ +exports.IconsSchema = z.object({ + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons: z.array(exports.IconSchema).optional() +}); +/** + * Base metadata interface for common properties across resources, tools, prompts, and implementations. + */ +exports.BaseMetadataSchema = z.object({ + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: z.string(), + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title: z.string().optional() +}); +/* Initialization */ +/** + * Describes the name and version of an MCP implementation. + */ +exports.ImplementationSchema = exports.BaseMetadataSchema.extend({ + ...exports.BaseMetadataSchema.shape, + ...exports.IconsSchema.shape, + version: z.string(), + /** + * An optional URL of the website for this implementation. + */ + websiteUrl: z.string().optional(), + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description: z.string().optional() +}); +const FormElicitationCapabilitySchema = z.intersection(z.object({ + applyDefaults: z.boolean().optional() +}), z.record(z.string(), z.unknown())); +const ElicitationCapabilitySchema = z.preprocess(value => { + if (value && typeof value === 'object' && !Array.isArray(value)) { + if (Object.keys(value).length === 0) { + return { form: {} }; + } + } + return value; +}, z.intersection(z.object({ + form: FormElicitationCapabilitySchema.optional(), + url: AssertObjectSchema.optional() +}), z.record(z.string(), z.unknown()).optional())); +/** + * Task capabilities for clients, indicating which request types support task creation. + */ +exports.ClientTasksCapabilitySchema = z.looseObject({ + /** + * Present if the client supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the client supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: z + .looseObject({ + /** + * Task support for sampling requests. + */ + sampling: z + .looseObject({ + createMessage: AssertObjectSchema.optional() + }) + .optional(), + /** + * Task support for elicitation requests. + */ + elicitation: z + .looseObject({ + create: AssertObjectSchema.optional() + }) + .optional() + }) + .optional() +}); +/** + * Task capabilities for servers, indicating which request types support task creation. + */ +exports.ServerTasksCapabilitySchema = z.looseObject({ + /** + * Present if the server supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the server supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: z + .looseObject({ + /** + * Task support for tool requests. + */ + tools: z + .looseObject({ + call: AssertObjectSchema.optional() + }) + .optional() + }) + .optional() +}); +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ +exports.ClientCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the client supports sampling from an LLM. + */ + sampling: z + .object({ + /** + * Present if the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context: AssertObjectSchema.optional(), + /** + * Present if the client supports tool use via tools and toolChoice parameters. + */ + tools: AssertObjectSchema.optional() + }) + .optional(), + /** + * Present if the client supports eliciting user input. + */ + elicitation: ElicitationCapabilitySchema.optional(), + /** + * Present if the client supports listing roots. + */ + roots: z + .object({ + /** + * Whether the client supports issuing notifications for changes to the roots list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the client supports task creation. + */ + tasks: exports.ClientTasksCapabilitySchema.optional() +}); +exports.InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: z.string(), + capabilities: exports.ClientCapabilitiesSchema, + clientInfo: exports.ImplementationSchema +}); +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ +exports.InitializeRequestSchema = exports.RequestSchema.extend({ + method: z.literal('initialize'), + params: exports.InitializeRequestParamsSchema +}); +const isInitializeRequest = (value) => exports.InitializeRequestSchema.safeParse(value).success; +exports.isInitializeRequest = isInitializeRequest; +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ +exports.ServerCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + */ + logging: AssertObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ + completions: AssertObjectSchema.optional(), + /** + * Present if the server offers any prompt templates. + */ + prompts: z + .object({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any resources to read. + */ + resources: z + .object({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: z.boolean().optional(), + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any tools to call. + */ + tools: z + .object({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server supports task creation. + */ + tasks: exports.ServerTasksCapabilitySchema.optional() +}); +/** + * After receiving an initialize request from the client, the server sends this response. + */ +exports.InitializeResultSchema = exports.ResultSchema.extend({ + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: z.string(), + capabilities: exports.ServerCapabilitiesSchema, + serverInfo: exports.ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: z.string().optional() +}); +/** + * This notification is sent from the client to the server after initialization has finished. + */ +exports.InitializedNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/initialized'), + params: NotificationsParamsSchema.optional() +}); +const isInitializedNotification = (value) => exports.InitializedNotificationSchema.safeParse(value).success; +exports.isInitializedNotification = isInitializedNotification; +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +exports.PingRequestSchema = exports.RequestSchema.extend({ + method: z.literal('ping'), + params: BaseRequestParamsSchema.optional() +}); +/* Progress notifications */ +exports.ProgressSchema = z.object({ + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: z.number(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: z.optional(z.number()), + /** + * An optional message describing the current progress. + */ + message: z.optional(z.string()) +}); +exports.ProgressNotificationParamsSchema = z.object({ + ...NotificationsParamsSchema.shape, + ...exports.ProgressSchema.shape, + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: exports.ProgressTokenSchema +}); +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ +exports.ProgressNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/progress'), + params: exports.ProgressNotificationParamsSchema +}); +exports.PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor: exports.CursorSchema.optional() +}); +/* Pagination */ +exports.PaginatedRequestSchema = exports.RequestSchema.extend({ + params: exports.PaginatedRequestParamsSchema.optional() +}); +exports.PaginatedResultSchema = exports.ResultSchema.extend({ + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor: exports.CursorSchema.optional() +}); +/** + * The status of a task. + * */ +exports.TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']); +/* Tasks */ +/** + * A pollable state object associated with a request. + */ +exports.TaskSchema = z.object({ + taskId: z.string(), + status: exports.TaskStatusSchema, + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: z.union([z.number(), z.null()]), + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: z.string(), + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: z.string(), + pollInterval: z.optional(z.number()), + /** + * Optional diagnostic message for failed tasks or other status information. + */ + statusMessage: z.optional(z.string()) +}); +/** + * Result returned when a task is created, containing the task data wrapped in a task field. + */ +exports.CreateTaskResultSchema = exports.ResultSchema.extend({ + task: exports.TaskSchema +}); +/** + * Parameters for task status notification. + */ +exports.TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(exports.TaskSchema); +/** + * A notification sent when a task's status changes. + */ +exports.TaskStatusNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/tasks/status'), + params: exports.TaskStatusNotificationParamsSchema +}); +/** + * A request to get the state of a specific task. + */ +exports.GetTaskRequestSchema = exports.RequestSchema.extend({ + method: z.literal('tasks/get'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) +}); +/** + * The response to a tasks/get request. + */ +exports.GetTaskResultSchema = exports.ResultSchema.merge(exports.TaskSchema); +/** + * A request to get the result of a specific task. + */ +exports.GetTaskPayloadRequestSchema = exports.RequestSchema.extend({ + method: z.literal('tasks/result'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) +}); +/** + * The response to a tasks/result request. + * The structure matches the result type of the original request. + * For example, a tools/call task would return the CallToolResult structure. + * + */ +exports.GetTaskPayloadResultSchema = exports.ResultSchema.loose(); +/** + * A request to list tasks. + */ +exports.ListTasksRequestSchema = exports.PaginatedRequestSchema.extend({ + method: z.literal('tasks/list') +}); +/** + * The response to a tasks/list request. + */ +exports.ListTasksResultSchema = exports.PaginatedResultSchema.extend({ + tasks: z.array(exports.TaskSchema) +}); +/** + * A request to cancel a specific task. + */ +exports.CancelTaskRequestSchema = exports.RequestSchema.extend({ + method: z.literal('tasks/cancel'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) +}); +/** + * The response to a tasks/cancel request. + */ +exports.CancelTaskResultSchema = exports.ResultSchema.merge(exports.TaskSchema); +/* Resources */ +/** + * The contents of a specific resource or sub-resource. + */ +exports.ResourceContentsSchema = z.object({ + /** + * The URI of this resource. + */ + uri: z.string(), + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +exports.TextResourceContentsSchema = exports.ResourceContentsSchema.extend({ + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: z.string() +}); +/** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ +const Base64Schema = z.string().refine(val => { + try { + // atob throws a DOMException if the string contains characters + // that are not part of the Base64 character set. + atob(val); + return true; + } + catch { + return false; + } +}, { message: 'Invalid Base64 string' }); +exports.BlobResourceContentsSchema = exports.ResourceContentsSchema.extend({ + /** + * A base64-encoded string representing the binary data of the item. + */ + blob: Base64Schema +}); +/** + * The sender or recipient of messages and data in a conversation. + */ +exports.RoleSchema = z.enum(['user', 'assistant']); +/** + * Optional annotations providing clients additional context about a resource. + */ +exports.AnnotationsSchema = z.object({ + /** + * Intended audience(s) for the resource. + */ + audience: z.array(exports.RoleSchema).optional(), + /** + * Importance hint for the resource, from 0 (least) to 1 (most). + */ + priority: z.number().min(0).max(1).optional(), + /** + * ISO 8601 timestamp for the most recent modification. + */ + lastModified: z.iso.datetime({ offset: true }).optional() +}); +/** + * A known resource that the server is capable of reading. + */ +exports.ResourceSchema = z.object({ + ...exports.BaseMetadataSchema.shape, + ...exports.IconsSchema.shape, + /** + * The URI of this resource. + */ + uri: z.string(), + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + /** + * Optional annotations for the client. + */ + annotations: exports.AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * A template description for resources available on the server. + */ +exports.ResourceTemplateSchema = z.object({ + ...exports.BaseMetadataSchema.shape, + ...exports.IconsSchema.shape, + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: z.string(), + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType: z.optional(z.string()), + /** + * Optional annotations for the client. + */ + annotations: exports.AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * Sent from the client to request a list of resources the server has. + */ +exports.ListResourcesRequestSchema = exports.PaginatedRequestSchema.extend({ + method: z.literal('resources/list') +}); +/** + * The server's response to a resources/list request from the client. + */ +exports.ListResourcesResultSchema = exports.PaginatedResultSchema.extend({ + resources: z.array(exports.ResourceSchema) +}); +/** + * Sent from the client to request a list of resource templates the server has. + */ +exports.ListResourceTemplatesRequestSchema = exports.PaginatedRequestSchema.extend({ + method: z.literal('resources/templates/list') +}); +/** + * The server's response to a resources/templates/list request from the client. + */ +exports.ListResourceTemplatesResultSchema = exports.PaginatedResultSchema.extend({ + resourceTemplates: z.array(exports.ResourceTemplateSchema) +}); +exports.ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: z.string() +}); +/** + * Parameters for a `resources/read` request. + */ +exports.ReadResourceRequestParamsSchema = exports.ResourceRequestParamsSchema; +/** + * Sent from the client to the server, to read a specific resource URI. + */ +exports.ReadResourceRequestSchema = exports.RequestSchema.extend({ + method: z.literal('resources/read'), + params: exports.ReadResourceRequestParamsSchema +}); +/** + * The server's response to a resources/read request from the client. + */ +exports.ReadResourceResultSchema = exports.ResultSchema.extend({ + contents: z.array(z.union([exports.TextResourceContentsSchema, exports.BlobResourceContentsSchema])) +}); +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ +exports.ResourceListChangedNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/resources/list_changed'), + params: NotificationsParamsSchema.optional() +}); +exports.SubscribeRequestParamsSchema = exports.ResourceRequestParamsSchema; +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + */ +exports.SubscribeRequestSchema = exports.RequestSchema.extend({ + method: z.literal('resources/subscribe'), + params: exports.SubscribeRequestParamsSchema +}); +exports.UnsubscribeRequestParamsSchema = exports.ResourceRequestParamsSchema; +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + */ +exports.UnsubscribeRequestSchema = exports.RequestSchema.extend({ + method: z.literal('resources/unsubscribe'), + params: exports.UnsubscribeRequestParamsSchema +}); +/** + * Parameters for a `notifications/resources/updated` notification. + */ +exports.ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + */ + uri: z.string() +}); +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + */ +exports.ResourceUpdatedNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/resources/updated'), + params: exports.ResourceUpdatedNotificationParamsSchema +}); +/* Prompts */ +/** + * Describes an argument that a prompt can accept. + */ +exports.PromptArgumentSchema = z.object({ + /** + * The name of the argument. + */ + name: z.string(), + /** + * A human-readable description of the argument. + */ + description: z.optional(z.string()), + /** + * Whether this argument must be provided. + */ + required: z.optional(z.boolean()) +}); +/** + * A prompt or prompt template that the server offers. + */ +exports.PromptSchema = z.object({ + ...exports.BaseMetadataSchema.shape, + ...exports.IconsSchema.shape, + /** + * An optional description of what this prompt provides + */ + description: z.optional(z.string()), + /** + * A list of arguments to use for templating the prompt. + */ + arguments: z.optional(z.array(exports.PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ +exports.ListPromptsRequestSchema = exports.PaginatedRequestSchema.extend({ + method: z.literal('prompts/list') +}); +/** + * The server's response to a prompts/list request from the client. + */ +exports.ListPromptsResultSchema = exports.PaginatedResultSchema.extend({ + prompts: z.array(exports.PromptSchema) +}); +/** + * Parameters for a `prompts/get` request. + */ +exports.GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the prompt or prompt template. + */ + name: z.string(), + /** + * Arguments to use for templating the prompt. + */ + arguments: z.record(z.string(), z.string()).optional() +}); +/** + * Used by the client to get a prompt provided by the server. + */ +exports.GetPromptRequestSchema = exports.RequestSchema.extend({ + method: z.literal('prompts/get'), + params: exports.GetPromptRequestParamsSchema +}); +/** + * Text provided to or from an LLM. + */ +exports.TextContentSchema = z.object({ + type: z.literal('text'), + /** + * The text content of the message. + */ + text: z.string(), + /** + * Optional annotations for the client. + */ + annotations: exports.AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * An image provided to or from an LLM. + */ +exports.ImageContentSchema = z.object({ + type: z.literal('image'), + /** + * The base64-encoded image data. + */ + data: Base64Schema, + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: z.string(), + /** + * Optional annotations for the client. + */ + annotations: exports.AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * An Audio provided to or from an LLM. + */ +exports.AudioContentSchema = z.object({ + type: z.literal('audio'), + /** + * The base64-encoded audio data. + */ + data: Base64Schema, + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: z.string(), + /** + * Optional annotations for the client. + */ + annotations: exports.AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + */ +exports.ToolUseContentSchema = z.object({ + type: z.literal('tool_use'), + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: z.string(), + /** + * Unique identifier for this tool call. + * Used to correlate with ToolResultContent in subsequent messages. + */ + id: z.string(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's inputSchema. + */ + input: z.record(z.string(), z.unknown()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * The contents of a resource, embedded into a prompt or tool call result. + */ +exports.EmbeddedResourceSchema = z.object({ + type: z.literal('resource'), + resource: z.union([exports.TextResourceContentsSchema, exports.BlobResourceContentsSchema]), + /** + * Optional annotations for the client. + */ + annotations: exports.AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + */ +exports.ResourceLinkSchema = exports.ResourceSchema.extend({ + type: z.literal('resource_link') +}); +/** + * A content block that can be used in prompts and tool results. + */ +exports.ContentBlockSchema = z.union([ + exports.TextContentSchema, + exports.ImageContentSchema, + exports.AudioContentSchema, + exports.ResourceLinkSchema, + exports.EmbeddedResourceSchema +]); +/** + * Describes a message returned as part of a prompt. + */ +exports.PromptMessageSchema = z.object({ + role: exports.RoleSchema, + content: exports.ContentBlockSchema +}); +/** + * The server's response to a prompts/get request from the client. + */ +exports.GetPromptResultSchema = exports.ResultSchema.extend({ + /** + * An optional description for the prompt. + */ + description: z.string().optional(), + messages: z.array(exports.PromptMessageSchema) +}); +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +exports.PromptListChangedNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/prompts/list_changed'), + params: NotificationsParamsSchema.optional() +}); +/* Tools */ +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + */ +exports.ToolAnnotationsSchema = z.object({ + /** + * A human-readable title for the tool. + */ + title: z.string().optional(), + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint: z.boolean().optional(), + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint: z.boolean().optional(), + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint: z.boolean().optional(), + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint: z.boolean().optional() +}); +/** + * Execution-related properties for a tool. + */ +exports.ToolExecutionSchema = z.object({ + /** + * Indicates the tool's preference for task-augmented execution. + * - "required": Clients MUST invoke the tool as a task + * - "optional": Clients MAY invoke the tool as a task or normal request + * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task + * + * If not present, defaults to "forbidden". + */ + taskSupport: z.enum(['required', 'optional', 'forbidden']).optional() +}); +/** + * Definition for a tool the client can call. + */ +exports.ToolSchema = z.object({ + ...exports.BaseMetadataSchema.shape, + ...exports.IconsSchema.shape, + /** + * A human-readable description of the tool. + */ + description: z.string().optional(), + /** + * A JSON Schema 2020-12 object defining the expected parameters for the tool. + * Must have type: 'object' at the root level per MCP spec. + */ + inputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), AssertObjectSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()), + /** + * An optional JSON Schema 2020-12 object defining the structure of the tool's output + * returned in the structuredContent field of a CallToolResult. + * Must have type: 'object' at the root level per MCP spec. + */ + outputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), AssertObjectSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()) + .optional(), + /** + * Optional additional tool information. + */ + annotations: exports.ToolAnnotationsSchema.optional(), + /** + * Execution-related properties for this tool. + */ + execution: exports.ToolExecutionSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Sent from the client to request a list of tools the server has. + */ +exports.ListToolsRequestSchema = exports.PaginatedRequestSchema.extend({ + method: z.literal('tools/list') +}); +/** + * The server's response to a tools/list request from the client. + */ +exports.ListToolsResultSchema = exports.PaginatedResultSchema.extend({ + tools: z.array(exports.ToolSchema) +}); +/** + * The server's response to a tool call. + */ +exports.CallToolResultSchema = exports.ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the Tool does not define an outputSchema, this field MUST be present in the result. + * For backwards compatibility, this field is always present, but it may be empty. + */ + content: z.array(exports.ContentBlockSchema).default([]), + /** + * An object containing structured tool output. + * + * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: z.record(z.string(), z.unknown()).optional(), + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError: z.boolean().optional() +}); +/** + * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. + */ +exports.CompatibilityCallToolResultSchema = exports.CallToolResultSchema.or(exports.ResultSchema.extend({ + toolResult: z.unknown() +})); +/** + * Parameters for a `tools/call` request. + */ +exports.CallToolRequestParamsSchema = exports.TaskAugmentedRequestParamsSchema.extend({ + /** + * The name of the tool to call. + */ + name: z.string(), + /** + * Arguments to pass to the tool. + */ + arguments: z.record(z.string(), z.unknown()).optional() +}); +/** + * Used by the client to invoke a tool provided by the server. + */ +exports.CallToolRequestSchema = exports.RequestSchema.extend({ + method: z.literal('tools/call'), + params: exports.CallToolRequestParamsSchema +}); +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +exports.ToolListChangedNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/tools/list_changed'), + params: NotificationsParamsSchema.optional() +}); +/** + * Base schema for list changed subscription options (without callback). + * Used internally for Zod validation of autoRefresh and debounceMs. + */ +exports.ListChangedOptionsBaseSchema = z.object({ + /** + * If true, the list will be refreshed automatically when a list changed notification is received. + * The callback will be called with the updated list. + * + * If false, the callback will be called with null items, allowing manual refresh. + * + * @default true + */ + autoRefresh: z.boolean().default(true), + /** + * Debounce time in milliseconds for list changed notification processing. + * + * Multiple notifications received within this timeframe will only trigger one refresh. + * Set to 0 to disable debouncing. + * + * @default 300 + */ + debounceMs: z.number().int().nonnegative().default(300) +}); +/* Logging */ +/** + * The severity of a log message. + */ +exports.LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); +/** + * Parameters for a `logging/setLevel` request. + */ +exports.SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. + */ + level: exports.LoggingLevelSchema +}); +/** + * A request from the client to the server, to enable or adjust logging. + */ +exports.SetLevelRequestSchema = exports.RequestSchema.extend({ + method: z.literal('logging/setLevel'), + params: exports.SetLevelRequestParamsSchema +}); +/** + * Parameters for a `notifications/message` notification. + */ +exports.LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The severity of this log message. + */ + level: exports.LoggingLevelSchema, + /** + * An optional name of the logger issuing this message. + */ + logger: z.string().optional(), + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: z.unknown() +}); +/** + * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + */ +exports.LoggingMessageNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/message'), + params: exports.LoggingMessageNotificationParamsSchema +}); +/* Sampling */ +/** + * Hints to use for model selection. + */ +exports.ModelHintSchema = z.object({ + /** + * A hint for a model name. + */ + name: z.string().optional() +}); +/** + * The server's preferences for model selection, requested of the client during sampling. + */ +exports.ModelPreferencesSchema = z.object({ + /** + * Optional hints to use for model selection. + */ + hints: z.array(exports.ModelHintSchema).optional(), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: z.number().min(0).max(1).optional(), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: z.number().min(0).max(1).optional(), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: z.number().min(0).max(1).optional() +}); +/** + * Controls tool usage behavior in sampling requests. + */ +exports.ToolChoiceSchema = z.object({ + /** + * Controls when tools are used: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode: z.enum(['auto', 'required', 'none']).optional() +}); +/** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via ToolUseContent. + */ +exports.ToolResultContentSchema = z.object({ + type: z.literal('tool_result'), + toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), + content: z.array(exports.ContentBlockSchema).default([]), + structuredContent: z.object({}).loose().optional(), + isError: z.boolean().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible CreateMessageResult when tools are not used. + */ +exports.SamplingContentSchema = z.discriminatedUnion('type', [exports.TextContentSchema, exports.ImageContentSchema, exports.AudioContentSchema]); +/** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + */ +exports.SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ + exports.TextContentSchema, + exports.ImageContentSchema, + exports.AudioContentSchema, + exports.ToolUseContentSchema, + exports.ToolResultContentSchema +]); +/** + * Describes a message issued to or received from an LLM API. + */ +exports.SamplingMessageSchema = z.object({ + role: exports.RoleSchema, + content: z.union([exports.SamplingMessageContentBlockSchema, z.array(exports.SamplingMessageContentBlockSchema)]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Parameters for a `sampling/createMessage` request. + */ +exports.CreateMessageRequestParamsSchema = exports.TaskAugmentedRequestParamsSchema.extend({ + messages: z.array(exports.SamplingMessageSchema), + /** + * The server's preferences for which model to select. The client MAY modify or omit this request. + */ + modelPreferences: exports.ModelPreferencesSchema.optional(), + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt: z.string().optional(), + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), + temperature: z.number().optional(), + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: z.number().int(), + stopSequences: z.array(z.string()).optional(), + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata: AssertObjectSchema.optional(), + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools: z.array(exports.ToolSchema).optional(), + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice: exports.ToolChoiceSchema.optional() +}); +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + */ +exports.CreateMessageRequestSchema = exports.RequestSchema.extend({ + method: z.literal('sampling/createMessage'), + params: exports.CreateMessageRequestParamsSchema +}); +/** + * The client's response to a sampling/create_message request from the server. + * This is the backwards-compatible version that returns single content (no arrays). + * Used when the request does not include tools. + */ +exports.CreateMessageResultSchema = exports.ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: z.string(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())), + role: exports.RoleSchema, + /** + * Response content. Single content block (text, image, or audio). + */ + content: exports.SamplingContentSchema +}); +/** + * The client's response to a sampling/create_message request when tools were provided. + * This version supports array content for tool use flows. + */ +exports.CreateMessageResultWithToolsSchema = exports.ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: z.string(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())), + role: exports.RoleSchema, + /** + * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". + */ + content: z.union([exports.SamplingMessageContentBlockSchema, z.array(exports.SamplingMessageContentBlockSchema)]) +}); +/* Elicitation */ +/** + * Primitive schema definition for boolean fields. + */ +exports.BooleanSchemaSchema = z.object({ + type: z.literal('boolean'), + title: z.string().optional(), + description: z.string().optional(), + default: z.boolean().optional() +}); +/** + * Primitive schema definition for string fields. + */ +exports.StringSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + minLength: z.number().optional(), + maxLength: z.number().optional(), + format: z.enum(['email', 'uri', 'date', 'date-time']).optional(), + default: z.string().optional() +}); +/** + * Primitive schema definition for number fields. + */ +exports.NumberSchemaSchema = z.object({ + type: z.enum(['number', 'integer']), + title: z.string().optional(), + description: z.string().optional(), + minimum: z.number().optional(), + maximum: z.number().optional(), + default: z.number().optional() +}); +/** + * Schema for single-selection enumeration without display titles for options. + */ +exports.UntitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + default: z.string().optional() +}); +/** + * Schema for single-selection enumeration with display titles for each option. + */ +exports.TitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + oneOf: z.array(z.object({ + const: z.string(), + title: z.string() + })), + default: z.string().optional() +}); +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + */ +exports.LegacyTitledEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + enumNames: z.array(z.string()).optional(), + default: z.string().optional() +}); +// Combined single selection enumeration +exports.SingleSelectEnumSchemaSchema = z.union([exports.UntitledSingleSelectEnumSchemaSchema, exports.TitledSingleSelectEnumSchemaSchema]); +/** + * Schema for multiple-selection enumeration without display titles for options. + */ +exports.UntitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + type: z.literal('string'), + enum: z.array(z.string()) + }), + default: z.array(z.string()).optional() +}); +/** + * Schema for multiple-selection enumeration with display titles for each option. + */ +exports.TitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + anyOf: z.array(z.object({ + const: z.string(), + title: z.string() + })) + }), + default: z.array(z.string()).optional() +}); +/** + * Combined schema for multiple-selection enumeration + */ +exports.MultiSelectEnumSchemaSchema = z.union([exports.UntitledMultiSelectEnumSchemaSchema, exports.TitledMultiSelectEnumSchemaSchema]); +/** + * Primitive schema definition for enum fields. + */ +exports.EnumSchemaSchema = z.union([exports.LegacyTitledEnumSchemaSchema, exports.SingleSelectEnumSchemaSchema, exports.MultiSelectEnumSchemaSchema]); +/** + * Union of all primitive schema definitions. + */ +exports.PrimitiveSchemaDefinitionSchema = z.union([exports.EnumSchemaSchema, exports.BooleanSchemaSchema, exports.StringSchemaSchema, exports.NumberSchemaSchema]); +/** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ +exports.ElicitRequestFormParamsSchema = exports.TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + * + * Optional for backward compatibility. Clients MUST treat missing mode as "form". + */ + mode: z.literal('form').optional(), + /** + * The message to present to the user describing what information is being requested. + */ + message: z.string(), + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: z.object({ + type: z.literal('object'), + properties: z.record(z.string(), exports.PrimitiveSchemaDefinitionSchema), + required: z.array(z.string()).optional() + }) +}); +/** + * Parameters for an `elicitation/create` request for URL-based elicitation. + */ +exports.ElicitRequestURLParamsSchema = exports.TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: z.literal('url'), + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: z.string(), + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: z.string(), + /** + * The URL that the user should navigate to. + */ + url: z.string().url() +}); +/** + * The parameters for a request to elicit additional information from the user via the client. + */ +exports.ElicitRequestParamsSchema = z.union([exports.ElicitRequestFormParamsSchema, exports.ElicitRequestURLParamsSchema]); +/** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ +exports.ElicitRequestSchema = exports.RequestSchema.extend({ + method: z.literal('elicitation/create'), + params: exports.ElicitRequestParamsSchema +}); +/** + * Parameters for a `notifications/elicitation/complete` notification. + * + * @category notifications/elicitation/complete + */ +exports.ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the elicitation that completed. + */ + elicitationId: z.string() +}); +/** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ +exports.ElicitationCompleteNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/elicitation/complete'), + params: exports.ElicitationCompleteNotificationParamsSchema +}); +/** + * The client's response to an elicitation/create request from the server. + */ +exports.ElicitResultSchema = exports.ResultSchema.extend({ + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: z.enum(['accept', 'decline', 'cancel']), + /** + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. + * Per MCP spec, content is "typically omitted" for decline/cancel actions. + * We normalize null to undefined for leniency while maintaining type compatibility. + */ + content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional()) +}); +/* Autocomplete */ +/** + * A reference to a resource or resource template definition. + */ +exports.ResourceTemplateReferenceSchema = z.object({ + type: z.literal('ref/resource'), + /** + * The URI or URI template of the resource. + */ + uri: z.string() +}); +/** + * @deprecated Use ResourceTemplateReferenceSchema instead + */ +exports.ResourceReferenceSchema = exports.ResourceTemplateReferenceSchema; +/** + * Identifies a prompt. + */ +exports.PromptReferenceSchema = z.object({ + type: z.literal('ref/prompt'), + /** + * The name of the prompt or prompt template + */ + name: z.string() +}); +/** + * Parameters for a `completion/complete` request. + */ +exports.CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: z.union([exports.PromptReferenceSchema, exports.ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: z.object({ + /** + * The name of the argument + */ + name: z.string(), + /** + * The value of the argument to use for completion matching. + */ + value: z.string() + }), + context: z + .object({ + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: z.record(z.string(), z.string()).optional() + }) + .optional() +}); +/** + * A request from the client to the server, to ask for completion options. + */ +exports.CompleteRequestSchema = exports.RequestSchema.extend({ + method: z.literal('completion/complete'), + params: exports.CompleteRequestParamsSchema +}); +function assertCompleteRequestPrompt(request) { + if (request.params.ref.type !== 'ref/prompt') { + throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); + } + void request; +} +function assertCompleteRequestResourceTemplate(request) { + if (request.params.ref.type !== 'ref/resource') { + throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); + } + void request; +} +/** + * The server's response to a completion/complete request + */ +exports.CompleteResultSchema = exports.ResultSchema.extend({ + completion: z.looseObject({ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.array(z.string()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.optional(z.number().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.optional(z.boolean()) + }) +}); +/* Roots */ +/** + * Represents a root directory or file that the server can operate on. + */ +exports.RootSchema = z.object({ + /** + * The URI identifying the root. This *must* start with file:// for now. + */ + uri: z.string().startsWith('file://'), + /** + * An optional name for the root. + */ + name: z.string().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Sent from the server to request a list of root URIs from the client. + */ +exports.ListRootsRequestSchema = exports.RequestSchema.extend({ + method: z.literal('roots/list'), + params: BaseRequestParamsSchema.optional() +}); +/** + * The client's response to a roots/list request from the server. + */ +exports.ListRootsResultSchema = exports.ResultSchema.extend({ + roots: z.array(exports.RootSchema) +}); +/** + * A notification from the client to the server, informing it that the list of roots has changed. + */ +exports.RootsListChangedNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/roots/list_changed'), + params: NotificationsParamsSchema.optional() +}); +/* Client messages */ +exports.ClientRequestSchema = z.union([ + exports.PingRequestSchema, + exports.InitializeRequestSchema, + exports.CompleteRequestSchema, + exports.SetLevelRequestSchema, + exports.GetPromptRequestSchema, + exports.ListPromptsRequestSchema, + exports.ListResourcesRequestSchema, + exports.ListResourceTemplatesRequestSchema, + exports.ReadResourceRequestSchema, + exports.SubscribeRequestSchema, + exports.UnsubscribeRequestSchema, + exports.CallToolRequestSchema, + exports.ListToolsRequestSchema, + exports.GetTaskRequestSchema, + exports.GetTaskPayloadRequestSchema, + exports.ListTasksRequestSchema, + exports.CancelTaskRequestSchema +]); +exports.ClientNotificationSchema = z.union([ + exports.CancelledNotificationSchema, + exports.ProgressNotificationSchema, + exports.InitializedNotificationSchema, + exports.RootsListChangedNotificationSchema, + exports.TaskStatusNotificationSchema +]); +exports.ClientResultSchema = z.union([ + exports.EmptyResultSchema, + exports.CreateMessageResultSchema, + exports.CreateMessageResultWithToolsSchema, + exports.ElicitResultSchema, + exports.ListRootsResultSchema, + exports.GetTaskResultSchema, + exports.ListTasksResultSchema, + exports.CreateTaskResultSchema +]); +/* Server messages */ +exports.ServerRequestSchema = z.union([ + exports.PingRequestSchema, + exports.CreateMessageRequestSchema, + exports.ElicitRequestSchema, + exports.ListRootsRequestSchema, + exports.GetTaskRequestSchema, + exports.GetTaskPayloadRequestSchema, + exports.ListTasksRequestSchema, + exports.CancelTaskRequestSchema +]); +exports.ServerNotificationSchema = z.union([ + exports.CancelledNotificationSchema, + exports.ProgressNotificationSchema, + exports.LoggingMessageNotificationSchema, + exports.ResourceUpdatedNotificationSchema, + exports.ResourceListChangedNotificationSchema, + exports.ToolListChangedNotificationSchema, + exports.PromptListChangedNotificationSchema, + exports.TaskStatusNotificationSchema, + exports.ElicitationCompleteNotificationSchema +]); +exports.ServerResultSchema = z.union([ + exports.EmptyResultSchema, + exports.InitializeResultSchema, + exports.CompleteResultSchema, + exports.GetPromptResultSchema, + exports.ListPromptsResultSchema, + exports.ListResourcesResultSchema, + exports.ListResourceTemplatesResultSchema, + exports.ReadResourceResultSchema, + exports.CallToolResultSchema, + exports.ListToolsResultSchema, + exports.GetTaskResultSchema, + exports.ListTasksResultSchema, + exports.CreateTaskResultSchema +]); +class McpError extends Error { + constructor(code, message, data) { + super(`MCP error ${code}: ${message}`); + this.code = code; + this.data = data; + this.name = 'McpError'; + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + // Check for specific error types + if (code === ErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) { + return new UrlElicitationRequiredError(errorData.elicitations, message); + } + } + // Default to generic McpError + return new McpError(code, message, data); + } +} +exports.McpError = McpError; +/** + * Specialized error type when a tool requires a URL mode elicitation. + * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. + */ +class UrlElicitationRequiredError extends McpError { + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) { + super(ErrorCode.UrlElicitationRequired, message, { + elicitations: elicitations + }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +} +exports.UrlElicitationRequiredError = UrlElicitationRequiredError; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/types.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/types.js.map new file mode 100644 index 000000000..b0fe26927 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAslEA,kEAKC;AAED,sFAKC;AAlmED,0CAA4B;AAGf,QAAA,uBAAuB,GAAG,YAAY,CAAC;AACvC,QAAA,mCAAmC,GAAG,YAAY,CAAC;AACnD,QAAA,2BAA2B,GAAG,CAAC,+BAAuB,EAAE,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC;AAEhH,QAAA,qBAAqB,GAAG,sCAAsC,CAAC;AAE5E,oBAAoB;AACP,QAAA,eAAe,GAAG,KAAK,CAAC;AAMrC;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAS,CAAC,CAA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AAC;QAJvB,SAAI,GAAJ,IAAI,CAAQ;QAEZ,SAAI,GAAJ,IAAI,CAAU;QAG9B,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,SAAS,CAAC,IAAY,EAAE,OAAe,EAAE,IAAc;QAC1D,iCAAiC;QACjC,IAAI,IAAI,KAAK,SAAS,CAAC,sBAAsB,IAAI,IAAI,EAAE,CAAC;YACpD,MAAM,SAAS,GAAG,IAAoC,CAAC;YACvD,IAAI,SAAS,CAAC,YAAY,EAAE,CAAC;gBACzB,OAAO,IAAI,2BAA2B,CAAC,SAAS,CAAC,YAAwC,EAAE,OAAO,CAAC,CAAC;YACxG,CAAC;QACL,CAAC;QAED,8BAA8B;QAC9B,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC7C,CAAC;CACJ;AAzBD,4BAyBC;AAED;;;GAGG;AACH,MAAa,2BAA4B,SAAQ,QAAQ;IACrD,YAAY,YAAsC,EAAE,UAAkB,kBAAkB,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,WAAW;QACjI,KAAK,CAAC,SAAS,CAAC,sBAAsB,EAAE,OAAO,EAAE;YAC7C,YAAY,EAAE,YAAY;SAC7B,CAAC,CAAC;IACP,CAAC;IAED,IAAI,YAAY;QACZ,OAAQ,IAAI,CAAC,IAAmD,EAAE,YAAY,IAAI,EAAE,CAAC;IACzF,CAAC;CACJ;AAVD,kEAUC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/ajv-provider.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/ajv-provider.d.ts new file mode 100644 index 000000000..952ee68df --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/ajv-provider.d.ts @@ -0,0 +1,53 @@ +/** + * AJV-based JSON Schema validator provider + */ +import Ajv from 'ajv'; +import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from './types.js'; +/** + * @example + * ```typescript + * // Use with default AJV instance (recommended) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Use with custom AJV instance + * import { Ajv } from 'ajv'; + * const ajv = new Ajv({ strict: true, allErrors: true }); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ +export declare class AjvJsonSchemaValidator implements jsonSchemaValidator { + private _ajv; + /** + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ + constructor(ajv?: Ajv); + /** + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema: JsonSchemaType): JsonSchemaValidator; +} +//# sourceMappingURL=ajv-provider.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/ajv-provider.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/ajv-provider.d.ts.map new file mode 100644 index 000000000..6704c4d92 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/ajv-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ajv-provider.d.ts","sourceRoot":"","sources":["../../../src/validation/ajv-provider.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,GAAG,MAAM,KAAK,CAAC;AAEtB,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAA6B,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAgBtH;;;;;;;;;;;;GAYG;AACH,qBAAa,sBAAuB,YAAW,mBAAmB;IAC9D,OAAO,CAAC,IAAI,CAAM;IAElB;;;;;;;;;;;;;;;;;;;OAmBG;gBACS,GAAG,CAAC,EAAE,GAAG;IAIrB;;;;;;;;OAQG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC;CAyBlE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/ajv-provider.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/ajv-provider.js new file mode 100644 index 000000000..a46f8c669 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/ajv-provider.js @@ -0,0 +1,94 @@ +"use strict"; +/** + * AJV-based JSON Schema validator provider + */ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AjvJsonSchemaValidator = void 0; +const ajv_1 = __importDefault(require("ajv")); +const ajv_formats_1 = __importDefault(require("ajv-formats")); +function createDefaultAjvInstance() { + const ajv = new ajv_1.default({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + const addFormats = ajv_formats_1.default; + addFormats(ajv); + return ajv; +} +/** + * @example + * ```typescript + * // Use with default AJV instance (recommended) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Use with custom AJV instance + * import { Ajv } from 'ajv'; + * const ajv = new Ajv({ strict: true, allErrors: true }); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ +class AjvJsonSchemaValidator { + /** + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ + constructor(ajv) { + this._ajv = ajv ?? createDefaultAjvInstance(); + } + /** + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema) { + // Check if schema has $id and is already compiled/cached + const ajvValidator = '$id' in schema && typeof schema.$id === 'string' + ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema)) + : this._ajv.compile(schema); + return (input) => { + const valid = ajvValidator(input); + if (valid) { + return { + valid: true, + data: input, + errorMessage: undefined + }; + } + else { + return { + valid: false, + data: undefined, + errorMessage: this._ajv.errorsText(ajvValidator.errors) + }; + } + }; + } +} +exports.AjvJsonSchemaValidator = AjvJsonSchemaValidator; +//# sourceMappingURL=ajv-provider.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/ajv-provider.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/ajv-provider.js.map new file mode 100644 index 000000000..2405e7b77 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/ajv-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ajv-provider.js","sourceRoot":"","sources":["../../../src/validation/ajv-provider.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;AAEH,8CAAsB;AACtB,8DAAsC;AAGtC,SAAS,wBAAwB;IAC7B,MAAM,GAAG,GAAG,IAAI,aAAG,CAAC;QAChB,MAAM,EAAE,KAAK;QACb,eAAe,EAAE,IAAI;QACrB,cAAc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_modules/@modelcontextprotocol/sdk/dist/cjs/validation/cfworker-provider.d.ts new file mode 100644 index 000000000..89c244a60 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/cfworker-provider.d.ts @@ -0,0 +1,51 @@ +/** + * Cloudflare Worker-compatible JSON Schema validator provider + * + * This provider uses @cfworker/json-schema for validation without code generation, + * making it compatible with edge runtimes like Cloudflare Workers that restrict + * eval and new Function. + */ +import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from './types.js'; +/** + * JSON Schema draft version supported by @cfworker/json-schema + */ +export type CfWorkerSchemaDraft = '4' | '7' | '2019-09' | '2020-12'; +/** + * + * @example + * ```typescript + * // Use with default configuration (2020-12, shortcircuit) + * const validator = new CfWorkerJsonSchemaValidator(); + * + * // Use with custom configuration + * const validator = new CfWorkerJsonSchemaValidator({ + * draft: '2020-12', + * shortcircuit: false // Report all errors + * }); + * ``` + */ +export declare class CfWorkerJsonSchemaValidator implements jsonSchemaValidator { + private shortcircuit; + private draft; + /** + * Create a validator + * + * @param options - Configuration options + * @param options.shortcircuit - If true, stop validation after first error (default: true) + * @param options.draft - JSON Schema draft version to use (default: '2020-12') + */ + constructor(options?: { + shortcircuit?: boolean; + draft?: CfWorkerSchemaDraft; + }); + /** + * Create a validator for the given JSON Schema + * + * Unlike AJV, this validator is not cached internally + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema: JsonSchemaType): JsonSchemaValidator; +} +//# sourceMappingURL=cfworker-provider.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/cfworker-provider.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/cfworker-provider.d.ts.map new file mode 100644 index 000000000..ce404d92f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/cfworker-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cfworker-provider.d.ts","sourceRoot":"","sources":["../../../src/validation/cfworker-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAA6B,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtH;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,GAAG,GAAG,GAAG,GAAG,SAAS,GAAG,SAAS,CAAC;AAEpE;;;;;;;;;;;;;GAaG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IACnE,OAAO,CAAC,YAAY,CAAU;IAC9B,OAAO,CAAC,KAAK,CAAsB;IAEnC;;;;;;OAMG;gBACS,OAAO,CAAC,EAAE;QAAE,YAAY,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,mBAAmB,CAAA;KAAE;IAK7E;;;;;;;OAOG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC;CAsBlE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/cfworker-provider.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/cfworker-provider.js new file mode 100644 index 000000000..91235b7bc --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/cfworker-provider.js @@ -0,0 +1,69 @@ +"use strict"; +/** + * Cloudflare Worker-compatible JSON Schema validator provider + * + * This provider uses @cfworker/json-schema for validation without code generation, + * making it compatible with edge runtimes like Cloudflare Workers that restrict + * eval and new Function. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CfWorkerJsonSchemaValidator = void 0; +const json_schema_1 = require("@cfworker/json-schema"); +/** + * + * @example + * ```typescript + * // Use with default configuration (2020-12, shortcircuit) + * const validator = new CfWorkerJsonSchemaValidator(); + * + * // Use with custom configuration + * const validator = new CfWorkerJsonSchemaValidator({ + * draft: '2020-12', + * shortcircuit: false // Report all errors + * }); + * ``` + */ +class CfWorkerJsonSchemaValidator { + /** + * Create a validator + * + * @param options - Configuration options + * @param options.shortcircuit - If true, stop validation after first error (default: true) + * @param options.draft - JSON Schema draft version to use (default: '2020-12') + */ + constructor(options) { + this.shortcircuit = options?.shortcircuit ?? true; + this.draft = options?.draft ?? '2020-12'; + } + /** + * Create a validator for the given JSON Schema + * + * Unlike AJV, this validator is not cached internally + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema) { + // Cast to the cfworker Schema type - our JsonSchemaType is structurally compatible + const validator = new json_schema_1.Validator(schema, this.draft, this.shortcircuit); + return (input) => { + const result = validator.validate(input); + if (result.valid) { + return { + valid: true, + data: input, + errorMessage: undefined + }; + } + else { + return { + valid: false, + data: undefined, + errorMessage: result.errors.map(err => `${err.instanceLocation}: ${err.error}`).join('; ') + }; + } + }; + } +} +exports.CfWorkerJsonSchemaValidator = CfWorkerJsonSchemaValidator; +//# sourceMappingURL=cfworker-provider.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/cfworker-provider.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/cfworker-provider.js.map new file mode 100644 index 000000000..88492c66b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/cfworker-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cfworker-provider.js","sourceRoot":"","sources":["../../../src/validation/cfworker-provider.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,uDAAkD;AAQlD;;;;;;;;;;;;;GAaG;AACH,MAAa,2BAA2B;IAIpC;;;;;;OAMG;IACH,YAAY,OAAiE;QACzE,IAAI,CAAC,YAAY,GAAG,OAAO,EAAE,YAAY,IAAI,IAAI,CAAC;QAClD,IAAI,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,IAAI,SAAS,CAAC;IAC7C,CAAC;IAED;;;;;;;OAOG;IACH,YAAY,CAAI,MAAsB;QAClC,mFAAmF;QACnF,MAAM,SAAS,GAAG,IAAI,uBAAS,CAAC,MAAoD,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QAErH,OAAO,CAAC,KAAc,EAAgC,EAAE;YACpD,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;YAEzC,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;gBACf,OAAO;oBACH,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,KAAU;oBAChB,YAAY,EAAE,SAAS;iBAC1B,CAAC;YACN,CAAC;iBAAM,CAAC;gBACJ,OAAO;oBACH,KAAK,EAAE,KAAK;oBACZ,IAAI,EAAE,SAAS;oBACf,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,gBAAgB,KAAK,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;iBAC7F,CAAC;YACN,CAAC;QACL,CAAC,CAAC;IACN,CAAC;CACJ;AA9CD,kEA8CC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/index.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/index.d.ts new file mode 100644 index 000000000..99e993967 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/index.d.ts @@ -0,0 +1,29 @@ +/** + * JSON Schema validation + * + * This module provides configurable JSON Schema validation for the MCP SDK. + * Choose a validator based on your runtime environment: + * + * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) + * Import from: @modelcontextprotocol/sdk/validation/ajv + * Requires peer dependencies: ajv, ajv-formats + * + * - CfWorkerJsonSchemaValidator: Best for edge runtimes + * Import from: @modelcontextprotocol/sdk/validation/cfworker + * Requires peer dependency: @cfworker/json-schema + * + * @example + * ```typescript + * // For Node.js with AJV + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // For Cloudflare Workers + * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; + * const validator = new CfWorkerJsonSchemaValidator(); + * ``` + * + * @module validation + */ +export type { JsonSchemaType, JsonSchemaValidator, JsonSchemaValidatorResult, jsonSchemaValidator } from './types.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/index.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/index.d.ts.map new file mode 100644 index 000000000..a8845b96e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGH,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/index.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/index.js new file mode 100644 index 000000000..c8be9256d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/index.js @@ -0,0 +1,30 @@ +"use strict"; +/** + * JSON Schema validation + * + * This module provides configurable JSON Schema validation for the MCP SDK. + * Choose a validator based on your runtime environment: + * + * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) + * Import from: @modelcontextprotocol/sdk/validation/ajv + * Requires peer dependencies: ajv, ajv-formats + * + * - CfWorkerJsonSchemaValidator: Best for edge runtimes + * Import from: @modelcontextprotocol/sdk/validation/cfworker + * Requires peer dependency: @cfworker/json-schema + * + * @example + * ```typescript + * // For Node.js with AJV + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // For Cloudflare Workers + * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; + * const validator = new CfWorkerJsonSchemaValidator(); + * ``` + * + * @module validation + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/index.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/index.js.map new file mode 100644 index 000000000..1d5874d99 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/types.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/types.d.ts new file mode 100644 index 000000000..9fa92226c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/types.d.ts @@ -0,0 +1,65 @@ +import type { JSONSchema } from 'json-schema-typed'; +/** + * JSON Schema type definition (JSON Schema Draft 2020-12) + * + * This uses the object form of JSON Schema (excluding boolean schemas). + * While `true` and `false` are valid JSON Schemas, this SDK uses the + * object form for practical type safety. + * + * Re-exported from json-schema-typed for convenience. + * @see https://json-schema.org/draft/2020-12/json-schema-core.html + */ +export type JsonSchemaType = JSONSchema.Interface; +/** + * Result of a JSON Schema validation operation + */ +export type JsonSchemaValidatorResult = { + valid: true; + data: T; + errorMessage: undefined; +} | { + valid: false; + data: undefined; + errorMessage: string; +}; +/** + * A validator function that validates data against a JSON Schema + */ +export type JsonSchemaValidator = (input: unknown) => JsonSchemaValidatorResult; +/** + * Provider interface for creating validators from JSON Schemas + * + * This is the main extension point for custom validator implementations. + * Implementations should: + * - Support JSON Schema Draft 2020-12 (or be compatible with it) + * - Return validator functions that can be called multiple times + * - Handle schema compilation/caching internally + * - Provide clear error messages on validation failure + * + * @example + * ```typescript + * class MyValidatorProvider implements jsonSchemaValidator { + * getValidator(schema: JsonSchemaType): JsonSchemaValidator { + * // Compile/cache validator from schema + * return (input: unknown) => { + * // Validate input against schema + * if (valid) { + * return { valid: true, data: input as T, errorMessage: undefined }; + * } else { + * return { valid: false, data: undefined, errorMessage: 'Error details' }; + * } + * }; + * } + * } + * ``` + */ +export interface jsonSchemaValidator { + /** + * Create a validator for the given JSON Schema + * + * @param schema - Standard JSON Schema object + * @returns A validator function that can be called multiple times + */ + getValidator(schema: JsonSchemaType): JsonSchemaValidator; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/types.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/types.d.ts.map new file mode 100644 index 000000000..52aa0ef42 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/validation/types.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD;;;;;;;;;GASG;AACH,MAAM,MAAM,cAAc,GAAG,UAAU,CAAC,SAAS,CAAC;AAElD;;GAEG;AACH,MAAM,MAAM,yBAAyB,CAAC,CAAC,IACjC;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,CAAC,CAAC;IAAC,YAAY,EAAE,SAAS,CAAA;CAAE,GACjD;IAAE,KAAK,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,SAAS,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC;AAE9D;;GAEG;AACH,MAAM,MAAM,mBAAmB,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,KAAK,yBAAyB,CAAC,CAAC,CAAC,CAAC;AAEtF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,WAAW,mBAAmB;IAChC;;;;;OAKG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAC;CACnE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/types.js b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/types.js new file mode 100644 index 000000000..11e638d1e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/types.js.map b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/types.js.map new file mode 100644 index 000000000..51361cf6a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/cjs/validation/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/validation/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth-extensions.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth-extensions.d.ts new file mode 100644 index 000000000..2a3f6bff6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth-extensions.d.ts @@ -0,0 +1,178 @@ +/** + * OAuth provider extensions for specialized authentication flows. + * + * This module provides ready-to-use OAuthClientProvider implementations + * for common machine-to-machine authentication scenarios. + */ +import { OAuthClientInformation, OAuthClientMetadata, OAuthTokens } from '../shared/auth.js'; +import { AddClientAuthentication, OAuthClientProvider } from './auth.js'; +/** + * Helper to produce a private_key_jwt client authentication function. + * + * Usage: + * const addClientAuth = createPrivateKeyJwtAuth({ issuer, subject, privateKey, alg, audience? }); + * // pass addClientAuth as provider.addClientAuthentication implementation + */ +export declare function createPrivateKeyJwtAuth(options: { + issuer: string; + subject: string; + privateKey: string | Uint8Array | Record; + alg: string; + audience?: string | URL; + lifetimeSeconds?: number; + claims?: Record; +}): AddClientAuthentication; +/** + * Options for creating a ClientCredentialsProvider. + */ +export interface ClientCredentialsProviderOptions { + /** + * The client_id for this OAuth client. + */ + clientId: string; + /** + * The client_secret for client_secret_basic authentication. + */ + clientSecret: string; + /** + * Optional client name for metadata. + */ + clientName?: string; +} +/** + * OAuth provider for client_credentials grant with client_secret_basic authentication. + * + * This provider is designed for machine-to-machine authentication where + * the client authenticates using a client_id and client_secret. + * + * @example + * const provider = new ClientCredentialsProvider({ + * clientId: 'my-client', + * clientSecret: 'my-secret' + * }); + * + * const transport = new StreamableHTTPClientTransport(serverUrl, { + * authProvider: provider + * }); + */ +export declare class ClientCredentialsProvider implements OAuthClientProvider { + private _tokens?; + private _clientInfo; + private _clientMetadata; + constructor(options: ClientCredentialsProviderOptions); + get redirectUrl(): undefined; + get clientMetadata(): OAuthClientMetadata; + clientInformation(): OAuthClientInformation; + saveClientInformation(info: OAuthClientInformation): void; + tokens(): OAuthTokens | undefined; + saveTokens(tokens: OAuthTokens): void; + redirectToAuthorization(): void; + saveCodeVerifier(): void; + codeVerifier(): string; + prepareTokenRequest(scope?: string): URLSearchParams; +} +/** + * Options for creating a PrivateKeyJwtProvider. + */ +export interface PrivateKeyJwtProviderOptions { + /** + * The client_id for this OAuth client. + */ + clientId: string; + /** + * The private key for signing JWT assertions. + * Can be a PEM string, Uint8Array, or JWK object. + */ + privateKey: string | Uint8Array | Record; + /** + * The algorithm to use for signing (e.g., 'RS256', 'ES256'). + */ + algorithm: string; + /** + * Optional client name for metadata. + */ + clientName?: string; + /** + * Optional JWT lifetime in seconds (default: 300). + */ + jwtLifetimeSeconds?: number; +} +/** + * OAuth provider for client_credentials grant with private_key_jwt authentication. + * + * This provider is designed for machine-to-machine authentication where + * the client authenticates using a signed JWT assertion (RFC 7523 Section 2.2). + * + * @example + * const provider = new PrivateKeyJwtProvider({ + * clientId: 'my-client', + * privateKey: pemEncodedPrivateKey, + * algorithm: 'RS256' + * }); + * + * const transport = new StreamableHTTPClientTransport(serverUrl, { + * authProvider: provider + * }); + */ +export declare class PrivateKeyJwtProvider implements OAuthClientProvider { + private _tokens?; + private _clientInfo; + private _clientMetadata; + addClientAuthentication: AddClientAuthentication; + constructor(options: PrivateKeyJwtProviderOptions); + get redirectUrl(): undefined; + get clientMetadata(): OAuthClientMetadata; + clientInformation(): OAuthClientInformation; + saveClientInformation(info: OAuthClientInformation): void; + tokens(): OAuthTokens | undefined; + saveTokens(tokens: OAuthTokens): void; + redirectToAuthorization(): void; + saveCodeVerifier(): void; + codeVerifier(): string; + prepareTokenRequest(scope?: string): URLSearchParams; +} +/** + * Options for creating a StaticPrivateKeyJwtProvider. + */ +export interface StaticPrivateKeyJwtProviderOptions { + /** + * The client_id for this OAuth client. + */ + clientId: string; + /** + * A pre-built JWT client assertion to use for authentication. + * + * This token should already contain the appropriate claims + * (iss, sub, aud, exp, etc.) and be signed by the client's key. + */ + jwtBearerAssertion: string; + /** + * Optional client name for metadata. + */ + clientName?: string; +} +/** + * OAuth provider for client_credentials grant with a static private_key_jwt assertion. + * + * This provider mirrors {@link PrivateKeyJwtProvider} but instead of constructing and + * signing a JWT on each request, it accepts a pre-built JWT assertion string and + * uses it directly for authentication. + */ +export declare class StaticPrivateKeyJwtProvider implements OAuthClientProvider { + private _tokens?; + private _clientInfo; + private _clientMetadata; + addClientAuthentication: AddClientAuthentication; + constructor(options: StaticPrivateKeyJwtProviderOptions); + get redirectUrl(): undefined; + get clientMetadata(): OAuthClientMetadata; + clientInformation(): OAuthClientInformation; + saveClientInformation(info: OAuthClientInformation): void; + tokens(): OAuthTokens | undefined; + saveTokens(tokens: OAuthTokens): void; + redirectToAuthorization(): void; + saveCodeVerifier(): void; + codeVerifier(): string; + prepareTokenRequest(scope?: string): URLSearchParams; +} +//# sourceMappingURL=auth-extensions.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth-extensions.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth-extensions.d.ts.map new file mode 100644 index 000000000..863e23a83 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth-extensions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-extensions.d.ts","sourceRoot":"","sources":["../../../src/client/auth-extensions.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC7F,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAEzE;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE;IAC7C,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC1D,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC,GAAG,uBAAuB,CAgE1B;AAED;;GAEG;AACH,MAAM,WAAW,gCAAgC;IAC7C;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IAErB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,yBAA0B,YAAW,mBAAmB;IACjE,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,WAAW,CAAyB;IAC5C,OAAO,CAAC,eAAe,CAAsB;gBAEjC,OAAO,EAAE,gCAAgC;IAarD,IAAI,WAAW,IAAI,SAAS,CAE3B;IAED,IAAI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,mBAAmB,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,eAAe;CAKvD;AAED;;GAEG;AACH,MAAM,WAAW,kCAAkC;IAC/C;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;;;;OAKG;IACH,kBAAkB,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;GAMG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IACnE,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,WAAW,CAAyB;IAC5C,OAAO,CAAC,eAAe,CAAsB;IAC7C,uBAAuB,EAAE,uBAAuB,CAAC;gBAErC,OAAO,EAAE,kCAAkC;IAkBvD,IAAI,WAAW,IAAI,SAAS,CAE3B;IAED,IAAI,cAAc,IAAI,mBAAmB,CAExC;IAED,iBAAiB,IAAI,sBAAsB;IAI3C,qBAAqB,CAAC,IAAI,EAAE,sBAAsB,GAAG,IAAI;IAIzD,MAAM,IAAI,WAAW,GAAG,SAAS;IAIjC,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI;IAIrC,uBAAuB,IAAI,IAAI;IAI/B,gBAAgB,IAAI,IAAI;IAIxB,YAAY,IAAI,MAAM;IAItB,mBAAmB,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,eAAe;CAKvD"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth-extensions.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth-extensions.js new file mode 100644 index 000000000..b1196757f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth-extensions.js @@ -0,0 +1,266 @@ +/** + * OAuth provider extensions for specialized authentication flows. + * + * This module provides ready-to-use OAuthClientProvider implementations + * for common machine-to-machine authentication scenarios. + */ +/** + * Helper to produce a private_key_jwt client authentication function. + * + * Usage: + * const addClientAuth = createPrivateKeyJwtAuth({ issuer, subject, privateKey, alg, audience? }); + * // pass addClientAuth as provider.addClientAuthentication implementation + */ +export function createPrivateKeyJwtAuth(options) { + return async (_headers, params, url, metadata) => { + // Lazy import to avoid heavy dependency unless used + if (typeof globalThis.crypto === 'undefined') { + throw new TypeError('crypto is not available, please ensure you add have Web Crypto API support for older Node.js versions (see https://github.com/modelcontextprotocol/typescript-sdk#nodejs-web-crypto-globalthiscrypto-compatibility)'); + } + const jose = await import('jose'); + const audience = String(options.audience ?? metadata?.issuer ?? url); + const lifetimeSeconds = options.lifetimeSeconds ?? 300; + const now = Math.floor(Date.now() / 1000); + const jti = `${Date.now()}-${Math.random().toString(36).slice(2)}`; + const baseClaims = { + iss: options.issuer, + sub: options.subject, + aud: audience, + exp: now + lifetimeSeconds, + iat: now, + jti + }; + const claims = options.claims ? { ...baseClaims, ...options.claims } : baseClaims; + // Import key for the requested algorithm + const alg = options.alg; + let key; + if (typeof options.privateKey === 'string') { + if (alg.startsWith('RS') || alg.startsWith('ES') || alg.startsWith('PS')) { + key = await jose.importPKCS8(options.privateKey, alg); + } + else if (alg.startsWith('HS')) { + key = new TextEncoder().encode(options.privateKey); + } + else { + throw new Error(`Unsupported algorithm ${alg}`); + } + } + else if (options.privateKey instanceof Uint8Array) { + if (alg.startsWith('HS')) { + key = options.privateKey; + } + else { + // Assume PKCS#8 DER in Uint8Array for asymmetric algorithms + key = await jose.importPKCS8(new TextDecoder().decode(options.privateKey), alg); + } + } + else { + // Treat as JWK + key = await jose.importJWK(options.privateKey, alg); + } + // Sign JWT + const assertion = await new jose.SignJWT(claims) + .setProtectedHeader({ alg, typ: 'JWT' }) + .setIssuer(options.issuer) + .setSubject(options.subject) + .setAudience(audience) + .setIssuedAt(now) + .setExpirationTime(now + lifetimeSeconds) + .setJti(jti) + .sign(key); + params.set('client_assertion', assertion); + params.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'); + }; +} +/** + * OAuth provider for client_credentials grant with client_secret_basic authentication. + * + * This provider is designed for machine-to-machine authentication where + * the client authenticates using a client_id and client_secret. + * + * @example + * const provider = new ClientCredentialsProvider({ + * clientId: 'my-client', + * clientSecret: 'my-secret' + * }); + * + * const transport = new StreamableHTTPClientTransport(serverUrl, { + * authProvider: provider + * }); + */ +export class ClientCredentialsProvider { + constructor(options) { + this._clientInfo = { + client_id: options.clientId, + client_secret: options.clientSecret + }; + this._clientMetadata = { + client_name: options.clientName ?? 'client-credentials-client', + redirect_uris: [], + grant_types: ['client_credentials'], + token_endpoint_auth_method: 'client_secret_basic' + }; + } + get redirectUrl() { + return undefined; + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInfo; + } + saveClientInformation(info) { + this._clientInfo = info; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization() { + throw new Error('redirectToAuthorization is not used for client_credentials flow'); + } + saveCodeVerifier() { + // Not used for client_credentials + } + codeVerifier() { + throw new Error('codeVerifier is not used for client_credentials flow'); + } + prepareTokenRequest(scope) { + const params = new URLSearchParams({ grant_type: 'client_credentials' }); + if (scope) + params.set('scope', scope); + return params; + } +} +/** + * OAuth provider for client_credentials grant with private_key_jwt authentication. + * + * This provider is designed for machine-to-machine authentication where + * the client authenticates using a signed JWT assertion (RFC 7523 Section 2.2). + * + * @example + * const provider = new PrivateKeyJwtProvider({ + * clientId: 'my-client', + * privateKey: pemEncodedPrivateKey, + * algorithm: 'RS256' + * }); + * + * const transport = new StreamableHTTPClientTransport(serverUrl, { + * authProvider: provider + * }); + */ +export class PrivateKeyJwtProvider { + constructor(options) { + this._clientInfo = { + client_id: options.clientId + }; + this._clientMetadata = { + client_name: options.clientName ?? 'private-key-jwt-client', + redirect_uris: [], + grant_types: ['client_credentials'], + token_endpoint_auth_method: 'private_key_jwt' + }; + this.addClientAuthentication = createPrivateKeyJwtAuth({ + issuer: options.clientId, + subject: options.clientId, + privateKey: options.privateKey, + alg: options.algorithm, + lifetimeSeconds: options.jwtLifetimeSeconds + }); + } + get redirectUrl() { + return undefined; + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInfo; + } + saveClientInformation(info) { + this._clientInfo = info; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization() { + throw new Error('redirectToAuthorization is not used for client_credentials flow'); + } + saveCodeVerifier() { + // Not used for client_credentials + } + codeVerifier() { + throw new Error('codeVerifier is not used for client_credentials flow'); + } + prepareTokenRequest(scope) { + const params = new URLSearchParams({ grant_type: 'client_credentials' }); + if (scope) + params.set('scope', scope); + return params; + } +} +/** + * OAuth provider for client_credentials grant with a static private_key_jwt assertion. + * + * This provider mirrors {@link PrivateKeyJwtProvider} but instead of constructing and + * signing a JWT on each request, it accepts a pre-built JWT assertion string and + * uses it directly for authentication. + */ +export class StaticPrivateKeyJwtProvider { + constructor(options) { + this._clientInfo = { + client_id: options.clientId + }; + this._clientMetadata = { + client_name: options.clientName ?? 'static-private-key-jwt-client', + redirect_uris: [], + grant_types: ['client_credentials'], + token_endpoint_auth_method: 'private_key_jwt' + }; + const assertion = options.jwtBearerAssertion; + this.addClientAuthentication = async (_headers, params) => { + params.set('client_assertion', assertion); + params.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'); + }; + } + get redirectUrl() { + return undefined; + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInfo; + } + saveClientInformation(info) { + this._clientInfo = info; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization() { + throw new Error('redirectToAuthorization is not used for client_credentials flow'); + } + saveCodeVerifier() { + // Not used for client_credentials + } + codeVerifier() { + throw new Error('codeVerifier is not used for client_credentials flow'); + } + prepareTokenRequest(scope) { + const params = new URLSearchParams({ grant_type: 'client_credentials' }); + if (scope) + params.set('scope', scope); + return params; + } +} +//# sourceMappingURL=auth-extensions.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth-extensions.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth-extensions.js.map new file mode 100644 index 000000000..d6aeb3466 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth-extensions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-extensions.js","sourceRoot":"","sources":["../../../src/client/auth-extensions.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH;;;;;;GAMG;AACH,MAAM,UAAU,uBAAuB,CAAC,OAQvC;IACG,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,EAAE;QAC7C,oDAAoD;QACpD,IAAI,OAAO,UAAU,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC;YAC3C,MAAM,IAAI,SAAS,CACf,qNAAqN,CACxN,CAAC;QACN,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC;QAElC,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,IAAI,QAAQ,EAAE,MAAM,IAAI,GAAG,CAAC,CAAC;QACrE,MAAM,eAAe,GAAG,OAAO,CAAC,eAAe,IAAI,GAAG,CAAC;QAEvD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;QAC1C,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;QAEnE,MAAM,UAAU,GAAG;YACf,GAAG,EAAE,OAAO,CAAC,MAAM;YACnB,GAAG,EAAE,OAAO,CAAC,OAAO;YACpB,GAAG,EAAE,QAAQ;YACb,GAAG,EAAE,GAAG,GAAG,eAAe;YAC1B,GAAG,EAAE,GAAG;YACR,GAAG;SACN,CAAC;QACF,MAAM,MAAM,GA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AAM,CAAC,GAAG,CAAC,kBAAkB,EAAE,SAAS,CAAC,CAAC;YAC1C,MAAM,CAAC,GAAG,CAAC,uBAAuB,EAAE,wDAAwD,CAAC,CAAC;QAClG,CAAC,CAAC;IACN,CAAC;IAED,IAAI,WAAW;QACX,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,IAAI,cAAc;QACd,OAAO,IAAI,CAAC,eAAe,CAAC;IAChC,CAAC;IAED,iBAAiB;QACb,OAAO,IAAI,CAAC,WAAW,CAAC;IAC5B,CAAC;IAED,qBAAqB,CAAC,IAA4B;QAC9C,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC5B,CAAC;IAED,MAAM;QACF,OAAO,IAAI,CAAC,OAAO,CAAC;IACxB,CAAC;IAED,UAAU,CAAC,MAAmB;QAC1B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAED,uBAAuB;QACnB,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAC;IACvF,CAAC;IAED,gBAAgB;QACZ,kCAAkC;IACtC,CAAC;IAED,YAAY;QACR,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC5E,CAAC;IAED,mBAAmB,CAAC,KAAc;QAC9B,MAAM,MAAM,GAAG,IAAI,eAAe,CAAC,EAAE,UAAU,EAAE,oBAAoB,EAAE,CAAC,CAAC;QACzE,IAAI,KAAK;YAAE,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACtC,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.d.ts new file mode 100644 index 000000000..c1405d6c0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.d.ts @@ -0,0 +1,368 @@ +import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens, OAuthMetadata, OAuthClientInformationFull, OAuthProtectedResourceMetadata, AuthorizationServerMetadata } from '../shared/auth.js'; +import { OAuthError } from '../server/auth/errors.js'; +import { FetchLike } from '../shared/transport.js'; +/** + * Function type for adding client authentication to token requests. + */ +export type AddClientAuthentication = (headers: Headers, params: URLSearchParams, url: string | URL, metadata?: AuthorizationServerMetadata) => void | Promise; +/** + * Implements an end-to-end OAuth client to be used with one MCP server. + * + * This client relies upon a concept of an authorized "session," the exact + * meaning of which is application-defined. Tokens, authorization codes, and + * code verifiers should not cross different sessions. + */ +export interface OAuthClientProvider { + /** + * The URL to redirect the user agent to after authorization. + * Return undefined for non-interactive flows that don't require user interaction + * (e.g., client_credentials, jwt-bearer). + */ + get redirectUrl(): string | URL | undefined; + /** + * External URL the server should use to fetch client metadata document + */ + clientMetadataUrl?: string; + /** + * Metadata about this OAuth client. + */ + get clientMetadata(): OAuthClientMetadata; + /** + * Returns a OAuth2 state parameter. + */ + state?(): string | Promise; + /** + * Loads information about this OAuth client, as registered already with the + * server, or returns `undefined` if the client is not registered with the + * server. + */ + clientInformation(): OAuthClientInformationMixed | undefined | Promise; + /** + * If implemented, this permits the OAuth client to dynamically register with + * the server. Client information saved this way should later be read via + * `clientInformation()`. + * + * This method is not required to be implemented if client information is + * statically known (e.g., pre-registered). + */ + saveClientInformation?(clientInformation: OAuthClientInformationMixed): void | Promise; + /** + * Loads any existing OAuth tokens for the current session, or returns + * `undefined` if there are no saved tokens. + */ + tokens(): OAuthTokens | undefined | Promise; + /** + * Stores new OAuth tokens for the current session, after a successful + * authorization. + */ + saveTokens(tokens: OAuthTokens): void | Promise; + /** + * Invoked to redirect the user agent to the given URL to begin the authorization flow. + */ + redirectToAuthorization(authorizationUrl: URL): void | Promise; + /** + * Saves a PKCE code verifier for the current session, before redirecting to + * the authorization flow. + */ + saveCodeVerifier(codeVerifier: string): void | Promise; + /** + * Loads the PKCE code verifier for the current session, necessary to validate + * the authorization result. + */ + codeVerifier(): string | Promise; + /** + * Adds custom client authentication to OAuth token requests. + * + * This optional method allows implementations to customize how client credentials + * are included in token exchange and refresh requests. When provided, this method + * is called instead of the default authentication logic, giving full control over + * the authentication mechanism. + * + * Common use cases include: + * - Supporting authentication methods beyond the standard OAuth 2.0 methods + * - Adding custom headers for proprietary authentication schemes + * - Implementing client assertion-based authentication (e.g., JWT bearer tokens) + * + * @param headers - The request headers (can be modified to add authentication) + * @param params - The request body parameters (can be modified to add credentials) + * @param url - The token endpoint URL being called + * @param metadata - Optional OAuth metadata for the server, which may include supported authentication methods + */ + addClientAuthentication?: AddClientAuthentication; + /** + * If defined, overrides the selection and validation of the + * RFC 8707 Resource Indicator. If left undefined, default + * validation behavior will be used. + * + * Implementations must verify the returned resource matches the MCP server. + */ + validateResourceURL?(serverUrl: string | URL, resource?: string): Promise; + /** + * If implemented, provides a way for the client to invalidate (e.g. delete) the specified + * credentials, in the case where the server has indicated that they are no longer valid. + * This avoids requiring the user to intervene manually. + */ + invalidateCredentials?(scope: 'all' | 'client' | 'tokens' | 'verifier'): void | Promise; + /** + * Prepares grant-specific parameters for a token request. + * + * This optional method allows providers to customize the token request based on + * the grant type they support. When implemented, it returns the grant type and + * any grant-specific parameters needed for the token exchange. + * + * If not implemented, the default behavior depends on the flow: + * - For authorization code flow: uses code, code_verifier, and redirect_uri + * - For client_credentials: detected via grant_types in clientMetadata + * + * @param scope - Optional scope to request + * @returns Grant type and parameters, or undefined to use default behavior + * + * @example + * // For client_credentials grant: + * prepareTokenRequest(scope) { + * return { + * grantType: 'client_credentials', + * params: scope ? { scope } : {} + * }; + * } + * + * @example + * // For authorization_code grant (default behavior): + * async prepareTokenRequest() { + * return { + * grantType: 'authorization_code', + * params: { + * code: this.authorizationCode, + * code_verifier: await this.codeVerifier(), + * redirect_uri: String(this.redirectUrl) + * } + * }; + * } + */ + prepareTokenRequest?(scope?: string): URLSearchParams | Promise | undefined; +} +export type AuthResult = 'AUTHORIZED' | 'REDIRECT'; +export declare class UnauthorizedError extends Error { + constructor(message?: string); +} +type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none'; +/** + * Determines the best client authentication method to use based on server support and client configuration. + * + * Priority order (highest to lowest): + * 1. client_secret_basic (if client secret is available) + * 2. client_secret_post (if client secret is available) + * 3. none (for public clients) + * + * @param clientInformation - OAuth client information containing credentials + * @param supportedMethods - Authentication methods supported by the authorization server + * @returns The selected authentication method + */ +export declare function selectClientAuthMethod(clientInformation: OAuthClientInformationMixed, supportedMethods: string[]): ClientAuthMethod; +/** + * Parses an OAuth error response from a string or Response object. + * + * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec + * and an instance of the appropriate OAuthError subclass will be returned. + * If parsing fails, it falls back to a generic ServerError that includes + * the response status (if available) and original content. + * + * @param input - A Response object or string containing the error response + * @returns A Promise that resolves to an OAuthError instance + */ +export declare function parseErrorResponse(input: Response | string): Promise; +/** + * Orchestrates the full auth flow with a server. + * + * This can be used as a single entry point for all authorization functionality, + * instead of linking together the other lower-level functions in this module. + */ +export declare function auth(provider: OAuthClientProvider, options: { + serverUrl: string | URL; + authorizationCode?: string; + scope?: string; + resourceMetadataUrl?: URL; + fetchFn?: FetchLike; +}): Promise; +/** + * SEP-991: URL-based Client IDs + * Validate that the client_id is a valid URL with https scheme + */ +export declare function isHttpsUrl(value?: string): boolean; +export declare function selectResourceURL(serverUrl: string | URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise; +/** + * Extract resource_metadata, scope, and error from WWW-Authenticate header. + */ +export declare function extractWWWAuthenticateParams(res: Response): { + resourceMetadataUrl?: URL; + scope?: string; + error?: string; +}; +/** + * Extract resource_metadata from response header. + * @deprecated Use `extractWWWAuthenticateParams` instead. + */ +export declare function extractResourceMetadataUrl(res: Response): URL | undefined; +/** + * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + */ +export declare function discoverOAuthProtectedResourceMetadata(serverUrl: string | URL, opts?: { + protocolVersion?: string; + resourceMetadataUrl?: string | URL; +}, fetchFn?: FetchLike): Promise; +/** + * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + * + * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. + */ +export declare function discoverOAuthMetadata(issuer: string | URL, { authorizationServerUrl, protocolVersion }?: { + authorizationServerUrl?: string | URL; + protocolVersion?: string; +}, fetchFn?: FetchLike): Promise; +/** + * Builds a list of discovery URLs to try for authorization server metadata. + * URLs are returned in priority order: + * 1. OAuth metadata at the given URL + * 2. OIDC metadata endpoints at the given URL + */ +export declare function buildDiscoveryUrls(authorizationServerUrl: string | URL): { + url: URL; + type: 'oauth' | 'oidc'; +}[]; +/** + * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata + * and OpenID Connect Discovery 1.0 specifications. + * + * This function implements a fallback strategy for authorization server discovery: + * 1. Attempts RFC 8414 OAuth metadata discovery first + * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery + * + * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's + * protected resource metadata, or the MCP server's URL if the + * metadata was not found. + * @param options - Configuration options + * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch + * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION + * @returns Promise resolving to authorization server metadata, or undefined if discovery fails + */ +export declare function discoverAuthorizationServerMetadata(authorizationServerUrl: string | URL, { fetchFn, protocolVersion }?: { + fetchFn?: FetchLike; + protocolVersion?: string; +}): Promise; +/** + * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. + */ +export declare function startAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, redirectUrl, scope, state, resource }: { + metadata?: AuthorizationServerMetadata; + clientInformation: OAuthClientInformationMixed; + redirectUrl: string | URL; + scope?: string; + state?: string; + resource?: URL; +}): Promise<{ + authorizationUrl: URL; + codeVerifier: string; +}>; +/** + * Prepares token request parameters for an authorization code exchange. + * + * This is the default implementation used by fetchToken when the provider + * doesn't implement prepareTokenRequest. + * + * @param authorizationCode - The authorization code received from the authorization endpoint + * @param codeVerifier - The PKCE code verifier + * @param redirectUri - The redirect URI used in the authorization request + * @returns URLSearchParams for the authorization_code grant + */ +export declare function prepareAuthorizationCodeRequest(authorizationCode: string, codeVerifier: string, redirectUri: string | URL): URLSearchParams; +/** + * Exchanges an authorization code for an access token with the given server. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Falls back to appropriate defaults when server metadata is unavailable + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, auth code, etc. + * @returns Promise resolving to OAuth tokens + * @throws {Error} When token exchange fails or authentication is invalid + */ +export declare function exchangeAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }: { + metadata?: AuthorizationServerMetadata; + clientInformation: OAuthClientInformationMixed; + authorizationCode: string; + codeVerifier: string; + redirectUri: string | URL; + resource?: URL; + addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; + fetchFn?: FetchLike; +}): Promise; +/** + * Exchange a refresh token for an updated access token. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Preserves the original refresh token if a new one is not returned + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, refresh token, etc. + * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) + * @throws {Error} When token refresh fails or authentication is invalid + */ +export declare function refreshAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }: { + metadata?: AuthorizationServerMetadata; + clientInformation: OAuthClientInformationMixed; + refreshToken: string; + resource?: URL; + addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; + fetchFn?: FetchLike; +}): Promise; +/** + * Unified token fetching that works with any grant type via provider.prepareTokenRequest(). + * + * This function provides a single entry point for obtaining tokens regardless of the + * OAuth grant type. The provider's prepareTokenRequest() method determines which grant + * to use and supplies the grant-specific parameters. + * + * @param provider - OAuth client provider that implements prepareTokenRequest() + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration for the token request + * @returns Promise resolving to OAuth tokens + * @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails + * + * @example + * // Provider for client_credentials: + * class MyProvider implements OAuthClientProvider { + * prepareTokenRequest(scope) { + * const params = new URLSearchParams({ grant_type: 'client_credentials' }); + * if (scope) params.set('scope', scope); + * return params; + * } + * // ... other methods + * } + * + * const tokens = await fetchToken(provider, authServerUrl, { metadata }); + */ +export declare function fetchToken(provider: OAuthClientProvider, authorizationServerUrl: string | URL, { metadata, resource, authorizationCode, fetchFn }?: { + metadata?: AuthorizationServerMetadata; + resource?: URL; + /** Authorization code for the default authorization_code grant flow */ + authorizationCode?: string; + fetchFn?: FetchLike; +}): Promise; +/** + * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. + */ +export declare function registerClient(authorizationServerUrl: string | URL, { metadata, clientMetadata, fetchFn }: { + metadata?: AuthorizationServerMetadata; + clientMetadata: OAuthClientMetadata; + fetchFn?: FetchLike; +}): Promise; +export {}; +//# sourceMappingURL=auth.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.d.ts.map new file mode 100644 index 000000000..012c44018 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":"AAEA,OAAO,EACH,mBAAmB,EAEnB,2BAA2B,EAC3B,WAAW,EACX,aAAa,EACb,0BAA0B,EAC1B,8BAA8B,EAE9B,2BAA2B,EAE9B,MAA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O,CAAC,EAAE,SAAS,CAAC;CAClB,GACP,OAAO,CAAC,WAAW,CAAC,CA+BtB;AAED;;GAEG;AACH,wBAAsB,cAAc,CAChC,sBAAsB,EAAE,MAAM,GAAG,GAAG,EACpC,EACI,QAAQ,EACR,cAAc,EACd,OAAO,EACV,EAAE;IACC,QAAQ,CAAC,EAAE,2BAA2B,CAAC;IACvC,cAAc,EAAE,mBAAmB,CAAC;IACpC,OAAO,CAAC,EAAE,SAAS,CAAC;CACvB,GACF,OAAO,CAAC,0BAA0B,CAAC,CA0BrC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js new file mode 100644 index 000000000..de86ff9c0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js @@ -0,0 +1,824 @@ +import pkceChallenge from 'pkce-challenge'; +import { LATEST_PROTOCOL_VERSION } from '../types.js'; +import { OAuthErrorResponseSchema, OpenIdProviderDiscoveryMetadataSchema } from '../shared/auth.js'; +import { OAuthClientInformationFullSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokensSchema } from '../shared/auth.js'; +import { checkResourceAllowed, resourceUrlFromServerUrl } from '../shared/auth-utils.js'; +import { InvalidClientError, InvalidClientMetadataError, InvalidGrantError, OAUTH_ERRORS, OAuthError, ServerError, UnauthorizedClientError } from '../server/auth/errors.js'; +export class UnauthorizedError extends Error { + constructor(message) { + super(message ?? 'Unauthorized'); + } +} +function isClientAuthMethod(method) { + return ['client_secret_basic', 'client_secret_post', 'none'].includes(method); +} +const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code'; +const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256'; +/** + * Determines the best client authentication method to use based on server support and client configuration. + * + * Priority order (highest to lowest): + * 1. client_secret_basic (if client secret is available) + * 2. client_secret_post (if client secret is available) + * 3. none (for public clients) + * + * @param clientInformation - OAuth client information containing credentials + * @param supportedMethods - Authentication methods supported by the authorization server + * @returns The selected authentication method + */ +export function selectClientAuthMethod(clientInformation, supportedMethods) { + const hasClientSecret = clientInformation.client_secret !== undefined; + // If server doesn't specify supported methods, use RFC 6749 defaults + if (supportedMethods.length === 0) { + return hasClientSecret ? 'client_secret_post' : 'none'; + } + // Prefer the method returned by the server during client registration if valid and supported + if ('token_endpoint_auth_method' in clientInformation && + clientInformation.token_endpoint_auth_method && + isClientAuthMethod(clientInformation.token_endpoint_auth_method) && + supportedMethods.includes(clientInformation.token_endpoint_auth_method)) { + return clientInformation.token_endpoint_auth_method; + } + // Try methods in priority order (most secure first) + if (hasClientSecret && supportedMethods.includes('client_secret_basic')) { + return 'client_secret_basic'; + } + if (hasClientSecret && supportedMethods.includes('client_secret_post')) { + return 'client_secret_post'; + } + if (supportedMethods.includes('none')) { + return 'none'; + } + // Fallback: use what we have + return hasClientSecret ? 'client_secret_post' : 'none'; +} +/** + * Applies client authentication to the request based on the specified method. + * + * Implements OAuth 2.1 client authentication methods: + * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1) + * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1) + * - none: Public client authentication (RFC 6749 Section 2.1) + * + * @param method - The authentication method to use + * @param clientInformation - OAuth client information containing credentials + * @param headers - HTTP headers object to modify + * @param params - URL search parameters to modify + * @throws {Error} When required credentials are missing + */ +function applyClientAuthentication(method, clientInformation, headers, params) { + const { client_id, client_secret } = clientInformation; + switch (method) { + case 'client_secret_basic': + applyBasicAuth(client_id, client_secret, headers); + return; + case 'client_secret_post': + applyPostAuth(client_id, client_secret, params); + return; + case 'none': + applyPublicAuth(client_id, params); + return; + default: + throw new Error(`Unsupported client authentication method: ${method}`); + } +} +/** + * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1) + */ +function applyBasicAuth(clientId, clientSecret, headers) { + if (!clientSecret) { + throw new Error('client_secret_basic authentication requires a client_secret'); + } + const credentials = btoa(`${clientId}:${clientSecret}`); + headers.set('Authorization', `Basic ${credentials}`); +} +/** + * Applies POST body authentication (RFC 6749 Section 2.3.1) + */ +function applyPostAuth(clientId, clientSecret, params) { + params.set('client_id', clientId); + if (clientSecret) { + params.set('client_secret', clientSecret); + } +} +/** + * Applies public client authentication (RFC 6749 Section 2.1) + */ +function applyPublicAuth(clientId, params) { + params.set('client_id', clientId); +} +/** + * Parses an OAuth error response from a string or Response object. + * + * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec + * and an instance of the appropriate OAuthError subclass will be returned. + * If parsing fails, it falls back to a generic ServerError that includes + * the response status (if available) and original content. + * + * @param input - A Response object or string containing the error response + * @returns A Promise that resolves to an OAuthError instance + */ +export async function parseErrorResponse(input) { + const statusCode = input instanceof Response ? input.status : undefined; + const body = input instanceof Response ? await input.text() : input; + try { + const result = OAuthErrorResponseSchema.parse(JSON.parse(body)); + const { error, error_description, error_uri } = result; + const errorClass = OAUTH_ERRORS[error] || ServerError; + return new errorClass(error_description || '', error_uri); + } + catch (error) { + // Not a valid OAuth error response, but try to inform the user of the raw data anyway + const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`; + return new ServerError(errorMessage); + } +} +/** + * Orchestrates the full auth flow with a server. + * + * This can be used as a single entry point for all authorization functionality, + * instead of linking together the other lower-level functions in this module. + */ +export async function auth(provider, options) { + try { + return await authInternal(provider, options); + } + catch (error) { + // Handle recoverable error types by invalidating credentials and retrying + if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) { + await provider.invalidateCredentials?.('all'); + return await authInternal(provider, options); + } + else if (error instanceof InvalidGrantError) { + await provider.invalidateCredentials?.('tokens'); + return await authInternal(provider, options); + } + // Throw otherwise + throw error; + } +} +async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) { + let resourceMetadata; + let authorizationServerUrl; + try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn); + if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { + authorizationServerUrl = resourceMetadata.authorization_servers[0]; + } + } + catch { + // Ignore errors and fall back to /.well-known/oauth-authorization-server + } + /** + * If we don't get a valid authorization server metadata from protected resource metadata, + * fallback to the legacy MCP spec's implementation (version 2025-03-26): MCP server base URL acts as the Authorization server. + */ + if (!authorizationServerUrl) { + authorizationServerUrl = new URL('/', serverUrl); + } + const resource = await selectResourceURL(serverUrl, provider, resourceMetadata); + const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { + fetchFn + }); + // Handle client registration if needed + let clientInformation = await Promise.resolve(provider.clientInformation()); + if (!clientInformation) { + if (authorizationCode !== undefined) { + throw new Error('Existing OAuth client information is required when exchanging an authorization code'); + } + const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true; + const clientMetadataUrl = provider.clientMetadataUrl; + if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) { + throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`); + } + const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl; + if (shouldUseUrlBasedClientId) { + // SEP-991: URL-based Client IDs + clientInformation = { + client_id: clientMetadataUrl + }; + await provider.saveClientInformation?.(clientInformation); + } + else { + // Fallback to dynamic registration + if (!provider.saveClientInformation) { + throw new Error('OAuth client information must be saveable for dynamic registration'); + } + const fullInformation = await registerClient(authorizationServerUrl, { + metadata, + clientMetadata: provider.clientMetadata, + fetchFn + }); + await provider.saveClientInformation(fullInformation); + clientInformation = fullInformation; + } + } + // Non-interactive flows (e.g., client_credentials, jwt-bearer) don't need a redirect URL + const nonInteractiveFlow = !provider.redirectUrl; + // Exchange authorization code for tokens, or fetch tokens directly for non-interactive flows + if (authorizationCode !== undefined || nonInteractiveFlow) { + const tokens = await fetchToken(provider, authorizationServerUrl, { + metadata, + resource, + authorizationCode, + fetchFn + }); + await provider.saveTokens(tokens); + return 'AUTHORIZED'; + } + const tokens = await provider.tokens(); + // Handle token refresh or new authorization + if (tokens?.refresh_token) { + try { + // Attempt to refresh the token + const newTokens = await refreshAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + refreshToken: tokens.refresh_token, + resource, + addClientAuthentication: provider.addClientAuthentication, + fetchFn + }); + await provider.saveTokens(newTokens); + return 'AUTHORIZED'; + } + catch (error) { + // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry. + if (!(error instanceof OAuthError) || error instanceof ServerError) { + // Could not refresh OAuth tokens + } + else { + // Refresh failed for another reason, re-throw + throw error; + } + } + } + const state = provider.state ? await provider.state() : undefined; + // Start new authorization flow + const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + state, + redirectUrl: provider.redirectUrl, + scope: scope || resourceMetadata?.scopes_supported?.join(' ') || provider.clientMetadata.scope, + resource + }); + await provider.saveCodeVerifier(codeVerifier); + await provider.redirectToAuthorization(authorizationUrl); + return 'REDIRECT'; +} +/** + * SEP-991: URL-based Client IDs + * Validate that the client_id is a valid URL with https scheme + */ +export function isHttpsUrl(value) { + if (!value) + return false; + try { + const url = new URL(value); + return url.protocol === 'https:' && url.pathname !== '/'; + } + catch { + return false; + } +} +export async function selectResourceURL(serverUrl, provider, resourceMetadata) { + const defaultResource = resourceUrlFromServerUrl(serverUrl); + // If provider has custom validation, delegate to it + if (provider.validateResourceURL) { + return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource); + } + // Only include resource parameter when Protected Resource Metadata is present + if (!resourceMetadata) { + return undefined; + } + // Validate that the metadata's resource is compatible with our request + if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) { + throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); + } + // Prefer the resource from metadata since it's what the server is telling us to request + return new URL(resourceMetadata.resource); +} +/** + * Extract resource_metadata, scope, and error from WWW-Authenticate header. + */ +export function extractWWWAuthenticateParams(res) { + const authenticateHeader = res.headers.get('WWW-Authenticate'); + if (!authenticateHeader) { + return {}; + } + const [type, scheme] = authenticateHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !scheme) { + return {}; + } + const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined; + let resourceMetadataUrl; + if (resourceMetadataMatch) { + try { + resourceMetadataUrl = new URL(resourceMetadataMatch); + } + catch { + // Ignore invalid URL + } + } + const scope = extractFieldFromWwwAuth(res, 'scope') || undefined; + const error = extractFieldFromWwwAuth(res, 'error') || undefined; + return { + resourceMetadataUrl, + scope, + error + }; +} +/** + * Extracts a specific field's value from the WWW-Authenticate header string. + * + * @param response The HTTP response object containing the headers. + * @param fieldName The name of the field to extract (e.g., "realm", "nonce"). + * @returns The field value + */ +function extractFieldFromWwwAuth(response, fieldName) { + const wwwAuthHeader = response.headers.get('WWW-Authenticate'); + if (!wwwAuthHeader) { + return null; + } + const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`); + const match = wwwAuthHeader.match(pattern); + if (match) { + // Pattern matches: field_name="value" or field_name=value (unquoted) + return match[1] || match[2]; + } + return null; +} +/** + * Extract resource_metadata from response header. + * @deprecated Use `extractWWWAuthenticateParams` instead. + */ +export function extractResourceMetadataUrl(res) { + const authenticateHeader = res.headers.get('WWW-Authenticate'); + if (!authenticateHeader) { + return undefined; + } + const [type, scheme] = authenticateHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !scheme) { + return undefined; + } + const regex = /resource_metadata="([^"]*)"/; + const match = regex.exec(authenticateHeader); + if (!match) { + return undefined; + } + try { + return new URL(match[1]); + } + catch { + return undefined; + } +} +/** + * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + */ +export async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) { + const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, { + protocolVersion: opts?.protocolVersion, + metadataUrl: opts?.resourceMetadataUrl + }); + if (!response || response.status === 404) { + await response?.body?.cancel(); + throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); + } + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); + } + return OAuthProtectedResourceMetadataSchema.parse(await response.json()); +} +/** + * Helper function to handle fetch with CORS retry logic + */ +async function fetchWithCorsRetry(url, headers, fetchFn = fetch) { + try { + return await fetchFn(url, { headers }); + } + catch (error) { + if (error instanceof TypeError) { + if (headers) { + // CORS errors come back as TypeError, retry without headers + return fetchWithCorsRetry(url, undefined, fetchFn); + } + else { + // We're getting CORS errors on retry too, return undefined + return undefined; + } + } + throw error; + } +} +/** + * Constructs the well-known path for auth-related metadata discovery + */ +function buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) { + // Strip trailing slash from pathname to avoid double slashes + if (pathname.endsWith('/')) { + pathname = pathname.slice(0, -1); + } + return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; +} +/** + * Tries to discover OAuth metadata at a specific URL + */ +async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) { + const headers = { + 'MCP-Protocol-Version': protocolVersion + }; + return await fetchWithCorsRetry(url, headers, fetchFn); +} +/** + * Determines if fallback to root discovery should be attempted + */ +function shouldAttemptFallback(response, pathname) { + return !response || (response.status >= 400 && response.status < 500 && pathname !== '/'); +} +/** + * Generic function for discovering OAuth metadata with fallback support + */ +async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) { + const issuer = new URL(serverUrl); + const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION; + let url; + if (opts?.metadataUrl) { + url = new URL(opts.metadataUrl); + } + else { + // Try path-aware discovery first + const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); + url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer); + url.search = issuer.search; + } + let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn); + // If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery + if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) { + const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer); + response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn); + } + return response; +} +/** + * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + * + * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. + */ +export async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) { + if (typeof issuer === 'string') { + issuer = new URL(issuer); + } + if (!authorizationServerUrl) { + authorizationServerUrl = issuer; + } + if (typeof authorizationServerUrl === 'string') { + authorizationServerUrl = new URL(authorizationServerUrl); + } + protocolVersion ?? (protocolVersion = LATEST_PROTOCOL_VERSION); + const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, { + protocolVersion, + metadataServerUrl: authorizationServerUrl + }); + if (!response || response.status === 404) { + await response?.body?.cancel(); + return undefined; + } + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`); + } + return OAuthMetadataSchema.parse(await response.json()); +} +/** + * Builds a list of discovery URLs to try for authorization server metadata. + * URLs are returned in priority order: + * 1. OAuth metadata at the given URL + * 2. OIDC metadata endpoints at the given URL + */ +export function buildDiscoveryUrls(authorizationServerUrl) { + const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl; + const hasPath = url.pathname !== '/'; + const urlsToTry = []; + if (!hasPath) { + // Root path: https://example.com/.well-known/oauth-authorization-server + urlsToTry.push({ + url: new URL('/.well-known/oauth-authorization-server', url.origin), + type: 'oauth' + }); + // OIDC: https://example.com/.well-known/openid-configuration + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration`, url.origin), + type: 'oidc' + }); + return urlsToTry; + } + // Strip trailing slash from pathname to avoid double slashes + let pathname = url.pathname; + if (pathname.endsWith('/')) { + pathname = pathname.slice(0, -1); + } + // 1. OAuth metadata at the given URL + // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1 + urlsToTry.push({ + url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin), + type: 'oauth' + }); + // 2. OIDC metadata endpoints + // RFC 8414 style: Insert /.well-known/openid-configuration before the path + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin), + type: 'oidc' + }); + // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path + urlsToTry.push({ + url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin), + type: 'oidc' + }); + return urlsToTry; +} +/** + * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata + * and OpenID Connect Discovery 1.0 specifications. + * + * This function implements a fallback strategy for authorization server discovery: + * 1. Attempts RFC 8414 OAuth metadata discovery first + * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery + * + * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's + * protected resource metadata, or the MCP server's URL if the + * metadata was not found. + * @param options - Configuration options + * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch + * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION + * @returns Promise resolving to authorization server metadata, or undefined if discovery fails + */ +export async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) { + const headers = { + 'MCP-Protocol-Version': protocolVersion, + Accept: 'application/json' + }; + // Get the list of URLs to try + const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); + // Try each URL in order + for (const { url: endpointUrl, type } of urlsToTry) { + const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); + if (!response) { + /** + * CORS error occurred - don't throw as the endpoint may not allow CORS, + * continue trying other possible endpoints + */ + continue; + } + if (!response.ok) { + await response.body?.cancel(); + // Continue looking for any 4xx response code. + if (response.status >= 400 && response.status < 500) { + continue; // Try next URL + } + throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`); + } + // Parse and validate based on type + if (type === 'oauth') { + return OAuthMetadataSchema.parse(await response.json()); + } + else { + return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); + } + } + return undefined; +} +/** + * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. + */ +export async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) { + let authorizationUrl; + if (metadata) { + authorizationUrl = new URL(metadata.authorization_endpoint); + if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) { + throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); + } + if (metadata.code_challenge_methods_supported && + !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) { + throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); + } + } + else { + authorizationUrl = new URL('/authorize', authorizationServerUrl); + } + // Generate PKCE challenge + const challenge = await pkceChallenge(); + const codeVerifier = challenge.code_verifier; + const codeChallenge = challenge.code_challenge; + authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE); + authorizationUrl.searchParams.set('client_id', clientInformation.client_id); + authorizationUrl.searchParams.set('code_challenge', codeChallenge); + authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD); + authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl)); + if (state) { + authorizationUrl.searchParams.set('state', state); + } + if (scope) { + authorizationUrl.searchParams.set('scope', scope); + } + if (scope?.includes('offline_access')) { + // if the request includes the OIDC-only "offline_access" scope, + // we need to set the prompt to "consent" to ensure the user is prompted to grant offline access + // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess + authorizationUrl.searchParams.append('prompt', 'consent'); + } + if (resource) { + authorizationUrl.searchParams.set('resource', resource.href); + } + return { authorizationUrl, codeVerifier }; +} +/** + * Prepares token request parameters for an authorization code exchange. + * + * This is the default implementation used by fetchToken when the provider + * doesn't implement prepareTokenRequest. + * + * @param authorizationCode - The authorization code received from the authorization endpoint + * @param codeVerifier - The PKCE code verifier + * @param redirectUri - The redirect URI used in the authorization request + * @returns URLSearchParams for the authorization_code grant + */ +export function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) { + return new URLSearchParams({ + grant_type: 'authorization_code', + code: authorizationCode, + code_verifier: codeVerifier, + redirect_uri: String(redirectUri) + }); +} +/** + * Internal helper to execute a token request with the given parameters. + * Used by exchangeAuthorization, refreshAuthorization, and fetchToken. + */ +async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) { + const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl); + const headers = new Headers({ + 'Content-Type': 'application/x-www-form-urlencoded', + Accept: 'application/json' + }); + if (resource) { + tokenRequestParams.set('resource', resource.href); + } + if (addClientAuthentication) { + await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata); + } + else if (clientInformation) { + const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? []; + const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); + applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams); + } + const response = await (fetchFn ?? fetch)(tokenUrl, { + method: 'POST', + headers, + body: tokenRequestParams + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return OAuthTokensSchema.parse(await response.json()); +} +/** + * Exchanges an authorization code for an access token with the given server. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Falls back to appropriate defaults when server metadata is unavailable + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, auth code, etc. + * @returns Promise resolving to OAuth tokens + * @throws {Error} When token exchange fails or authentication is invalid + */ +export async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) { + const tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri); + return executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation, + addClientAuthentication, + resource, + fetchFn + }); +} +/** + * Exchange a refresh token for an updated access token. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Preserves the original refresh token if a new one is not returned + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, refresh token, etc. + * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) + * @throws {Error} When token refresh fails or authentication is invalid + */ +export async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) { + const tokenRequestParams = new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: refreshToken + }); + const tokens = await executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation, + addClientAuthentication, + resource, + fetchFn + }); + // Preserve original refresh token if server didn't return a new one + return { refresh_token: refreshToken, ...tokens }; +} +/** + * Unified token fetching that works with any grant type via provider.prepareTokenRequest(). + * + * This function provides a single entry point for obtaining tokens regardless of the + * OAuth grant type. The provider's prepareTokenRequest() method determines which grant + * to use and supplies the grant-specific parameters. + * + * @param provider - OAuth client provider that implements prepareTokenRequest() + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration for the token request + * @returns Promise resolving to OAuth tokens + * @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails + * + * @example + * // Provider for client_credentials: + * class MyProvider implements OAuthClientProvider { + * prepareTokenRequest(scope) { + * const params = new URLSearchParams({ grant_type: 'client_credentials' }); + * if (scope) params.set('scope', scope); + * return params; + * } + * // ... other methods + * } + * + * const tokens = await fetchToken(provider, authServerUrl, { metadata }); + */ +export async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) { + const scope = provider.clientMetadata.scope; + // Use provider's prepareTokenRequest if available, otherwise fall back to authorization_code + let tokenRequestParams; + if (provider.prepareTokenRequest) { + tokenRequestParams = await provider.prepareTokenRequest(scope); + } + // Default to authorization_code grant if no custom prepareTokenRequest + if (!tokenRequestParams) { + if (!authorizationCode) { + throw new Error('Either provider.prepareTokenRequest() or authorizationCode is required'); + } + if (!provider.redirectUrl) { + throw new Error('redirectUrl is required for authorization_code flow'); + } + const codeVerifier = await provider.codeVerifier(); + tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl); + } + const clientInformation = await provider.clientInformation(); + return executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation: clientInformation ?? undefined, + addClientAuthentication: provider.addClientAuthentication, + resource, + fetchFn + }); +} +/** + * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. + */ +export async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) { + let registrationUrl; + if (metadata) { + if (!metadata.registration_endpoint) { + throw new Error('Incompatible auth server: does not support dynamic client registration'); + } + registrationUrl = new URL(metadata.registration_endpoint); + } + else { + registrationUrl = new URL('/register', authorizationServerUrl); + } + const response = await (fetchFn ?? fetch)(registrationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(clientMetadata) + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return OAuthClientInformationFullSchema.parse(await response.json()); +} +//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js.map new file mode 100644 index 000000000..6d43f391b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":"AAAA,OAAO,aAAa,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAQH,wBAAwB,EAExB,qCAAqC,EACxC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACH,gCAAgC,EAChC,mBAAmB,EACnB,oCAAoC,EACpC,iBAAiB,EACpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EACH,kBAAkB,EAClB,0BAA0B,EAC1B,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,WAAW,EACX,uBAAuB,EAC1B,MAAM,0BAA0B,CAAC;AAsKlC,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IACxC,YAAY,OAAgB;QACxB,KAAK,CAAC,OAAO,IAAI,cAAc,CAAC,CAAC;IACrC,CAAC;CACJ;AAID,SAAS,kBAAkB,CAAC,MAAc;IACtC,OAAO,CAAC,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAClF,CAAC;AAED,MAAM,gCAAgC,GAAG,MAAM,CAAC;AAChD,MAAM,mCAAmC,GAAG,MAAM,CAAC;AAEnD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,sBAAsB,CAAC,iBAA8C,EAAE,gBAA0B;IAC7G,MAAM,eAAe,GAAG,iBAAiB,CAAC,aAAa,KAAK,SAAS,CAAC;IAEtE,qEAAqE;IACrE,IAAI,gBAAgB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAChC,OAAO,eAAe,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,MAAM,CAAC;IAC3D,CAAC;IAED,6FAA6F;I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CAAC,qBAAqB,CAAC,CAAC;IAC9D,CAAC;SAAM,CAAC;QACJ,eAAe,GAAG,IAAI,GAAG,CAAC,WAAW,EAAE,sBAAsB,CAAC,CAAC;IACnE,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,IAAI,KAAK,CAAC,CAAC,eAAe,EAAE;QACvD,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACL,cAAc,EAAE,kBAAkB;SACrC;QACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC;KACvC,CAAC,CAAC;IAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACf,MAAM,MAAM,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,gCAAgC,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;AACzE,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.d.ts new file mode 100644 index 000000000..efc018654 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.d.ts @@ -0,0 +1,588 @@ +import { Protocol, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; +import type { Transport } from '../shared/transport.js'; +import { type CallToolRequest, CallToolResultSchema, type ClientCapabilities, type ClientNotification, type ClientRequest, type ClientResult, type CompatibilityCallToolResultSchema, type CompleteRequest, type GetPromptRequest, type Implementation, type ListPromptsRequest, type ListResourcesRequest, type ListResourceTemplatesRequest, type ListToolsRequest, type LoggingLevel, type ReadResourceRequest, type ServerCapabilities, type SubscribeRequest, type UnsubscribeRequest, type ListChangedHandlers, type Request, type Notification, type Result } from '../types.js'; +import type { jsonSchemaValidator } from '../validation/types.js'; +import { AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js'; +import type { RequestHandlerExtra } from '../shared/protocol.js'; +import { ExperimentalClientTasks } from '../experimental/tasks/client.js'; +/** + * Determines which elicitation modes are supported based on declared client capabilities. + * + * According to the spec: + * - An empty elicitation capability object defaults to form mode support (backwards compatibility) + * - URL mode is only supported if explicitly declared + * + * @param capabilities - The client's elicitation capabilities + * @returns An object indicating which modes are supported + */ +export declare function getSupportedElicitationModes(capabilities: ClientCapabilities['elicitation']): { + supportsFormMode: boolean; + supportsUrlMode: boolean; +}; +export type ClientOptions = ProtocolOptions & { + /** + * Capabilities to advertise as being supported by this client. + */ + capabilities?: ClientCapabilities; + /** + * JSON Schema validator for tool output validation. + * + * The validator is used to validate structured content returned by tools + * against their declared output schemas. + * + * @default AjvJsonSchemaValidator + * + * @example + * ```typescript + * // ajv + * const client = new Client( + * { name: 'my-client', version: '1.0.0' }, + * { + * capabilities: {}, + * jsonSchemaValidator: new AjvJsonSchemaValidator() + * } + * ); + * + * // @cfworker/json-schema + * const client = new Client( + * { name: 'my-client', version: '1.0.0' }, + * { + * capabilities: {}, + * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() + * } + * ); + * ``` + */ + jsonSchemaValidator?: jsonSchemaValidator; + /** + * Configure handlers for list changed notifications (tools, prompts, resources). + * + * @example + * ```typescript + * const client = new Client( + * { name: 'my-client', version: '1.0.0' }, + * { + * listChanged: { + * tools: { + * onChanged: (error, tools) => { + * if (error) { + * console.error('Failed to refresh tools:', error); + * return; + * } + * console.log('Tools updated:', tools); + * } + * }, + * prompts: { + * onChanged: (error, prompts) => console.log('Prompts updated:', prompts) + * } + * } + * } + * ); + * ``` + */ + listChanged?: ListChangedHandlers; +}; +/** + * An MCP client on top of a pluggable transport. + * + * The client will automatically begin the initialization flow with the server when connect() is called. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed client + * const client = new Client({ + * name: "CustomClient", + * version: "1.0.0" + * }) + * ``` + */ +export declare class Client extends Protocol { + private _clientInfo; + private _serverCapabilities?; + private _serverVersion?; + private _capabilities; + private _instructions?; + private _jsonSchemaValidator; + private _cachedToolOutputValidators; + private _cachedKnownTaskTools; + private _cachedRequiredTaskTools; + private _experimental?; + private _listChangedDebounceTimers; + private _pendingListChangedConfig?; + /** + * Initializes this client with the given name and version information. + */ + constructor(_clientInfo: Implementation, options?: ClientOptions); + /** + * Set up handlers for list changed notifications based on config and server capabilities. + * This should only be called after initialization when server capabilities are known. + * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability. + * @internal + */ + private _setupListChangedHandlers; + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental(): { + tasks: ExperimentalClientTasks; + }; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities: ClientCapabilities): void; + /** + * Override request handler registration to enforce client-side validation for elicitation. + */ + setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => ClientResult | ResultT | Promise): void; + protected assertCapability(capability: keyof ServerCapabilities, method: string): void; + connect(transport: Transport, options?: RequestOptions): Promise; + /** + * After initialization has completed, this will be populated with the server's reported capabilities. + */ + getServerCapabilities(): ServerCapabilities | undefined; + /** + * After initialization has completed, this will be populated with information about the server's name and version. + */ + getServerVersion(): Implementation | undefined; + /** + * After initialization has completed, this may be populated with information about the server's instructions. + */ + getInstructions(): string | undefined; + protected assertCapabilityForMethod(method: RequestT['method']): void; + protected assertNotificationCapability(method: NotificationT['method']): void; + protected assertRequestHandlerCapability(method: string): void; + protected assertTaskCapability(method: string): void; + protected assertTaskHandlerCapability(method: string): void; + ping(options?: RequestOptions): Promise<{ + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + complete(params: CompleteRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + completion: { + [x: string]: unknown; + values: string[]; + total?: number | undefined; + hasMore?: boolean | undefined; + }; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + setLoggingLevel(level: LoggingLevel, options?: RequestOptions): Promise<{ + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + getPrompt(params: GetPromptRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + messages: { + role: "user" | "assistant"; + content: { + type: "text"; + text: string; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + type: "resource"; + resource: { + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + }; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + uri: string; + name: string; + type: "resource_link"; + description?: string | undefined; + mimeType?: string | undefined; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + theme?: "light" | "dark" | undefined; + }[] | undefined; + title?: string | undefined; + }; + }[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + description?: string | undefined; + }>; + listPrompts(params?: ListPromptsRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + prompts: { + name: string; + description?: string | undefined; + arguments?: { + name: string; + description?: string | undefined; + required?: boolean | undefined; + }[] | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + theme?: "light" | "dark" | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + nextCursor?: string | undefined; + }>; + listResources(params?: ListResourcesRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + resources: { + uri: string; + name: string; + description?: string | undefined; + mimeType?: string | undefined; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + theme?: "light" | "dark" | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + nextCursor?: string | undefined; + }>; + listResourceTemplates(params?: ListResourceTemplatesRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + resourceTemplates: { + uriTemplate: string; + name: string; + description?: string | undefined; + mimeType?: string | undefined; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + theme?: "light" | "dark" | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + nextCursor?: string | undefined; + }>; + readResource(params: ReadResourceRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + contents: ({ + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + })[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + subscribeResource(params: SubscribeRequest['params'], options?: RequestOptions): Promise<{ + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + unsubscribeResource(params: UnsubscribeRequest['params'], options?: RequestOptions): Promise<{ + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + /** + * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema. + * + * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead. + */ + callTool(params: CallToolRequest['params'], resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<{ + [x: string]: unknown; + content: ({ + type: "text"; + text: string; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + type: "resource"; + resource: { + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + }; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: Record | undefined; + } | { + uri: string; + name: string; + type: "resource_link"; + description?: string | undefined; + mimeType?: string | undefined; + annotations?: { + audience?: ("user" | "assistant")[] | undefined; + priority?: number | undefined; + lastModified?: string | undefined; + } | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + theme?: "light" | "dark" | undefined; + }[] | undefined; + title?: string | undefined; + })[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + structuredContent?: Record | undefined; + isError?: boolean | undefined; + } | { + [x: string]: unknown; + toolResult: unknown; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + private isToolTask; + /** + * Check if a tool requires task-based execution. + * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'. + */ + private isToolTaskRequired; + /** + * Cache validators for tool output schemas. + * Called after listTools() to pre-compile validators for better performance. + */ + private cacheToolMetadata; + /** + * Get cached validator for a tool + */ + private getToolOutputValidator; + listTools(params?: ListToolsRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + tools: { + inputSchema: { + [x: string]: unknown; + type: "object"; + properties?: Record | undefined; + required?: string[] | undefined; + }; + name: string; + description?: string | undefined; + outputSchema?: { + [x: string]: unknown; + type: "object"; + properties?: Record | undefined; + required?: string[] | undefined; + } | undefined; + annotations?: { + title?: string | undefined; + readOnlyHint?: boolean | undefined; + destructiveHint?: boolean | undefined; + idempotentHint?: boolean | undefined; + openWorldHint?: boolean | undefined; + } | undefined; + execution?: { + taskSupport?: "optional" | "required" | "forbidden" | undefined; + } | undefined; + _meta?: Record | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + theme?: "light" | "dark" | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + nextCursor?: string | undefined; + }>; + /** + * Set up a single list changed handler. + * @internal + */ + private _setupListChangedHandler; + sendRootsListChanged(): Promise; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.d.ts.map new file mode 100644 index 000000000..12d0abf3c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC/G,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAExD,OAAO,EACH,KAAK,eAAe,EACpB,oBAAoB,EACpB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,iCAAiC,EACtC,KAAK,eAAe,EAIpB,KAAK,gBAAgB,EAErB,KAAK,cAAc,EAGnB,KAAK,kBAAkB,EAEvB,KAAK,oBAAoB,EAEzB,KAAK,4BAA4B,EAEjC,KAAK,gBAAgB,EAErB,KAAK,YAAY,EAEjB,KAAK,mBAAmB,EAExB,KAAK,kBAAkB,EAEvB,KAAK,gBAAgB,EAErB,KAAK,kBAAkB,EAYvB,KAAK,mBAAmB,EACxB,KAAK,OAAO,EACZ,KAAK,YAAY,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AE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;IAI9E,mBAAmB,CAAC,MAAM,EAAE,kBAAkB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;IAIxF;;;;OAIG;IACG,QAAQ,CACV,MAAM,EAAE,eAAe,CAAC,QAAQ,CAAC,EACjC,YAAY,GAAE,OAAO,oBAAoB,GAAG,OAAO,iCAAwD,EAC3G,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAkD5B,OAAO,CAAC,UAAU;IAQlB;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAI1B;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAuBzB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAIxB,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAS7E;;;OAGG;IACH,OAAO,CAAC,wBAAwB;IAwD1B,oBAAoB;CAG7B"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js new file mode 100644 index 000000000..49b12c6cd --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js @@ -0,0 +1,624 @@ +import { mergeCapabilities, Protocol } from '../shared/protocol.js'; +import { CallToolResultSchema, CompleteResultSchema, EmptyResultSchema, ErrorCode, GetPromptResultSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ListToolsResultSchema, McpError, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, ElicitResultSchema, ElicitRequestSchema, CreateTaskResultSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ListChangedOptionsBaseSchema } from '../types.js'; +import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; +import { getObjectShape, isZ4Schema, safeParse } from '../server/zod-compat.js'; +import { ExperimentalClientTasks } from '../experimental/tasks/client.js'; +import { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js'; +/** + * Elicitation default application helper. Applies defaults to the data based on the schema. + * + * @param schema - The schema to apply defaults to. + * @param data - The data to apply defaults to. + */ +function applyElicitationDefaults(schema, data) { + if (!schema || data === null || typeof data !== 'object') + return; + // Handle object properties + if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') { + const obj = data; + const props = schema.properties; + for (const key of Object.keys(props)) { + const propSchema = props[key]; + // If missing or explicitly undefined, apply default if present + if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) { + obj[key] = propSchema.default; + } + // Recurse into existing nested objects/arrays + if (obj[key] !== undefined) { + applyElicitationDefaults(propSchema, obj[key]); + } + } + } + if (Array.isArray(schema.anyOf)) { + for (const sub of schema.anyOf) { + // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults) + if (typeof sub !== 'boolean') { + applyElicitationDefaults(sub, data); + } + } + } + // Combine schemas + if (Array.isArray(schema.oneOf)) { + for (const sub of schema.oneOf) { + // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults) + if (typeof sub !== 'boolean') { + applyElicitationDefaults(sub, data); + } + } + } +} +/** + * Determines which elicitation modes are supported based on declared client capabilities. + * + * According to the spec: + * - An empty elicitation capability object defaults to form mode support (backwards compatibility) + * - URL mode is only supported if explicitly declared + * + * @param capabilities - The client's elicitation capabilities + * @returns An object indicating which modes are supported + */ +export function getSupportedElicitationModes(capabilities) { + if (!capabilities) { + return { supportsFormMode: false, supportsUrlMode: false }; + } + const hasFormCapability = capabilities.form !== undefined; + const hasUrlCapability = capabilities.url !== undefined; + // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility) + const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability); + const supportsUrlMode = hasUrlCapability; + return { supportsFormMode, supportsUrlMode }; +} +/** + * An MCP client on top of a pluggable transport. + * + * The client will automatically begin the initialization flow with the server when connect() is called. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed client + * const client = new Client({ + * name: "CustomClient", + * version: "1.0.0" + * }) + * ``` + */ +export class Client extends Protocol { + /** + * Initializes this client with the given name and version information. + */ + constructor(_clientInfo, options) { + super(options); + this._clientInfo = _clientInfo; + this._cachedToolOutputValidators = new Map(); + this._cachedKnownTaskTools = new Set(); + this._cachedRequiredTaskTools = new Set(); + this._listChangedDebounceTimers = new Map(); + this._capabilities = options?.capabilities ?? {}; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + // Store list changed config for setup after connection (when we know server capabilities) + if (options?.listChanged) { + this._pendingListChangedConfig = options.listChanged; + } + } + /** + * Set up handlers for list changed notifications based on config and server capabilities. + * This should only be called after initialization when server capabilities are known. + * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability. + * @internal + */ + _setupListChangedHandlers(config) { + if (config.tools && this._serverCapabilities?.tools?.listChanged) { + this._setupListChangedHandler('tools', ToolListChangedNotificationSchema, config.tools, async () => { + const result = await this.listTools(); + return result.tools; + }); + } + if (config.prompts && this._serverCapabilities?.prompts?.listChanged) { + this._setupListChangedHandler('prompts', PromptListChangedNotificationSchema, config.prompts, async () => { + const result = await this.listPrompts(); + return result.prompts; + }); + } + if (config.resources && this._serverCapabilities?.resources?.listChanged) { + this._setupListChangedHandler('resources', ResourceListChangedNotificationSchema, config.resources, async () => { + const result = await this.listResources(); + return result.resources; + }); + } + } + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental() { + if (!this._experimental) { + this._experimental = { + tasks: new ExperimentalClientTasks(this) + }; + } + return this._experimental; + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error('Cannot register capabilities after connecting to transport'); + } + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + } + /** + * Override request handler registration to enforce client-side validation for elicitation. + */ + setRequestHandler(requestSchema, handler) { + const shape = getObjectShape(requestSchema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + // Extract literal value using type-safe property access + let methodValue; + if (isZ4Schema(methodSchema)) { + const v4Schema = methodSchema; + const v4Def = v4Schema._zod?.def; + methodValue = v4Def?.value ?? v4Schema.value; + } + else { + const v3Schema = methodSchema; + const legacyDef = v3Schema._def; + methodValue = legacyDef?.value ?? v3Schema.value; + } + if (typeof methodValue !== 'string') { + throw new Error('Schema method literal must be a string'); + } + const method = methodValue; + if (method === 'elicitation/create') { + const wrappedHandler = async (request, extra) => { + const validatedRequest = safeParse(ElicitRequestSchema, request); + if (!validatedRequest.success) { + // Type guard: if success is false, error is guaranteed to exist + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + params.mode = params.mode ?? 'form'; + const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); + if (params.mode === 'form' && !supportsFormMode) { + throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests'); + } + if (params.mode === 'url' && !supportsUrlMode) { + throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests'); + } + const result = await Promise.resolve(handler(request, extra)); + // When task creation is requested, validate and return CreateTaskResult + if (params.task) { + const taskValidationResult = safeParse(CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error + ? taskValidationResult.error.message + : String(taskValidationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + // For non-task requests, validate against ElicitResultSchema + const validationResult = safeParse(ElicitResultSchema, result); + if (!validationResult.success) { + // Type guard: if success is false, error is guaranteed to exist + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`); + } + const validatedResult = validationResult.data; + const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined; + if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) { + if (this._capabilities.elicitation?.form?.applyDefaults) { + try { + applyElicitationDefaults(requestedSchema, validatedResult.content); + } + catch { + // gracefully ignore errors in default application + } + } + } + return validatedResult; + }; + // Install the wrapped handler + return super.setRequestHandler(requestSchema, wrappedHandler); + } + if (method === 'sampling/createMessage') { + const wrappedHandler = async (request, extra) => { + const validatedRequest = safeParse(CreateMessageRequestSchema, request); + if (!validatedRequest.success) { + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + const result = await Promise.resolve(handler(request, extra)); + // When task creation is requested, validate and return CreateTaskResult + if (params.task) { + const taskValidationResult = safeParse(CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error + ? taskValidationResult.error.message + : String(taskValidationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + // For non-task requests, validate against appropriate schema based on tools presence + const hasTools = params.tools || params.toolChoice; + const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema; + const validationResult = safeParse(resultSchema, result); + if (!validationResult.success) { + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`); + } + return validationResult.data; + }; + // Install the wrapped handler + return super.setRequestHandler(requestSchema, wrappedHandler); + } + // Other handlers use default behavior + return super.setRequestHandler(requestSchema, handler); + } + assertCapability(capability, method) { + if (!this._serverCapabilities?.[capability]) { + throw new Error(`Server does not support ${capability} (required for ${method})`); + } + } + async connect(transport, options) { + await super.connect(transport); + // When transport sessionId is already set this means we are trying to reconnect. + // In this case we don't need to initialize again. + if (transport.sessionId !== undefined) { + return; + } + try { + const result = await this.request({ + method: 'initialize', + params: { + protocolVersion: LATEST_PROTOCOL_VERSION, + capabilities: this._capabilities, + clientInfo: this._clientInfo + } + }, InitializeResultSchema, options); + if (result === undefined) { + throw new Error(`Server sent invalid initialize result: ${result}`); + } + if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) { + throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); + } + this._serverCapabilities = result.capabilities; + this._serverVersion = result.serverInfo; + // HTTP transports must set the protocol version in each header after initialization. + if (transport.setProtocolVersion) { + transport.setProtocolVersion(result.protocolVersion); + } + this._instructions = result.instructions; + await this.notification({ + method: 'notifications/initialized' + }); + // Set up list changed handlers now that we know server capabilities + if (this._pendingListChangedConfig) { + this._setupListChangedHandlers(this._pendingListChangedConfig); + this._pendingListChangedConfig = undefined; + } + } + catch (error) { + // Disconnect if initialization fails. + void this.close(); + throw error; + } + } + /** + * After initialization has completed, this will be populated with the server's reported capabilities. + */ + getServerCapabilities() { + return this._serverCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the server's name and version. + */ + getServerVersion() { + return this._serverVersion; + } + /** + * After initialization has completed, this may be populated with information about the server's instructions. + */ + getInstructions() { + return this._instructions; + } + assertCapabilityForMethod(method) { + switch (method) { + case 'logging/setLevel': + if (!this._serverCapabilities?.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'prompts/get': + case 'prompts/list': + if (!this._serverCapabilities?.prompts) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case 'resources/list': + case 'resources/templates/list': + case 'resources/read': + case 'resources/subscribe': + case 'resources/unsubscribe': + if (!this._serverCapabilities?.resources) { + throw new Error(`Server does not support resources (required for ${method})`); + } + if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) { + throw new Error(`Server does not support resource subscriptions (required for ${method})`); + } + break; + case 'tools/call': + case 'tools/list': + if (!this._serverCapabilities?.tools) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case 'completion/complete': + if (!this._serverCapabilities?.completions) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case 'initialize': + // No specific capability required for initialize + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertNotificationCapability(method) { + switch (method) { + case 'notifications/roots/list_changed': + if (!this._capabilities.roots?.listChanged) { + throw new Error(`Client does not support roots list changed notifications (required for ${method})`); + } + break; + case 'notifications/initialized': + // No specific capability required for initialized + break; + case 'notifications/cancelled': + // Cancellation notifications are always allowed + break; + case 'notifications/progress': + // Progress notifications are always allowed + break; + } + } + assertRequestHandlerCapability(method) { + // Task handlers are registered in Protocol constructor before _capabilities is initialized + // Skip capability check for task methods during initialization + if (!this._capabilities) { + return; + } + switch (method) { + case 'sampling/createMessage': + if (!this._capabilities.sampling) { + throw new Error(`Client does not support sampling capability (required for ${method})`); + } + break; + case 'elicitation/create': + if (!this._capabilities.elicitation) { + throw new Error(`Client does not support elicitation capability (required for ${method})`); + } + break; + case 'roots/list': + if (!this._capabilities.roots) { + throw new Error(`Client does not support roots capability (required for ${method})`); + } + break; + case 'tasks/get': + case 'tasks/list': + case 'tasks/result': + case 'tasks/cancel': + if (!this._capabilities.tasks) { + throw new Error(`Client does not support tasks capability (required for ${method})`); + } + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertTaskCapability(method) { + assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, 'Server'); + } + assertTaskHandlerCapability(method) { + // Task handlers are registered in Protocol constructor before _capabilities is initialized + // Skip capability check for task methods during initialization + if (!this._capabilities) { + return; + } + assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, 'Client'); + } + async ping(options) { + return this.request({ method: 'ping' }, EmptyResultSchema, options); + } + async complete(params, options) { + return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options); + } + async setLoggingLevel(level, options) { + return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options); + } + async getPrompt(params, options) { + return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options); + } + async listPrompts(params, options) { + return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options); + } + async listResources(params, options) { + return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options); + } + async listResourceTemplates(params, options) { + return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options); + } + async readResource(params, options) { + return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options); + } + async subscribeResource(params, options) { + return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options); + } + async unsubscribeResource(params, options) { + return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options); + } + /** + * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema. + * + * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead. + */ + async callTool(params, resultSchema = CallToolResultSchema, options) { + // Guard: required-task tools need experimental API + if (this.isToolTaskRequired(params.name)) { + throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`); + } + const result = await this.request({ method: 'tools/call', params }, resultSchema, options); + // Check if the tool has an outputSchema + const validator = this.getToolOutputValidator(params.name); + if (validator) { + // If tool has outputSchema, it MUST return structuredContent (unless it's an error) + if (!result.structuredContent && !result.isError) { + throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`); + } + // Only validate structured content if present (not when there's an error) + if (result.structuredContent) { + try { + // Validate the structured content against the schema + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) { + throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`); + } + } + catch (error) { + if (error instanceof McpError) { + throw error; + } + throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`); + } + } + } + return result; + } + isToolTask(toolName) { + if (!this._serverCapabilities?.tasks?.requests?.tools?.call) { + return false; + } + return this._cachedKnownTaskTools.has(toolName); + } + /** + * Check if a tool requires task-based execution. + * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'. + */ + isToolTaskRequired(toolName) { + return this._cachedRequiredTaskTools.has(toolName); + } + /** + * Cache validators for tool output schemas. + * Called after listTools() to pre-compile validators for better performance. + */ + cacheToolMetadata(tools) { + this._cachedToolOutputValidators.clear(); + this._cachedKnownTaskTools.clear(); + this._cachedRequiredTaskTools.clear(); + for (const tool of tools) { + // If the tool has an outputSchema, create and cache the validator + if (tool.outputSchema) { + const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema); + this._cachedToolOutputValidators.set(tool.name, toolValidator); + } + // If the tool supports task-based execution, cache that information + const taskSupport = tool.execution?.taskSupport; + if (taskSupport === 'required' || taskSupport === 'optional') { + this._cachedKnownTaskTools.add(tool.name); + } + if (taskSupport === 'required') { + this._cachedRequiredTaskTools.add(tool.name); + } + } + } + /** + * Get cached validator for a tool + */ + getToolOutputValidator(toolName) { + return this._cachedToolOutputValidators.get(toolName); + } + async listTools(params, options) { + const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options); + // Cache the tools and their output schemas for future validation + this.cacheToolMetadata(result.tools); + return result; + } + /** + * Set up a single list changed handler. + * @internal + */ + _setupListChangedHandler(listType, notificationSchema, options, fetcher) { + // Validate options using Zod schema (validates autoRefresh and debounceMs) + const parseResult = ListChangedOptionsBaseSchema.safeParse(options); + if (!parseResult.success) { + throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`); + } + // Validate callback + if (typeof options.onChanged !== 'function') { + throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`); + } + const { autoRefresh, debounceMs } = parseResult.data; + const { onChanged } = options; + const refresh = async () => { + if (!autoRefresh) { + onChanged(null, null); + return; + } + try { + const items = await fetcher(); + onChanged(null, items); + } + catch (e) { + const error = e instanceof Error ? e : new Error(String(e)); + onChanged(error, null); + } + }; + const handler = () => { + if (debounceMs) { + // Clear any pending debounce timer for this list type + const existingTimer = this._listChangedDebounceTimers.get(listType); + if (existingTimer) { + clearTimeout(existingTimer); + } + // Set up debounced refresh + const timer = setTimeout(refresh, debounceMs); + this._listChangedDebounceTimers.set(listType, timer); + } + else { + // No debounce, refresh immediately + refresh(); + } + }; + // Register notification handler + this.setNotificationHandler(notificationSchema, handler); + } + async sendRootsListChanged() { + return this.notification({ method: 'notifications/roots/list_changed' }); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js.map new file mode 100644 index 000000000..da53f926a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAA6C,MAAM,uBAAuB,CAAC;AAG/G,OAAO,EAEH,oBAAoB,EAOpB,oBAAoB,EACpB,iBAAiB,EACjB,SAAS,EAET,qBAAqB,EAErB,sBAAsB,EACtB,uBAAuB,EAEvB,uBAAuB,EAEvB,yBAAyB,EAEzB,iCAAiC,EAE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AC,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC,CAAC;IAC7E,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/middleware.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/middleware.d.ts new file mode 100644 index 000000000..726ac578a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/middleware.d.ts @@ -0,0 +1,169 @@ +import { OAuthClientProvider } from './auth.js'; +import { FetchLike } from '../shared/transport.js'; +/** + * Middleware function that wraps and enhances fetch functionality. + * Takes a fetch handler and returns an enhanced fetch handler. + */ +export type Middleware = (next: FetchLike) => FetchLike; +/** + * Creates a fetch wrapper that handles OAuth authentication automatically. + * + * This wrapper will: + * - Add Authorization headers with access tokens + * - Handle 401 responses by attempting re-authentication + * - Retry the original request after successful auth + * - Handle OAuth errors appropriately (InvalidClientError, etc.) + * + * The baseUrl parameter is optional and defaults to using the domain from the request URL. + * However, you should explicitly provide baseUrl when: + * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) + * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) + * - The OAuth server is on a different domain than your API requests + * - You want to ensure consistent OAuth behavior regardless of request URLs + * + * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. + * + * Note: This wrapper is designed for general-purpose fetch operations. + * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling + * and should not need this wrapper. + * + * @param provider - OAuth client provider for authentication + * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) + * @returns A fetch middleware function + */ +export declare const withOAuth: (provider: OAuthClientProvider, baseUrl?: string | URL) => Middleware; +/** + * Logger function type for HTTP requests + */ +export type RequestLogger = (input: { + method: string; + url: string | URL; + status: number; + statusText: string; + duration: number; + requestHeaders?: Headers; + responseHeaders?: Headers; + error?: Error; +}) => void; +/** + * Configuration options for the logging middleware + */ +export type LoggingOptions = { + /** + * Custom logger function, defaults to console logging + */ + logger?: RequestLogger; + /** + * Whether to include request headers in logs + * @default false + */ + includeRequestHeaders?: boolean; + /** + * Whether to include response headers in logs + * @default false + */ + includeResponseHeaders?: boolean; + /** + * Status level filter - only log requests with status >= this value + * Set to 0 to log all requests, 400 to log only errors + * @default 0 + */ + statusLevel?: number; +}; +/** + * Creates a fetch middleware that logs HTTP requests and responses. + * + * When called without arguments `withLogging()`, it uses the default logger that: + * - Logs successful requests (2xx) to `console.log` + * - Logs error responses (4xx/5xx) and network errors to `console.error` + * - Logs all requests regardless of status (statusLevel: 0) + * - Does not include request or response headers in logs + * - Measures and displays request duration in milliseconds + * + * Important: the default logger uses both `console.log` and `console.error` so it should not be used with + * `stdio` transports and applications. + * + * @param options - Logging configuration options + * @returns A fetch middleware function + */ +export declare const withLogging: (options?: LoggingOptions) => Middleware; +/** + * Composes multiple fetch middleware functions into a single middleware pipeline. + * Middleware are applied in the order they appear, creating a chain of handlers. + * + * @example + * ```typescript + * // Create a middleware pipeline that handles both OAuth and logging + * const enhancedFetch = applyMiddlewares( + * withOAuth(oauthProvider, 'https://api.example.com'), + * withLogging({ statusLevel: 400 }) + * )(fetch); + * + * // Use the enhanced fetch - it will handle auth and log errors + * const response = await enhancedFetch('https://api.example.com/data'); + * ``` + * + * @param middleware - Array of fetch middleware to compose into a pipeline + * @returns A single composed middleware function + */ +export declare const applyMiddlewares: (...middleware: Middleware[]) => Middleware; +/** + * Helper function to create custom fetch middleware with cleaner syntax. + * Provides the next handler and request details as separate parameters for easier access. + * + * @example + * ```typescript + * // Create custom authentication middleware + * const customAuthMiddleware = createMiddleware(async (next, input, init) => { + * const headers = new Headers(init?.headers); + * headers.set('X-Custom-Auth', 'my-token'); + * + * const response = await next(input, { ...init, headers }); + * + * if (response.status === 401) { + * console.log('Authentication failed'); + * } + * + * return response; + * }); + * + * // Create conditional middleware + * const conditionalMiddleware = createMiddleware(async (next, input, init) => { + * const url = typeof input === 'string' ? input : input.toString(); + * + * // Only add headers for API routes + * if (url.includes('/api/')) { + * const headers = new Headers(init?.headers); + * headers.set('X-API-Version', 'v2'); + * return next(input, { ...init, headers }); + * } + * + * // Pass through for non-API routes + * return next(input, init); + * }); + * + * // Create caching middleware + * const cacheMiddleware = createMiddleware(async (next, input, init) => { + * const cacheKey = typeof input === 'string' ? input : input.toString(); + * + * // Check cache first + * const cached = await getFromCache(cacheKey); + * if (cached) { + * return new Response(cached, { status: 200 }); + * } + * + * // Make request and cache result + * const response = await next(input, init); + * if (response.ok) { + * await saveToCache(cacheKey, await response.clone().text()); + * } + * + * return response; + * }); + * ``` + * + * @param handler - Function that receives the next handler and request parameters + * @returns A fetch middleware function + */ +export declare const createMiddleware: (handler: (next: FetchLike, input: string | URL, init?: RequestInit) => Promise) => Middleware; +//# sourceMappingURL=middleware.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/middleware.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/middleware.d.ts.map new file mode 100644 index 000000000..88ac77806 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/middleware.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsC,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AACvG,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,SAAS,KAAK,SAAS,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,SAAS,aACP,mBAAmB,YAAY,MAAM,GAAG,GAAG,KAAG,UA0DxD,CAAC;AAEN;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,KAAK,CAAC,EAAE,KAAK,CAAC;CACjB,KAAK,IAAI,CAAC;AAEX;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IACzB;;OAEG;IACH,MAAM,CAAC,EAAE,aAAa,CAAC;IAEvB;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAEhC;;;OAGG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;IAEjC;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,WAAW,aAAa,cAAc,KAAQ,UA6E1D,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,gBAAgB,kBAAmB,UAAU,EAAE,KAAG,UAI9D,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AACH,eAAO,MAAM,gBAAgB,YAAa,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,KAAG,UAE3H,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/middleware.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/middleware.js new file mode 100644 index 000000000..bfeb9760e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/middleware.js @@ -0,0 +1,245 @@ +import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; +/** + * Creates a fetch wrapper that handles OAuth authentication automatically. + * + * This wrapper will: + * - Add Authorization headers with access tokens + * - Handle 401 responses by attempting re-authentication + * - Retry the original request after successful auth + * - Handle OAuth errors appropriately (InvalidClientError, etc.) + * + * The baseUrl parameter is optional and defaults to using the domain from the request URL. + * However, you should explicitly provide baseUrl when: + * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) + * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) + * - The OAuth server is on a different domain than your API requests + * - You want to ensure consistent OAuth behavior regardless of request URLs + * + * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. + * + * Note: This wrapper is designed for general-purpose fetch operations. + * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling + * and should not need this wrapper. + * + * @param provider - OAuth client provider for authentication + * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) + * @returns A fetch middleware function + */ +export const withOAuth = (provider, baseUrl) => next => { + return async (input, init) => { + const makeRequest = async () => { + const headers = new Headers(init?.headers); + // Add authorization header if tokens are available + const tokens = await provider.tokens(); + if (tokens) { + headers.set('Authorization', `Bearer ${tokens.access_token}`); + } + return await next(input, { ...init, headers }); + }; + let response = await makeRequest(); + // Handle 401 responses by attempting re-authentication + if (response.status === 401) { + try { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + // Use provided baseUrl or extract from request URL + const serverUrl = baseUrl || (typeof input === 'string' ? new URL(input).origin : input.origin); + const result = await auth(provider, { + serverUrl, + resourceMetadataUrl, + scope, + fetchFn: next + }); + if (result === 'REDIRECT') { + throw new UnauthorizedError('Authentication requires user authorization - redirect initiated'); + } + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(`Authentication failed with result: ${result}`); + } + // Retry the request with fresh tokens + response = await makeRequest(); + } + catch (error) { + if (error instanceof UnauthorizedError) { + throw error; + } + throw new UnauthorizedError(`Failed to re-authenticate: ${error instanceof Error ? error.message : String(error)}`); + } + } + // If we still have a 401 after re-auth attempt, throw an error + if (response.status === 401) { + const url = typeof input === 'string' ? input : input.toString(); + throw new UnauthorizedError(`Authentication failed for ${url}`); + } + return response; + }; +}; +/** + * Creates a fetch middleware that logs HTTP requests and responses. + * + * When called without arguments `withLogging()`, it uses the default logger that: + * - Logs successful requests (2xx) to `console.log` + * - Logs error responses (4xx/5xx) and network errors to `console.error` + * - Logs all requests regardless of status (statusLevel: 0) + * - Does not include request or response headers in logs + * - Measures and displays request duration in milliseconds + * + * Important: the default logger uses both `console.log` and `console.error` so it should not be used with + * `stdio` transports and applications. + * + * @param options - Logging configuration options + * @returns A fetch middleware function + */ +export const withLogging = (options = {}) => { + const { logger, includeRequestHeaders = false, includeResponseHeaders = false, statusLevel = 0 } = options; + const defaultLogger = input => { + const { method, url, status, statusText, duration, requestHeaders, responseHeaders, error } = input; + let message = error + ? `HTTP ${method} ${url} failed: ${error.message} (${duration}ms)` + : `HTTP ${method} ${url} ${status} ${statusText} (${duration}ms)`; + // Add headers to message if requested + if (includeRequestHeaders && requestHeaders) { + const reqHeaders = Array.from(requestHeaders.entries()) + .map(([key, value]) => `${key}: ${value}`) + .join(', '); + message += `\n Request Headers: {${reqHeaders}}`; + } + if (includeResponseHeaders && responseHeaders) { + const resHeaders = Array.from(responseHeaders.entries()) + .map(([key, value]) => `${key}: ${value}`) + .join(', '); + message += `\n Response Headers: {${resHeaders}}`; + } + if (error || status >= 400) { + // eslint-disable-next-line no-console + console.error(message); + } + else { + // eslint-disable-next-line no-console + console.log(message); + } + }; + const logFn = logger || defaultLogger; + return next => async (input, init) => { + const startTime = performance.now(); + const method = init?.method || 'GET'; + const url = typeof input === 'string' ? input : input.toString(); + const requestHeaders = includeRequestHeaders ? new Headers(init?.headers) : undefined; + try { + const response = await next(input, init); + const duration = performance.now() - startTime; + // Only log if status meets the log level threshold + if (response.status >= statusLevel) { + logFn({ + method, + url, + status: response.status, + statusText: response.statusText, + duration, + requestHeaders, + responseHeaders: includeResponseHeaders ? response.headers : undefined + }); + } + return response; + } + catch (error) { + const duration = performance.now() - startTime; + // Always log errors regardless of log level + logFn({ + method, + url, + status: 0, + statusText: 'Network Error', + duration, + requestHeaders, + error: error + }); + throw error; + } + }; +}; +/** + * Composes multiple fetch middleware functions into a single middleware pipeline. + * Middleware are applied in the order they appear, creating a chain of handlers. + * + * @example + * ```typescript + * // Create a middleware pipeline that handles both OAuth and logging + * const enhancedFetch = applyMiddlewares( + * withOAuth(oauthProvider, 'https://api.example.com'), + * withLogging({ statusLevel: 400 }) + * )(fetch); + * + * // Use the enhanced fetch - it will handle auth and log errors + * const response = await enhancedFetch('https://api.example.com/data'); + * ``` + * + * @param middleware - Array of fetch middleware to compose into a pipeline + * @returns A single composed middleware function + */ +export const applyMiddlewares = (...middleware) => { + return next => { + return middleware.reduce((handler, mw) => mw(handler), next); + }; +}; +/** + * Helper function to create custom fetch middleware with cleaner syntax. + * Provides the next handler and request details as separate parameters for easier access. + * + * @example + * ```typescript + * // Create custom authentication middleware + * const customAuthMiddleware = createMiddleware(async (next, input, init) => { + * const headers = new Headers(init?.headers); + * headers.set('X-Custom-Auth', 'my-token'); + * + * const response = await next(input, { ...init, headers }); + * + * if (response.status === 401) { + * console.log('Authentication failed'); + * } + * + * return response; + * }); + * + * // Create conditional middleware + * const conditionalMiddleware = createMiddleware(async (next, input, init) => { + * const url = typeof input === 'string' ? input : input.toString(); + * + * // Only add headers for API routes + * if (url.includes('/api/')) { + * const headers = new Headers(init?.headers); + * headers.set('X-API-Version', 'v2'); + * return next(input, { ...init, headers }); + * } + * + * // Pass through for non-API routes + * return next(input, init); + * }); + * + * // Create caching middleware + * const cacheMiddleware = createMiddleware(async (next, input, init) => { + * const cacheKey = typeof input === 'string' ? input : input.toString(); + * + * // Check cache first + * const cached = await getFromCache(cacheKey); + * if (cached) { + * return new Response(cached, { status: 200 }); + * } + * + * // Make request and cache result + * const response = await next(input, init); + * if (response.ok) { + * await saveToCache(cacheKey, await response.clone().text()); + * } + * + * return response; + * }); + * ``` + * + * @param handler - Function that receives the next handler and request parameters + * @returns A fetch middleware function + */ +export const createMiddleware = (handler) => { + return next => (input, init) => handler(next, input, init); +}; +//# sourceMappingURL=middleware.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/middleware.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/middleware.js.map new file mode 100644 index 000000000..e3ded1a37 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/middleware.js.map @@ -0,0 +1 @@ +{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,4BAA4B,EAAuB,iBAAiB,EAAE,MAAM,WAAW,CAAC;AASvG;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,CAAC,MAAM,SAAS,GAClB,CAAC,QAA6B,EAAE,OAAsB,EAAc,EAAE,CACtE,IAAI,CAAC,EAAE;IACH,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,WAAW,GAAG,KAAK,IAAuB,EAAE;YAC9C,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YAE3C,mDAAmD;YACnD,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,MAAM,EAAE,CAAC;YACvC,IAAI,MAAM,EAAE,CAAC;gBACT,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC;YAClE,CAAC;YAED,OAAO,MAAM,IAAI,CAAC,KAAK,EAAE,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;QACnD,CAAC,CAAC;QAEF,IAAI,QAAQ,GAAG,MAAM,WAAW,EAAE,CAAC;QAEnC,uDAAuD;QACvD,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YAC1B,IAAI,CAAC;gBACD,MAAM,EAAE,mBAAmB,EAAE,KAAK,EAAE,GAAG,4BAA4B,CAAC,QAAQ,CAAC,CAAC;gBAE9E,mDAAmD;gBAC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SAAS;iBACzE,CAAC,CAAC;YACP,CAAC;YAED,OAAO,QAAQ,CAAC;QACpB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,MAAM,QAAQ,GAAG,WAAW,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC;YAE/C,4CAA4C;YAC5C,KAAK,CAAC;gBACF,MAAM;gBACN,GAAG;gBACH,MAAM,EAAE,CAAC;gBACT,UAAU,EAAE,eAAe;gBAC3B,QAAQ;gBACR,cAAc;gBACd,KAAK,EAAE,KAAc;aACxB,CAAC,CAAC;YAEH,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC,CAAC;AACN,CAAC,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAG,UAAwB,EAAc,EAAE;IACxE,OAAO,IAAI,CAAC,EAAE;QACV,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,CAAC;IACjE,CAAC,CAAC;AACN,CAAC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,OAAwF,EAAc,EAAE;IACrI,OAAO,IAAI,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,KAAqB,EAAE,IAAI,CAAC,CAAC;AAC/E,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.d.ts new file mode 100644 index 000000000..acf99f1ea --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.d.ts @@ -0,0 +1,81 @@ +import { type ErrorEvent, type EventSourceInit } from 'eventsource'; +import { Transport, FetchLike } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +import { OAuthClientProvider } from './auth.js'; +export declare class SseError extends Error { + readonly code: number | undefined; + readonly event: ErrorEvent; + constructor(code: number | undefined, message: string | undefined, event: ErrorEvent); +} +/** + * Configuration options for the `SSEClientTransport`. + */ +export type SSEClientTransportOptions = { + /** + * An OAuth client provider to use for authentication. + * + * When an `authProvider` is specified and the SSE connection is started: + * 1. The connection is attempted with any existing access token from the `authProvider`. + * 2. If the access token has expired, the `authProvider` is used to refresh the token. + * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. + * + * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `SSEClientTransport.finishAuth` with the authorization code before retrying the connection. + * + * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. + * + * `UnauthorizedError` might also be thrown when sending any message over the SSE transport, indicating that the session has expired, and needs to be re-authed and reconnected. + */ + authProvider?: OAuthClientProvider; + /** + * Customizes the initial SSE request to the server (the request that begins the stream). + * + * NOTE: Setting this property will prevent an `Authorization` header from + * being automatically attached to the SSE request, if an `authProvider` is + * also given. This can be worked around by setting the `Authorization` header + * manually. + */ + eventSourceInit?: EventSourceInit; + /** + * Customizes recurring POST requests to the server. + */ + requestInit?: RequestInit; + /** + * Custom fetch implementation used for all network requests. + */ + fetch?: FetchLike; +}; +/** + * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving + * messages and make separate POST requests for sending messages. + * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. + */ +export declare class SSEClientTransport implements Transport { + private _eventSource?; + private _endpoint?; + private _abortController?; + private _url; + private _resourceMetadataUrl?; + private _scope?; + private _eventSourceInit?; + private _requestInit?; + private _authProvider?; + private _fetch?; + private _fetchWithInit; + private _protocolVersion?; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(url: URL, opts?: SSEClientTransportOptions); + private _authThenStart; + private _commonHeaders; + private _startOrAuth; + start(): Promise; + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + finishAuth(authorizationCode: string): Promise; + close(): Promise; + send(message: JSONRPCMessage): Promise; + setProtocolVersion(version: string): void; +} +//# sourceMappingURL=sse.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.d.ts.map new file mode 100644 index 000000000..14ee939e2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../../src/client/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,KAAK,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,SAAS,EAAyC,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AACnE,OAAO,EAAkD,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AAEnH,qBAAa,QAAS,SAAQ,KAAK;aAEX,IAAI,EAAE,MAAM,GAAG,SAAS;aAExB,KAAK,EAAE,UAAU;gBAFjB,IAAI,EAAE,MAAM,GAAG,SAAS,EACxC,OAAO,EAAE,MAAM,GAAG,SAAS,EACX,KAAK,EAAE,UAAU;CAIxC;AAED;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACpC;;;;;;;;;;;;;OAaG;IACH,YAAY,CAAC,EAAE,mBAAmB,CAAC;IAEnC;;;;;;;OAOG;IACH,eAAe,CAAC,EAAE,eAAe,CAAC;IAElC;;OAEG;IACH,WAAW,CAAC,EAAE,WAAW,CAAC;IAE1B;;OAEG;IACH,KAAK,CAAC,EAAE,SAAS,CAAC;CACrB,CAAC;AAEF;;;;GAIG;AACH,qBAAa,kBAAmB,YAAW,SAAS;IAChD,OAAO,CAAC,YAAY,CAAC,CAAc;IACnC,OAAO,CAAC,SAAS,CAAC,CAAM;IACxB,OAAO,CAAC,gBAAgB,CAAC,CAAkB;IAC3C,OAAO,CAAC,IAAI,CAAM;IAClB,OAAO,CAAC,oBAAoB,CAAC,CAAM;IACnC,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,gBAAgB,CAAC,CAAkB;IAC3C,OAAO,CAAC,YAAY,CAAC,CAAc;IACnC,OAAO,CAAC,aAAa,CAAC,CAAsB;IAC5C,OAAO,CAAC,MAAM,CAAC,CAAY;IAC3B,OAAO,CAAC,cAAc,CAAY;IAClC,OAAO,CAAC,gBAAgB,CAAC,CAAS;IAElC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,yBAAyB;YAWxC,cAAc;YAyBd,cAAc;IAoB5B,OAAO,CAAC,YAAY;IAyEd,KAAK;IAQX;;OAEG;IACG,UAAU,CAAC,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiBpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAMtB,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAkDlD,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;CAG5C"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js new file mode 100644 index 000000000..58c474156 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js @@ -0,0 +1,206 @@ +import { EventSource } from 'eventsource'; +import { createFetchWithInit, normalizeHeaders } from '../shared/transport.js'; +import { JSONRPCMessageSchema } from '../types.js'; +import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; +export class SseError extends Error { + constructor(code, message, event) { + super(`SSE error: ${message}`); + this.code = code; + this.event = event; + } +} +/** + * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving + * messages and make separate POST requests for sending messages. + * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. + */ +export class SSEClientTransport { + constructor(url, opts) { + this._url = url; + this._resourceMetadataUrl = undefined; + this._scope = undefined; + this._eventSourceInit = opts?.eventSourceInit; + this._requestInit = opts?.requestInit; + this._authProvider = opts?.authProvider; + this._fetch = opts?.fetch; + this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit); + } + async _authThenStart() { + if (!this._authProvider) { + throw new UnauthorizedError('No auth provider'); + } + let result; + try { + result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } + catch (error) { + this.onerror?.(error); + throw error; + } + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + return await this._startOrAuth(); + } + async _commonHeaders() { + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) { + headers['Authorization'] = `Bearer ${tokens.access_token}`; + } + } + if (this._protocolVersion) { + headers['mcp-protocol-version'] = this._protocolVersion; + } + const extraHeaders = normalizeHeaders(this._requestInit?.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + _startOrAuth() { + const fetchImpl = (this?._eventSourceInit?.fetch ?? this._fetch ?? fetch); + return new Promise((resolve, reject) => { + this._eventSource = new EventSource(this._url.href, { + ...this._eventSourceInit, + fetch: async (url, init) => { + const headers = await this._commonHeaders(); + headers.set('Accept', 'text/event-stream'); + const response = await fetchImpl(url, { + ...init, + headers + }); + if (response.status === 401 && response.headers.has('www-authenticate')) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + } + return response; + } + }); + this._abortController = new AbortController(); + this._eventSource.onerror = event => { + if (event.code === 401 && this._authProvider) { + this._authThenStart().then(resolve, reject); + return; + } + const error = new SseError(event.code, event.message, event); + reject(error); + this.onerror?.(error); + }; + this._eventSource.onopen = () => { + // The connection is open, but we need to wait for the endpoint to be received. + }; + this._eventSource.addEventListener('endpoint', (event) => { + const messageEvent = event; + try { + this._endpoint = new URL(messageEvent.data, this._url); + if (this._endpoint.origin !== this._url.origin) { + throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); + } + } + catch (error) { + reject(error); + this.onerror?.(error); + void this.close(); + return; + } + resolve(); + }); + this._eventSource.onmessage = (event) => { + const messageEvent = event; + let message; + try { + message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); + } + catch (error) { + this.onerror?.(error); + return; + } + this.onmessage?.(message); + }; + }); + } + async start() { + if (this._eventSource) { + throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return await this._startOrAuth(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) { + throw new UnauthorizedError('No auth provider'); + } + const result = await auth(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError('Failed to authorize'); + } + } + async close() { + this._abortController?.abort(); + this._eventSource?.close(); + this.onclose?.(); + } + async send(message) { + if (!this._endpoint) { + throw new Error('Not connected'); + } + try { + const headers = await this._commonHeaders(); + headers.set('content-type', 'application/json'); + const init = { + ...this._requestInit, + method: 'POST', + headers, + body: JSON.stringify(message), + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._endpoint, init); + if (!response.ok) { + const text = await response.text().catch(() => null); + if (response.status === 401 && this._authProvider) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + // Purposely _not_ awaited, so we don't call onerror twice + return this.send(message); + } + throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); + } + // Release connection - POST responses don't have content we need + await response.body?.cancel(); + } + catch (error) { + this.onerror?.(error); + throw error; + } + } + setProtocolVersion(version) { + this._protocolVersion = version; + } +} +//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js.map new file mode 100644 index 000000000..9957f95d8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.js","sourceRoot":"","sources":["../../../src/client/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAyC,MAAM,aAAa,CAAC;AACjF,OAAO,EAAwB,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAkB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,IAAI,EAAc,4BAA4B,EAAuB,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAEnH,MAAM,OAAO,QAAS,SAAQ,KAAK;IAC/B,YACoB,IAAwB,EACxC,OAA2B,EACX,KAAiB;QAEjC,KAAK,CA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Ae;QAC9B,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IACpC,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.d.ts new file mode 100644 index 000000000..a411dba81 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.d.ts @@ -0,0 +1,77 @@ +import { IOType } from 'node:child_process'; +import { Stream } from 'node:stream'; +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +export type StdioServerParameters = { + /** + * The executable to run to start the server. + */ + command: string; + /** + * Command line arguments to pass to the executable. + */ + args?: string[]; + /** + * The environment to use when spawning the process. + * + * If not specified, the result of getDefaultEnvironment() will be used. + */ + env?: Record; + /** + * How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`. + * + * The default is "inherit", meaning messages to stderr will be printed to the parent process's stderr. + */ + stderr?: IOType | Stream | number; + /** + * The working directory to use when spawning the process. + * + * If not specified, the current working directory will be inherited. + */ + cwd?: string; +}; +/** + * Environment variables to inherit by default, if an environment is not explicitly given. + */ +export declare const DEFAULT_INHERITED_ENV_VARS: string[]; +/** + * Returns a default environment object including only environment variables deemed safe to inherit. + */ +export declare function getDefaultEnvironment(): Record; +/** + * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. + * + * This transport is only available in Node.js environments. + */ +export declare class StdioClientTransport implements Transport { + private _process?; + private _readBuffer; + private _serverParams; + private _stderrStream; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(server: StdioServerParameters); + /** + * Starts the server process and prepares to communicate with it. + */ + start(): Promise; + /** + * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". + * + * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to + * attach listeners before the start method is invoked. This prevents loss of any early + * error output emitted by the child process. + */ + get stderr(): Stream | null; + /** + * The child process pid spawned by this transport. + * + * This is only available after the transport has been started. + */ + get pid(): number | null; + private processReadBuffer; + close(): Promise; + send(message: JSONRPCMessage): Promise; +} +//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.d.ts.map new file mode 100644 index 000000000..73b267bce --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,EAAE,MAAM,EAAe,MAAM,aAAa,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7C,MAAM,MAAM,qBAAqB,GAAG;IAChC;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAEhB;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAE7B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IAElC;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,0BAA0B,UAiBuB,CAAC;AAE/D;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAkB9D;AAED;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,SAAS;IAClD,OAAO,CAAC,QAAQ,CAAC,CAAe;IAChC,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,aAAa,CAAwB;IAC7C,OAAO,CAAC,aAAa,CAA4B;IAEjD,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,MAAM,EAAE,qBAAqB;IAOzC;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAqD5B;;;;;;OAMG;IACH,IAAI,MAAM,IAAI,MAAM,GAAG,IAAI,CAM1B;IAED;;;;OAIG;IACH,IAAI,GAAG,IAAI,MAAM,GAAG,IAAI,CAEvB;IAED,OAAO,CAAC,iBAAiB;IAenB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAyC5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAc/C"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js new file mode 100644 index 000000000..e1e4b9c60 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js @@ -0,0 +1,191 @@ +import spawn from 'cross-spawn'; +import process from 'node:process'; +import { PassThrough } from 'node:stream'; +import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; +/** + * Environment variables to inherit by default, if an environment is not explicitly given. + */ +export const DEFAULT_INHERITED_ENV_VARS = process.platform === 'win32' + ? [ + 'APPDATA', + 'HOMEDRIVE', + 'HOMEPATH', + 'LOCALAPPDATA', + 'PATH', + 'PROCESSOR_ARCHITECTURE', + 'SYSTEMDRIVE', + 'SYSTEMROOT', + 'TEMP', + 'USERNAME', + 'USERPROFILE', + 'PROGRAMFILES' + ] + : /* list inspired by the default env inheritance of sudo */ + ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER']; +/** + * Returns a default environment object including only environment variables deemed safe to inherit. + */ +export function getDefaultEnvironment() { + const env = {}; + for (const key of DEFAULT_INHERITED_ENV_VARS) { + const value = process.env[key]; + if (value === undefined) { + continue; + } + if (value.startsWith('()')) { + // Skip functions, which are a security risk. + continue; + } + env[key] = value; + } + return env; +} +/** + * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. + * + * This transport is only available in Node.js environments. + */ +export class StdioClientTransport { + constructor(server) { + this._readBuffer = new ReadBuffer(); + this._stderrStream = null; + this._serverParams = server; + if (server.stderr === 'pipe' || server.stderr === 'overlapped') { + this._stderrStream = new PassThrough(); + } + } + /** + * Starts the server process and prepares to communicate with it. + */ + async start() { + if (this._process) { + throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return new Promise((resolve, reject) => { + this._process = spawn(this._serverParams.command, this._serverParams.args ?? [], { + // merge default env with server env because mcp server needs some env vars + env: { + ...getDefaultEnvironment(), + ...this._serverParams.env + }, + stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'], + shell: false, + windowsHide: process.platform === 'win32' && isElectron(), + cwd: this._serverParams.cwd + }); + this._process.on('error', error => { + reject(error); + this.onerror?.(error); + }); + this._process.on('spawn', () => { + resolve(); + }); + this._process.on('close', _code => { + this._process = undefined; + this.onclose?.(); + }); + this._process.stdin?.on('error', error => { + this.onerror?.(error); + }); + this._process.stdout?.on('data', chunk => { + this._readBuffer.append(chunk); + this.processReadBuffer(); + }); + this._process.stdout?.on('error', error => { + this.onerror?.(error); + }); + if (this._stderrStream && this._process.stderr) { + this._process.stderr.pipe(this._stderrStream); + } + }); + } + /** + * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". + * + * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to + * attach listeners before the start method is invoked. This prevents loss of any early + * error output emitted by the child process. + */ + get stderr() { + if (this._stderrStream) { + return this._stderrStream; + } + return this._process?.stderr ?? null; + } + /** + * The child process pid spawned by this transport. + * + * This is only available after the transport has been started. + */ + get pid() { + return this._process?.pid ?? null; + } + processReadBuffer() { + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + this.onmessage?.(message); + } + catch (error) { + this.onerror?.(error); + } + } + } + async close() { + if (this._process) { + const processToClose = this._process; + this._process = undefined; + const closePromise = new Promise(resolve => { + processToClose.once('close', () => { + resolve(); + }); + }); + try { + processToClose.stdin?.end(); + } + catch { + // ignore + } + await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]); + if (processToClose.exitCode === null) { + try { + processToClose.kill('SIGTERM'); + } + catch { + // ignore + } + await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]); + } + if (processToClose.exitCode === null) { + try { + processToClose.kill('SIGKILL'); + } + catch { + // ignore + } + } + } + this._readBuffer.clear(); + } + send(message) { + return new Promise(resolve => { + if (!this._process?.stdin) { + throw new Error('Not connected'); + } + const json = serializeMessage(message); + if (this._process.stdin.write(json)) { + resolve(); + } + else { + this._process.stdin.once('drain', resolve); + } + }); + } +} +function isElectron() { + return 'type' in process; +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js.map new file mode 100644 index 000000000..60182337b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,aAAa,CAAC;AAChC,OAAO,OAAO,MAAM,cAAc,CAAC;AACnC,OAAO,EAAU,WAAW,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAqClE;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GACnC,OAAO,CAAC,QAAQ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AC;QACL,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,CAAC,OAAuB;QACxB,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;YACzB,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC;gBACxB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;YACrC,CAAC;YAED,MAAM,IAAI,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;YACvC,IAAI,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAClC,OAAO,EAAE,CAAC;YACd,CAAC;iBAAM,CAAC;gBACJ,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC/C,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAED,SAAS,UAAU;IACf,OAAO,MAAM,IAAI,OAAO,CAAC;AAC7B,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.d.ts new file mode 100644 index 000000000..6035b2462 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.d.ts @@ -0,0 +1,171 @@ +import { Transport, FetchLike } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +import { OAuthClientProvider } from './auth.js'; +export declare class StreamableHTTPError extends Error { + readonly code: number | undefined; + constructor(code: number | undefined, message: string | undefined); +} +/** + * Options for starting or authenticating an SSE connection + */ +export interface StartSSEOptions { + /** + * The resumption token used to continue long-running requests that were interrupted. + * + * This allows clients to reconnect and continue from where they left off. + */ + resumptionToken?: string; + /** + * A callback that is invoked when the resumption token changes. + * + * This allows clients to persist the latest token for potential reconnection. + */ + onresumptiontoken?: (token: string) => void; + /** + * Override Message ID to associate with the replay message + * so that response can be associate with the new resumed request. + */ + replayMessageId?: string | number; +} +/** + * Configuration options for reconnection behavior of the StreamableHTTPClientTransport. + */ +export interface StreamableHTTPReconnectionOptions { + /** + * Maximum backoff time between reconnection attempts in milliseconds. + * Default is 30000 (30 seconds). + */ + maxReconnectionDelay: number; + /** + * Initial backoff time between reconnection attempts in milliseconds. + * Default is 1000 (1 second). + */ + initialReconnectionDelay: number; + /** + * The factor by which the reconnection delay increases after each attempt. + * Default is 1.5. + */ + reconnectionDelayGrowFactor: number; + /** + * Maximum number of reconnection attempts before giving up. + * Default is 2. + */ + maxRetries: number; +} +/** + * Configuration options for the `StreamableHTTPClientTransport`. + */ +export type StreamableHTTPClientTransportOptions = { + /** + * An OAuth client provider to use for authentication. + * + * When an `authProvider` is specified and the connection is started: + * 1. The connection is attempted with any existing access token from the `authProvider`. + * 2. If the access token has expired, the `authProvider` is used to refresh the token. + * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. + * + * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `StreamableHTTPClientTransport.finishAuth` with the authorization code before retrying the connection. + * + * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. + * + * `UnauthorizedError` might also be thrown when sending any message over the transport, indicating that the session has expired, and needs to be re-authed and reconnected. + */ + authProvider?: OAuthClientProvider; + /** + * Customizes HTTP requests to the server. + */ + requestInit?: RequestInit; + /** + * Custom fetch implementation used for all network requests. + */ + fetch?: FetchLike; + /** + * Options to configure the reconnection behavior. + */ + reconnectionOptions?: StreamableHTTPReconnectionOptions; + /** + * Session ID for the connection. This is used to identify the session on the server. + * When not provided and connecting to a server that supports session IDs, the server will generate a new session ID. + */ + sessionId?: string; +}; +/** + * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events + * for receiving messages. + */ +export declare class StreamableHTTPClientTransport implements Transport { + private _abortController?; + private _url; + private _resourceMetadataUrl?; + private _scope?; + private _requestInit?; + private _authProvider?; + private _fetch?; + private _fetchWithInit; + private _sessionId?; + private _reconnectionOptions; + private _protocolVersion?; + private _hasCompletedAuthFlow; + private _lastUpscopingHeader?; + private _serverRetryMs?; + private _reconnectionTimeout?; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(url: URL, opts?: StreamableHTTPClientTransportOptions); + private _authThenStart; + private _commonHeaders; + private _startOrAuthSse; + /** + * Calculates the next reconnection delay using backoff algorithm + * + * @param attempt Current reconnection attempt count for the specific stream + * @returns Time to wait in milliseconds before next reconnection attempt + */ + private _getNextReconnectionDelay; + /** + * Schedule a reconnection attempt using server-provided retry interval or backoff + * + * @param lastEventId The ID of the last received event for resumability + * @param attemptCount Current reconnection attempt count for this specific stream + */ + private _scheduleReconnection; + private _handleSseStream; + start(): Promise; + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + finishAuth(authorizationCode: string): Promise; + close(): Promise; + send(message: JSONRPCMessage | JSONRPCMessage[], options?: { + resumptionToken?: string; + onresumptiontoken?: (token: string) => void; + }): Promise; + get sessionId(): string | undefined; + /** + * Terminates the current session by sending a DELETE request to the server. + * + * Clients that no longer need a particular session + * (e.g., because the user is leaving the client application) SHOULD send an + * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly + * terminate the session. + * + * The server MAY respond with HTTP 405 Method Not Allowed, indicating that + * the server does not allow clients to terminate sessions. + */ + terminateSession(): Promise; + setProtocolVersion(version: string): void; + get protocolVersion(): string | undefined; + /** + * Resume an SSE stream from a previous event ID. + * Opens a GET SSE connection with Last-Event-ID header to replay missed events. + * + * @param lastEventId The event ID to resume from + * @param options Optional callback to receive new resumption tokens + */ + resumeStream(lastEventId: string, options?: { + onresumptiontoken?: (token: string) => void; + }): Promise; +} +//# sourceMappingURL=streamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.d.ts.map new file mode 100644 index 000000000..5b6ffb8a3 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.d.ts","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAyC,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAwE,cAAc,EAAwB,MAAM,aAAa,CAAC;AACzI,OAAO,EAAkD,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AAWnH,qBAAa,mBAAoB,SAAQ,KAAK;aAEtB,IAAI,EAAE,MAAM,GAAG,SAAS;gBAAxB,IAAI,EAAE,MAAM,GAAG,SAAS,EACxC,OAAO,EAAE,MAAM,GAAG,SAAS;CAIlC;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC5B;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAE5C;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;CACrC;AAED;;GAEG;AACH,MAAM,WAAW,iCAAiC;IAC9C;;;OAGG;IACH,oBAAoB,EAAE,MAAM,CAAC;IAE7B;;;OAGG;IACH,wBAAwB,EAAE,MAAM,CAAC;IAEjC;;;OAGG;IACH,2BAA2B,EAAE,MAAM,CAAC;IAEpC;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,MAAM,oCAAoC,GAAG;IAC/C;;;;;;;;;;;;;OAaG;IACH,YAAY,CAAC,EAAE,mB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G;IACG,UAAU,CAAC,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiBpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAStB,IAAI,CACN,OAAO,EAAE,cAAc,GAAG,cAAc,EAAE,EAC1C,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,MAAM,CAAC;QAAC,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;KAAE,GACpF,OAAO,CAAC,IAAI,CAAC;IA0JhB,IAAI,SAAS,IAAI,MAAM,GAAG,SAAS,CAElC;IAED;;;;;;;;;;OAUG;IACG,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IA+BvC,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAGzC,IAAI,eAAe,IAAI,MAAM,GAAG,SAAS,CAExC;IAED;;;;;;OAMG;IACG,YAAY,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAMpH"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js new file mode 100644 index 000000000..624172aa2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js @@ -0,0 +1,477 @@ +import { createFetchWithInit, normalizeHeaders } from '../shared/transport.js'; +import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema } from '../types.js'; +import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; +import { EventSourceParserStream } from 'eventsource-parser/stream'; +// Default reconnection options for StreamableHTTP connections +const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = { + initialReconnectionDelay: 1000, + maxReconnectionDelay: 30000, + reconnectionDelayGrowFactor: 1.5, + maxRetries: 2 +}; +export class StreamableHTTPError extends Error { + constructor(code, message) { + super(`Streamable HTTP error: ${message}`); + this.code = code; + } +} +/** + * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events + * for receiving messages. + */ +export class StreamableHTTPClientTransport { + constructor(url, opts) { + this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401 + this._url = url; + this._resourceMetadataUrl = undefined; + this._scope = undefined; + this._requestInit = opts?.requestInit; + this._authProvider = opts?.authProvider; + this._fetch = opts?.fetch; + this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit); + this._sessionId = opts?.sessionId; + this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; + } + async _authThenStart() { + if (!this._authProvider) { + throw new UnauthorizedError('No auth provider'); + } + let result; + try { + result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } + catch (error) { + this.onerror?.(error); + throw error; + } + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + return await this._startOrAuthSse({ resumptionToken: undefined }); + } + async _commonHeaders() { + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) { + headers['Authorization'] = `Bearer ${tokens.access_token}`; + } + } + if (this._sessionId) { + headers['mcp-session-id'] = this._sessionId; + } + if (this._protocolVersion) { + headers['mcp-protocol-version'] = this._protocolVersion; + } + const extraHeaders = normalizeHeaders(this._requestInit?.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + async _startOrAuthSse(options) { + const { resumptionToken } = options; + try { + // Try to open an initial SSE stream with GET to listen for server messages + // This is optional according to the spec - server may not support it + const headers = await this._commonHeaders(); + headers.set('Accept', 'text/event-stream'); + // Include Last-Event-ID header for resumable streams if provided + if (resumptionToken) { + headers.set('last-event-id', resumptionToken); + } + const response = await (this._fetch ?? fetch)(this._url, { + method: 'GET', + headers, + signal: this._abortController?.signal + }); + if (!response.ok) { + await response.body?.cancel(); + if (response.status === 401 && this._authProvider) { + // Need to authenticate + return await this._authThenStart(); + } + // 405 indicates that the server does not offer an SSE stream at GET endpoint + // This is an expected case that should not trigger an error + if (response.status === 405) { + return; + } + throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`); + } + this._handleSseStream(response.body, options, true); + } + catch (error) { + this.onerror?.(error); + throw error; + } + } + /** + * Calculates the next reconnection delay using backoff algorithm + * + * @param attempt Current reconnection attempt count for the specific stream + * @returns Time to wait in milliseconds before next reconnection attempt + */ + _getNextReconnectionDelay(attempt) { + // Use server-provided retry value if available + if (this._serverRetryMs !== undefined) { + return this._serverRetryMs; + } + // Fall back to exponential backoff + const initialDelay = this._reconnectionOptions.initialReconnectionDelay; + const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; + const maxDelay = this._reconnectionOptions.maxReconnectionDelay; + // Cap at maximum delay + return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); + } + /** + * Schedule a reconnection attempt using server-provided retry interval or backoff + * + * @param lastEventId The ID of the last received event for resumability + * @param attemptCount Current reconnection attempt count for this specific stream + */ + _scheduleReconnection(options, attemptCount = 0) { + // Use provided options or default options + const maxRetries = this._reconnectionOptions.maxRetries; + // Check if we've exceeded maximum retry attempts + if (attemptCount >= maxRetries) { + this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); + return; + } + // Calculate next delay based on current attempt count + const delay = this._getNextReconnectionDelay(attemptCount); + // Schedule the reconnection + this._reconnectionTimeout = setTimeout(() => { + // Use the last event ID to resume where we left off + this._startOrAuthSse(options).catch(error => { + this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`)); + // Schedule another attempt if this one failed, incrementing the attempt counter + this._scheduleReconnection(options, attemptCount + 1); + }); + }, delay); + } + _handleSseStream(stream, options, isReconnectable) { + if (!stream) { + return; + } + const { onresumptiontoken, replayMessageId } = options; + let lastEventId; + // Track whether we've received a priming event (event with ID) + // Per spec, server SHOULD send a priming event with ID before closing + let hasPrimingEvent = false; + // Track whether we've received a response - if so, no need to reconnect + // Reconnection is for when server disconnects BEFORE sending response + let receivedResponse = false; + const processStream = async () => { + // this is the closest we can get to trying to catch network errors + // if something happens reader will throw + try { + // Create a pipeline: binary stream -> text decoder -> SSE parser + const reader = stream + .pipeThrough(new TextDecoderStream()) + .pipeThrough(new EventSourceParserStream({ + onRetry: (retryMs) => { + // Capture server-provided retry value for reconnection timing + this._serverRetryMs = retryMs; + } + })) + .getReader(); + while (true) { + const { value: event, done } = await reader.read(); + if (done) { + break; + } + // Update last event ID if provided + if (event.id) { + lastEventId = event.id; + // Mark that we've received a priming event - stream is now resumable + hasPrimingEvent = true; + onresumptiontoken?.(event.id); + } + // Skip events with no data (priming events, keep-alives) + if (!event.data) { + continue; + } + if (!event.event || event.event === 'message') { + try { + const message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); + if (isJSONRPCResultResponse(message)) { + // Mark that we received a response - no need to reconnect for this request + receivedResponse = true; + if (replayMessageId !== undefined) { + message.id = replayMessageId; + } + } + this.onmessage?.(message); + } + catch (error) { + this.onerror?.(error); + } + } + } + // Handle graceful server-side disconnect + // Server may close connection after sending event ID and retry field + // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID) + // BUT don't reconnect if we already received a response - the request is complete + const canResume = isReconnectable || hasPrimingEvent; + const needsReconnect = canResume && !receivedResponse; + if (needsReconnect && this._abortController && !this._abortController.signal.aborted) { + this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId + }, 0); + } + } + catch (error) { + // Handle stream errors - likely a network disconnect + this.onerror?.(new Error(`SSE stream disconnected: ${error}`)); + // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing + // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID) + // BUT don't reconnect if we already received a response - the request is complete + const canResume = isReconnectable || hasPrimingEvent; + const needsReconnect = canResume && !receivedResponse; + if (needsReconnect && this._abortController && !this._abortController.signal.aborted) { + // Use the exponential backoff reconnection strategy + try { + this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId + }, 0); + } + catch (error) { + this.onerror?.(new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`)); + } + } + } + }; + processStream(); + } + async start() { + if (this._abortController) { + throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + this._abortController = new AbortController(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) { + throw new UnauthorizedError('No auth provider'); + } + const result = await auth(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError('Failed to authorize'); + } + } + async close() { + if (this._reconnectionTimeout) { + clearTimeout(this._reconnectionTimeout); + this._reconnectionTimeout = undefined; + } + this._abortController?.abort(); + this.onclose?.(); + } + async send(message, options) { + try { + const { resumptionToken, onresumptiontoken } = options || {}; + if (resumptionToken) { + // If we have at last event ID, we need to reconnect the SSE stream + this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : undefined }).catch(err => this.onerror?.(err)); + return; + } + const headers = await this._commonHeaders(); + headers.set('content-type', 'application/json'); + headers.set('accept', 'application/json, text/event-stream'); + const init = { + ...this._requestInit, + method: 'POST', + headers, + body: JSON.stringify(message), + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._url, init); + // Handle session ID received during initialization + const sessionId = response.headers.get('mcp-session-id'); + if (sessionId) { + this._sessionId = sessionId; + } + if (!response.ok) { + const text = await response.text().catch(() => null); + if (response.status === 401 && this._authProvider) { + // Prevent infinite recursion when server returns 401 after successful auth + if (this._hasCompletedAuthFlow) { + throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication'); + } + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + // Mark that we completed auth flow + this._hasCompletedAuthFlow = true; + // Purposely _not_ awaited, so we don't call onerror twice + return this.send(message); + } + if (response.status === 403 && this._authProvider) { + const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response); + if (error === 'insufficient_scope') { + const wwwAuthHeader = response.headers.get('WWW-Authenticate'); + // Check if we've already tried upscoping with this header to prevent infinite loops. + if (this._lastUpscopingHeader === wwwAuthHeader) { + throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping'); + } + if (scope) { + this._scope = scope; + } + if (resourceMetadataUrl) { + this._resourceMetadataUrl = resourceMetadataUrl; + } + // Mark that upscoping was tried. + this._lastUpscopingHeader = wwwAuthHeader ?? undefined; + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetch + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + return this.send(message); + } + } + throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`); + } + // Reset auth loop flag on successful response + this._hasCompletedAuthFlow = false; + this._lastUpscopingHeader = undefined; + // If the response is 202 Accepted, there's no body to process + if (response.status === 202) { + await response.body?.cancel(); + // if the accepted notification is initialized, we start the SSE stream + // if it's supported by the server + if (isInitializedNotification(message)) { + // Start without a lastEventId since this is a fresh connection + this._startOrAuthSse({ resumptionToken: undefined }).catch(err => this.onerror?.(err)); + } + return; + } + // Get original message(s) for detecting request IDs + const messages = Array.isArray(message) ? message : [message]; + const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0; + // Check the response type + const contentType = response.headers.get('content-type'); + if (hasRequests) { + if (contentType?.includes('text/event-stream')) { + // Handle SSE stream responses for requests + // We use the same handler as standalone streams, which now supports + // reconnection with the last event ID + this._handleSseStream(response.body, { onresumptiontoken }, false); + } + else if (contentType?.includes('application/json')) { + // For non-streaming servers, we might get direct JSON responses + const data = await response.json(); + const responseMessages = Array.isArray(data) + ? data.map(msg => JSONRPCMessageSchema.parse(msg)) + : [JSONRPCMessageSchema.parse(data)]; + for (const msg of responseMessages) { + this.onmessage?.(msg); + } + } + else { + await response.body?.cancel(); + throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`); + } + } + else { + // No requests in message but got 200 OK - still need to release connection + await response.body?.cancel(); + } + } + catch (error) { + this.onerror?.(error); + throw error; + } + } + get sessionId() { + return this._sessionId; + } + /** + * Terminates the current session by sending a DELETE request to the server. + * + * Clients that no longer need a particular session + * (e.g., because the user is leaving the client application) SHOULD send an + * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly + * terminate the session. + * + * The server MAY respond with HTTP 405 Method Not Allowed, indicating that + * the server does not allow clients to terminate sessions. + */ + async terminateSession() { + if (!this._sessionId) { + return; // No session to terminate + } + try { + const headers = await this._commonHeaders(); + const init = { + ...this._requestInit, + method: 'DELETE', + headers, + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._url, init); + await response.body?.cancel(); + // We specifically handle 405 as a valid response according to the spec, + // meaning the server does not support explicit session termination + if (!response.ok && response.status !== 405) { + throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`); + } + this._sessionId = undefined; + } + catch (error) { + this.onerror?.(error); + throw error; + } + } + setProtocolVersion(version) { + this._protocolVersion = version; + } + get protocolVersion() { + return this._protocolVersion; + } + /** + * Resume an SSE stream from a previous event ID. + * Opens a GET SSE connection with Last-Event-ID header to replay missed events. + * + * @param lastEventId The event ID to resume from + * @param options Optional callback to receive new resumption tokens + */ + async resumeStream(lastEventId, options) { + await this._startOrAuthSse({ + resumptionToken: lastEventId, + onresumptiontoken: options?.onresumptiontoken + }); + } +} +//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js.map new file mode 100644 index 000000000..fd4e70c15 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.js","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,uBAAuB,EAAkB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACzI,OAAO,EAAE,IAAI,EAAc,4BAA4B,EAAuB,iBAAiB,EAAE,MAAM,WAAW,CAAC;AACnH,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAEpE,8DAA8D;AAC9D,MAAM,4CAA4C,GAAsC;IACpF,wBAAwB,EAAE,IAAI;IAC9B,oBAAoB,EAAE,KAAK;IAC3B,2BAA2B,EAAE,GAAG;IAChC,UAAU,EAAE,CAAC;CAChB,CAAC;AAEF,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAC1C,YACoB,IAAwB,EACxC,OAA2B;QAE3B,KAAK,CAAC,0BAA0B,OAAO,EAAE,CAAC,CAAC;QAH3B,SAAI,GAAJ,IAAI,CAAoB;IAI5C,CAAC;CACJ;AAkGD;;;;GAIG;AACH,MAAM,OAAO,6BAA6B;IAqBtC,YAAY,GAAQ,EAAE,IAA2C;QATzD,0BAAqB,GAAG,KAAK,CAA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IAAI,GAAG;gBACT,GAAG,IAAI,CAAC,YAAY;gBACpB,MAAM,EAAE,QAAQ;gBAChB,OAAO;gBACP,MAAM,EAAE,IAAI,CAAC,gBAAgB,EAAE,MAAM;aACxC,CAAC;YAEF,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAC/D,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC;YAE9B,wEAAwE;YACxE,mEAAmE;YACnE,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;gBAC1C,MAAM,IAAI,mBAAmB,CAAC,QAAQ,CAAC,MAAM,EAAE,gCAAgC,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;YAC1G,CAAC;YAED,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAChC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,CAAC,OAAO,EAAE,CAAC,KAAc,CAAC,CAAC;YAC/B,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC;IAED,kBAAkB,CAAC,OAAe;QAC9B,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IACpC,CAAC;IACD,IAAI,eAAe;QACf,OAAO,IAAI,CAAC,gBAAgB,CAAC;IACjC,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,YAAY,CAAC,WAAmB,EAAE,OAAyD;QAC7F,MAAM,IAAI,CAAC,eAAe,CAAC;YACvB,eAAe,EAAE,WAAW;YAC5B,iBAAiB,EAAE,OAAO,EAAE,iBAAiB;SAChD,CAAC,CAAC;IACP,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.d.ts new file mode 100644 index 000000000..78f95de3b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.d.ts @@ -0,0 +1,17 @@ +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +/** + * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. + */ +export declare class WebSocketClientTransport implements Transport { + private _socket?; + private _url; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(url: URL); + start(): Promise; + close(): Promise; + send(message: JSONRPCMessage): Promise; +} +//# sourceMappingURL=websocket.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.d.ts.map new file mode 100644 index 000000000..2882d9822 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAInE;;GAEG;AACH,qBAAa,wBAAyB,YAAW,SAAS;IACtD,OAAO,CAAC,OAAO,CAAC,CAAY;IAC5B,OAAO,CAAC,IAAI,CAAM;IAElB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG;IAIpB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAsChB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAW/C"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.js new file mode 100644 index 000000000..1325e46b4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.js @@ -0,0 +1,54 @@ +import { JSONRPCMessageSchema } from '../types.js'; +const SUBPROTOCOL = 'mcp'; +/** + * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. + */ +export class WebSocketClientTransport { + constructor(url) { + this._url = url; + } + start() { + if (this._socket) { + throw new Error('WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return new Promise((resolve, reject) => { + this._socket = new WebSocket(this._url, SUBPROTOCOL); + this._socket.onerror = event => { + const error = 'error' in event ? event.error : new Error(`WebSocket error: ${JSON.stringify(event)}`); + reject(error); + this.onerror?.(error); + }; + this._socket.onopen = () => { + resolve(); + }; + this._socket.onclose = () => { + this.onclose?.(); + }; + this._socket.onmessage = (event) => { + let message; + try { + message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); + } + catch (error) { + this.onerror?.(error); + return; + } + this.onmessage?.(message); + }; + }); + } + async close() { + this._socket?.close(); + } + send(message) { + return new Promise((resolve, reject) => { + if (!this._socket) { + reject(new Error('Not connected')); + return; + } + this._socket?.send(JSON.stringify(message)); + resolve(); + }); + } +} +//# sourceMappingURL=websocket.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.js.map new file mode 100644 index 000000000..bd2ed86dd --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.js","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":"AACA,OAAO,EAAkB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnE,MAAM,WAAW,GAAG,KAAK,CAAC;AAE1B;;GAEG;AACH,MAAM,OAAO,w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C/B,OAAO;gBACX,CAAC;gBAED,IAAI,CAAC,SAAS,EAAE,CAAC,OAAO,CAAC,CAAC;YAC9B,CAAC,CAAC;QACN,CAAC,CAAC,CAAC;IACP,CAAC;IAED,KAAK,CAAC,KAAK;QACP,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,CAAC;IAC1B,CAAC;IAED,IAAI,CAAC,OAAuB;QACxB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACnC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;gBAChB,MAAM,CAAC,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC;gBACnC,OAAO;YACX,CAAC;YAED,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;YAC5C,OAAO,EAAE,CAAC;QACd,CAAC,CAAC,CAAC;IACP,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/elicitationUrlExample.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/elicitationUrlExample.d.ts new file mode 100644 index 000000000..611f6eba2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/elicitationUrlExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=elicitationUrlExample.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/elicitationUrlExample.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/elicitationUrlExample.d.ts.map new file mode 100644 index 000000000..e749adfb9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/elicitationUrlExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/elicitationUrlExample.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/elicitationUrlExample.js new file mode 100644 index 000000000..aa99e12c5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/elicitationUrlExample.js @@ -0,0 +1,690 @@ +// Run with: npx tsx src/examples/client/elicitationUrlExample.ts +// +// This example demonstrates how to use URL elicitation to securely +// collect user input in a remote (HTTP) server. +// URL elicitation allows servers to prompt the end-user to open a URL in their browser +// to collect sensitive information. +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { createInterface } from 'node:readline'; +import { ListToolsResultSchema, CallToolResultSchema, ElicitRequestSchema, McpError, ErrorCode, UrlElicitationRequiredError, ElicitationCompleteNotificationSchema } from '../../types.js'; +import { getDisplayName } from '../../shared/metadataUtils.js'; +import { exec } from 'node:child_process'; +import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider.js'; +import { UnauthorizedError } from '../../client/auth.js'; +import { createServer } from 'node:http'; +// Set up OAuth (required for this example) +const OAUTH_CALLBACK_PORT = 8090; // Use different port than auth server (3001) +const OAUTH_CALLBACK_URL = `http://localhost:${OAUTH_CALLBACK_PORT}/callback`; +let oauthProvider = undefined; +console.log('Getting OAuth token...'); +const clientMetadata = { + client_name: 'Elicitation MCP Client', + redirect_uris: [OAUTH_CALLBACK_URL], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'client_secret_post', + scope: 'mcp:tools' +}; +oauthProvider = new InMemoryOAuthClientProvider(OAUTH_CALLBACK_URL, clientMetadata, (redirectUrl) => { + console.log(`🌐 Opening browser for OAuth redirect: ${redirectUrl.toString()}`); + openBrowser(redirectUrl.toString()); +}); +// Create readline interface for user input +const readline = createInterface({ + input: process.stdin, + output: process.stdout +}); +let abortCommand = new AbortController(); +// Global client and transport for interactive commands +let client = null; +let transport = null; +let serverUrl = 'http://localhost:3000/mcp'; +let sessionId = undefined; +let isProcessingCommand = false; +let isProcessingElicitations = false; +const elicitationQueue = []; +let elicitationQueueSignal = null; +let elicitationsCompleteSignal = null; +// Map to track pending URL elicitations waiting for completion notifications +const pendingURLElicitations = new Map(); +async function main() { + console.log('MCP Interactive Client'); + console.log('====================='); + // Connect to server immediately with default settings + await connect(); + // Start the elicitation loop in the background + elicitationLoop().catch(error => { + console.error('Unexpected error in elicitation loop:', error); + process.exit(1); + }); + // Short delay allowing the server to send any SSE elicitations on connection + await new Promise(resolve => setTimeout(resolve, 200)); + // Wait until we are done processing any initial elicitations + await waitForElicitationsToComplete(); + // Print help and start the command loop + printHelp(); + await commandLoop(); +} +async function waitForElicitationsToComplete() { + // Wait until the queue is empty and nothing is being processed + while (elicitationQueue.length > 0 || isProcessingElicitations) { + await new Promise(resolve => setTimeout(resolve, 100)); + } +} +function printHelp() { + console.log('\nAvailable commands:'); + console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); + console.log(' disconnect - Disconnect from server'); + console.log(' terminate-session - Terminate the current session'); + console.log(' reconnect - Reconnect to the server'); + console.log(' list-tools - List available tools'); + console.log(' call-tool [args] - Call a tool with optional JSON arguments'); + console.log(' payment-confirm - Test URL elicitation via error response with payment-confirm tool'); + console.log(' third-party-auth - Test tool that requires third-party OAuth credentials'); + console.log(' help - Show this help'); + console.log(' quit - Exit the program'); +} +async function commandLoop() { + await new Promise(resolve => { + if (!isProcessingElicitations) { + resolve(); + } + else { + elicitationsCompleteSignal = resolve; + } + }); + readline.question('\n> ', { signal: abortCommand.signal }, async (input) => { + isProcessingCommand = true; + const args = input.trim().split(/\s+/); + const command = args[0]?.toLowerCase(); + try { + switch (command) { + case 'connect': + await connect(args[1]); + break; + case 'disconnect': + await disconnect(); + break; + case 'terminate-session': + await terminateSession(); + break; + case 'reconnect': + await reconnect(); + break; + case 'list-tools': + await listTools(); + break; + case 'call-tool': + if (args.length < 2) { + console.log('Usage: call-tool [args]'); + } + else { + const toolName = args[1]; + let toolArgs = {}; + if (args.length > 2) { + try { + toolArgs = JSON.parse(args.slice(2).join(' ')); + } + catch { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await callTool(toolName, toolArgs); + } + break; + case 'payment-confirm': + await callPaymentConfirmTool(); + break; + case 'third-party-auth': + await callThirdPartyAuthTool(); + break; + case 'help': + printHelp(); + break; + case 'quit': + case 'exit': + await cleanup(); + return; + default: + if (command) { + console.log(`Unknown command: ${command}`); + } + break; + } + } + catch (error) { + console.error(`Error executing command: ${error}`); + } + finally { + isProcessingCommand = false; + } + // Process another command after we've processed the this one + await commandLoop(); + }); +} +async function elicitationLoop() { + while (true) { + // Wait until we have elicitations to process + await new Promise(resolve => { + if (elicitationQueue.length > 0) { + resolve(); + } + else { + elicitationQueueSignal = resolve; + } + }); + isProcessingElicitations = true; + abortCommand.abort(); // Abort the command loop if it's running + // Process all queued elicitations + while (elicitationQueue.length > 0) { + const queued = elicitationQueue.shift(); + console.log(`📤 Processing queued elicitation (${elicitationQueue.length} remaining)`); + try { + const result = await handleElicitationRequest(queued.request); + queued.resolve(result); + } + catch (error) { + queued.reject(error instanceof Error ? error : new Error(String(error))); + } + } + console.log('✅ All queued elicitations processed. Resuming command loop...\n'); + isProcessingElicitations = false; + // Reset the abort controller for the next command loop + abortCommand = new AbortController(); + // Resume the command loop + if (elicitationsCompleteSignal) { + elicitationsCompleteSignal(); + elicitationsCompleteSignal = null; + } + } +} +async function openBrowser(url) { + const command = `open "${url}"`; + exec(command, error => { + if (error) { + console.error(`Failed to open browser: ${error.message}`); + console.log(`Please manually open: ${url}`); + } + }); +} +/** + * Enqueues an elicitation request and returns the result. + * + * This function is used so that our CLI (which can only handle one input request at a time) + * can handle elicitation requests and the command loop. + * + * @param request - The elicitation request to be handled + * @returns The elicitation result + */ +async function elicitationRequestHandler(request) { + // If we are processing a command, handle this elicitation immediately + if (isProcessingCommand) { + console.log('📋 Processing elicitation immediately (during command execution)'); + return await handleElicitationRequest(request); + } + // Otherwise, queue the request to be handled by the elicitation loop + console.log(`📥 Queueing elicitation request (queue size will be: ${elicitationQueue.length + 1})`); + return new Promise((resolve, reject) => { + elicitationQueue.push({ + request, + resolve, + reject + }); + // Signal the elicitation loop that there's work to do + if (elicitationQueueSignal) { + elicitationQueueSignal(); + elicitationQueueSignal = null; + } + }); +} +/** + * Handles an elicitation request. + * + * This function is used to handle the elicitation request and return the result. + * + * @param request - The elicitation request to be handled + * @returns The elicitation result + */ +async function handleElicitationRequest(request) { + const mode = request.params.mode; + console.log('\n🔔 Elicitation Request Received:'); + console.log(`Mode: ${mode}`); + if (mode === 'url') { + return { + action: await handleURLElicitation(request.params) + }; + } + else { + // Should not happen because the client declares its capabilities to the server, + // but being defensive is a good practice: + throw new McpError(ErrorCode.InvalidParams, `Unsupported elicitation mode: ${mode}`); + } +} +/** + * Handles a URL elicitation by opening the URL in the browser. + * + * Note: This is a shared code for both request handlers and error handlers. + * As a result of sharing schema, there is no big forking of logic for the client. + * + * @param params - The URL elicitation request parameters + * @returns The action to take (accept, cancel, or decline) + */ +async function handleURLElicitation(params) { + const url = params.url; + const elicitationId = params.elicitationId; + const message = params.message; + console.log(`🆔 Elicitation ID: ${elicitationId}`); // Print for illustration + // Parse URL to show domain for security + let domain = 'unknown domain'; + try { + const parsedUrl = new URL(url); + domain = parsedUrl.hostname; + } + catch { + console.error('Invalid URL provided by server'); + return 'decline'; + } + // Example security warning to help prevent phishing attacks + console.log('\n⚠️ \x1b[33mSECURITY WARNING\x1b[0m ⚠️'); + console.log('\x1b[33mThe server is requesting you to open an external URL.\x1b[0m'); + console.log('\x1b[33mOnly proceed if you trust this server and understand why it needs this.\x1b[0m\n'); + console.log(`🌐 Target domain: \x1b[36m${domain}\x1b[0m`); + console.log(`🔗 Full URL: \x1b[36m${url}\x1b[0m`); + console.log(`\nℹ️ Server's reason:\n\n\x1b[36m${message}\x1b[0m\n`); + // 1. Ask for user consent to open the URL + const consent = await new Promise(resolve => { + readline.question('\nDo you want to open this URL in your browser? (y/n): ', input => { + resolve(input.trim().toLowerCase()); + }); + }); + // 2. If user did not consent, return appropriate result + if (consent === 'no' || consent === 'n') { + console.log('❌ URL navigation declined.'); + return 'decline'; + } + else if (consent !== 'yes' && consent !== 'y') { + console.log('🚫 Invalid response. Cancelling elicitation.'); + return 'cancel'; + } + // 3. Wait for completion notification in the background + const completionPromise = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + pendingURLElicitations.delete(elicitationId); + console.log(`\x1b[31m❌ Elicitation ${elicitationId} timed out waiting for completion.\x1b[0m`); + reject(new Error('Elicitation completion timeout')); + }, 5 * 60 * 1000); // 5 minute timeout + pendingURLElicitations.set(elicitationId, { + resolve: () => { + clearTimeout(timeout); + resolve(); + }, + reject, + timeout + }); + }); + completionPromise.catch(error => { + console.error('Background completion wait failed:', error); + }); + // 4. Open the URL in the browser + console.log(`\n🚀 Opening browser to: ${url}`); + await openBrowser(url); + console.log('\n⏳ Waiting for you to complete the interaction in your browser...'); + console.log(' The server will send a notification once you complete the action.'); + // 5. Acknowledge the user accepted the elicitation + return 'accept'; +} +/** + * Example OAuth callback handler - in production, use a more robust approach + * for handling callbacks and storing tokens + */ +/** + * Starts a temporary HTTP server to receive the OAuth callback + */ +async function waitForOAuthCallback() { + return new Promise((resolve, reject) => { + const server = createServer((req, res) => { + // Ignore favicon requests + if (req.url === '/favicon.ico') { + res.writeHead(404); + res.end(); + return; + } + console.log(`📥 Received callback: ${req.url}`); + const parsedUrl = new URL(req.url || '', 'http://localhost'); + const code = parsedUrl.searchParams.get('code'); + const error = parsedUrl.searchParams.get('error'); + if (code) { + console.log(`✅ Authorization code received: ${code?.substring(0, 10)}...`); + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Successful!

+

This simulates successful authorization of the MCP client, which now has an access token for the MCP server.

+

This window will close automatically in 10 seconds.

+ + + + `); + resolve(code); + setTimeout(() => server.close(), 15000); + } + else if (error) { + console.log(`❌ Authorization error: ${error}`); + res.writeHead(400, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Failed

+

Error: ${error}

+ + + `); + reject(new Error(`OAuth authorization failed: ${error}`)); + } + else { + console.log(`❌ No authorization code or error in callback`); + res.writeHead(400); + res.end('Bad request'); + reject(new Error('No authorization code provided')); + } + }); + server.listen(OAUTH_CALLBACK_PORT, () => { + console.log(`OAuth callback server started on http://localhost:${OAUTH_CALLBACK_PORT}`); + }); + }); +} +/** + * Attempts to connect to the MCP server with OAuth authentication. + * Handles OAuth flow recursively if authorization is required. + */ +async function attemptConnection(oauthProvider) { + console.log('🚢 Creating transport with OAuth provider...'); + const baseUrl = new URL(serverUrl); + transport = new StreamableHTTPClientTransport(baseUrl, { + sessionId: sessionId, + authProvider: oauthProvider + }); + console.log('🚢 Transport created'); + try { + console.log('🔌 Attempting connection (this will trigger OAuth redirect if needed)...'); + await client.connect(transport); + sessionId = transport.sessionId; + console.log('Transport created with session ID:', sessionId); + console.log('✅ Connected successfully'); + } + catch (error) { + if (error instanceof UnauthorizedError) { + console.log('🔐 OAuth required - waiting for authorization...'); + const callbackPromise = waitForOAuthCallback(); + const authCode = await callbackPromise; + await transport.finishAuth(authCode); + console.log('🔐 Authorization code received:', authCode); + console.log('🔌 Reconnecting with authenticated transport...'); + // Recursively retry connection after OAuth completion + await attemptConnection(oauthProvider); + } + else { + console.error('❌ Connection failed with non-auth error:', error); + throw error; + } + } +} +async function connect(url) { + if (client) { + console.log('Already connected. Disconnect first.'); + return; + } + if (url) { + serverUrl = url; + } + console.log(`🔗 Attempting to connect to ${serverUrl}...`); + // Create a new client with elicitation capability + console.log('👤 Creating MCP client...'); + client = new Client({ + name: 'example-client', + version: '1.0.0' + }, { + capabilities: { + elicitation: { + // Only URL elicitation is supported in this demo + // (see server/elicitationExample.ts for a demo of form mode elicitation) + url: {} + } + } + }); + console.log('👤 Client created'); + // Set up elicitation request handler with proper validation + client.setRequestHandler(ElicitRequestSchema, elicitationRequestHandler); + // Set up notification handler for elicitation completion + client.setNotificationHandler(ElicitationCompleteNotificationSchema, notification => { + const { elicitationId } = notification.params; + const pending = pendingURLElicitations.get(elicitationId); + if (pending) { + clearTimeout(pending.timeout); + pendingURLElicitations.delete(elicitationId); + console.log(`\x1b[32m✅ Elicitation ${elicitationId} completed!\x1b[0m`); + pending.resolve(); + } + else { + // Shouldn't happen - discard it! + console.warn(`Received completion notification for unknown elicitation: ${elicitationId}`); + } + }); + try { + console.log('🔐 Starting OAuth flow...'); + await attemptConnection(oauthProvider); + console.log('Connected to MCP server'); + // Set up error handler after connection is established so we don't double log errors + client.onerror = error => { + console.error('\x1b[31mClient error:', error, '\x1b[0m'); + }; + } + catch (error) { + console.error('Failed to connect:', error); + client = null; + transport = null; + return; + } +} +async function disconnect() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + await transport.close(); + console.log('Disconnected from MCP server'); + client = null; + transport = null; + } + catch (error) { + console.error('Error disconnecting:', error); + } +} +async function terminateSession() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + console.log('Terminating session with ID:', transport.sessionId); + await transport.terminateSession(); + console.log('Session terminated successfully'); + // Check if sessionId was cleared after termination + if (!transport.sessionId) { + console.log('Session ID has been cleared'); + sessionId = undefined; + // Also close the transport and clear client objects + await transport.close(); + console.log('Transport closed after session termination'); + client = null; + transport = null; + } + else { + console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); + console.log('Session ID is still active:', transport.sessionId); + } + } + catch (error) { + console.error('Error terminating session:', error); + } +} +async function reconnect() { + if (client) { + await disconnect(); + } + await connect(); +} +async function listTools() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - id: ${tool.name}, name: ${getDisplayName(tool)}, description: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server (${error})`); + } +} +async function callTool(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const request = { + method: 'tools/call', + params: { + name, + arguments: args + } + }; + console.log(`Calling tool '${name}' with args:`, args); + const result = await client.request(request, CallToolResultSchema); + console.log('Tool result:'); + const resourceLinks = []; + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else if (item.type === 'resource_link') { + const resourceLink = item; + resourceLinks.push(resourceLink); + console.log(` 📁 Resource Link: ${resourceLink.name}`); + console.log(` URI: ${resourceLink.uri}`); + if (resourceLink.mimeType) { + console.log(` Type: ${resourceLink.mimeType}`); + } + if (resourceLink.description) { + console.log(` Description: ${resourceLink.description}`); + } + } + else if (item.type === 'resource') { + console.log(` [Embedded Resource: ${item.resource.uri}]`); + } + else if (item.type === 'image') { + console.log(` [Image: ${item.mimeType}]`); + } + else if (item.type === 'audio') { + console.log(` [Audio: ${item.mimeType}]`); + } + else { + console.log(` [Unknown content type]:`, item); + } + }); + // Offer to read resource links + if (resourceLinks.length > 0) { + console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); + } + } + catch (error) { + if (error instanceof UrlElicitationRequiredError) { + console.log('\n🔔 Elicitation Required Error Received:'); + console.log(`Message: ${error.message}`); + for (const e of error.elicitations) { + await handleURLElicitation(e); // For the error handler, we discard the action result because we don't respond to an error response + } + return; + } + console.log(`Error calling tool ${name}: ${error}`); + } +} +async function cleanup() { + if (client && transport) { + try { + // First try to terminate the session gracefully + if (transport.sessionId) { + try { + console.log('Terminating session before exit...'); + await transport.terminateSession(); + console.log('Session terminated successfully'); + } + catch (error) { + console.error('Error terminating session:', error); + } + } + // Then close the transport + await transport.close(); + } + catch (error) { + console.error('Error closing transport:', error); + } + } + process.stdin.setRawMode(false); + readline.close(); + console.log('\nGoodbye!'); + process.exit(0); +} +async function callPaymentConfirmTool() { + console.log('Calling payment-confirm tool...'); + await callTool('payment-confirm', { cartId: 'cart_123' }); +} +async function callThirdPartyAuthTool() { + console.log('Calling third-party-auth tool...'); + await callTool('third-party-auth', { param1: 'test' }); +} +// Set up raw mode for keyboard input to capture Escape key +process.stdin.setRawMode(true); +process.stdin.on('data', async (data) => { + // Check for Escape key (27) + if (data.length === 1 && data[0] === 27) { + console.log('\nESC key pressed. Disconnecting from server...'); + // Abort current operation and disconnect from server + if (client && transport) { + await disconnect(); + console.log('Disconnected. Press Enter to continue.'); + } + else { + console.log('Not connected to server.'); + } + // Re-display the prompt + process.stdout.write('> '); + } +}); +// Handle Ctrl+C +process.on('SIGINT', async () => { + console.log('\nReceived SIGINT. Cleaning up...'); + await cleanup(); +}); +// Start the interactive client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=elicitationUrlExample.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/elicitationUrlExample.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/elicitationUrlExample.js.map new file mode 100644 index 000000000..f221fbe3c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/elicitationUrlExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.js","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,EAAE;AACF,mEAAmE;AACnE,gDAAgD;AAChD,uFAAuF;AACvF,oCAAoC;AAEpC,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAEH,qBAAqB,EAErB,oBAAoB,EACpB,mBAAmB,EAKnB,QAAQ,EACR,SAAS,EACT,2BAA2B,EAC3B,qCAAqC,EACxC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;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,GAAG,CAAC,mCAAmC,CAAC,CAAC;IACjD,MAAM,OAAO,EAAE,CAAC;AACpB,CAAC,CAAC,CAAC;AAEH,+BAA+B;AAC/B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/multipleClientsParallel.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/multipleClientsParallel.d.ts new file mode 100644 index 000000000..0ac5af8e5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/multipleClientsParallel.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=multipleClientsParallel.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/multipleClientsParallel.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/multipleClientsParallel.d.ts.map new file mode 100644 index 000000000..91051dc94 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/multipleClientsParallel.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"multipleClientsParallel.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/multipleClientsParallel.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/multipleClientsParallel.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/multipleClientsParallel.js new file mode 100644 index 000000000..426485673 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/multipleClientsParallel.js @@ -0,0 +1,132 @@ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { CallToolResultSchema, LoggingMessageNotificationSchema } from '../../types.js'; +/** + * Multiple Clients MCP Example + * + * This client demonstrates how to: + * 1. Create multiple MCP clients in parallel + * 2. Each client calls a single tool + * 3. Track notifications from each client independently + */ +// Command line args processing +const args = process.argv.slice(2); +const serverUrl = args[0] || 'http://localhost:3000/mcp'; +async function createAndRunClient(config) { + console.log(`[${config.id}] Creating client: ${config.name}`); + const client = new Client({ + name: config.name, + version: '1.0.0' + }); + const transport = new StreamableHTTPClientTransport(new URL(serverUrl)); + // Set up client-specific error handler + client.onerror = error => { + console.error(`[${config.id}] Client error:`, error); + }; + // Set up client-specific notification handler + client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { + console.log(`[${config.id}] Notification: ${notification.params.data}`); + }); + try { + // Connect to the server + await client.connect(transport); + console.log(`[${config.id}] Connected to MCP server`); + // Call the specified tool + console.log(`[${config.id}] Calling tool: ${config.toolName}`); + const toolRequest = { + method: 'tools/call', + params: { + name: config.toolName, + arguments: { + ...config.toolArguments, + // Add client ID to arguments for identification in notifications + caller: config.id + } + } + }; + const result = await client.request(toolRequest, CallToolResultSchema); + console.log(`[${config.id}] Tool call completed`); + // Keep the connection open for a bit to receive notifications + await new Promise(resolve => setTimeout(resolve, 5000)); + // Disconnect + await transport.close(); + console.log(`[${config.id}] Disconnected from MCP server`); + return { id: config.id, result }; + } + catch (error) { + console.error(`[${config.id}] Error:`, error); + throw error; + } +} +async function main() { + console.log('MCP Multiple Clients Example'); + console.log('============================'); + console.log(`Server URL: ${serverUrl}`); + console.log(''); + try { + // Define client configurations + const clientConfigs = [ + { + id: 'client1', + name: 'basic-client-1', + toolName: 'start-notification-stream', + toolArguments: { + interval: 3, // 1 second between notifications + count: 5 // Send 5 notifications + } + }, + { + id: 'client2', + name: 'basic-client-2', + toolName: 'start-notification-stream', + toolArguments: { + interval: 2, // 2 seconds between notifications + count: 3 // Send 3 notifications + } + }, + { + id: 'client3', + name: 'basic-client-3', + toolName: 'start-notification-stream', + toolArguments: { + interval: 1, // 0.5 second between notifications + count: 8 // Send 8 notifications + } + } + ]; + // Start all clients in parallel + console.log(`Starting ${clientConfigs.length} clients in parallel...`); + console.log(''); + const clientPromises = clientConfigs.map(config => createAndRunClient(config)); + const results = await Promise.all(clientPromises); + // Display results from all clients + console.log('\n=== Final Results ==='); + results.forEach(({ id, result }) => { + console.log(`\n[${id}] Tool result:`); + if (Array.isArray(result.content)) { + result.content.forEach((item) => { + if (item.type === 'text' && item.text) { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + else { + console.log(` Unexpected result format:`, result); + } + }); + console.log('\n=== All clients completed successfully ==='); + } + catch (error) { + console.error('Error running multiple clients:', error); + process.exit(1); + } +} +// Start the example +main().catch((error) => { + console.error('Error running MCP multiple clients example:', error); + process.exit(1); +}); +//# sourceMappingURL=multipleClientsParallel.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/multipleClientsParallel.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/multipleClientsParallel.js.map new file mode 100644 index 000000000..d02ce2280 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/multipleClientsParallel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"multipleClientsParallel.js","sourceRoot":"","sources":["../../../../src/examples/client/multipleClientsParallel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAmB,oBAAoB,EAAE,gCAAgC,EAAkB,MAAM,gBAAgB,CAAC;AAEzH;;;;;;;GAOG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AASzD,KAAK,UAAU,kBAAkB,CAAC,M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BACjD,CAAC;gBACL,CAAC,CAAC,CAAC;YACP,CAAC;iBAAM,CAAC;gBACJ,OAAO,CAAC,GAAG,CAAC,6BAA6B,EAAE,MAAM,CAAC,CAAC;YACvD,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,GAAG,CAAC,8CAA8C,CAAC,CAAC;IAChE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;QACxD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACL,CAAC;AAED,oBAAoB;AACpB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,CAAC,CAAC;IACpE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/parallelToolCallsClient.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/parallelToolCallsClient.d.ts new file mode 100644 index 000000000..e93d4d69d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/parallelToolCallsClient.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=parallelToolCallsClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/parallelToolCallsClient.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/parallelToolCallsClient.d.ts.map new file mode 100644 index 000000000..25a3b820c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/parallelToolCallsClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parallelToolCallsClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/parallelToolCallsClient.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/parallelToolCallsClient.js new file mode 100644 index 000000000..9d2a2e915 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/parallelToolCallsClient.js @@ -0,0 +1,174 @@ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { ListToolsResultSchema, CallToolResultSchema, LoggingMessageNotificationSchema } from '../../types.js'; +/** + * Parallel Tool Calls MCP Client + * + * This client demonstrates how to: + * 1. Start multiple tool calls in parallel + * 2. Track notifications from each tool call using a caller parameter + */ +// Command line args processing +const args = process.argv.slice(2); +const serverUrl = args[0] || 'http://localhost:3000/mcp'; +async function main() { + console.log('MCP Parallel Tool Calls Client'); + console.log('=============================='); + console.log(`Connecting to server at: ${serverUrl}`); + let client; + let transport; + try { + // Create client with streamable HTTP transport + client = new Client({ + name: 'parallel-tool-calls-client', + version: '1.0.0' + }); + client.onerror = error => { + console.error('Client error:', error); + }; + // Connect to the server + transport = new StreamableHTTPClientTransport(new URL(serverUrl)); + await client.connect(transport); + console.log('Successfully connected to MCP server'); + // Set up notification handler with caller identification + client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { + console.log(`Notification: ${notification.params.data}`); + }); + console.log('List tools'); + const toolsRequest = await listTools(client); + console.log('Tools: ', toolsRequest); + // 2. Start multiple notification tools in parallel + console.log('\n=== Starting Multiple Notification Streams in Parallel ==='); + const toolResults = await startParallelNotificationTools(client); + // Log the results from each tool call + for (const [caller, result] of Object.entries(toolResults)) { + console.log(`\n=== Tool result for ${caller} ===`); + result.content.forEach((item) => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + // 3. Wait for all notifications (10 seconds) + console.log('\n=== Waiting for all notifications ==='); + await new Promise(resolve => setTimeout(resolve, 10000)); + // 4. Disconnect + console.log('\n=== Disconnecting ==='); + await transport.close(); + console.log('Disconnected from MCP server'); + } + catch (error) { + console.error('Error running client:', error); + process.exit(1); + } +} +/** + * List available tools on the server + */ +async function listTools(client) { + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - ${tool.name}: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server: ${error}`); + } +} +/** + * Start multiple notification tools in parallel with different configurations + * Each tool call includes a caller parameter to identify its notifications + */ +async function startParallelNotificationTools(client) { + try { + // Define multiple tool calls with different configurations + const toolCalls = [ + { + caller: 'fast-notifier', + request: { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 2, // 0.5 second between notifications + count: 10, // Send 10 notifications + caller: 'fast-notifier' // Identify this tool call + } + } + } + }, + { + caller: 'slow-notifier', + request: { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 5, // 2 seconds between notifications + count: 5, // Send 5 notifications + caller: 'slow-notifier' // Identify this tool call + } + } + } + }, + { + caller: 'burst-notifier', + request: { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 1, // 0.1 second between notifications + count: 3, // Send just 3 notifications + caller: 'burst-notifier' // Identify this tool call + } + } + } + } + ]; + console.log(`Starting ${toolCalls.length} notification tools in parallel...`); + // Start all tool calls in parallel + const toolPromises = toolCalls.map(({ caller, request }) => { + console.log(`Starting tool call for ${caller}...`); + return client + .request(request, CallToolResultSchema) + .then(result => ({ caller, result })) + .catch(error => { + console.error(`Error in tool call for ${caller}:`, error); + throw error; + }); + }); + // Wait for all tool calls to complete + const results = await Promise.all(toolPromises); + // Organize results by caller + const resultsByTool = {}; + results.forEach(({ caller, result }) => { + resultsByTool[caller] = result; + }); + return resultsByTool; + } + catch (error) { + console.error(`Error starting parallel notification tools:`, error); + throw error; + } +} +// Start the client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=parallelToolCallsClient.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/parallelToolCallsClient.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/parallelToolCallsClient.js.map new file mode 100644 index 000000000..0a044818e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/parallelToolCallsClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parallelToolCallsClient.js","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAEH,qBAAqB,EACrB,oBAAoB,EACpB,gCAAgC,EAEnC,MAAM,gBAAgB,CAAC;AAExB;;;;;;GAMG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AAEzD,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,4BAA4B,SAAS,EAAE,CAAC,CAAC;IAErD,IAAI,MAAc,CAAC;IACnB,IAAI,SAAwC,CAAC;IAE7C,IAAI,CAAC;QACD,+CAA+C;QAC/C,MAAM,GAAG,IAAI,MAAM,CAAC;YAChB,IAAI,EAAE,4BAA4B;YAClC,OAAO,EAAE,OAAO;SACnB,CAAC,CAAC;QAEH,MAAM,CAAC,OAAO,GAAG,KAAK,CAAC,EAAE;YACrB,OAAO,CAA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vD,OAAO,CAAC,GAAG,CAAC,0BAA0B,MAAM,KAAK,CAAC,CAAC;YACnD,OAAO,MAAM;iBACR,OAAO,CAAC,OAAO,EAAE,oBAAoB,CAAC;iBACtC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;iBACpC,KAAK,CAAC,KAAK,CAAC,EAAE;gBACX,OAAO,CAAC,KAAK,CAAC,0BAA0B,MAAM,GAAG,EAAE,KAAK,CAAC,CAAC;gBAC1D,MAAM,KAAK,CAAC;YAChB,CAAC,CAAC,CAAC;QACX,CAAC,CAAC,CAAC;QAEH,sCAAsC;QACtC,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QAEhD,6BAA6B;QAC7B,MAAM,aAAa,GAAmC,EAAE,CAAC;QACzD,OAAO,CAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE;YACnC,aAAa,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;QACnC,CAAC,CAAC,CAAC;QAEH,OAAO,aAAa,CAAC;IACzB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,CAAC,CAAC;QACpE,MAAM,KAAK,CAAC;IAChB,CAAC;AACL,CAAC;AAED,mBAAmB;AACnB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleClientCredentials.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleClientCredentials.d.ts new file mode 100644 index 000000000..876d25d3a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleClientCredentials.d.ts @@ -0,0 +1,20 @@ +#!/usr/bin/env node +/** + * Example demonstrating client_credentials grant for machine-to-machine authentication. + * + * Supports two authentication methods based on environment variables: + * + * 1. client_secret_basic (default): + * MCP_CLIENT_ID - OAuth client ID (required) + * MCP_CLIENT_SECRET - OAuth client secret (required) + * + * 2. private_key_jwt (when MCP_CLIENT_PRIVATE_KEY_PEM is set): + * MCP_CLIENT_ID - OAuth client ID (required) + * MCP_CLIENT_PRIVATE_KEY_PEM - PEM-encoded private key for JWT signing (required) + * MCP_CLIENT_ALGORITHM - Signing algorithm (default: RS256) + * + * Common: + * MCP_SERVER_URL - Server URL (default: http://localhost:3000/mcp) + */ +export {}; +//# sourceMappingURL=simpleClientCredentials.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleClientCredentials.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleClientCredentials.d.ts.map new file mode 100644 index 000000000..7a935db41 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleClientCredentials.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleClientCredentials.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleClientCredentials.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;;;;;GAgBG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleClientCredentials.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleClientCredentials.js new file mode 100644 index 000000000..7694badfa --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleClientCredentials.js @@ -0,0 +1,68 @@ +#!/usr/bin/env node +/** + * Example demonstrating client_credentials grant for machine-to-machine authentication. + * + * Supports two authentication methods based on environment variables: + * + * 1. client_secret_basic (default): + * MCP_CLIENT_ID - OAuth client ID (required) + * MCP_CLIENT_SECRET - OAuth client secret (required) + * + * 2. private_key_jwt (when MCP_CLIENT_PRIVATE_KEY_PEM is set): + * MCP_CLIENT_ID - OAuth client ID (required) + * MCP_CLIENT_PRIVATE_KEY_PEM - PEM-encoded private key for JWT signing (required) + * MCP_CLIENT_ALGORITHM - Signing algorithm (default: RS256) + * + * Common: + * MCP_SERVER_URL - Server URL (default: http://localhost:3000/mcp) + */ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { ClientCredentialsProvider, PrivateKeyJwtProvider } from '../../client/auth-extensions.js'; +const DEFAULT_SERVER_URL = process.env.MCP_SERVER_URL || 'http://localhost:3000/mcp'; +function createProvider() { + const clientId = process.env.MCP_CLIENT_ID; + if (!clientId) { + console.error('MCP_CLIENT_ID environment variable is required'); + process.exit(1); + } + // If private key is provided, use private_key_jwt authentication + const privateKeyPem = process.env.MCP_CLIENT_PRIVATE_KEY_PEM; + if (privateKeyPem) { + const algorithm = process.env.MCP_CLIENT_ALGORITHM || 'RS256'; + console.log('Using private_key_jwt authentication'); + return new PrivateKeyJwtProvider({ + clientId, + privateKey: privateKeyPem, + algorithm + }); + } + // Otherwise, use client_secret_basic authentication + const clientSecret = process.env.MCP_CLIENT_SECRET; + if (!clientSecret) { + console.error('MCP_CLIENT_SECRET or MCP_CLIENT_PRIVATE_KEY_PEM environment variable is required'); + process.exit(1); + } + console.log('Using client_secret_basic authentication'); + return new ClientCredentialsProvider({ + clientId, + clientSecret + }); +} +async function main() { + const provider = createProvider(); + const client = new Client({ name: 'client-credentials-example', version: '1.0.0' }, { capabilities: {} }); + const transport = new StreamableHTTPClientTransport(new URL(DEFAULT_SERVER_URL), { + authProvider: provider + }); + await client.connect(transport); + console.log('Connected successfully.'); + const tools = await client.listTools(); + console.log('Available tools:', tools.tools.map(t => t.name).join(', ') || '(none)'); + await transport.close(); +} +main().catch(err => { + console.error(err); + process.exit(1); +}); +//# sourceMappingURL=simpleClientCredentials.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleClientCredentials.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleClientCredentials.js.map new file mode 100644 index 000000000..f6e7e2117 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleClientCredentials.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleClientCredentials.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleClientCredentials.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,yBAAyB,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAGnG,MAAM,kBAAkB,GAAG,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,2BAA2B,CAAC;AAErF,SAAS,cAAc;IACnB,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;IAC3C,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,OAAO,CAAC,KAAK,CAAC,gDAAgD,CAAC,CAAC;QAChE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IAED,iEAAiE;IACjE,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC;IAC7D,IAAI,aAAa,EAAE,CAAC;QAChB,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,oBAAoB,IAAI,OAAO,CAAC;QAC9D,OAAO,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;QACpD,OAAO,IAAI,qBAAqB,CAAC;YAC7B,QAAQ;YACR,UAAU,EAAE,aAAa;YACzB,SAAS;SACZ,CAAC,CAAC;IACP,CAAC;IAED,oDAAoD;IACpD,MAAM,YAAY,GAAG,OAAO,CAA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newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClient.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClient.d.ts new file mode 100644 index 000000000..e4b43dbc0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClient.d.ts @@ -0,0 +1,3 @@ +#!/usr/bin/env node +export {}; +//# sourceMappingURL=simpleOAuthClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClient.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClient.d.ts.map new file mode 100644 index 000000000..c09eef86e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClient.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClient.js new file mode 100644 index 000000000..c723097be --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClient.js @@ -0,0 +1,411 @@ +#!/usr/bin/env node +import { createServer } from 'node:http'; +import { createInterface } from 'node:readline'; +import { URL } from 'node:url'; +import { exec } from 'node:child_process'; +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { CallToolResultSchema, ListToolsResultSchema } from '../../types.js'; +import { UnauthorizedError } from '../../client/auth.js'; +import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider.js'; +// Configuration +const DEFAULT_SERVER_URL = 'http://localhost:3000/mcp'; +const CALLBACK_PORT = 8090; // Use different port than auth server (3001) +const CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`; +/** + * Interactive MCP client with OAuth authentication + * Demonstrates the complete OAuth flow with browser-based authorization + */ +class InteractiveOAuthClient { + constructor(serverUrl, clientMetadataUrl) { + this.serverUrl = serverUrl; + this.clientMetadataUrl = clientMetadataUrl; + this.client = null; + this.rl = createInterface({ + input: process.stdin, + output: process.stdout + }); + } + /** + * Prompts user for input via readline + */ + async question(query) { + return new Promise(resolve => { + this.rl.question(query, resolve); + }); + } + /** + * Opens the authorization URL in the user's default browser + */ + async openBrowser(url) { + console.log(`🌐 Opening browser for authorization: ${url}`); + const command = `open "${url}"`; + exec(command, error => { + if (error) { + console.error(`Failed to open browser: ${error.message}`); + console.log(`Please manually open: ${url}`); + } + }); + } + /** + * Example OAuth callback handler - in production, use a more robust approach + * for handling callbacks and storing tokens + */ + /** + * Starts a temporary HTTP server to receive the OAuth callback + */ + async waitForOAuthCallback() { + return new Promise((resolve, reject) => { + const server = createServer((req, res) => { + // Ignore favicon requests + if (req.url === '/favicon.ico') { + res.writeHead(404); + res.end(); + return; + } + console.log(`📥 Received callback: ${req.url}`); + const parsedUrl = new URL(req.url || '', 'http://localhost'); + const code = parsedUrl.searchParams.get('code'); + const error = parsedUrl.searchParams.get('error'); + if (code) { + console.log(`✅ Authorization code received: ${code?.substring(0, 10)}...`); + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Successful!

+

You can close this window and return to the terminal.

+ + + + `); + resolve(code); + setTimeout(() => server.close(), 3000); + } + else if (error) { + console.log(`❌ Authorization error: ${error}`); + res.writeHead(400, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Failed

+

Error: ${error}

+ + + `); + reject(new Error(`OAuth authorization failed: ${error}`)); + } + else { + console.log(`❌ No authorization code or error in callback`); + res.writeHead(400); + res.end('Bad request'); + reject(new Error('No authorization code provided')); + } + }); + server.listen(CALLBACK_PORT, () => { + console.log(`OAuth callback server started on http://localhost:${CALLBACK_PORT}`); + }); + }); + } + async attemptConnection(oauthProvider) { + console.log('🚢 Creating transport with OAuth provider...'); + const baseUrl = new URL(this.serverUrl); + const transport = new StreamableHTTPClientTransport(baseUrl, { + authProvider: oauthProvider + }); + console.log('🚢 Transport created'); + try { + console.log('🔌 Attempting connection (this will trigger OAuth redirect)...'); + await this.client.connect(transport); + console.log('✅ Connected successfully'); + } + catch (error) { + if (error instanceof UnauthorizedError) { + console.log('🔐 OAuth required - waiting for authorization...'); + const callbackPromise = this.waitForOAuthCallback(); + const authCode = await callbackPromise; + await transport.finishAuth(authCode); + console.log('🔐 Authorization code received:', authCode); + console.log('🔌 Reconnecting with authenticated transport...'); + await this.attemptConnection(oauthProvider); + } + else { + console.error('❌ Connection failed with non-auth error:', error); + throw error; + } + } + } + /** + * Establishes connection to the MCP server with OAuth authentication + */ + async connect() { + console.log(`🔗 Attempting to connect to ${this.serverUrl}...`); + const clientMetadata = { + client_name: 'Simple OAuth MCP Client', + redirect_uris: [CALLBACK_URL], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'client_secret_post' + }; + console.log('🔐 Creating OAuth provider...'); + const oauthProvider = new InMemoryOAuthClientProvider(CALLBACK_URL, clientMetadata, (redirectUrl) => { + console.log(`📌 OAuth redirect handler called - opening browser`); + console.log(`Opening browser to: ${redirectUrl.toString()}`); + this.openBrowser(redirectUrl.toString()); + }, this.clientMetadataUrl); + console.log('🔐 OAuth provider created'); + console.log('👤 Creating MCP client...'); + this.client = new Client({ + name: 'simple-oauth-client', + version: '1.0.0' + }, { capabilities: {} }); + console.log('👤 Client created'); + console.log('🔐 Starting OAuth flow...'); + await this.attemptConnection(oauthProvider); + // Start interactive loop + await this.interactiveLoop(); + } + /** + * Main interactive loop for user commands + */ + async interactiveLoop() { + console.log('\n🎯 Interactive MCP Client with OAuth'); + console.log('Commands:'); + console.log(' list - List available tools'); + console.log(' call [args] - Call a tool'); + console.log(' stream [args] - Call a tool with streaming (shows task status)'); + console.log(' quit - Exit the client'); + console.log(); + while (true) { + try { + const command = await this.question('mcp> '); + if (!command.trim()) { + continue; + } + if (command === 'quit') { + console.log('\n👋 Goodbye!'); + this.close(); + process.exit(0); + } + else if (command === 'list') { + await this.listTools(); + } + else if (command.startsWith('call ')) { + await this.handleCallTool(command); + } + else if (command.startsWith('stream ')) { + await this.handleStreamTool(command); + } + else { + console.log("❌ Unknown command. Try 'list', 'call ', 'stream ', or 'quit'"); + } + } + catch (error) { + if (error instanceof Error && error.message === 'SIGINT') { + console.log('\n\n👋 Goodbye!'); + break; + } + console.error('❌ Error:', error); + } + } + } + async listTools() { + if (!this.client) { + console.log('❌ Not connected to server'); + return; + } + try { + const request = { + method: 'tools/list', + params: {} + }; + const result = await this.client.request(request, ListToolsResultSchema); + if (result.tools && result.tools.length > 0) { + console.log('\n📋 Available tools:'); + result.tools.forEach((tool, index) => { + console.log(`${index + 1}. ${tool.name}`); + if (tool.description) { + console.log(` Description: ${tool.description}`); + } + console.log(); + }); + } + else { + console.log('No tools available'); + } + } + catch (error) { + console.error('❌ Failed to list tools:', error); + } + } + async handleCallTool(command) { + const parts = command.split(/\s+/); + const toolName = parts[1]; + if (!toolName) { + console.log('❌ Please specify a tool name'); + return; + } + // Parse arguments (simple JSON-like format) + let toolArgs = {}; + if (parts.length > 2) { + const argsString = parts.slice(2).join(' '); + try { + toolArgs = JSON.parse(argsString); + } + catch { + console.log('❌ Invalid arguments format (expected JSON)'); + return; + } + } + await this.callTool(toolName, toolArgs); + } + async callTool(toolName, toolArgs) { + if (!this.client) { + console.log('❌ Not connected to server'); + return; + } + try { + const request = { + method: 'tools/call', + params: { + name: toolName, + arguments: toolArgs + } + }; + const result = await this.client.request(request, CallToolResultSchema); + console.log(`\n🔧 Tool '${toolName}' result:`); + if (result.content) { + result.content.forEach(content => { + if (content.type === 'text') { + console.log(content.text); + } + else { + console.log(content); + } + }); + } + else { + console.log(result); + } + } + catch (error) { + console.error(`❌ Failed to call tool '${toolName}':`, error); + } + } + async handleStreamTool(command) { + const parts = command.split(/\s+/); + const toolName = parts[1]; + if (!toolName) { + console.log('❌ Please specify a tool name'); + return; + } + // Parse arguments (simple JSON-like format) + let toolArgs = {}; + if (parts.length > 2) { + const argsString = parts.slice(2).join(' '); + try { + toolArgs = JSON.parse(argsString); + } + catch { + console.log('❌ Invalid arguments format (expected JSON)'); + return; + } + } + await this.streamTool(toolName, toolArgs); + } + async streamTool(toolName, toolArgs) { + if (!this.client) { + console.log('❌ Not connected to server'); + return; + } + try { + // Using the experimental tasks API - WARNING: may change without notice + console.log(`\n🔧 Streaming tool '${toolName}'...`); + const stream = this.client.experimental.tasks.callToolStream({ + name: toolName, + arguments: toolArgs + }, CallToolResultSchema, { + task: { + taskId: `task-${Date.now()}`, + ttl: 60000 + } + }); + // Iterate through all messages yielded by the generator + for await (const message of stream) { + switch (message.type) { + case 'taskCreated': + console.log(`✓ Task created: ${message.task.taskId}`); + break; + case 'taskStatus': + console.log(`⟳ Status: ${message.task.status}`); + if (message.task.statusMessage) { + console.log(` ${message.task.statusMessage}`); + } + break; + case 'result': + console.log('✓ Completed!'); + message.result.content.forEach(content => { + if (content.type === 'text') { + console.log(content.text); + } + else { + console.log(content); + } + }); + break; + case 'error': + console.log('✗ Error:'); + console.log(` ${message.error.message}`); + break; + } + } + } + catch (error) { + console.error(`❌ Failed to stream tool '${toolName}':`, error); + } + } + close() { + this.rl.close(); + if (this.client) { + // Note: Client doesn't have a close method in the current implementation + // This would typically close the transport connection + } + } +} +/** + * Main entry point + */ +async function main() { + const args = process.argv.slice(2); + const serverUrl = args[0] || DEFAULT_SERVER_URL; + const clientMetadataUrl = args[1]; + console.log('🚀 Simple MCP OAuth Client'); + console.log(`Connecting to: ${serverUrl}`); + if (clientMetadataUrl) { + console.log(`Client Metadata URL: ${clientMetadataUrl}`); + } + console.log(); + const client = new InteractiveOAuthClient(serverUrl, clientMetadataUrl); + // Handle graceful shutdown + process.on('SIGINT', () => { + console.log('\n\n👋 Goodbye!'); + client.close(); + process.exit(0); + }); + try { + await client.connect(); + } + catch (error) { + console.error('Failed to start client:', error); + process.exit(1); + } + finally { + client.close(); + } +} +// Run if this file is executed directly +main().catch(error => { + console.error('Unhandled error:', error); + process.exit(1); +}); +//# sourceMappingURL=simpleOAuthClient.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClient.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClient.js.map new file mode 100644 index 000000000..b6470b669 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClient.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAE/E,OAAO,EAAqC,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAChH,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAE7E,gBAAgB;AAChB,MAAM,kBAAkB,GAAG,2BAA2B,CAAC;AACvD,MAAM,aAAa,GAAG,IAAI,CAAC,CAAC,6CAA6C;AACzE,MAAM,YAAY,GAAG,oBAAoB,aAAa,WAAW,CAAC;AAElE;;;GAGG;AACH,MAAM,sBAAsB;IAOxB,YACY,SAAiB,EACjB,iBAA0B;QAD1B,cAAS,GAAT,SAAS,CAAQ;QACjB,sBAAiB,GAAjB,iBAAiB,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AAC,CAAC,CAAC,CAAC;IAElC,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,kBAAkB,SAAS,EAAE,CAAC,CAAC;IAC3C,IAAI,iBAAiB,EAAE,CAAC;QACpB,OAAO,CAAC,GAAG,CAAC,wBAAwB,iBAAiB,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,CAAC,GAAG,EAAE,CAAC;IAEd,MAAM,MAAM,GAAG,IAAI,sBAAsB,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;IAExE,2BAA2B;IAC3B,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;QACtB,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC;QACD,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;YAAS,CAAC;QACP,MAAM,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;AACL,CAAC;AAED,wCAAwC;AACxC,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;IACzC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClientProvider.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClientProvider.d.ts new file mode 100644 index 000000000..092616cf5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClientProvider.d.ts @@ -0,0 +1,26 @@ +import { OAuthClientProvider } from '../../client/auth.js'; +import { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from '../../shared/auth.js'; +/** + * In-memory OAuth client provider for demonstration purposes + * In production, you should persist tokens securely + */ +export declare class InMemoryOAuthClientProvider implements OAuthClientProvider { + private readonly _redirectUrl; + private readonly _clientMetadata; + readonly clientMetadataUrl?: string | undefined; + private _clientInformation?; + private _tokens?; + private _codeVerifier?; + constructor(_redirectUrl: string | URL, _clientMetadata: OAuthClientMetadata, onRedirect?: (url: URL) => void, clientMetadataUrl?: string | undefined); + private _onRedirect; + get redirectUrl(): string | URL; + get clientMetadata(): OAuthClientMetadata; + clientInformation(): OAuthClientInformationMixed | undefined; + saveClientInformation(clientInformation: OAuthClientInformationMixed): void; + tokens(): OAuthTokens | undefined; + saveTokens(tokens: OAuthTokens): void; + redirectToAuthorization(authorizationUrl: URL): void; + saveCodeVerifier(codeVerifier: string): void; + codeVerifier(): string; +} +//# sourceMappingURL=simpleOAuthClientProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClientProvider.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClientProvider.d.ts.map new file mode 100644 index 000000000..21efe9444 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClientProvider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClientProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAErG;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IAM/D,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,eAAe;aAEhB,iBAAiB,CAAC,EAAE,MAAM;IAR9C,OAAO,CAAC,kBAAkB,CAAC,CAA8B;IACzD,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,aAAa,CAAC,CAAS;gBAGV,YAAY,EAAE,MAAM,GAAG,GAAG,EAC1B,eAAe,EAAE,mBAAmB,EACrD,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,EACf,iBAAiB,CAAC,EAAE,MAAM,YAAA;IAS9C,OAAO,CAAC,WAAW,CAAqB;IAExC,IAAI,WAAW,IAAI,MAAM,GAAG,GAAG,CAE9B;IAED,IAAI,cAAc,IAAI,mBAAmB,CAExC;IAED,iBAAiB,IAAI,2BAA2B,GAAG,SAAS;IAI5D,qBAAqB,CAAC,iBAAiB,EAAE,2BAA2B,GAAG,IAAI;IAI3E,MAAM,IAAI,WAAW,GAAG,SAAS;IAIjC,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI;IAIrC,uBAAuB,CAAC,gBAAgB,EAAE,GAAG,GAAG,IAAI;IAIpD,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI;IAI5C,YAAY,IAAI,MAAM;CAMzB"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClientProvider.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClientProvider.js new file mode 100644 index 000000000..7c350d131 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClientProvider.js @@ -0,0 +1,47 @@ +/** + * In-memory OAuth client provider for demonstration purposes + * In production, you should persist tokens securely + */ +export class InMemoryOAuthClientProvider { + constructor(_redirectUrl, _clientMetadata, onRedirect, clientMetadataUrl) { + this._redirectUrl = _redirectUrl; + this._clientMetadata = _clientMetadata; + this.clientMetadataUrl = clientMetadataUrl; + this._onRedirect = + onRedirect || + (url => { + console.log(`Redirect to: ${url.toString()}`); + }); + } + get redirectUrl() { + return this._redirectUrl; + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInformation; + } + saveClientInformation(clientInformation) { + this._clientInformation = clientInformation; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization(authorizationUrl) { + this._onRedirect(authorizationUrl); + } + saveCodeVerifier(codeVerifier) { + this._codeVerifier = codeVerifier; + } + codeVerifier() { + if (!this._codeVerifier) { + throw new Error('No code verifier saved'); + } + return this._codeVerifier; + } +} +//# sourceMappingURL=simpleOAuthClientProvider.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClientProvider.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClientProvider.js.map new file mode 100644 index 000000000..88f15cde5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleOAuthClientProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClientProvider.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,MAAM,OAAO,2BAA2B;IAKpC,YACqB,YAA0B,EAC1B,eAAoC,EACrD,UAA+B,EACf,iBAA0B;QAHzB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,oBAAe,GAAf,eAAe,CAAqB;QAErC,sBAAiB,GAAjB,iBAAiB,CAAS;QAE1C,IAAI,CAAC,WAAW;YACZ,UAAU;gBACV,CAAC,GAAG,CAAC,EAAE;oBACH,OAAO,CAAC,GAAG,CAAC,gBAAgB,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;gBAClD,CAAC,CAAC,CAAC;IACX,CAAC;IAID,IAAI,WAAW;QACX,OAAO,IAAI,CAAC,YAAY,CAAC;IAC7B,CAAC;IAED,IAAI,cAAc;QACd,OAAO,IAAI,CAAC,eAAe,CAAC;IAChC,CAAC;IAED,iBAAiB;QACb,OAAO,IAAI,CAAC,kBAAkB,CAAC;IACnC,CAAC;IAED,qBAAqB,CAAC,iBAA8C;QAChE,IAAI,CAAC,kBAAkB,GAAG,iBAAiB,CAAC;IAChD,CAAC;IAED,MAAM;QACF,OAAO,IAAI,CAAC,OAAO,CAAC;IACxB,CAAC;IAED,UAAU,CAAC,MAAmB;QAC1B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAED,uBAAuB,CAAC,gBAAqB;QACzC,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;IACvC,CAAC;IAED,gBAAgB,CAAC,YAAoB;QACjC,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;IACtC,CAAC;IAED,YAAY;QACR,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC;IAC9B,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.d.ts new file mode 100644 index 000000000..a20be42ca --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.d.ts.map new file mode 100644 index 000000000..28406b0c1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.js new file mode 100644 index 000000000..2ece6a4e4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.js @@ -0,0 +1,816 @@ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { createInterface } from 'node:readline'; +import { ListToolsResultSchema, CallToolResultSchema, ListPromptsResultSchema, GetPromptResultSchema, ListResourcesResultSchema, LoggingMessageNotificationSchema, ResourceListChangedNotificationSchema, ElicitRequestSchema, ReadResourceResultSchema, RELATED_TASK_META_KEY, ErrorCode, McpError } from '../../types.js'; +import { getDisplayName } from '../../shared/metadataUtils.js'; +import { Ajv } from 'ajv'; +// Create readline interface for user input +const readline = createInterface({ + input: process.stdin, + output: process.stdout +}); +// Track received notifications for debugging resumability +let notificationCount = 0; +// Global client and transport for interactive commands +let client = null; +let transport = null; +let serverUrl = 'http://localhost:3000/mcp'; +let notificationsToolLastEventId = undefined; +let sessionId = undefined; +async function main() { + console.log('MCP Interactive Client'); + console.log('====================='); + // Connect to server immediately with default settings + await connect(); + // Print help and start the command loop + printHelp(); + commandLoop(); +} +function printHelp() { + console.log('\nAvailable commands:'); + console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); + console.log(' disconnect - Disconnect from server'); + console.log(' terminate-session - Terminate the current session'); + console.log(' reconnect - Reconnect to the server'); + console.log(' list-tools - List available tools'); + console.log(' call-tool [args] - Call a tool with optional JSON arguments'); + console.log(' call-tool-task [args] - Call a tool with task-based execution (example: call-tool-task delay {"duration":3000})'); + console.log(' greet [name] - Call the greet tool'); + console.log(' multi-greet [name] - Call the multi-greet tool with notifications'); + console.log(' collect-info [type] - Test form elicitation with collect-user-info tool (contact/preferences/feedback)'); + console.log(' start-notifications [interval] [count] - Start periodic notifications'); + console.log(' run-notifications-tool-with-resumability [interval] [count] - Run notification tool with resumability'); + console.log(' list-prompts - List available prompts'); + console.log(' get-prompt [name] [args] - Get a prompt with optional JSON arguments'); + console.log(' list-resources - List available resources'); + console.log(' read-resource - Read a specific resource by URI'); + console.log(' help - Show this help'); + console.log(' quit - Exit the program'); +} +function commandLoop() { + readline.question('\n> ', async (input) => { + const args = input.trim().split(/\s+/); + const command = args[0]?.toLowerCase(); + try { + switch (command) { + case 'connect': + await connect(args[1]); + break; + case 'disconnect': + await disconnect(); + break; + case 'terminate-session': + await terminateSession(); + break; + case 'reconnect': + await reconnect(); + break; + case 'list-tools': + await listTools(); + break; + case 'call-tool': + if (args.length < 2) { + console.log('Usage: call-tool [args]'); + } + else { + const toolName = args[1]; + let toolArgs = {}; + if (args.length > 2) { + try { + toolArgs = JSON.parse(args.slice(2).join(' ')); + } + catch { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await callTool(toolName, toolArgs); + } + break; + case 'greet': + await callGreetTool(args[1] || 'MCP User'); + break; + case 'multi-greet': + await callMultiGreetTool(args[1] || 'MCP User'); + break; + case 'collect-info': + await callCollectInfoTool(args[1] || 'contact'); + break; + case 'start-notifications': { + const interval = args[1] ? parseInt(args[1], 10) : 2000; + const count = args[2] ? parseInt(args[2], 10) : 10; + await startNotifications(interval, count); + break; + } + case 'run-notifications-tool-with-resumability': { + const interval = args[1] ? parseInt(args[1], 10) : 2000; + const count = args[2] ? parseInt(args[2], 10) : 10; + await runNotificationsToolWithResumability(interval, count); + break; + } + case 'call-tool-task': + if (args.length < 2) { + console.log('Usage: call-tool-task [args]'); + } + else { + const toolName = args[1]; + let toolArgs = {}; + if (args.length > 2) { + try { + toolArgs = JSON.parse(args.slice(2).join(' ')); + } + catch { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await callToolTask(toolName, toolArgs); + } + break; + case 'list-prompts': + await listPrompts(); + break; + case 'get-prompt': + if (args.length < 2) { + console.log('Usage: get-prompt [args]'); + } + else { + const promptName = args[1]; + let promptArgs = {}; + if (args.length > 2) { + try { + promptArgs = JSON.parse(args.slice(2).join(' ')); + } + catch { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await getPrompt(promptName, promptArgs); + } + break; + case 'list-resources': + await listResources(); + break; + case 'read-resource': + if (args.length < 2) { + console.log('Usage: read-resource '); + } + else { + await readResource(args[1]); + } + break; + case 'help': + printHelp(); + break; + case 'quit': + case 'exit': + await cleanup(); + return; + default: + if (command) { + console.log(`Unknown command: ${command}`); + } + break; + } + } + catch (error) { + console.error(`Error executing command: ${error}`); + } + // Continue the command loop + commandLoop(); + }); +} +async function connect(url) { + if (client) { + console.log('Already connected. Disconnect first.'); + return; + } + if (url) { + serverUrl = url; + } + console.log(`Connecting to ${serverUrl}...`); + try { + // Create a new client with form elicitation capability + client = new Client({ + name: 'example-client', + version: '1.0.0' + }, { + capabilities: { + elicitation: { + form: {} + } + } + }); + client.onerror = error => { + console.error('\x1b[31mClient error:', error, '\x1b[0m'); + }; + // Set up elicitation request handler with proper validation + client.setRequestHandler(ElicitRequestSchema, async (request) => { + if (request.params.mode !== 'form') { + throw new McpError(ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`); + } + console.log('\n🔔 Elicitation (form) Request Received:'); + console.log(`Message: ${request.params.message}`); + console.log(`Related Task: ${request.params._meta?.[RELATED_TASK_META_KEY]?.taskId}`); + console.log('Requested Schema:'); + console.log(JSON.stringify(request.params.requestedSchema, null, 2)); + const schema = request.params.requestedSchema; + const properties = schema.properties; + const required = schema.required || []; + // Set up AJV validator for the requested schema + const ajv = new Ajv(); + const validate = ajv.compile(schema); + let attempts = 0; + const maxAttempts = 3; + while (attempts < maxAttempts) { + attempts++; + console.log(`\nPlease provide the following information (attempt ${attempts}/${maxAttempts}):`); + const content = {}; + let inputCancelled = false; + // Collect input for each field + for (const [fieldName, fieldSchema] of Object.entries(properties)) { + const field = fieldSchema; + const isRequired = required.includes(fieldName); + let prompt = `${field.title || fieldName}`; + // Add helpful information to the prompt + if (field.description) { + prompt += ` (${field.description})`; + } + if (field.enum) { + prompt += ` [options: ${field.enum.join(', ')}]`; + } + if (field.type === 'number' || field.type === 'integer') { + if (field.minimum !== undefined && field.maximum !== undefined) { + prompt += ` [${field.minimum}-${field.maximum}]`; + } + else if (field.minimum !== undefined) { + prompt += ` [min: ${field.minimum}]`; + } + else if (field.maximum !== undefined) { + prompt += ` [max: ${field.maximum}]`; + } + } + if (field.type === 'string' && field.format) { + prompt += ` [format: ${field.format}]`; + } + if (isRequired) { + prompt += ' *required*'; + } + if (field.default !== undefined) { + prompt += ` [default: ${field.default}]`; + } + prompt += ': '; + const answer = await new Promise(resolve => { + readline.question(prompt, input => { + resolve(input.trim()); + }); + }); + // Check for cancellation + if (answer.toLowerCase() === 'cancel' || answer.toLowerCase() === 'c') { + inputCancelled = true; + break; + } + // Parse and validate the input + try { + if (answer === '' && field.default !== undefined) { + content[fieldName] = field.default; + } + else if (answer === '' && !isRequired) { + // Skip optional empty fields + continue; + } + else if (answer === '') { + throw new Error(`${fieldName} is required`); + } + else { + // Parse the value based on type + let parsedValue; + if (field.type === 'boolean') { + parsedValue = answer.toLowerCase() === 'true' || answer.toLowerCase() === 'yes' || answer === '1'; + } + else if (field.type === 'number') { + parsedValue = parseFloat(answer); + if (isNaN(parsedValue)) { + throw new Error(`${fieldName} must be a valid number`); + } + } + else if (field.type === 'integer') { + parsedValue = parseInt(answer, 10); + if (isNaN(parsedValue)) { + throw new Error(`${fieldName} must be a valid integer`); + } + } + else if (field.enum) { + if (!field.enum.includes(answer)) { + throw new Error(`${fieldName} must be one of: ${field.enum.join(', ')}`); + } + parsedValue = answer; + } + else { + parsedValue = answer; + } + content[fieldName] = parsedValue; + } + } + catch (error) { + console.log(`❌ Error: ${error}`); + // Continue to next attempt + break; + } + } + if (inputCancelled) { + return { action: 'cancel' }; + } + // If we didn't complete all fields due to an error, try again + if (Object.keys(content).length !== + Object.keys(properties).filter(name => required.includes(name) || content[name] !== undefined).length) { + if (attempts < maxAttempts) { + console.log('Please try again...'); + continue; + } + else { + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + } + } + // Validate the complete object against the schema + const isValid = validate(content); + if (!isValid) { + console.log('❌ Validation errors:'); + validate.errors?.forEach(error => { + console.log(` - ${error.instancePath || 'root'}: ${error.message}`); + }); + if (attempts < maxAttempts) { + console.log('Please correct the errors and try again...'); + continue; + } + else { + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + } + } + // Show the collected data and ask for confirmation + console.log('\n✅ Collected data:'); + console.log(JSON.stringify(content, null, 2)); + const confirmAnswer = await new Promise(resolve => { + readline.question('\nSubmit this information? (yes/no/cancel): ', input => { + resolve(input.trim().toLowerCase()); + }); + }); + if (confirmAnswer === 'yes' || confirmAnswer === 'y') { + return { + action: 'accept', + content + }; + } + else if (confirmAnswer === 'cancel' || confirmAnswer === 'c') { + return { action: 'cancel' }; + } + else if (confirmAnswer === 'no' || confirmAnswer === 'n') { + if (attempts < maxAttempts) { + console.log('Please re-enter the information...'); + continue; + } + else { + return { action: 'decline' }; + } + } + } + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + }); + transport = new StreamableHTTPClientTransport(new URL(serverUrl), { + sessionId: sessionId + }); + // Set up notification handlers + client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { + notificationCount++; + console.log(`\nNotification #${notificationCount}: ${notification.params.level} - ${notification.params.data}`); + // Re-display the prompt + process.stdout.write('> '); + }); + client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_) => { + console.log(`\nResource list changed notification received!`); + try { + if (!client) { + console.log('Client disconnected, cannot fetch resources'); + return; + } + const resourcesResult = await client.request({ + method: 'resources/list', + params: {} + }, ListResourcesResultSchema); + console.log('Available resources count:', resourcesResult.resources.length); + } + catch { + console.log('Failed to list resources after change notification'); + } + // Re-display the prompt + process.stdout.write('> '); + }); + // Connect the client + await client.connect(transport); + sessionId = transport.sessionId; + console.log('Transport created with session ID:', sessionId); + console.log('Connected to MCP server'); + } + catch (error) { + console.error('Failed to connect:', error); + client = null; + transport = null; + } +} +async function disconnect() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + await transport.close(); + console.log('Disconnected from MCP server'); + client = null; + transport = null; + } + catch (error) { + console.error('Error disconnecting:', error); + } +} +async function terminateSession() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + console.log('Terminating session with ID:', transport.sessionId); + await transport.terminateSession(); + console.log('Session terminated successfully'); + // Check if sessionId was cleared after termination + if (!transport.sessionId) { + console.log('Session ID has been cleared'); + sessionId = undefined; + // Also close the transport and clear client objects + await transport.close(); + console.log('Transport closed after session termination'); + client = null; + transport = null; + } + else { + console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); + console.log('Session ID is still active:', transport.sessionId); + } + } + catch (error) { + console.error('Error terminating session:', error); + } +} +async function reconnect() { + if (client) { + await disconnect(); + } + await connect(); +} +async function listTools() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - id: ${tool.name}, name: ${getDisplayName(tool)}, description: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server (${error})`); + } +} +async function callTool(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const request = { + method: 'tools/call', + params: { + name, + arguments: args + } + }; + console.log(`Calling tool '${name}' with args:`, args); + const result = await client.request(request, CallToolResultSchema); + console.log('Tool result:'); + const resourceLinks = []; + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else if (item.type === 'resource_link') { + const resourceLink = item; + resourceLinks.push(resourceLink); + console.log(` 📁 Resource Link: ${resourceLink.name}`); + console.log(` URI: ${resourceLink.uri}`); + if (resourceLink.mimeType) { + console.log(` Type: ${resourceLink.mimeType}`); + } + if (resourceLink.description) { + console.log(` Description: ${resourceLink.description}`); + } + } + else if (item.type === 'resource') { + console.log(` [Embedded Resource: ${item.resource.uri}]`); + } + else if (item.type === 'image') { + console.log(` [Image: ${item.mimeType}]`); + } + else if (item.type === 'audio') { + console.log(` [Audio: ${item.mimeType}]`); + } + else { + console.log(` [Unknown content type]:`, item); + } + }); + // Offer to read resource links + if (resourceLinks.length > 0) { + console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); + } + } + catch (error) { + console.log(`Error calling tool ${name}: ${error}`); + } +} +async function callGreetTool(name) { + await callTool('greet', { name }); +} +async function callMultiGreetTool(name) { + console.log('Calling multi-greet tool with notifications...'); + await callTool('multi-greet', { name }); +} +async function callCollectInfoTool(infoType) { + console.log(`Testing form elicitation with collect-user-info tool (${infoType})...`); + await callTool('collect-user-info', { infoType }); +} +async function startNotifications(interval, count) { + console.log(`Starting notification stream: interval=${interval}ms, count=${count || 'unlimited'}`); + await callTool('start-notification-stream', { interval, count }); +} +async function runNotificationsToolWithResumability(interval, count) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + console.log(`Starting notification stream with resumability: interval=${interval}ms, count=${count || 'unlimited'}`); + console.log(`Using resumption token: ${notificationsToolLastEventId || 'none'}`); + const request = { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { interval, count } + } + }; + const onLastEventIdUpdate = (event) => { + notificationsToolLastEventId = event; + console.log(`Updated resumption token: ${event}`); + }; + const result = await client.request(request, CallToolResultSchema, { + resumptionToken: notificationsToolLastEventId, + onresumptiontoken: onLastEventIdUpdate + }); + console.log('Tool result:'); + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + catch (error) { + console.log(`Error starting notification stream: ${error}`); + } +} +async function listPrompts() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const promptsRequest = { + method: 'prompts/list', + params: {} + }; + const promptsResult = await client.request(promptsRequest, ListPromptsResultSchema); + console.log('Available prompts:'); + if (promptsResult.prompts.length === 0) { + console.log(' No prompts available'); + } + else { + for (const prompt of promptsResult.prompts) { + console.log(` - id: ${prompt.name}, name: ${getDisplayName(prompt)}, description: ${prompt.description}`); + } + } + } + catch (error) { + console.log(`Prompts not supported by this server (${error})`); + } +} +async function getPrompt(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const promptRequest = { + method: 'prompts/get', + params: { + name, + arguments: args + } + }; + const promptResult = await client.request(promptRequest, GetPromptResultSchema); + console.log('Prompt template:'); + promptResult.messages.forEach((msg, index) => { + console.log(` [${index + 1}] ${msg.role}: ${msg.content.type === 'text' ? msg.content.text : JSON.stringify(msg.content)}`); + }); + } + catch (error) { + console.log(`Error getting prompt ${name}: ${error}`); + } +} +async function listResources() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const resourcesRequest = { + method: 'resources/list', + params: {} + }; + const resourcesResult = await client.request(resourcesRequest, ListResourcesResultSchema); + console.log('Available resources:'); + if (resourcesResult.resources.length === 0) { + console.log(' No resources available'); + } + else { + for (const resource of resourcesResult.resources) { + console.log(` - id: ${resource.name}, name: ${getDisplayName(resource)}, description: ${resource.uri}`); + } + } + } + catch (error) { + console.log(`Resources not supported by this server (${error})`); + } +} +async function readResource(uri) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const request = { + method: 'resources/read', + params: { uri } + }; + console.log(`Reading resource: ${uri}`); + const result = await client.request(request, ReadResourceResultSchema); + console.log('Resource contents:'); + for (const content of result.contents) { + console.log(` URI: ${content.uri}`); + if (content.mimeType) { + console.log(` Type: ${content.mimeType}`); + } + if ('text' in content && typeof content.text === 'string') { + console.log(' Content:'); + console.log(' ---'); + console.log(content.text + .split('\n') + .map((line) => ' ' + line) + .join('\n')); + console.log(' ---'); + } + else if ('blob' in content && typeof content.blob === 'string') { + console.log(` [Binary data: ${content.blob.length} bytes]`); + } + } + } + catch (error) { + console.log(`Error reading resource ${uri}: ${error}`); + } +} +async function callToolTask(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + console.log(`Calling tool '${name}' with task-based execution...`); + console.log('Arguments:', args); + // Use task-based execution - call now, fetch later + // Using the experimental tasks API - WARNING: may change without notice + console.log('This will return immediately while processing continues in the background...'); + try { + // Call the tool with task metadata using streaming API + const stream = client.experimental.tasks.callToolStream({ + name, + arguments: args + }, CallToolResultSchema, { + task: { + ttl: 60000 // Keep results for 60 seconds + } + }); + console.log('Waiting for task completion...'); + let lastStatus = ''; + for await (const message of stream) { + switch (message.type) { + case 'taskCreated': + console.log('Task created successfully with ID:', message.task.taskId); + break; + case 'taskStatus': + if (lastStatus !== message.task.status) { + console.log(` ${message.task.status}${message.task.statusMessage ? ` - ${message.task.statusMessage}` : ''}`); + } + lastStatus = message.task.status; + break; + case 'result': + console.log('Task completed!'); + console.log('Tool result:'); + message.result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + }); + break; + case 'error': + throw message.error; + } + } + } + catch (error) { + console.log(`Error with task-based execution: ${error}`); + } +} +async function cleanup() { + if (client && transport) { + try { + // First try to terminate the session gracefully + if (transport.sessionId) { + try { + console.log('Terminating session before exit...'); + await transport.terminateSession(); + console.log('Session terminated successfully'); + } + catch (error) { + console.error('Error terminating session:', error); + } + } + // Then close the transport + await transport.close(); + } + catch (error) { + console.error('Error closing transport:', error); + } + } + process.stdin.setRawMode(false); + readline.close(); + console.log('\nGoodbye!'); + process.exit(0); +} +// Set up raw mode for keyboard input to capture Escape key +process.stdin.setRawMode(true); +process.stdin.on('data', async (data) => { + // Check for Escape key (27) + if (data.length === 1 && data[0] === 27) { + console.log('\nESC key pressed. Disconnecting from server...'); + // Abort current operation and disconnect from server + if (client && transport) { + await disconnect(); + console.log('Disconnected. Press Enter to continue.'); + } + else { + console.log('Not connected to server.'); + } + // Re-display the prompt + process.stdout.write('> '); + } +}); +// Handle Ctrl+C +process.on('SIGINT', async () => { + console.log('\nReceived SIGINT. Cleaning up...'); + await cleanup(); +}); +// Start the interactive client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=simpleStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.js.map new file mode 100644 index 000000000..c9a780d55 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAEH,qBAAqB,EAErB,oBAAoB,EAEpB,uBAAuB,EAEvB,qBAAqB,EAErB,yBAAyB,EACzB,gCAAgC,EAChC,qCAAqC,EACrC,mBAAmB,EAGnB,wBAAwB,EACxB,qBAAqB,EACrB,SAAS,EACT,QAAQ,EACX,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE1B,2CAA2C;AAC3C,MAAM,QAAQ,GAAG,eAAe,CAAC;IAC7B,KAAK,EAAE,OAAO,CAAC,KAAK;IACpB,MAAM,EAAE,OAAO,CAAC,MAAM;CACzB,CAAC,CAAC;AAEH,0DAA0D;AAC1D,IAAI,iBAAiB,GAAG,CAAC,CAA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AC,IAAI,CAAC,CAAC;IAC/B,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,gBAAgB;AAChB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;IACjD,MAAM,OAAO,EAAE,CAAC;AACpB,CAAC,CAAC,CAAC;AAEH,+BAA+B;AAC/B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleTaskInteractiveClient.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleTaskInteractiveClient.d.ts new file mode 100644 index 000000000..c79406602 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleTaskInteractiveClient.d.ts @@ -0,0 +1,10 @@ +/** + * Simple interactive task client demonstrating elicitation and sampling responses. + * + * This client connects to simpleTaskInteractive.ts server and demonstrates: + * - Handling elicitation requests (y/n confirmation) + * - Handling sampling requests (returns a hardcoded haiku) + * - Using task-based tool execution with streaming + */ +export {}; +//# sourceMappingURL=simpleTaskInteractiveClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleTaskInteractiveClient.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleTaskInteractiveClient.d.ts.map new file mode 100644 index 000000000..89b73386e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleTaskInteractiveClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleTaskInteractiveClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleTaskInteractiveClient.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleTaskInteractiveClient.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleTaskInteractiveClient.js new file mode 100644 index 000000000..5a238c5f6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleTaskInteractiveClient.js @@ -0,0 +1,155 @@ +/** + * Simple interactive task client demonstrating elicitation and sampling responses. + * + * This client connects to simpleTaskInteractive.ts server and demonstrates: + * - Handling elicitation requests (y/n confirmation) + * - Handling sampling requests (returns a hardcoded haiku) + * - Using task-based tool execution with streaming + */ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { createInterface } from 'node:readline'; +import { CallToolResultSchema, ElicitRequestSchema, CreateMessageRequestSchema, ErrorCode, McpError } from '../../types.js'; +// Create readline interface for user input +const readline = createInterface({ + input: process.stdin, + output: process.stdout +}); +function question(prompt) { + return new Promise(resolve => { + readline.question(prompt, answer => { + resolve(answer.trim()); + }); + }); +} +function getTextContent(result) { + const textContent = result.content.find((c) => c.type === 'text'); + return textContent?.text ?? '(no text)'; +} +async function elicitationCallback(params) { + console.log(`\n[Elicitation] Server asks: ${params.message}`); + // Simple terminal prompt for y/n + const response = await question('Your response (y/n): '); + const confirmed = ['y', 'yes', 'true', '1'].includes(response.toLowerCase()); + console.log(`[Elicitation] Responding with: confirm=${confirmed}`); + return { action: 'accept', content: { confirm: confirmed } }; +} +async function samplingCallback(params) { + // Get the prompt from the first message + let prompt = 'unknown'; + if (params.messages && params.messages.length > 0) { + const firstMessage = params.messages[0]; + const content = firstMessage.content; + if (typeof content === 'object' && !Array.isArray(content) && content.type === 'text' && 'text' in content) { + prompt = content.text; + } + else if (Array.isArray(content)) { + const textPart = content.find(c => c.type === 'text' && 'text' in c); + if (textPart && 'text' in textPart) { + prompt = textPart.text; + } + } + } + console.log(`\n[Sampling] Server requests LLM completion for: ${prompt}`); + // Return a hardcoded haiku (in real use, call your LLM here) + const haiku = `Cherry blossoms fall +Softly on the quiet pond +Spring whispers goodbye`; + console.log('[Sampling] Responding with haiku'); + return { + model: 'mock-haiku-model', + role: 'assistant', + content: { type: 'text', text: haiku } + }; +} +async function run(url) { + console.log('Simple Task Interactive Client'); + console.log('=============================='); + console.log(`Connecting to ${url}...`); + // Create client with elicitation and sampling capabilities + const client = new Client({ name: 'simple-task-interactive-client', version: '1.0.0' }, { + capabilities: { + elicitation: { form: {} }, + sampling: {} + } + }); + // Set up elicitation request handler + client.setRequestHandler(ElicitRequestSchema, async (request) => { + if (request.params.mode && request.params.mode !== 'form') { + throw new McpError(ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`); + } + return elicitationCallback(request.params); + }); + // Set up sampling request handler + client.setRequestHandler(CreateMessageRequestSchema, async (request) => { + return samplingCallback(request.params); + }); + // Connect to server + const transport = new StreamableHTTPClientTransport(new URL(url)); + await client.connect(transport); + console.log('Connected!\n'); + // List tools + const toolsResult = await client.listTools(); + console.log(`Available tools: ${toolsResult.tools.map(t => t.name).join(', ')}`); + // Demo 1: Elicitation (confirm_delete) + console.log('\n--- Demo 1: Elicitation ---'); + console.log('Calling confirm_delete tool...'); + const confirmStream = client.experimental.tasks.callToolStream({ name: 'confirm_delete', arguments: { filename: 'important.txt' } }, CallToolResultSchema, { task: { ttl: 60000 } }); + for await (const message of confirmStream) { + switch (message.type) { + case 'taskCreated': + console.log(`Task created: ${message.task.taskId}`); + break; + case 'taskStatus': + console.log(`Task status: ${message.task.status}`); + break; + case 'result': + console.log(`Result: ${getTextContent(message.result)}`); + break; + case 'error': + console.error(`Error: ${message.error}`); + break; + } + } + // Demo 2: Sampling (write_haiku) + console.log('\n--- Demo 2: Sampling ---'); + console.log('Calling write_haiku tool...'); + const haikuStream = client.experimental.tasks.callToolStream({ name: 'write_haiku', arguments: { topic: 'autumn leaves' } }, CallToolResultSchema, { + task: { ttl: 60000 } + }); + for await (const message of haikuStream) { + switch (message.type) { + case 'taskCreated': + console.log(`Task created: ${message.task.taskId}`); + break; + case 'taskStatus': + console.log(`Task status: ${message.task.status}`); + break; + case 'result': + console.log(`Result:\n${getTextContent(message.result)}`); + break; + case 'error': + console.error(`Error: ${message.error}`); + break; + } + } + // Cleanup + console.log('\nDemo complete. Closing connection...'); + await transport.close(); + readline.close(); +} +// Parse command line arguments +const args = process.argv.slice(2); +let url = 'http://localhost:8000/mcp'; +for (let i = 0; i < args.length; i++) { + if (args[i] === '--url' && args[i + 1]) { + url = args[i + 1]; + i++; + } +} +// Run the client +run(url).catch(error => { + console.error('Error running client:', error); + process.exit(1); +}); +//# sourceMappingURL=simpleTaskInteractiveClient.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleTaskInteractiveClient.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleTaskInteractiveClient.js.map new file mode 100644 index 000000000..6adb4ff3d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleTaskInteractiveClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleTaskInteractiveClient.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleTaskInteractiveClient.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EACH,oBAAoB,EAEpB,mBAAmB,EACnB,0BAA0B,EAG1B,SAAS,EACT,QAAQ,EACX,MAAM,gBAAgB,CAAC;AAExB,2CAA2C;AAC3C,MAAM,QAAQ,GAAG,eAAe,CAAC;IAC7B,KAAK,EAAE,OAAO,CAAC,KAAK;IACpB,MAAM,EAAE,OAAO,CAAC,MAAM;CACz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CAAC,KAAK,CAAC,EAAE;IACnB,OAAO,CAAC,KAAK,CAAC,uBAAuB,EAAE,KAAK,CAAC,CAAC;IAC9C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/ssePollingClient.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/ssePollingClient.d.ts new file mode 100644 index 000000000..134b4b0cf --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/ssePollingClient.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=ssePollingClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/ssePollingClient.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/ssePollingClient.d.ts.map new file mode 100644 index 000000000..59e4153d2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/ssePollingClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ssePollingClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/ssePollingClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/ssePollingClient.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/ssePollingClient.js new file mode 100644 index 000000000..6bd93a932 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/ssePollingClient.js @@ -0,0 +1,93 @@ +/** + * SSE Polling Example Client (SEP-1699) + * + * This example demonstrates client-side behavior during server-initiated + * SSE stream disconnection and automatic reconnection. + * + * Key features demonstrated: + * - Automatic reconnection when server closes SSE stream + * - Event replay via Last-Event-ID header + * - Resumption token tracking via onresumptiontoken callback + * + * Run with: npx tsx src/examples/client/ssePollingClient.ts + * Requires: ssePollingExample.ts server running on port 3001 + */ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { CallToolResultSchema, LoggingMessageNotificationSchema } from '../../types.js'; +const SERVER_URL = 'http://localhost:3001/mcp'; +async function main() { + console.log('SSE Polling Example Client'); + console.log('=========================='); + console.log(`Connecting to ${SERVER_URL}...`); + console.log(''); + // Create transport with reconnection options + const transport = new StreamableHTTPClientTransport(new URL(SERVER_URL), { + // Use default reconnection options - SDK handles automatic reconnection + }); + // Track the last event ID for debugging + let lastEventId; + // Set up transport error handler to observe disconnections + // Filter out expected errors from SSE reconnection + transport.onerror = error => { + // Skip abort errors during intentional close + if (error.message.includes('AbortError')) + return; + // Show SSE disconnect (expected when server closes stream) + if (error.message.includes('Unexpected end of JSON')) { + console.log('[Transport] SSE stream disconnected - client will auto-reconnect'); + return; + } + console.log(`[Transport] Error: ${error.message}`); + }; + // Set up transport close handler + transport.onclose = () => { + console.log('[Transport] Connection closed'); + }; + // Create and connect client + const client = new Client({ + name: 'sse-polling-client', + version: '1.0.0' + }); + // Set up notification handler to receive progress updates + client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { + const data = notification.params.data; + console.log(`[Notification] ${data}`); + }); + try { + await client.connect(transport); + console.log('[Client] Connected successfully'); + console.log(''); + // Call the long-task tool + console.log('[Client] Calling long-task tool...'); + console.log('[Client] Server will disconnect mid-task to demonstrate polling'); + console.log(''); + const result = await client.request({ + method: 'tools/call', + params: { + name: 'long-task', + arguments: {} + } + }, CallToolResultSchema, { + // Track resumption tokens for debugging + onresumptiontoken: token => { + lastEventId = token; + console.log(`[Event ID] ${token}`); + } + }); + console.log(''); + console.log('[Client] Tool completed!'); + console.log(`[Result] ${JSON.stringify(result.content, null, 2)}`); + console.log(''); + console.log(`[Debug] Final event ID: ${lastEventId}`); + } + catch (error) { + console.error('[Error]', error); + } + finally { + await transport.close(); + console.log('[Client] Disconnected'); + } +} +main().catch(console.error); +//# sourceMappingURL=ssePollingClient.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/ssePollingClient.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/ssePollingClient.js.map new file mode 100644 index 000000000..c41b4332a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/ssePollingClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ssePollingClient.js","sourceRoot":"","sources":["../../../../src/examples/client/ssePollingClient.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,oBAAoB,EAAE,gCAAgC,EAAE,MAAM,gBAAgB,CAAC;AAExF,MAAM,UAAU,GAAG,2BAA2B,CAAC;AAE/C,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,iBAAiB,UAAU,KAAK,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAEhB,6CAA6C;IAC7C,MAAM,SAAS,GAAG,IAAI,6BAA6B,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,EAAE;IACrE,wEAAwE;KAC3E,CAAC,CAAC;IAEH,wCAAwC;IACxC,IAAI,WAA+B,CAAC;IAEpC,2DAA2D;IAC3D,mDAAmD;IACnD,SAAS,CAAC,OAAO,GAAG,KAAK,CAAC,EAAE;QACxB,6CAA6C;QAC7C,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAC;YAAE,OAAO;QACjD,2DAA2D;QAC3D,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,wBAAwB,CAAC,EAAE,CAAC;YACnD,OAAO,CAAC,GAAG,CAAC,kEAAkE,CAAC,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C,cAAc,KAAK,EAAE,CAAC,CAAC;YACvC,CAAC;SACJ,CACJ,CAAC;QAEF,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAChB,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QACxC,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;QACnE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAChB,OAAO,CAAC,GAAG,CAAC,2BAA2B,WAAW,EAAE,CAAC,CAAC;IAC1D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;IACpC,CAAC;YAAS,CAAC;QACP,MAAM,SAAS,CAAC,KAAK,EAAE,CAAC;QACxB,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IACzC,CAAC;AACL,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts new file mode 100644 index 000000000..c2679e669 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=streamableHttpWithSseFallbackClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts.map new file mode 100644 index 000000000..b79ae2a72 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttpWithSseFallbackClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js new file mode 100644 index 000000000..1bea76828 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js @@ -0,0 +1,166 @@ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { SSEClientTransport } from '../../client/sse.js'; +import { ListToolsResultSchema, CallToolResultSchema, LoggingMessageNotificationSchema } from '../../types.js'; +/** + * Simplified Backwards Compatible MCP Client + * + * This client demonstrates backward compatibility with both: + * 1. Modern servers using Streamable HTTP transport (protocol version 2025-03-26) + * 2. Older servers using HTTP+SSE transport (protocol version 2024-11-05) + * + * Following the MCP specification for backwards compatibility: + * - Attempts to POST an initialize request to the server URL first (modern transport) + * - If that fails with 4xx status, falls back to GET request for SSE stream (older transport) + */ +// Command line args processing +const args = process.argv.slice(2); +const serverUrl = args[0] || 'http://localhost:3000/mcp'; +async function main() { + console.log('MCP Backwards Compatible Client'); + console.log('==============================='); + console.log(`Connecting to server at: ${serverUrl}`); + let client; + let transport; + try { + // Try connecting with automatic transport detection + const connection = await connectWithBackwardsCompatibility(serverUrl); + client = connection.client; + transport = connection.transport; + // Set up notification handler + client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { + console.log(`Notification: ${notification.params.level} - ${notification.params.data}`); + }); + // DEMO WORKFLOW: + // 1. List available tools + console.log('\n=== Listing Available Tools ==='); + await listTools(client); + // 2. Call the notification tool + console.log('\n=== Starting Notification Stream ==='); + await startNotificationTool(client); + // 3. Wait for all notifications (5 seconds) + console.log('\n=== Waiting for all notifications ==='); + await new Promise(resolve => setTimeout(resolve, 5000)); + // 4. Disconnect + console.log('\n=== Disconnecting ==='); + await transport.close(); + console.log('Disconnected from MCP server'); + } + catch (error) { + console.error('Error running client:', error); + process.exit(1); + } +} +/** + * Connect to an MCP server with backwards compatibility + * Following the spec for client backward compatibility + */ +async function connectWithBackwardsCompatibility(url) { + console.log('1. Trying Streamable HTTP transport first...'); + // Step 1: Try Streamable HTTP transport first + const client = new Client({ + name: 'backwards-compatible-client', + version: '1.0.0' + }); + client.onerror = error => { + console.error('Client error:', error); + }; + const baseUrl = new URL(url); + try { + // Create modern transport + const streamableTransport = new StreamableHTTPClientTransport(baseUrl); + await client.connect(streamableTransport); + console.log('Successfully connected using modern Streamable HTTP transport.'); + return { + client, + transport: streamableTransport, + transportType: 'streamable-http' + }; + } + catch (error) { + // Step 2: If transport fails, try the older SSE transport + console.log(`StreamableHttp transport connection failed: ${error}`); + console.log('2. Falling back to deprecated HTTP+SSE transport...'); + try { + // Create SSE transport pointing to /sse endpoint + const sseTransport = new SSEClientTransport(baseUrl); + const sseClient = new Client({ + name: 'backwards-compatible-client', + version: '1.0.0' + }); + await sseClient.connect(sseTransport); + console.log('Successfully connected using deprecated HTTP+SSE transport.'); + return { + client: sseClient, + transport: sseTransport, + transportType: 'sse' + }; + } + catch (sseError) { + console.error(`Failed to connect with either transport method:\n1. Streamable HTTP error: ${error}\n2. SSE error: ${sseError}`); + throw new Error('Could not connect to server with any available transport'); + } + } +} +/** + * List available tools on the server + */ +async function listTools(client) { + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - ${tool.name}: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server: ${error}`); + } +} +/** + * Start a notification stream by calling the notification tool + */ +async function startNotificationTool(client) { + try { + // Call the notification tool using reasonable defaults + const request = { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 1000, // 1 second between notifications + count: 5 // Send 5 notifications + } + } + }; + console.log('Calling notification tool...'); + const result = await client.request(request, CallToolResultSchema); + console.log('Tool result:'); + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + catch (error) { + console.log(`Error calling notification tool: ${error}`); + } +} +// Start the client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=streamableHttpWithSseFallbackClient.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js.map new file mode 100644 index 000000000..0d9399dc9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttpWithSseFallbackClient.js","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAEH,qBAAqB,EAErB,oBAAoB,EACpB,gCAAgC,EACnC,MAAM,gBAAgB,CAAC;AAExB;;;;;;;;;;GAUG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AAEzD,KAAK,UAAU,IAAI;IACf,OAA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AAM,EAAE,YAAY;YACpB,MAAM,EAAE;gBACJ,IAAI,EAAE,2BAA2B;gBACjC,SAAS,EAAE;oBACP,QAAQ,EAAE,IAAI,EAAE,iCAAiC;oBACjD,KAAK,EAAE,CAAC,CAAC,uBAAuB;iBACnC;aACJ;SACJ,CAAC;QAEF,OAAO,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;QAC5C,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,oBAAoB,CAAC,CAAC;QAEnE,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;QAC5B,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;YAC1B,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBACvB,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAClC,CAAC;iBAAM,CAAC;gBACJ,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,WAAW,EAAE,IAAI,CAAC,CAAC;YACjD,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,GAAG,CAAC,oCAAoC,KAAK,EAAE,CAAC,CAAC;IAC7D,CAAC;AACL,CAAC;AAED,mBAAmB;AACnB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts new file mode 100644 index 000000000..218aeac8b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts @@ -0,0 +1,78 @@ +import { AuthorizationParams, OAuthServerProvider } from '../../server/auth/provider.js'; +import { OAuthRegisteredClientsStore } from '../../server/auth/clients.js'; +import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from '../../shared/auth.js'; +import { Response } from 'express'; +import { AuthInfo } from '../../server/auth/types.js'; +export declare class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { + private clients; + getClient(clientId: string): Promise<{ + redirect_uris: string[]; + client_id: string; + token_endpoint_auth_method?: string | undefined; + grant_types?: string[] | undefined; + response_types?: string[] | undefined; + client_name?: string | undefined; + client_uri?: string | undefined; + logo_uri?: string | undefined; + scope?: string | undefined; + contacts?: string[] | undefined; + tos_uri?: string | undefined; + policy_uri?: string | undefined; + jwks_uri?: string | undefined; + jwks?: any; + software_id?: string | undefined; + software_version?: string | undefined; + software_statement?: string | undefined; + client_secret?: string | undefined; + client_id_issued_at?: number | undefined; + client_secret_expires_at?: number | undefined; + } | undefined>; + registerClient(clientMetadata: OAuthClientInformationFull): Promise<{ + redirect_uris: string[]; + client_id: string; + token_endpoint_auth_method?: string | undefined; + grant_types?: string[] | undefined; + response_types?: string[] | undefined; + client_name?: string | undefined; + client_uri?: string | undefined; + logo_uri?: string | undefined; + scope?: string | undefined; + contacts?: string[] | undefined; + tos_uri?: string | undefined; + policy_uri?: string | undefined; + jwks_uri?: string | undefined; + jwks?: any; + software_id?: string | undefined; + software_version?: string | undefined; + software_statement?: string | undefined; + client_secret?: string | undefined; + client_id_issued_at?: number | undefined; + client_secret_expires_at?: number | undefined; + }>; +} +/** + * 🚨 DEMO ONLY - NOT FOR PRODUCTION + * + * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, + * for example: + * - Persistent token storage + * - Rate limiting + */ +export declare class DemoInMemoryAuthProvider implements OAuthServerProvider { + private validateResource?; + clientsStore: DemoInMemoryClientsStore; + private codes; + private tokens; + constructor(validateResource?: ((resource?: URL) => boolean) | undefined); + authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; + challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; + exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, _codeVerifier?: string): Promise; + exchangeRefreshToken(_client: OAuthClientInformationFull, _refreshToken: string, _scopes?: string[], _resource?: URL): Promise; + verifyAccessToken(token: string): Promise; +} +export declare const setupAuthServer: ({ authServerUrl, mcpServerUrl, strictResource }: { + authServerUrl: URL; + mcpServerUrl: URL; + strictResource: boolean; +}) => OAuthMetadata; +//# sourceMappingURL=demoInMemoryOAuthProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts.map new file mode 100644 index 000000000..8a4a43fe8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"demoInMemoryOAuthProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACzF,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAgB,EAAW,QAAQ,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAKtD,qBAAa,wBAAyB,YAAW,2BAA2B;IACxE,OAAO,CAAC,OAAO,CAAiD;IAE1D,SAAS,CAAC,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;IAI1B,cAAc,CAAC,cAAc,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;CAIlE;AAED;;;;;;;GAOG;AACH,qBAAa,wBAAyB,YAAW,mBAAmB;IAWpD,OAAO,CAAC,gBAAgB,CAAC;IAVrC,YAAY,2BAAkC;IAC9C,OAAO,CAAC,KAAK,CAMT;IACJ,OAAO,CAAC,MAAM,CAA+B;gBAEzB,gBAAgB,CAAC,GAAE,CAAC,QAAQ,CAAC,EAAE,GAAG,KAAK,OAAO,aAAA;IAE5D,SAAS,CAAC,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAwCxG,6BAA6B,CAAC,MAAM,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAU7G,yBAAyB,CAC3B,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EAGzB,aAAa,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,WAAW,CAAC;IAoCjB,oBAAoB,CACtB,OAAO,EAAE,0BAA0B,EACnC,aAAa,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE,MAAM,EAAE,EAClB,SAAS,CAAC,EAAE,GAAG,GAChB,OAAO,CAAC,WAAW,CAAC;IAIjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAc5D;AAED,eAAO,MAAM,eAAe,oDAIzB;IACC,aAAa,EAAE,GAAG,CAAC;IACnB,YAAY,EAAE,GAAG,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;CAC3B,KAAG,aA+EH,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/demoInMemoryOAuthProvider.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/demoInMemoryOAuthProvider.js new file mode 100644 index 000000000..45bde7043 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/demoInMemoryOAuthProvider.js @@ -0,0 +1,196 @@ +import { randomUUID } from 'node:crypto'; +import express from 'express'; +import { createOAuthMetadata, mcpAuthRouter } from '../../server/auth/router.js'; +import { resourceUrlFromServerUrl } from '../../shared/auth-utils.js'; +import { InvalidRequestError } from '../../server/auth/errors.js'; +export class DemoInMemoryClientsStore { + constructor() { + this.clients = new Map(); + } + async getClient(clientId) { + return this.clients.get(clientId); + } + async registerClient(clientMetadata) { + this.clients.set(clientMetadata.client_id, clientMetadata); + return clientMetadata; + } +} +/** + * 🚨 DEMO ONLY - NOT FOR PRODUCTION + * + * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, + * for example: + * - Persistent token storage + * - Rate limiting + */ +export class DemoInMemoryAuthProvider { + constructor(validateResource) { + this.validateResource = validateResource; + this.clientsStore = new DemoInMemoryClientsStore(); + this.codes = new Map(); + this.tokens = new Map(); + } + async authorize(client, params, res) { + const code = randomUUID(); + const searchParams = new URLSearchParams({ + code + }); + if (params.state !== undefined) { + searchParams.set('state', params.state); + } + this.codes.set(code, { + client, + params + }); + // Simulate a user login + // Set a secure HTTP-only session cookie with authorization info + if (res.cookie) { + const authCookieData = { + userId: 'demo_user', + name: 'Demo User', + timestamp: Date.now() + }; + res.cookie('demo_session', JSON.stringify(authCookieData), { + httpOnly: true, + secure: false, // In production, this should be true + sameSite: 'lax', + maxAge: 24 * 60 * 60 * 1000, // 24 hours - for demo purposes + path: '/' // Available to all routes + }); + } + if (!client.redirect_uris.includes(params.redirectUri)) { + throw new InvalidRequestError('Unregistered redirect_uri'); + } + const targetUrl = new URL(params.redirectUri); + targetUrl.search = searchParams.toString(); + res.redirect(targetUrl.toString()); + } + async challengeForAuthorizationCode(client, authorizationCode) { + // Store the challenge with the code data + const codeData = this.codes.get(authorizationCode); + if (!codeData) { + throw new Error('Invalid authorization code'); + } + return codeData.params.codeChallenge; + } + async exchangeAuthorizationCode(client, authorizationCode, + // Note: code verifier is checked in token.ts by default + // it's unused here for that reason. + _codeVerifier) { + const codeData = this.codes.get(authorizationCode); + if (!codeData) { + throw new Error('Invalid authorization code'); + } + if (codeData.client.client_id !== client.client_id) { + throw new Error(`Authorization code was not issued to this client, ${codeData.client.client_id} != ${client.client_id}`); + } + if (this.validateResource && !this.validateResource(codeData.params.resource)) { + throw new Error(`Invalid resource: ${codeData.params.resource}`); + } + this.codes.delete(authorizationCode); + const token = randomUUID(); + const tokenData = { + token, + clientId: client.client_id, + scopes: codeData.params.scopes || [], + expiresAt: Date.now() + 3600000, // 1 hour + resource: codeData.params.resource, + type: 'access' + }; + this.tokens.set(token, tokenData); + return { + access_token: token, + token_type: 'bearer', + expires_in: 3600, + scope: (codeData.params.scopes || []).join(' ') + }; + } + async exchangeRefreshToken(_client, _refreshToken, _scopes, _resource) { + throw new Error('Not implemented for example demo'); + } + async verifyAccessToken(token) { + const tokenData = this.tokens.get(token); + if (!tokenData || !tokenData.expiresAt || tokenData.expiresAt < Date.now()) { + throw new Error('Invalid or expired token'); + } + return { + token, + clientId: tokenData.clientId, + scopes: tokenData.scopes, + expiresAt: Math.floor(tokenData.expiresAt / 1000), + resource: tokenData.resource + }; + } +} +export const setupAuthServer = ({ authServerUrl, mcpServerUrl, strictResource }) => { + // Create separate auth server app + // NOTE: This is a separate app on a separate port to illustrate + // how to separate an OAuth Authorization Server from a Resource + // server in the SDK. The SDK is not intended to be provide a standalone + // authorization server. + const validateResource = strictResource + ? (resource) => { + if (!resource) + return false; + const expectedResource = resourceUrlFromServerUrl(mcpServerUrl); + return resource.toString() === expectedResource.toString(); + } + : undefined; + const provider = new DemoInMemoryAuthProvider(validateResource); + const authApp = express(); + authApp.use(express.json()); + // For introspection requests + authApp.use(express.urlencoded()); + // Add OAuth routes to the auth server + // NOTE: this will also add a protected resource metadata route, + // but it won't be used, so leave it. + authApp.use(mcpAuthRouter({ + provider, + issuerUrl: authServerUrl, + scopesSupported: ['mcp:tools'] + })); + authApp.post('/introspect', async (req, res) => { + try { + const { token } = req.body; + if (!token) { + res.status(400).json({ error: 'Token is required' }); + return; + } + const tokenInfo = await provider.verifyAccessToken(token); + res.json({ + active: true, + client_id: tokenInfo.clientId, + scope: tokenInfo.scopes.join(' '), + exp: tokenInfo.expiresAt, + aud: tokenInfo.resource + }); + return; + } + catch (error) { + res.status(401).json({ + active: false, + error: 'Unauthorized', + error_description: `Invalid token: ${error}` + }); + } + }); + const auth_port = authServerUrl.port; + // Start the auth server + authApp.listen(auth_port, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`OAuth Authorization Server listening on port ${auth_port}`); + }); + // Note: we could fetch this from the server, but then we end up + // with some top level async which gets annoying. + const oauthMetadata = createOAuthMetadata({ + provider, + issuerUrl: authServerUrl, + scopesSupported: ['mcp:tools'] + }); + oauthMetadata.introspection_endpoint = new URL('/introspect', authServerUrl).href; + return oauthMetadata; +}; +//# sourceMappingURL=demoInMemoryOAuthProvider.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/demoInMemoryOAuthProvider.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/demoInMemoryOAuthProvider.js.map new file mode 100644 index 000000000..80fcc5502 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/demoInMemoryOAuthProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"demoInMemoryOAuthProvider.js","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAIzC,OAAO,OAA8B,MAAM,SAAS,CAAC;AAErD,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,MAAM,OAAO,wBAAwB;IAArC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,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,KAAK,CAAC,EAAE;QAC9B,IAAI,KAAK,EAAE,CAAC;YACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;YAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,SAAS,EAAE,CAAC,CAAC;IAC7E,CAAC,CAAC,CAAC;IAEH,gEAAgE;IAChE,iDAAiD;IACjD,MAAM,aAAa,GAAkB,mBAAmB,CAAC;QACrD,QAAQ;QACR,SAAS,EAAE,aAAa;QACxB,eAAe,EAAE,CAAC,WAAW,CAAC;KACjC,CAAC,CAAC;IAEH,aAAa,CAAC,sBAAsB,GAAG,IAAI,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC,IAAI,CAAC;IAElF,OAAO,aAAa,CAAC;AACzB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationFormExample.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationFormExample.d.ts new file mode 100644 index 000000000..e4b736e0f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationFormExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=elicitationFormExample.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationFormExample.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationFormExample.d.ts.map new file mode 100644 index 000000000..c569df428 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationFormExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationFormExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationFormExample.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationFormExample.js new file mode 100644 index 000000000..0f99d0ce0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationFormExample.js @@ -0,0 +1,429 @@ +// Run with: npx tsx src/examples/server/elicitationFormExample.ts +// +// This example demonstrates how to use form elicitation to collect structured user input +// with JSON Schema validation via a local HTTP server with SSE streaming. +// Form elicitation allows servers to request *non-sensitive* user input through the client +// with schema-based validation. +// Note: See also elicitationUrlExample.ts for an example of using URL elicitation +// to collect *sensitive* user input via a browser. +import { randomUUID } from 'node:crypto'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { isInitializeRequest } from '../../types.js'; +import { createMcpExpressApp } from '../../server/express.js'; +// Create MCP server - it will automatically use AjvJsonSchemaValidator with sensible defaults +// The validator supports format validation (email, date, etc.) if ajv-formats is installed +const mcpServer = new McpServer({ + name: 'form-elicitation-example-server', + version: '1.0.0' +}, { + capabilities: {} +}); +/** + * Example 1: Simple user registration tool + * Collects username, email, and password from the user + */ +mcpServer.registerTool('register_user', { + description: 'Register a new user account by collecting their information', + inputSchema: {} +}, async () => { + try { + // Request user information through form elicitation + const result = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Please provide your registration information:', + requestedSchema: { + type: 'object', + properties: { + username: { + type: 'string', + title: 'Username', + description: 'Your desired username (3-20 characters)', + minLength: 3, + maxLength: 20 + }, + email: { + type: 'string', + title: 'Email', + description: 'Your email address', + format: 'email' + }, + password: { + type: 'string', + title: 'Password', + description: 'Your password (min 8 characters)', + minLength: 8 + }, + newsletter: { + type: 'boolean', + title: 'Newsletter', + description: 'Subscribe to newsletter?', + default: false + } + }, + required: ['username', 'email', 'password'] + } + }); + // Handle the different possible actions + if (result.action === 'accept' && result.content) { + const { username, email, newsletter } = result.content; + return { + content: [ + { + type: 'text', + text: `Registration successful!\n\nUsername: ${username}\nEmail: ${email}\nNewsletter: ${newsletter ? 'Yes' : 'No'}` + } + ] + }; + } + else if (result.action === 'decline') { + return { + content: [ + { + type: 'text', + text: 'Registration cancelled by user.' + } + ] + }; + } + else { + return { + content: [ + { + type: 'text', + text: 'Registration was cancelled.' + } + ] + }; + } + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Registration failed: ${error instanceof Error ? error.message : String(error)}` + } + ], + isError: true + }; + } +}); +/** + * Example 2: Multi-step workflow with multiple form elicitation requests + * Demonstrates how to collect information in multiple steps + */ +mcpServer.registerTool('create_event', { + description: 'Create a calendar event by collecting event details', + inputSchema: {} +}, async () => { + try { + // Step 1: Collect basic event information + const basicInfo = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Step 1: Enter basic event information', + requestedSchema: { + type: 'object', + properties: { + title: { + type: 'string', + title: 'Event Title', + description: 'Name of the event', + minLength: 1 + }, + description: { + type: 'string', + title: 'Description', + description: 'Event description (optional)' + } + }, + required: ['title'] + } + }); + if (basicInfo.action !== 'accept' || !basicInfo.content) { + return { + content: [{ type: 'text', text: 'Event creation cancelled.' }] + }; + } + // Step 2: Collect date and time + const dateTime = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Step 2: Enter date and time', + requestedSchema: { + type: 'object', + properties: { + date: { + type: 'string', + title: 'Date', + description: 'Event date', + format: 'date' + }, + startTime: { + type: 'string', + title: 'Start Time', + description: 'Event start time (HH:MM)' + }, + duration: { + type: 'integer', + title: 'Duration', + description: 'Duration in minutes', + minimum: 15, + maximum: 480 + } + }, + required: ['date', 'startTime', 'duration'] + } + }); + if (dateTime.action !== 'accept' || !dateTime.content) { + return { + content: [{ type: 'text', text: 'Event creation cancelled.' }] + }; + } + // Combine all collected information + const event = { + ...basicInfo.content, + ...dateTime.content + }; + return { + content: [ + { + type: 'text', + text: `Event created successfully!\n\n${JSON.stringify(event, null, 2)}` + } + ] + }; + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Event creation failed: ${error instanceof Error ? error.message : String(error)}` + } + ], + isError: true + }; + } +}); +/** + * Example 3: Collecting address information + * Demonstrates validation with patterns and optional fields + */ +mcpServer.registerTool('update_shipping_address', { + description: 'Update shipping address with validation', + inputSchema: {} +}, async () => { + try { + const result = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Please provide your shipping address:', + requestedSchema: { + type: 'object', + properties: { + name: { + type: 'string', + title: 'Full Name', + description: 'Recipient name', + minLength: 1 + }, + street: { + type: 'string', + title: 'Street Address', + minLength: 1 + }, + city: { + type: 'string', + title: 'City', + minLength: 1 + }, + state: { + type: 'string', + title: 'State/Province', + minLength: 2, + maxLength: 2 + }, + zipCode: { + type: 'string', + title: 'ZIP/Postal Code', + description: '5-digit ZIP code' + }, + phone: { + type: 'string', + title: 'Phone Number (optional)', + description: 'Contact phone number' + } + }, + required: ['name', 'street', 'city', 'state', 'zipCode'] + } + }); + if (result.action === 'accept' && result.content) { + return { + content: [ + { + type: 'text', + text: `Address updated successfully!\n\n${JSON.stringify(result.content, null, 2)}` + } + ] + }; + } + else if (result.action === 'decline') { + return { + content: [{ type: 'text', text: 'Address update cancelled by user.' }] + }; + } + else { + return { + content: [{ type: 'text', text: 'Address update was cancelled.' }] + }; + } + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Address update failed: ${error instanceof Error ? error.message : String(error)}` + } + ], + isError: true + }; + } +}); +async function main() { + const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000; + const app = createMcpExpressApp(); + // Map to store transports by session ID + const transports = {}; + // MCP POST endpoint + const mcpPostHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (sessionId) { + console.log(`Received MCP request for session: ${sessionId}`); + } + try { + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport for this session + transport = transports[sessionId]; + } + else if (!sessionId && isInitializeRequest(req.body)) { + // New initialization request - create new transport + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + } + }; + // Connect the transport to the MCP server BEFORE handling the request + await mcpServer.connect(transport); + await transport.handleRequest(req, res, req.body); + return; + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } + }; + app.post('/mcp', mcpPostHandler); + // Handle GET requests for SSE streams + const mcpGetHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Establishing SSE stream for session ${sessionId}`); + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + }; + app.get('/mcp', mcpGetHandler); + // Handle DELETE requests for session termination + const mcpDeleteHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Received session termination request for session ${sessionId}`); + try { + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + } + catch (error) { + console.error('Error handling session termination:', error); + if (!res.headersSent) { + res.status(500).send('Error processing session termination'); + } + } + }; + app.delete('/mcp', mcpDeleteHandler); + // Start listening + app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Form elicitation example server is running on http://localhost:${PORT}/mcp`); + console.log('Available tools:'); + console.log(' - register_user: Collect user registration information'); + console.log(' - create_event: Multi-step event creation'); + console.log(' - update_shipping_address: Collect and validate address'); + console.log('\nConnect your MCP client to this server using the HTTP transport.'); + }); + // Handle server shutdown + process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); + }); +} +main().catch(error => { + console.error('Server error:', error); + process.exit(1); +}); +//# sourceMappingURL=elicitationFormExample.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationFormExample.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationFormExample.js.map new file mode 100644 index 000000000..799b0d7f4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationFormExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationFormExample.js","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,yFAAyF;AACzF,0EAA0E;AAC1E,2FAA2F;AAC3F,gCAAgC;AAChC,kFAAkF;AAClF,mDAAmD;AAEnD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAE9D,8FAA8F;AAC9F,2FAA2F;AAC3F,MAAM,SAAS,GAAG,IAAI,SAAS,CAC3B;IACI,IAAI,EAAE,iCAAiC;IACvC,OAAO,EAAE,OAAO;CACnB,EACD;IACI,YAAY,EAAE,EAAE;CACnB,CACJ,CAAC;AAEF;;;GAGG;AACH,SA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C,CAAC,KAAK,EAAE,CAAC;gBACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;YACjC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;YAC9E,CAAC;QACL,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationUrlExample.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationUrlExample.d.ts new file mode 100644 index 000000000..611f6eba2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationUrlExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=elicitationUrlExample.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationUrlExample.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationUrlExample.d.ts.map new file mode 100644 index 000000000..04acd6664 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationUrlExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationUrlExample.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationUrlExample.js new file mode 100644 index 000000000..8aa072c79 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationUrlExample.js @@ -0,0 +1,651 @@ +// Run with: npx tsx src/examples/server/elicitationUrlExample.ts +// +// This example demonstrates how to use URL elicitation to securely collect +// *sensitive* user input in a remote (HTTP) server. +// URL elicitation allows servers to prompt the end-user to open a URL in their browser +// to collect sensitive information. +// Note: See also elicitationFormExample.ts for an example of using form (not URL) elicitation +// to collect *non-sensitive* user input with a structured schema. +import express from 'express'; +import { randomUUID } from 'node:crypto'; +import { z } from 'zod'; +import { McpServer } from '../../server/mcp.js'; +import { createMcpExpressApp } from '../../server/express.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter } from '../../server/auth/router.js'; +import { requireBearerAuth } from '../../server/auth/middleware/bearerAuth.js'; +import { UrlElicitationRequiredError, isInitializeRequest } from '../../types.js'; +import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; +import { setupAuthServer } from './demoInMemoryOAuthProvider.js'; +import { checkResourceAllowed } from '../../shared/auth-utils.js'; +import cors from 'cors'; +// Create an MCP server with implementation details +const getServer = () => { + const mcpServer = new McpServer({ + name: 'url-elicitation-http-server', + version: '1.0.0' + }, { + capabilities: { logging: {} } + }); + mcpServer.registerTool('payment-confirm', { + description: 'A tool that confirms a payment directly with a user', + inputSchema: { + cartId: z.string().describe('The ID of the cart to confirm') + } + }, async ({ cartId }, extra) => { + /* + In a real world scenario, there would be some logic here to check if the user has the provided cartId. + For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to confirm payment) + */ + const sessionId = extra.sessionId; + if (!sessionId) { + throw new Error('Expected a Session ID'); + } + // Create and track the elicitation + const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId)); + throw new UrlElicitationRequiredError([ + { + mode: 'url', + message: 'This tool requires a payment confirmation. Open the link to confirm payment!', + url: `http://localhost:${MCP_PORT}/confirm-payment?session=${sessionId}&elicitation=${elicitationId}&cartId=${encodeURIComponent(cartId)}`, + elicitationId + } + ]); + }); + mcpServer.registerTool('third-party-auth', { + description: 'A demo tool that requires third-party OAuth credentials', + inputSchema: { + param1: z.string().describe('First parameter') + } + }, async (_, extra) => { + /* + In a real world scenario, there would be some logic here to check if we already have a valid access token for the user. + Auth info (with a subject or `sub` claim) can be typically be found in `extra.authInfo`. + If we do, we can just return the result of the tool call. + If we don't, we can throw an ElicitationRequiredError to request the user to authenticate. + For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to authenticate). + */ + const sessionId = extra.sessionId; + if (!sessionId) { + throw new Error('Expected a Session ID'); + } + // Create and track the elicitation + const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId)); + // Simulate OAuth callback and token exchange after 5 seconds + // In a real app, this would be called from your OAuth callback handler + setTimeout(() => { + console.log(`Simulating OAuth token received for elicitation ${elicitationId}`); + completeURLElicitation(elicitationId); + }, 5000); + throw new UrlElicitationRequiredError([ + { + mode: 'url', + message: 'This tool requires access to your example.com account. Open the link to authenticate!', + url: 'https://www.example.com/oauth/authorize', + elicitationId + } + ]); + }); + return mcpServer; +}; +const elicitationsMap = new Map(); +// Clean up old elicitations after 1 hour to prevent memory leaks +const ELICITATION_TTL_MS = 60 * 60 * 1000; // 1 hour +const CLEANUP_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes +function cleanupOldElicitations() { + const now = new Date(); + for (const [id, metadata] of elicitationsMap.entries()) { + if (now.getTime() - metadata.createdAt.getTime() > ELICITATION_TTL_MS) { + elicitationsMap.delete(id); + console.log(`Cleaned up expired elicitation: ${id}`); + } + } +} +setInterval(cleanupOldElicitations, CLEANUP_INTERVAL_MS); +/** + * Elicitation IDs must be unique strings within the MCP session + * UUIDs are used in this example for simplicity + */ +function generateElicitationId() { + return randomUUID(); +} +/** + * Helper function to create and track a new elicitation. + */ +function generateTrackedElicitation(sessionId, createCompletionNotifier) { + const elicitationId = generateElicitationId(); + // Create a Promise and its resolver for tracking completion + let completeResolver; + const completedPromise = new Promise(resolve => { + completeResolver = resolve; + }); + const completionNotifier = createCompletionNotifier ? createCompletionNotifier(elicitationId) : undefined; + // Store the elicitation in our map + elicitationsMap.set(elicitationId, { + status: 'pending', + completedPromise, + completeResolver: completeResolver, + createdAt: new Date(), + sessionId, + completionNotifier + }); + return elicitationId; +} +/** + * Helper function to complete an elicitation. + */ +function completeURLElicitation(elicitationId) { + const elicitation = elicitationsMap.get(elicitationId); + if (!elicitation) { + console.warn(`Attempted to complete unknown elicitation: ${elicitationId}`); + return; + } + if (elicitation.status === 'complete') { + console.warn(`Elicitation already complete: ${elicitationId}`); + return; + } + // Update metadata + elicitation.status = 'complete'; + // Send completion notification to the client + if (elicitation.completionNotifier) { + console.log(`Sending notifications/elicitation/complete notification for elicitation ${elicitationId}`); + elicitation.completionNotifier().catch(error => { + console.error(`Failed to send completion notification for elicitation ${elicitationId}:`, error); + }); + } + // Resolve the promise to unblock any waiting code + elicitation.completeResolver(); +} +const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; +const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; +const app = createMcpExpressApp(); +// Allow CORS all domains, expose the Mcp-Session-Id header +app.use(cors({ + origin: '*', // Allow all origins + exposedHeaders: ['Mcp-Session-Id'], + credentials: true // Allow cookies to be sent cross-origin +})); +// Set up OAuth (required for this example) +let authMiddleware = null; +// Create auth middleware for MCP endpoints +const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); +const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); +const oauthMetadata = setupAuthServer({ authServerUrl, mcpServerUrl, strictResource: true }); +const tokenVerifier = { + verifyAccessToken: async (token) => { + const endpoint = oauthMetadata.introspection_endpoint; + if (!endpoint) { + throw new Error('No token verification endpoint available in metadata'); + } + const response = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: new URLSearchParams({ + token: token + }).toString() + }); + if (!response.ok) { + const text = await response.text().catch(() => null); + throw new Error(`Invalid or expired token: ${text}`); + } + const data = await response.json(); + if (!data.aud) { + throw new Error(`Resource Indicator (RFC8707) missing`); + } + if (!checkResourceAllowed({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { + throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); + } + // Convert the response to AuthInfo format + return { + token, + clientId: data.client_id, + scopes: data.scope ? data.scope.split(' ') : [], + expiresAt: data.exp + }; + } +}; +// Add metadata routes to the main MCP server +app.use(mcpAuthMetadataRouter({ + oauthMetadata, + resourceServerUrl: mcpServerUrl, + scopesSupported: ['mcp:tools'], + resourceName: 'MCP Demo Server' +})); +authMiddleware = requireBearerAuth({ + verifier: tokenVerifier, + requiredScopes: [], + resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl) +}); +/** + * API Key Form Handling + * + * Many servers today require an API key to operate, but there's no scalable way to do this dynamically for remote servers within MCP protocol. + * URL-mode elicitation enables the server to host a simple form and get the secret data securely from the user without involving the LLM or client. + **/ +async function sendApiKeyElicitation(sessionId, sender, createCompletionNotifier) { + if (!sessionId) { + console.error('No session ID provided'); + throw new Error('Expected a Session ID to track elicitation'); + } + console.log('🔑 URL elicitation demo: Requesting API key from client...'); + const elicitationId = generateTrackedElicitation(sessionId, createCompletionNotifier); + try { + const result = await sender({ + mode: 'url', + message: 'Please provide your API key to authenticate with this server', + // Host the form on the same server. In a real app, you might coordinate passing these state variables differently. + url: `http://localhost:${MCP_PORT}/api-key-form?session=${sessionId}&elicitation=${elicitationId}`, + elicitationId + }); + switch (result.action) { + case 'accept': + console.log('🔑 URL elicitation demo: Client accepted the API key elicitation (now pending form submission)'); + // Wait for the API key to be submitted via the form + // The form submission will complete the elicitation + break; + default: + console.log('🔑 URL elicitation demo: Client declined to provide an API key'); + // In a real app, this might close the connection, but for the demo, we'll continue + break; + } + } + catch (error) { + console.error('Error during API key elicitation:', error); + } +} +// API Key Form endpoint - serves a simple HTML form +app.get('/api-key-form', (req, res) => { + const mcpSessionId = req.query.session; + const elicitationId = req.query.elicitation; + if (!mcpSessionId || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie + // In production, this is often handled by some user auth middleware to ensure the user has a valid session + // This session is different from the MCP session. + // This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in. + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + // Serve a simple HTML form + res.send(` + + + + Submit Your API Key + + + +

API Key Required

+
✓ Logged in as: ${userSession.name}
+
+ + + + +
+
This is a demo showing how a server can securely elicit sensitive data from a user using a URL.
+ + + `); +}); +// Handle API key form submission +app.post('/api-key-form', express.urlencoded(), (req, res) => { + const { session: sessionId, apiKey, elicitation: elicitationId } = req.body; + if (!sessionId || !apiKey || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie here too + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + // A real app might store this API key to be used later for the user. + console.log(`🔑 Received API key \x1b[32m${apiKey}\x1b[0m for session ${sessionId}`); + // If we have an elicitationId, complete the elicitation + completeURLElicitation(elicitationId); + // Send a success response + res.send(` + + + + Success + + + +
+

Success ✓

+

API key received.

+
+

You can close this window and return to your MCP client.

+ + + `); +}); +// Helper to get the user session from the demo_session cookie +function getUserSessionCookie(cookieHeader) { + if (!cookieHeader) + return null; + const cookies = cookieHeader.split(';'); + for (const cookie of cookies) { + const [name, value] = cookie.trim().split('='); + if (name === 'demo_session' && value) { + try { + return JSON.parse(decodeURIComponent(value)); + } + catch (error) { + console.error('Failed to parse demo_session cookie:', error); + return null; + } + } + } + return null; +} +/** + * Payment Confirmation Form Handling + * + * This demonstrates how a server can use URL-mode elicitation to get user confirmation + * for sensitive operations like payment processing. + **/ +// Payment Confirmation Form endpoint - serves a simple HTML form +app.get('/confirm-payment', (req, res) => { + const mcpSessionId = req.query.session; + const elicitationId = req.query.elicitation; + const cartId = req.query.cartId; + if (!mcpSessionId || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie + // In production, this is often handled by some user auth middleware to ensure the user has a valid session + // This session is different from the MCP session. + // This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in. + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + // Serve a simple HTML form + res.send(` + + + + Confirm Payment + + + +

Confirm Payment

+
✓ Logged in as: ${userSession.name}
+ ${cartId ? `
Cart ID: ${cartId}
` : ''} +
+ ⚠️ Please review your order before confirming. +
+
+ + + ${cartId ? `` : ''} + + +
+
This is a demo showing how a server can securely get user confirmation for sensitive operations using URL-mode elicitation.
+ + + `); +}); +// Handle Payment Confirmation form submission +app.post('/confirm-payment', express.urlencoded(), (req, res) => { + const { session: sessionId, elicitation: elicitationId, cartId, action } = req.body; + if (!sessionId || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie here too + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + if (action === 'confirm') { + // A real app would process the payment here + console.log(`💳 Payment confirmed for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`); + // Complete the elicitation + completeURLElicitation(elicitationId); + // Send a success response + res.send(` + + + + Payment Confirmed + + + +
+

Payment Confirmed ✓

+

Your payment has been successfully processed.

+ ${cartId ? `

Cart ID: ${cartId}

` : ''} +
+

You can close this window and return to your MCP client.

+ + + `); + } + else if (action === 'cancel') { + console.log(`💳 Payment cancelled for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`); + // The client will still receive a notifications/elicitation/complete notification, + // which indicates that the out-of-band interaction is complete (but not necessarily successful) + completeURLElicitation(elicitationId); + res.send(` + + + + Payment Cancelled + + + +
+

Payment Cancelled

+

Your payment has been cancelled.

+
+

You can close this window and return to your MCP client.

+ + + `); + } + else { + res.status(400).send('

Error

Invalid action

'); + } +}); +// Map to store transports by session ID +const transports = {}; +const sessionsNeedingElicitation = {}; +// MCP POST endpoint +const mcpPostHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + console.debug(`Received MCP POST for session: ${sessionId || 'unknown'}`); + try { + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && isInitializeRequest(req.body)) { + const server = getServer(); + // New initialization request + const eventStore = new InMemoryEventStore(); + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + eventStore, // Enable resumability + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + sessionsNeedingElicitation[sessionId] = { + elicitationSender: params => server.server.elicitInput(params), + createCompletionNotifier: elicitationId => server.server.createElicitationCompletionNotifier(elicitationId) + }; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + delete sessionsNeedingElicitation[sid]; + } + }; + // Connect the transport to the MCP server BEFORE handling the request + // so responses can flow back through the same transport + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport - no need to reconnect + // The existing transport is already connected to the server + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}; +// Set up routes with auth middleware +app.post('/mcp', authMiddleware, mcpPostHandler); +// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) +const mcpGetHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + // Check for Last-Event-ID header for resumability + const lastEventId = req.headers['last-event-id']; + if (lastEventId) { + console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); + } + else { + console.log(`Establishing new SSE stream for session ${sessionId}`); + } + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + if (sessionsNeedingElicitation[sessionId]) { + const { elicitationSender, createCompletionNotifier } = sessionsNeedingElicitation[sessionId]; + // Send an elicitation request to the client in the background + sendApiKeyElicitation(sessionId, elicitationSender, createCompletionNotifier) + .then(() => { + // Only delete on successful send for this demo + delete sessionsNeedingElicitation[sessionId]; + console.log(`🔑 URL elicitation demo: Finished sending API key elicitation request for session ${sessionId}`); + }) + .catch(error => { + console.error('Error sending API key elicitation:', error); + // Keep in map to potentially retry on next reconnect + }); + } +}; +// Set up GET route with conditional auth middleware +app.get('/mcp', authMiddleware, mcpGetHandler); +// Handle DELETE requests for session termination (according to MCP spec) +const mcpDeleteHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Received session termination request for session ${sessionId}`); + try { + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + } + catch (error) { + console.error('Error handling session termination:', error); + if (!res.headersSent) { + res.status(500).send('Error processing session termination'); + } + } +}; +// Set up DELETE route with auth middleware +app.delete('/mcp', authMiddleware, mcpDeleteHandler); +app.listen(MCP_PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + delete sessionsNeedingElicitation[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=elicitationUrlExample.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationUrlExample.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationUrlExample.js.map new file mode 100644 index 000000000..fe2a5f7b6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/elicitationUrlExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.js","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,EAAE;AACF,2EAA2E;AAC3E,oDAAoD;AACpD,uFAAuF;AACvF,oCAAoC;AACpC,8FAA8F;AAC9F,kEAAkE;AAElE,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,oCAAoC,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAC1G,OAAO,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAC;AAC/E,OAAO,EAAkB,2BAA2B,EAAwC,mBAAmB,EAAE,MAAM,gBAAgB,CAA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QACjD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/honoWebStandardStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/honoWebStandardStreamableHttp.d.ts new file mode 100644 index 000000000..bc6abddea --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/honoWebStandardStreamableHttp.d.ts @@ -0,0 +1,10 @@ +/** + * Example MCP server using Hono with WebStandardStreamableHTTPServerTransport + * + * This example demonstrates using the Web Standard transport directly with Hono, + * which works on any runtime: Node.js, Cloudflare Workers, Deno, Bun, etc. + * + * Run with: npx tsx src/examples/server/honoWebStandardStreamableHttp.ts + */ +export {}; +//# sourceMappingURL=honoWebStandardStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/honoWebStandardStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/honoWebStandardStreamableHttp.d.ts.map new file mode 100644 index 000000000..a6a6199d6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/honoWebStandardStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"honoWebStandardStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/honoWebStandardStreamableHttp.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/honoWebStandardStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/honoWebStandardStreamableHttp.js new file mode 100644 index 000000000..ddb1abb8f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/honoWebStandardStreamableHttp.js @@ -0,0 +1,56 @@ +/** + * Example MCP server using Hono with WebStandardStreamableHTTPServerTransport + * + * This example demonstrates using the Web Standard transport directly with Hono, + * which works on any runtime: Node.js, Cloudflare Workers, Deno, Bun, etc. + * + * Run with: npx tsx src/examples/server/honoWebStandardStreamableHttp.ts + */ +import { Hono } from 'hono'; +import { cors } from 'hono/cors'; +import { serve } from '@hono/node-server'; +import * as z from 'zod/v4'; +import { McpServer } from '../../server/mcp.js'; +import { WebStandardStreamableHTTPServerTransport } from '../../server/webStandardStreamableHttp.js'; +// Create the MCP server +const server = new McpServer({ + name: 'hono-webstandard-mcp-server', + version: '1.0.0' +}); +// Register a simple greeting tool +server.registerTool('greet', { + title: 'Greeting Tool', + description: 'A simple greeting tool', + inputSchema: { name: z.string().describe('Name to greet') } +}, async ({ name }) => { + return { + content: [{ type: 'text', text: `Hello, ${name}! (from Hono + WebStandard transport)` }] + }; +}); +// Create a stateless transport (no options = no session management) +const transport = new WebStandardStreamableHTTPServerTransport(); +// Create the Hono app +const app = new Hono(); +// Enable CORS for all origins +app.use('*', cors({ + origin: '*', + allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS'], + allowHeaders: ['Content-Type', 'mcp-session-id', 'Last-Event-ID', 'mcp-protocol-version'], + exposeHeaders: ['mcp-session-id', 'mcp-protocol-version'] +})); +// Health check endpoint +app.get('/health', c => c.json({ status: 'ok' })); +// MCP endpoint +app.all('/mcp', c => transport.handleRequest(c.req.raw)); +// Start the server +const PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; +server.connect(transport).then(() => { + console.log(`Starting Hono MCP server on port ${PORT}`); + console.log(`Health check: http://localhost:${PORT}/health`); + console.log(`MCP endpoint: http://localhost:${PORT}/mcp`); + serve({ + fetch: app.fetch, + port: PORT + }); +}); +//# sourceMappingURL=honoWebStandardStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/honoWebStandardStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/honoWebStandardStreamableHttp.js.map new file mode 100644 index 000000000..9d609286e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/honoWebStandardStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"honoWebStandardStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/honoWebStandardStreamableHttp.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AAGrG,wBAAwB;AACxB,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC;IACzB,IAAI,EAAE,6BAA6B;IACnC,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,kCAAkC;AAClC,MAAM,CAAC,YAAY,CACf,OAAO,EACP;IACI,KAAK,EAAE,eAAe;IACtB,WAAW,EAAE,wBAAwB;IACrC,WAAW,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,eAAe,CAAC,EAAE;CAC9D,EACD,KAAK,EAAE,EAAE,IAAI,EAAE,EAA2B,EAAE;IACxC,OAAO;QACH,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,IAAI,uCAAuC,EAAE,CAAC;KAC3F,CAAC;AACN,CAAC,CACJ,CAAC;A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,CAAC,KAAK;QAChB,IAAI,EAAE,IAAI;KACb,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts new file mode 100644 index 000000000..477fa6bae --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=jsonResponseStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts.map new file mode 100644 index 000000000..ee8117ee2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonResponseStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/jsonResponseStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/jsonResponseStreamableHttp.js new file mode 100644 index 000000000..b2ef0cea5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/jsonResponseStreamableHttp.js @@ -0,0 +1,146 @@ +import { randomUUID } from 'node:crypto'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import * as z from 'zod/v4'; +import { isInitializeRequest } from '../../types.js'; +import { createMcpExpressApp } from '../../server/express.js'; +// Create an MCP server with implementation details +const getServer = () => { + const server = new McpServer({ + name: 'json-response-streamable-http-server', + version: '1.0.0' + }, { + capabilities: { + logging: {} + } + }); + // Register a simple tool that returns a greeting + server.registerTool('greet', { + description: 'A simple greeting tool', + inputSchema: { + name: z.string().describe('Name to greet') + } + }, async ({ name }) => { + return { + content: [ + { + type: 'text', + text: `Hello, ${name}!` + } + ] + }; + }); + // Register a tool that sends multiple greetings with notifications + server.registerTool('multi-greet', { + description: 'A tool that sends different greetings with delays between them', + inputSchema: { + name: z.string().describe('Name to greet') + } + }, async ({ name }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + await server.sendLoggingMessage({ + level: 'debug', + data: `Starting multi-greet for ${name}` + }, extra.sessionId); + await sleep(1000); // Wait 1 second before first greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending first greeting to ${name}` + }, extra.sessionId); + await sleep(1000); // Wait another second before second greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending second greeting to ${name}` + }, extra.sessionId); + return { + content: [ + { + type: 'text', + text: `Good morning, ${name}!` + } + ] + }; + }); + return server; +}; +const app = createMcpExpressApp(); +// Map to store transports by session ID +const transports = {}; +app.post('/mcp', async (req, res) => { + console.log('Received MCP request:', req.body); + try { + // Check for existing session ID + const sessionId = req.headers['mcp-session-id']; + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && isInitializeRequest(req.body)) { + // New initialization request - use JSON response mode + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + enableJsonResponse: true, // Enable JSON response mode + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Connect the transport to the MCP server BEFORE handling the request + const server = getServer(); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport - no need to reconnect + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +// Handle GET requests for SSE streams according to spec +app.get('/mcp', async (req, res) => { + // Since this is a very simple example, we don't support GET requests for this server + // The spec requires returning 405 Method Not Allowed in this case + res.status(405).set('Allow', 'POST').send('Method Not Allowed'); +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Streamable HTTP Server listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + process.exit(0); +}); +//# sourceMappingURL=jsonResponseStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/jsonResponseStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/jsonResponseStreamableHttp.js.map new file mode 100644 index 000000000..8a52d919f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/jsonResponseStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonResponseStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAkB,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAE9D,mDAAmD;AACnD,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,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AE,GAAa,EAAE,EAAE;IAClD,qFAAqF;IACrF,kEAAkE;IAClE,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;AACpE,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,IAAI,EAAE,CAAC,CAAC;AACxE,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/mcpServerOutputSchema.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/mcpServerOutputSchema.d.ts new file mode 100644 index 000000000..a6cb49747 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/mcpServerOutputSchema.d.ts @@ -0,0 +1,7 @@ +#!/usr/bin/env node +/** + * Example MCP server using the high-level McpServer API with outputSchema + * This demonstrates how to easily create tools with structured output + */ +export {}; +//# sourceMappingURL=mcpServerOutputSchema.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/mcpServerOutputSchema.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/mcpServerOutputSchema.d.ts.map new file mode 100644 index 000000000..bd3abdcc2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/mcpServerOutputSchema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mcpServerOutputSchema.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";AACA;;;GAGG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/mcpServerOutputSchema.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/mcpServerOutputSchema.js new file mode 100644 index 000000000..17b52b73e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/mcpServerOutputSchema.js @@ -0,0 +1,70 @@ +#!/usr/bin/env node +/** + * Example MCP server using the high-level McpServer API with outputSchema + * This demonstrates how to easily create tools with structured output + */ +import { McpServer } from '../../server/mcp.js'; +import { StdioServerTransport } from '../../server/stdio.js'; +import * as z from 'zod/v4'; +const server = new McpServer({ + name: 'mcp-output-schema-high-level-example', + version: '1.0.0' +}); +// Define a tool with structured output - Weather data +server.registerTool('get_weather', { + description: 'Get weather information for a city', + inputSchema: { + city: z.string().describe('City name'), + country: z.string().describe('Country code (e.g., US, UK)') + }, + outputSchema: { + temperature: z.object({ + celsius: z.number(), + fahrenheit: z.number() + }), + conditions: z.enum(['sunny', 'cloudy', 'rainy', 'stormy', 'snowy']), + humidity: z.number().min(0).max(100), + wind: z.object({ + speed_kmh: z.number(), + direction: z.string() + }) + } +}, async ({ city, country }) => { + // Parameters are available but not used in this example + void city; + void country; + // Simulate weather API call + const temp_c = Math.round((Math.random() * 35 - 5) * 10) / 10; + const conditions = ['sunny', 'cloudy', 'rainy', 'stormy', 'snowy'][Math.floor(Math.random() * 5)]; + const structuredContent = { + temperature: { + celsius: temp_c, + fahrenheit: Math.round(((temp_c * 9) / 5 + 32) * 10) / 10 + }, + conditions, + humidity: Math.round(Math.random() * 100), + wind: { + speed_kmh: Math.round(Math.random() * 50), + direction: ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][Math.floor(Math.random() * 8)] + } + }; + return { + content: [ + { + type: 'text', + text: JSON.stringify(structuredContent, null, 2) + } + ], + structuredContent + }; +}); +async function main() { + const transport = new StdioServerTransport(); + await server.connect(transport); + console.error('High-level Output Schema Example Server running on stdio'); +} +main().catch(error => { + console.error('Server error:', error); + process.exit(1); +}); +//# sourceMappingURL=mcpServerOutputSchema.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/mcpServerOutputSchema.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/mcpServerOutputSchema.js.map new file mode 100644 index 000000000..b932b856b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/mcpServerOutputSchema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mcpServerOutputSchema.js","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";AACA;;;GAGG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC;IACzB,IAAI,EAAE,sCAAsC;IAC5C,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,sDAAsD;AACtD,MAAM,CAAC,YAAY,CACf,aAAa,EACb;IACI,WAAW,EAAE,oCAAoC;IACjD,WAAW,EAAE;QACT,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,WAAW,CAAC;QACtC,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,6BAA6B,CAAC;KAC9D;IACD,YAAY,EAAE;QACV,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC;YAClB,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,EAAE;YACF,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC;YACzC,SAAS,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;SACzF;KACJ,CAAC;IAEF,OAAO;QACH,OAAO,EAAE;YACL;gBACI,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC;aACnD;SACJ;QACD,iBAAiB;KACpB,CAAC;AACN,CAAC,CACJ,CAAC;AAEF,KAAK,UAAU,IAAI;IACf,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;IAC7C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,CAAC,KAAK,CAAC,0DAA0D,CAAC,CAAC;AAC9E,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleSseServer.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleSseServer.d.ts new file mode 100644 index 000000000..4269b7814 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleSseServer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleSseServer.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleSseServer.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleSseServer.d.ts.map new file mode 100644 index 000000000..08a1b4502 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleSseServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleSseServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleSseServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleSseServer.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleSseServer.js new file mode 100644 index 000000000..60c3eb675 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleSseServer.js @@ -0,0 +1,143 @@ +import { McpServer } from '../../server/mcp.js'; +import { SSEServerTransport } from '../../server/sse.js'; +import * as z from 'zod/v4'; +import { createMcpExpressApp } from '../../server/express.js'; +/** + * This example server demonstrates the deprecated HTTP+SSE transport + * (protocol version 2024-11-05). It mainly used for testing backward compatible clients. + * + * The server exposes two endpoints: + * - /mcp: For establishing the SSE stream (GET) + * - /messages: For receiving client messages (POST) + * + */ +// Create an MCP server instance +const getServer = () => { + const server = new McpServer({ + name: 'simple-sse-server', + version: '1.0.0' + }, { capabilities: { logging: {} } }); + server.registerTool('start-notification-stream', { + description: 'Starts sending periodic notifications', + inputSchema: { + interval: z.number().describe('Interval in milliseconds between notifications').default(1000), + count: z.number().describe('Number of notifications to send').default(10) + } + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + // Send the initial notification + await server.sendLoggingMessage({ + level: 'info', + data: `Starting notification stream with ${count} messages every ${interval}ms` + }, extra.sessionId); + // Send periodic notifications + while (counter < count) { + counter++; + await sleep(interval); + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + } + return { + content: [ + { + type: 'text', + text: `Completed sending ${count} notifications every ${interval}ms` + } + ] + }; + }); + return server; +}; +const app = createMcpExpressApp(); +// Store transports by session ID +const transports = {}; +// SSE endpoint for establishing the stream +app.get('/mcp', async (req, res) => { + console.log('Received GET request to /sse (establishing SSE stream)'); + try { + // Create a new SSE transport for the client + // The endpoint for POST messages is '/messages' + const transport = new SSEServerTransport('/messages', res); + // Store the transport by session ID + const sessionId = transport.sessionId; + transports[sessionId] = transport; + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + console.log(`SSE transport closed for session ${sessionId}`); + delete transports[sessionId]; + }; + // Connect the transport to the MCP server + const server = getServer(); + await server.connect(transport); + console.log(`Established SSE stream with session ID: ${sessionId}`); + } + catch (error) { + console.error('Error establishing SSE stream:', error); + if (!res.headersSent) { + res.status(500).send('Error establishing SSE stream'); + } + } +}); +// Messages endpoint for receiving client JSON-RPC requests +app.post('/messages', async (req, res) => { + console.log('Received POST request to /messages'); + // Extract session ID from URL query parameter + // In the SSE protocol, this is added by the client based on the endpoint event + const sessionId = req.query.sessionId; + if (!sessionId) { + console.error('No session ID provided in request URL'); + res.status(400).send('Missing sessionId parameter'); + return; + } + const transport = transports[sessionId]; + if (!transport) { + console.error(`No active transport found for session ID: ${sessionId}`); + res.status(404).send('Session not found'); + return; + } + try { + // Handle the POST message with the transport + await transport.handlePostMessage(req, res, req.body); + } + catch (error) { + console.error('Error handling request:', error); + if (!res.headersSent) { + res.status(500).send('Error handling request'); + } + } +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Simple SSE Server (deprecated protocol version 2024-11-05) listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=simpleSseServer.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleSseServer.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleSseServer.js.map new file mode 100644 index 000000000..8028aa52c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleSseServer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleSseServer.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleSseServer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAE9D;;;;;;;;GAQG;AAEH,gCAAgC;AAChC,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,SAAS,CACxB;QACI,IAAI,EAAE,mBAAmB;QACzB,OAAO,EAAE,OAAO;KACnB,EACD,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,CACpC,CAAC;IAEF,MAAM,CAAC,YAAY,CACf,2BAA2B,EAC3B;QACI,WAAW,EAAE,uCAAuC;QACpD,WAAW,EAAE;YACT,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,gDAAgD,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;YAC7F,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,iCAAiC,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;SAC5E;KACJ,EACD,KAAK,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,KAAK,EAA2B,EAAE;QAC1D,MAAM,KAAK,GAAG,CAAC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K,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts new file mode 100644 index 000000000..0aa4ad243 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleStatelessStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts.map new file mode 100644 index 000000000..92deb06ec --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStatelessStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleStatelessStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStatelessStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStatelessStreamableHttp.js new file mode 100644 index 000000000..aa66f0ed8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStatelessStreamableHttp.js @@ -0,0 +1,141 @@ +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import * as z from 'zod/v4'; +import { createMcpExpressApp } from '../../server/express.js'; +const getServer = () => { + // Create an MCP server with implementation details + const server = new McpServer({ + name: 'stateless-streamable-http-server', + version: '1.0.0' + }, { capabilities: { logging: {} } }); + // Register a simple prompt + server.registerPrompt('greeting-template', { + description: 'A simple greeting prompt template', + argsSchema: { + name: z.string().describe('Name to include in greeting') + } + }, async ({ name }) => { + return { + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please greet ${name} in a friendly manner.` + } + } + ] + }; + }); + // Register a tool specifically for testing resumability + server.registerTool('start-notification-stream', { + description: 'Starts sending periodic notifications for testing resumability', + inputSchema: { + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(10) + } + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + while (count === 0 || counter < count) { + counter++; + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Periodic notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + // Wait for the specified interval + await sleep(interval); + } + return { + content: [ + { + type: 'text', + text: `Started sending periodic notifications every ${interval}ms` + } + ] + }; + }); + // Create a simple resource at a fixed URI + server.registerResource('greeting-resource', 'https://example.com/greetings/default', { mimeType: 'text/plain' }, async () => { + return { + contents: [ + { + uri: 'https://example.com/greetings/default', + text: 'Hello, world!' + } + ] + }; + }); + return server; +}; +const app = createMcpExpressApp(); +app.post('/mcp', async (req, res) => { + const server = getServer(); + try { + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined + }); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + res.on('close', () => { + console.log('Request closed'); + transport.close(); + server.close(); + }); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +app.get('/mcp', async (req, res) => { + console.log('Received GET MCP request'); + res.writeHead(405).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + })); +}); +app.delete('/mcp', async (req, res) => { + console.log('Received DELETE MCP request'); + res.writeHead(405).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + })); +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Stateless Streamable HTTP Server listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + process.exit(0); +}); +//# sourceMappingURL=simpleStatelessStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStatelessStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStatelessStreamableHttp.js.map new file mode 100644 index 000000000..0617e71d8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStatelessStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStatelessStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleStatelessStreamableHttp.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAA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;IACrD,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAC3C,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,CAClB,IAAI,CAAC,SAAS,CAAC;QACX,OAAO,EAAE,KAAK;QACd,KAAK,EAAE;YACH,IAAI,EAAE,CAAC,KAAK;YACZ,OAAO,EAAE,qBAAqB;SACjC;QACD,EAAE,EAAE,IAAI;KACX,CAAC,CACL,CAAC;AACN,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,EAAE,CAAC,CAAC;AAClF,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStreamableHttp.d.ts new file mode 100644 index 000000000..a20be42ca --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStreamableHttp.d.ts.map new file mode 100644 index 000000000..e3cf04224 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStreamableHttp.js new file mode 100644 index 000000000..742c30693 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStreamableHttp.js @@ -0,0 +1,636 @@ +import { randomUUID } from 'node:crypto'; +import * as z from 'zod/v4'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter } from '../../server/auth/router.js'; +import { requireBearerAuth } from '../../server/auth/middleware/bearerAuth.js'; +import { createMcpExpressApp } from '../../server/express.js'; +import { ElicitResultSchema, isInitializeRequest } from '../../types.js'; +import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; +import { InMemoryTaskStore, InMemoryTaskMessageQueue } from '../../experimental/tasks/stores/in-memory.js'; +import { setupAuthServer } from './demoInMemoryOAuthProvider.js'; +import { checkResourceAllowed } from '../../shared/auth-utils.js'; +// Check for OAuth flag +const useOAuth = process.argv.includes('--oauth'); +const strictOAuth = process.argv.includes('--oauth-strict'); +// Create shared task store for demonstration +const taskStore = new InMemoryTaskStore(); +// Create an MCP server with implementation details +const getServer = () => { + const server = new McpServer({ + name: 'simple-streamable-http-server', + version: '1.0.0', + icons: [{ src: './mcp.svg', sizes: ['512x512'], mimeType: 'image/svg+xml' }], + websiteUrl: 'https://github.com/modelcontextprotocol/typescript-sdk' + }, { + capabilities: { logging: {}, tasks: { requests: { tools: { call: {} } } } }, + taskStore, // Enable task support + taskMessageQueue: new InMemoryTaskMessageQueue() + }); + // Register a simple tool that returns a greeting + server.registerTool('greet', { + title: 'Greeting Tool', // Display name for UI + description: 'A simple greeting tool', + inputSchema: { + name: z.string().describe('Name to greet') + } + }, async ({ name }) => { + return { + content: [ + { + type: 'text', + text: `Hello, ${name}!` + } + ] + }; + }); + // Register a tool that sends multiple greetings with notifications (with annotations) + server.registerTool('multi-greet', { + description: 'A tool that sends different greetings with delays between them', + inputSchema: { + name: z.string().describe('Name to greet') + }, + annotations: { + title: 'Multiple Greeting Tool', + readOnlyHint: true, + openWorldHint: false + } + }, async ({ name }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + await server.sendLoggingMessage({ + level: 'debug', + data: `Starting multi-greet for ${name}` + }, extra.sessionId); + await sleep(1000); // Wait 1 second before first greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending first greeting to ${name}` + }, extra.sessionId); + await sleep(1000); // Wait another second before second greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending second greeting to ${name}` + }, extra.sessionId); + return { + content: [ + { + type: 'text', + text: `Good morning, ${name}!` + } + ] + }; + }); + // Register a tool that demonstrates form elicitation (user input collection with a schema) + // This creates a closure that captures the server instance + server.registerTool('collect-user-info', { + description: 'A tool that collects user information through form elicitation', + inputSchema: { + infoType: z.enum(['contact', 'preferences', 'feedback']).describe('Type of information to collect') + } + }, async ({ infoType }, extra) => { + let message; + let requestedSchema; + switch (infoType) { + case 'contact': + message = 'Please provide your contact information'; + requestedSchema = { + type: 'object', + properties: { + name: { + type: 'string', + title: 'Full Name', + description: 'Your full name' + }, + email: { + type: 'string', + title: 'Email Address', + description: 'Your email address', + format: 'email' + }, + phone: { + type: 'string', + title: 'Phone Number', + description: 'Your phone number (optional)' + } + }, + required: ['name', 'email'] + }; + break; + case 'preferences': + message = 'Please set your preferences'; + requestedSchema = { + type: 'object', + properties: { + theme: { + type: 'string', + title: 'Theme', + description: 'Choose your preferred theme', + enum: ['light', 'dark', 'auto'], + enumNames: ['Light', 'Dark', 'Auto'] + }, + notifications: { + type: 'boolean', + title: 'Enable Notifications', + description: 'Would you like to receive notifications?', + default: true + }, + frequency: { + type: 'string', + title: 'Notification Frequency', + description: 'How often would you like notifications?', + enum: ['daily', 'weekly', 'monthly'], + enumNames: ['Daily', 'Weekly', 'Monthly'] + } + }, + required: ['theme'] + }; + break; + case 'feedback': + message = 'Please provide your feedback'; + requestedSchema = { + type: 'object', + properties: { + rating: { + type: 'integer', + title: 'Rating', + description: 'Rate your experience (1-5)', + minimum: 1, + maximum: 5 + }, + comments: { + type: 'string', + title: 'Comments', + description: 'Additional comments (optional)', + maxLength: 500 + }, + recommend: { + type: 'boolean', + title: 'Would you recommend this?', + description: 'Would you recommend this to others?' + } + }, + required: ['rating', 'recommend'] + }; + break; + default: + throw new Error(`Unknown info type: ${infoType}`); + } + try { + // Use sendRequest through the extra parameter to elicit input + const result = await extra.sendRequest({ + method: 'elicitation/create', + params: { + mode: 'form', + message, + requestedSchema + } + }, ElicitResultSchema); + if (result.action === 'accept') { + return { + content: [ + { + type: 'text', + text: `Thank you! Collected ${infoType} information: ${JSON.stringify(result.content, null, 2)}` + } + ] + }; + } + else if (result.action === 'decline') { + return { + content: [ + { + type: 'text', + text: `No information was collected. User declined ${infoType} information request.` + } + ] + }; + } + else { + return { + content: [ + { + type: 'text', + text: `Information collection was cancelled by the user.` + } + ] + }; + } + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Error collecting ${infoType} information: ${error}` + } + ] + }; + } + }); + // Register a simple prompt with title + server.registerPrompt('greeting-template', { + title: 'Greeting Template', // Display name for UI + description: 'A simple greeting prompt template', + argsSchema: { + name: z.string().describe('Name to include in greeting') + } + }, async ({ name }) => { + return { + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please greet ${name} in a friendly manner.` + } + } + ] + }; + }); + // Register a tool specifically for testing resumability + server.registerTool('start-notification-stream', { + description: 'Starts sending periodic notifications for testing resumability', + inputSchema: { + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(50) + } + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + while (count === 0 || counter < count) { + counter++; + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Periodic notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + // Wait for the specified interval + await sleep(interval); + } + return { + content: [ + { + type: 'text', + text: `Started sending periodic notifications every ${interval}ms` + } + ] + }; + }); + // Create a simple resource at a fixed URI + server.registerResource('greeting-resource', 'https://example.com/greetings/default', { + title: 'Default Greeting', // Display name for UI + description: 'A simple greeting resource', + mimeType: 'text/plain' + }, async () => { + return { + contents: [ + { + uri: 'https://example.com/greetings/default', + text: 'Hello, world!' + } + ] + }; + }); + // Create additional resources for ResourceLink demonstration + server.registerResource('example-file-1', 'file:///example/file1.txt', { + title: 'Example File 1', + description: 'First example file for ResourceLink demonstration', + mimeType: 'text/plain' + }, async () => { + return { + contents: [ + { + uri: 'file:///example/file1.txt', + text: 'This is the content of file 1' + } + ] + }; + }); + server.registerResource('example-file-2', 'file:///example/file2.txt', { + title: 'Example File 2', + description: 'Second example file for ResourceLink demonstration', + mimeType: 'text/plain' + }, async () => { + return { + contents: [ + { + uri: 'file:///example/file2.txt', + text: 'This is the content of file 2' + } + ] + }; + }); + // Register a tool that returns ResourceLinks + server.registerTool('list-files', { + title: 'List Files with ResourceLinks', + description: 'Returns a list of files as ResourceLinks without embedding their content', + inputSchema: { + includeDescriptions: z.boolean().optional().describe('Whether to include descriptions in the resource links') + } + }, async ({ includeDescriptions = true }) => { + const resourceLinks = [ + { + type: 'resource_link', + uri: 'https://example.com/greetings/default', + name: 'Default Greeting', + mimeType: 'text/plain', + ...(includeDescriptions && { description: 'A simple greeting resource' }) + }, + { + type: 'resource_link', + uri: 'file:///example/file1.txt', + name: 'Example File 1', + mimeType: 'text/plain', + ...(includeDescriptions && { description: 'First example file for ResourceLink demonstration' }) + }, + { + type: 'resource_link', + uri: 'file:///example/file2.txt', + name: 'Example File 2', + mimeType: 'text/plain', + ...(includeDescriptions && { description: 'Second example file for ResourceLink demonstration' }) + } + ]; + return { + content: [ + { + type: 'text', + text: 'Here are the available files as resource links:' + }, + ...resourceLinks, + { + type: 'text', + text: '\nYou can read any of these resources using their URI.' + } + ] + }; + }); + // Register a long-running tool that demonstrates task execution + // Using the experimental tasks API - WARNING: may change without notice + server.experimental.tasks.registerToolTask('delay', { + title: 'Delay', + description: 'A simple tool that delays for a specified duration, useful for testing task execution', + inputSchema: { + duration: z.number().describe('Duration in milliseconds').default(5000) + } + }, { + async createTask({ duration }, { taskStore, taskRequestedTtl }) { + // Create the task + const task = await taskStore.createTask({ + ttl: taskRequestedTtl + }); + // Simulate out-of-band work + (async () => { + await new Promise(resolve => setTimeout(resolve, duration)); + await taskStore.storeTaskResult(task.taskId, 'completed', { + content: [ + { + type: 'text', + text: `Completed ${duration}ms delay` + } + ] + }); + })(); + // Return CreateTaskResult with the created task + return { + task + }; + }, + async getTask(_args, { taskId, taskStore }) { + return await taskStore.getTask(taskId); + }, + async getTaskResult(_args, { taskId, taskStore }) { + const result = await taskStore.getTaskResult(taskId); + return result; + } + }); + return server; +}; +const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; +const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; +const app = createMcpExpressApp(); +// Set up OAuth if enabled +let authMiddleware = null; +if (useOAuth) { + // Create auth middleware for MCP endpoints + const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); + const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); + const oauthMetadata = setupAuthServer({ authServerUrl, mcpServerUrl, strictResource: strictOAuth }); + const tokenVerifier = { + verifyAccessToken: async (token) => { + const endpoint = oauthMetadata.introspection_endpoint; + if (!endpoint) { + throw new Error('No token verification endpoint available in metadata'); + } + const response = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: new URLSearchParams({ + token: token + }).toString() + }); + if (!response.ok) { + const text = await response.text().catch(() => null); + throw new Error(`Invalid or expired token: ${text}`); + } + const data = await response.json(); + if (strictOAuth) { + if (!data.aud) { + throw new Error(`Resource Indicator (RFC8707) missing`); + } + if (!checkResourceAllowed({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { + throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); + } + } + // Convert the response to AuthInfo format + return { + token, + clientId: data.client_id, + scopes: data.scope ? data.scope.split(' ') : [], + expiresAt: data.exp + }; + } + }; + // Add metadata routes to the main MCP server + app.use(mcpAuthMetadataRouter({ + oauthMetadata, + resourceServerUrl: mcpServerUrl, + scopesSupported: ['mcp:tools'], + resourceName: 'MCP Demo Server' + })); + authMiddleware = requireBearerAuth({ + verifier: tokenVerifier, + requiredScopes: [], + resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl) + }); +} +// Map to store transports by session ID +const transports = {}; +// MCP POST endpoint with optional auth +const mcpPostHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (sessionId) { + console.log(`Received MCP request for session: ${sessionId}`); + } + else { + console.log('Request body:', req.body); + } + if (useOAuth && req.auth) { + console.log('Authenticated user:', req.auth); + } + try { + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && isInitializeRequest(req.body)) { + // New initialization request + const eventStore = new InMemoryEventStore(); + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + eventStore, // Enable resumability + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + } + }; + // Connect the transport to the MCP server BEFORE handling the request + // so responses can flow back through the same transport + const server = getServer(); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport - no need to reconnect + // The existing transport is already connected to the server + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}; +// Set up routes with conditional auth middleware +if (useOAuth && authMiddleware) { + app.post('/mcp', authMiddleware, mcpPostHandler); +} +else { + app.post('/mcp', mcpPostHandler); +} +// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) +const mcpGetHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + if (useOAuth && req.auth) { + console.log('Authenticated SSE connection from user:', req.auth); + } + // Check for Last-Event-ID header for resumability + const lastEventId = req.headers['last-event-id']; + if (lastEventId) { + console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); + } + else { + console.log(`Establishing new SSE stream for session ${sessionId}`); + } + const transport = transports[sessionId]; + await transport.handleRequest(req, res); +}; +// Set up GET route with conditional auth middleware +if (useOAuth && authMiddleware) { + app.get('/mcp', authMiddleware, mcpGetHandler); +} +else { + app.get('/mcp', mcpGetHandler); +} +// Handle DELETE requests for session termination (according to MCP spec) +const mcpDeleteHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Received session termination request for session ${sessionId}`); + try { + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + } + catch (error) { + console.error('Error handling session termination:', error); + if (!res.headersSent) { + res.status(500).send('Error processing session termination'); + } + } +}; +// Set up DELETE route with conditional auth middleware +if (useOAuth && authMiddleware) { + app.delete('/mcp', authMiddleware, mcpDeleteHandler); +} +else { + app.delete('/mcp', mcpDeleteHandler); +} +app.listen(MCP_PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=simpleStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStreamableHttp.js.map new file mode 100644 index 000000000..9f4258431 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleStreamableHttp.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,oCAAoC,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAC1G,OAAO,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAC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CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,EAAE,gBAAgB,CAAC,CAAC;AACzD,CAAC;KAAM,CAAC;IACJ,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;AACzC,CAAC;AAED,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE;IACzB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,QAAQ,EAAE,CAAC,CAAC;AAC5E,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAEvC,6DAA6D;IAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleTaskInteractive.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleTaskInteractive.d.ts new file mode 100644 index 000000000..661c9f010 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleTaskInteractive.d.ts @@ -0,0 +1,12 @@ +/** + * Simple interactive task server demonstrating elicitation and sampling. + * + * This server demonstrates the task message queue pattern from the MCP Tasks spec: + * - confirm_delete: Uses elicitation to ask the user for confirmation + * - write_haiku: Uses sampling to request an LLM to generate content + * + * Both tools use the "call-now, fetch-later" pattern where the initial call + * creates a task, and the result is fetched via tasks/result endpoint. + */ +export {}; +//# sourceMappingURL=simpleTaskInteractive.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleTaskInteractive.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleTaskInteractive.d.ts.map new file mode 100644 index 000000000..3e48b9e76 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleTaskInteractive.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleTaskInteractive.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleTaskInteractive.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleTaskInteractive.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleTaskInteractive.js new file mode 100644 index 000000000..220049273 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleTaskInteractive.js @@ -0,0 +1,598 @@ +/** + * Simple interactive task server demonstrating elicitation and sampling. + * + * This server demonstrates the task message queue pattern from the MCP Tasks spec: + * - confirm_delete: Uses elicitation to ask the user for confirmation + * - write_haiku: Uses sampling to request an LLM to generate content + * + * Both tools use the "call-now, fetch-later" pattern where the initial call + * creates a task, and the result is fetched via tasks/result endpoint. + */ +import { randomUUID } from 'node:crypto'; +import { Server } from '../../server/index.js'; +import { createMcpExpressApp } from '../../server/express.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { RELATED_TASK_META_KEY, ListToolsRequestSchema, CallToolRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema } from '../../types.js'; +import { isTerminal } from '../../experimental/tasks/interfaces.js'; +import { InMemoryTaskStore } from '../../experimental/tasks/stores/in-memory.js'; +// ============================================================================ +// Resolver - Promise-like for passing results between async operations +// ============================================================================ +class Resolver { + constructor() { + this._done = false; + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + } + setResult(value) { + if (this._done) + return; + this._done = true; + this._resolve(value); + } + setException(error) { + if (this._done) + return; + this._done = true; + this._reject(error); + } + wait() { + return this._promise; + } + done() { + return this._done; + } +} +class TaskMessageQueueWithResolvers { + constructor() { + this.queues = new Map(); + this.waitResolvers = new Map(); + } + getQueue(taskId) { + let queue = this.queues.get(taskId); + if (!queue) { + queue = []; + this.queues.set(taskId, queue); + } + return queue; + } + async enqueue(taskId, message, _sessionId, maxSize) { + const queue = this.getQueue(taskId); + if (maxSize !== undefined && queue.length >= maxSize) { + throw new Error(`Task message queue overflow: queue size (${queue.length}) exceeds maximum (${maxSize})`); + } + queue.push(message); + // Notify any waiters + this.notifyWaiters(taskId); + } + async enqueueWithResolver(taskId, message, resolver, originalRequestId) { + const queue = this.getQueue(taskId); + const queuedMessage = { + type: 'request', + message, + timestamp: Date.now(), + resolver, + originalRequestId + }; + queue.push(queuedMessage); + this.notifyWaiters(taskId); + } + async dequeue(taskId, _sessionId) { + const queue = this.getQueue(taskId); + return queue.shift(); + } + async dequeueAll(taskId, _sessionId) { + const queue = this.queues.get(taskId) ?? []; + this.queues.delete(taskId); + return queue; + } + async waitForMessage(taskId) { + // Check if there are already messages + const queue = this.getQueue(taskId); + if (queue.length > 0) + return; + // Wait for a message to be added + return new Promise(resolve => { + let waiters = this.waitResolvers.get(taskId); + if (!waiters) { + waiters = []; + this.waitResolvers.set(taskId, waiters); + } + waiters.push(resolve); + }); + } + notifyWaiters(taskId) { + const waiters = this.waitResolvers.get(taskId); + if (waiters) { + this.waitResolvers.delete(taskId); + for (const resolve of waiters) { + resolve(); + } + } + } + cleanup() { + this.queues.clear(); + this.waitResolvers.clear(); + } +} +// ============================================================================ +// Extended task store with wait functionality +// ============================================================================ +class TaskStoreWithNotifications extends InMemoryTaskStore { + constructor() { + super(...arguments); + this.updateResolvers = new Map(); + } + async updateTaskStatus(taskId, status, statusMessage, sessionId) { + await super.updateTaskStatus(taskId, status, statusMessage, sessionId); + this.notifyUpdate(taskId); + } + async storeTaskResult(taskId, status, result, sessionId) { + await super.storeTaskResult(taskId, status, result, sessionId); + this.notifyUpdate(taskId); + } + async waitForUpdate(taskId) { + return new Promise(resolve => { + let waiters = this.updateResolvers.get(taskId); + if (!waiters) { + waiters = []; + this.updateResolvers.set(taskId, waiters); + } + waiters.push(resolve); + }); + } + notifyUpdate(taskId) { + const waiters = this.updateResolvers.get(taskId); + if (waiters) { + this.updateResolvers.delete(taskId); + for (const resolve of waiters) { + resolve(); + } + } + } +} +// ============================================================================ +// Task Result Handler - delivers queued messages and routes responses +// ============================================================================ +class TaskResultHandler { + constructor(store, queue) { + this.store = store; + this.queue = queue; + this.pendingRequests = new Map(); + } + async handle(taskId, server, _sessionId) { + while (true) { + // Get fresh task state + const task = await this.store.getTask(taskId); + if (!task) { + throw new Error(`Task not found: ${taskId}`); + } + // Dequeue and send all pending messages + await this.deliverQueuedMessages(taskId, server, _sessionId); + // If task is terminal, return result + if (isTerminal(task.status)) { + const result = await this.store.getTaskResult(taskId); + // Add related-task metadata per spec + return { + ...result, + _meta: { + ...(result._meta || {}), + [RELATED_TASK_META_KEY]: { taskId } + } + }; + } + // Wait for task update or new message + await this.waitForUpdate(taskId); + } + } + async deliverQueuedMessages(taskId, server, _sessionId) { + while (true) { + const message = await this.queue.dequeue(taskId); + if (!message) + break; + console.log(`[Server] Delivering queued ${message.type} message for task ${taskId}`); + if (message.type === 'request') { + const reqMessage = message; + // Send the request via the server + // Store the resolver so we can route the response back + if (reqMessage.resolver && reqMessage.originalRequestId) { + this.pendingRequests.set(reqMessage.originalRequestId, reqMessage.resolver); + } + // Send the message - for elicitation/sampling, we use the server's methods + // But since we're in tasks/result context, we need to send via transport + // This is simplified - in production you'd use proper message routing + try { + const request = reqMessage.message; + let response; + if (request.method === 'elicitation/create') { + // Send elicitation request to client + const params = request.params; + response = await server.elicitInput(params); + } + else if (request.method === 'sampling/createMessage') { + // Send sampling request to client + const params = request.params; + response = await server.createMessage(params); + } + else { + throw new Error(`Unknown request method: ${request.method}`); + } + // Route response back to resolver + if (reqMessage.resolver) { + reqMessage.resolver.setResult(response); + } + } + catch (error) { + if (reqMessage.resolver) { + reqMessage.resolver.setException(error instanceof Error ? error : new Error(String(error))); + } + } + } + // For notifications, we'd send them too but this example focuses on requests + } + } + async waitForUpdate(taskId) { + // Race between store update and queue message + await Promise.race([this.store.waitForUpdate(taskId), this.queue.waitForMessage(taskId)]); + } + routeResponse(requestId, response) { + const resolver = this.pendingRequests.get(requestId); + if (resolver && !resolver.done()) { + this.pendingRequests.delete(requestId); + resolver.setResult(response); + return true; + } + return false; + } + routeError(requestId, error) { + const resolver = this.pendingRequests.get(requestId); + if (resolver && !resolver.done()) { + this.pendingRequests.delete(requestId); + resolver.setException(error); + return true; + } + return false; + } +} +// ============================================================================ +// Task Session - wraps server to enqueue requests during task execution +// ============================================================================ +class TaskSession { + constructor(server, taskId, store, queue) { + this.server = server; + this.taskId = taskId; + this.store = store; + this.queue = queue; + this.requestCounter = 0; + } + nextRequestId() { + return `task-${this.taskId}-${++this.requestCounter}`; + } + async elicit(message, requestedSchema) { + // Update task status to input_required + await this.store.updateTaskStatus(this.taskId, 'input_required'); + const requestId = this.nextRequestId(); + // Build the elicitation request with related-task metadata + const params = { + message, + requestedSchema, + mode: 'form', + _meta: { + [RELATED_TASK_META_KEY]: { taskId: this.taskId } + } + }; + const jsonrpcRequest = { + jsonrpc: '2.0', + id: requestId, + method: 'elicitation/create', + params + }; + // Create resolver to wait for response + const resolver = new Resolver(); + // Enqueue the request + await this.queue.enqueueWithResolver(this.taskId, jsonrpcRequest, resolver, requestId); + try { + // Wait for response + const response = await resolver.wait(); + // Update status back to working + await this.store.updateTaskStatus(this.taskId, 'working'); + return response; + } + catch (error) { + await this.store.updateTaskStatus(this.taskId, 'working'); + throw error; + } + } + async createMessage(messages, maxTokens) { + // Update task status to input_required + await this.store.updateTaskStatus(this.taskId, 'input_required'); + const requestId = this.nextRequestId(); + // Build the sampling request with related-task metadata + const params = { + messages, + maxTokens, + _meta: { + [RELATED_TASK_META_KEY]: { taskId: this.taskId } + } + }; + const jsonrpcRequest = { + jsonrpc: '2.0', + id: requestId, + method: 'sampling/createMessage', + params + }; + // Create resolver to wait for response + const resolver = new Resolver(); + // Enqueue the request + await this.queue.enqueueWithResolver(this.taskId, jsonrpcRequest, resolver, requestId); + try { + // Wait for response + const response = await resolver.wait(); + // Update status back to working + await this.store.updateTaskStatus(this.taskId, 'working'); + return response; + } + catch (error) { + await this.store.updateTaskStatus(this.taskId, 'working'); + throw error; + } + } +} +// ============================================================================ +// Server Setup +// ============================================================================ +const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 8000; +// Create shared stores +const taskStore = new TaskStoreWithNotifications(); +const messageQueue = new TaskMessageQueueWithResolvers(); +const taskResultHandler = new TaskResultHandler(taskStore, messageQueue); +// Track active task executions +const activeTaskExecutions = new Map(); +// Create the server +const createServer = () => { + const server = new Server({ name: 'simple-task-interactive', version: '1.0.0' }, { + capabilities: { + tools: {}, + tasks: { + requests: { + tools: { call: {} } + } + } + } + }); + // Register tools + server.setRequestHandler(ListToolsRequestSchema, async () => { + return { + tools: [ + { + name: 'confirm_delete', + description: 'Asks for confirmation before deleting (demonstrates elicitation)', + inputSchema: { + type: 'object', + properties: { + filename: { type: 'string' } + } + }, + execution: { taskSupport: 'required' } + }, + { + name: 'write_haiku', + description: 'Asks LLM to write a haiku (demonstrates sampling)', + inputSchema: { + type: 'object', + properties: { + topic: { type: 'string' } + } + }, + execution: { taskSupport: 'required' } + } + ] + }; + }); + // Handle tool calls + server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { + const { name, arguments: args } = request.params; + const taskParams = (request.params._meta?.task || request.params.task); + // Validate task mode - these tools require tasks + if (!taskParams) { + throw new Error(`Tool ${name} requires task mode`); + } + // Create task + const taskOptions = { + ttl: taskParams.ttl, + pollInterval: taskParams.pollInterval ?? 1000 + }; + const task = await taskStore.createTask(taskOptions, extra.requestId, request, extra.sessionId); + console.log(`\n[Server] ${name} called, task created: ${task.taskId}`); + // Start background task execution + const taskExecution = (async () => { + try { + const taskSession = new TaskSession(server, task.taskId, taskStore, messageQueue); + if (name === 'confirm_delete') { + const filename = args?.filename ?? 'unknown.txt'; + console.log(`[Server] confirm_delete: asking about '${filename}'`); + console.log('[Server] Sending elicitation request to client...'); + const result = await taskSession.elicit(`Are you sure you want to delete '${filename}'?`, { + type: 'object', + properties: { + confirm: { type: 'boolean' } + }, + required: ['confirm'] + }); + console.log(`[Server] Received elicitation response: action=${result.action}, content=${JSON.stringify(result.content)}`); + let text; + if (result.action === 'accept' && result.content) { + const confirmed = result.content.confirm; + text = confirmed ? `Deleted '${filename}'` : 'Deletion cancelled'; + } + else { + text = 'Deletion cancelled'; + } + console.log(`[Server] Completing task with result: ${text}`); + await taskStore.storeTaskResult(task.taskId, 'completed', { + content: [{ type: 'text', text }] + }); + } + else if (name === 'write_haiku') { + const topic = args?.topic ?? 'nature'; + console.log(`[Server] write_haiku: topic '${topic}'`); + console.log('[Server] Sending sampling request to client...'); + const result = await taskSession.createMessage([ + { + role: 'user', + content: { type: 'text', text: `Write a haiku about ${topic}` } + } + ], 50); + let haiku = 'No response'; + if (result.content && 'text' in result.content) { + haiku = result.content.text; + } + console.log(`[Server] Received sampling response: ${haiku.substring(0, 50)}...`); + console.log('[Server] Completing task with haiku'); + await taskStore.storeTaskResult(task.taskId, 'completed', { + content: [{ type: 'text', text: `Haiku:\n${haiku}` }] + }); + } + } + catch (error) { + console.error(`[Server] Task ${task.taskId} failed:`, error); + await taskStore.storeTaskResult(task.taskId, 'failed', { + content: [{ type: 'text', text: `Error: ${error}` }], + isError: true + }); + } + finally { + activeTaskExecutions.delete(task.taskId); + } + })(); + activeTaskExecutions.set(task.taskId, { + promise: taskExecution, + server, + sessionId: extra.sessionId ?? '' + }); + return { task }; + }); + // Handle tasks/get + server.setRequestHandler(GetTaskRequestSchema, async (request) => { + const { taskId } = request.params; + const task = await taskStore.getTask(taskId); + if (!task) { + throw new Error(`Task ${taskId} not found`); + } + return task; + }); + // Handle tasks/result + server.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { + const { taskId } = request.params; + console.log(`[Server] tasks/result called for task ${taskId}`); + return taskResultHandler.handle(taskId, server, extra.sessionId ?? ''); + }); + return server; +}; +// ============================================================================ +// Express App Setup +// ============================================================================ +const app = createMcpExpressApp(); +// Map to store transports by session ID +const transports = {}; +// Helper to check if request is initialize +const isInitializeRequest = (body) => { + return typeof body === 'object' && body !== null && 'method' in body && body.method === 'initialize'; +}; +// MCP POST endpoint +app.post('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + try { + let transport; + if (sessionId && transports[sessionId]) { + transport = transports[sessionId]; + } + else if (!sessionId && isInitializeRequest(req.body)) { + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + onsessioninitialized: sid => { + console.log(`Session initialized: ${sid}`); + transports[sid] = transport; + } + }); + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}`); + delete transports[sid]; + } + }; + const server = createServer(); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; + } + else { + res.status(400).json({ + jsonrpc: '2.0', + error: { code: -32000, message: 'Bad Request: No valid session ID' }, + id: null + }); + return; + } + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { code: -32603, message: 'Internal server error' }, + id: null + }); + } + } +}); +// Handle GET requests for SSE streams +app.get('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + const transport = transports[sessionId]; + await transport.handleRequest(req, res); +}); +// Handle DELETE requests for session termination +app.delete('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Session termination request: ${sessionId}`); + const transport = transports[sessionId]; + await transport.handleRequest(req, res); +}); +// Start server +app.listen(PORT, () => { + console.log(`Starting server on http://localhost:${PORT}/mcp`); + console.log('\nAvailable tools:'); + console.log(' - confirm_delete: Demonstrates elicitation (asks user y/n)'); + console.log(' - write_haiku: Demonstrates sampling (requests LLM completion)'); +}); +// Handle shutdown +process.on('SIGINT', async () => { + console.log('\nShutting down server...'); + for (const sessionId of Object.keys(transports)) { + try { + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing session ${sessionId}:`, error); + } + } + taskStore.cleanup(); + messageQueue.cleanup(); + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=simpleTaskInteractive.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleTaskInteractive.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleTaskInteractive.js.map new file mode 100644 index 000000000..7c71678d5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/simpleTaskInteractive.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleTaskInteractive.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleTaskInteractive.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C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MAAM,CAAC,CAAC;IAC/D,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IAClC,OAAO,CAAC,GAAG,CAAC,8DAA8D,CAAC,CAAC;IAC5E,OAAO,CAAC,GAAG,CAAC,kEAAkE,CAAC,CAAC;AACpF,CAAC,CAAC,CAAC;AAEH,kBAAkB;AAClB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;IACzC,KAAK,MAAM,SAAS,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QAC9C,IAAI,CAAC;YACD,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,yBAAyB,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAChE,CAAC;IACL,CAAC;IACD,SAAS,CAAC,OAAO,EAAE,CAAC;IACpB,YAAY,CAAC,OAAO,EAAE,CAAC;IACvB,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts new file mode 100644 index 000000000..c536d0c80 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map new file mode 100644 index 000000000..fb982c84a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sseAndStreamableHttpCompatibleServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/sseAndStreamableHttpCompatibleServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js new file mode 100644 index 000000000..020cb0fe6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js @@ -0,0 +1,231 @@ +import { randomUUID } from 'node:crypto'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { SSEServerTransport } from '../../server/sse.js'; +import * as z from 'zod/v4'; +import { isInitializeRequest } from '../../types.js'; +import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; +import { createMcpExpressApp } from '../../server/express.js'; +/** + * This example server demonstrates backwards compatibility with both: + * 1. The deprecated HTTP+SSE transport (protocol version 2024-11-05) + * 2. The Streamable HTTP transport (protocol version 2025-11-25) + * + * It maintains a single MCP server instance but exposes two transport options: + * - /mcp: The new Streamable HTTP endpoint (supports GET/POST/DELETE) + * - /sse: The deprecated SSE endpoint for older clients (GET to establish stream) + * - /messages: The deprecated POST endpoint for older clients (POST to send messages) + */ +const getServer = () => { + const server = new McpServer({ + name: 'backwards-compatible-server', + version: '1.0.0' + }, { capabilities: { logging: {} } }); + // Register a simple tool that sends notifications over time + server.registerTool('start-notification-stream', { + description: 'Starts sending periodic notifications for testing resumability', + inputSchema: { + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(50) + } + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + while (count === 0 || counter < count) { + counter++; + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Periodic notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + // Wait for the specified interval + await sleep(interval); + } + return { + content: [ + { + type: 'text', + text: `Started sending periodic notifications every ${interval}ms` + } + ] + }; + }); + return server; +}; +// Create Express application +const app = createMcpExpressApp(); +// Store transports by session ID +const transports = {}; +//============================================================================= +// STREAMABLE HTTP TRANSPORT (PROTOCOL VERSION 2025-11-25) +//============================================================================= +// Handle all MCP Streamable HTTP requests (GET, POST, DELETE) on a single endpoint +app.all('/mcp', async (req, res) => { + console.log(`Received ${req.method} request to /mcp`); + try { + // Check for existing session ID + const sessionId = req.headers['mcp-session-id']; + let transport; + if (sessionId && transports[sessionId]) { + // Check if the transport is of the correct type + const existingTransport = transports[sessionId]; + if (existingTransport instanceof StreamableHTTPServerTransport) { + // Reuse existing transport + transport = existingTransport; + } + else { + // Transport exists but is not a StreamableHTTPServerTransport (could be SSEServerTransport) + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Session exists but uses a different transport protocol' + }, + id: null + }); + return; + } + } + else if (!sessionId && req.method === 'POST' && isInitializeRequest(req.body)) { + const eventStore = new InMemoryEventStore(); + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + eventStore, // Enable resumability + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + console.log(`StreamableHTTP session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + } + }; + // Connect the transport to the MCP server + const server = getServer(); + await server.connect(transport); + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with the transport + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +//============================================================================= +// DEPRECATED HTTP+SSE TRANSPORT (PROTOCOL VERSION 2024-11-05) +//============================================================================= +app.get('/sse', async (req, res) => { + console.log('Received GET request to /sse (deprecated SSE transport)'); + const transport = new SSEServerTransport('/messages', res); + transports[transport.sessionId] = transport; + res.on('close', () => { + delete transports[transport.sessionId]; + }); + const server = getServer(); + await server.connect(transport); +}); +app.post('/messages', async (req, res) => { + const sessionId = req.query.sessionId; + let transport; + const existingTransport = transports[sessionId]; + if (existingTransport instanceof SSEServerTransport) { + // Reuse existing transport + transport = existingTransport; + } + else { + // Transport exists but is not a SSEServerTransport (could be StreamableHTTPServerTransport) + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Session exists but uses a different transport protocol' + }, + id: null + }); + return; + } + if (transport) { + await transport.handlePostMessage(req, res, req.body); + } + else { + res.status(400).send('No transport found for sessionId'); + } +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Backwards compatible MCP server listening on port ${PORT}`); + console.log(` +============================================== +SUPPORTED TRANSPORT OPTIONS: + +1. Streamable Http(Protocol version: 2025-11-25) + Endpoint: /mcp + Methods: GET, POST, DELETE + Usage: + - Initialize with POST to /mcp + - Establish SSE stream with GET to /mcp + - Send requests with POST to /mcp + - Terminate session with DELETE to /mcp + +2. Http + SSE (Protocol version: 2024-11-05) + Endpoints: /sse (GET) and /messages (POST) + Usage: + - Establish SSE stream with GET to /sse + - Send requests with POST to /messages?sessionId= +============================================== +`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js.map new file mode 100644 index 000000000..bea467a6c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sseAndStreamableHttpCompatibleServer.js","sourceRoot":"","sources":["../../../../src/examples/server/sseAndStreamableHttpCompatibleServer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAkB,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAE9D;;;;;;;;;GASG;AAEH,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,SAAS,CACxB;QACI,IAAI,EAAE,6BAA6B;QACnC,OAAO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CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/ssePollingExample.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/ssePollingExample.d.ts new file mode 100644 index 000000000..63e45548e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/ssePollingExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=ssePollingExample.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/ssePollingExample.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/ssePollingExample.d.ts.map new file mode 100644 index 000000000..93827316a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/ssePollingExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ssePollingExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/ssePollingExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/ssePollingExample.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/ssePollingExample.js new file mode 100644 index 000000000..1f78609e5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/ssePollingExample.js @@ -0,0 +1,97 @@ +import { randomUUID } from 'node:crypto'; +import { McpServer } from '../../server/mcp.js'; +import { createMcpExpressApp } from '../../server/express.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; +import cors from 'cors'; +// Create the MCP server +const server = new McpServer({ + name: 'sse-polling-example', + version: '1.0.0' +}, { + capabilities: { logging: {} } +}); +// Register a long-running tool that demonstrates server-initiated disconnect +server.tool('long-task', 'A long-running task that sends progress updates. Server will disconnect mid-task to demonstrate polling.', {}, async (_args, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + console.log(`[${extra.sessionId}] Starting long-task...`); + // Send first progress notification + await server.sendLoggingMessage({ + level: 'info', + data: 'Progress: 25% - Starting work...' + }, extra.sessionId); + await sleep(1000); + // Send second progress notification + await server.sendLoggingMessage({ + level: 'info', + data: 'Progress: 50% - Halfway there...' + }, extra.sessionId); + await sleep(1000); + // Server decides to disconnect the client to free resources + // Client will reconnect via GET with Last-Event-ID after the transport's retryInterval + // Use extra.closeSSEStream callback - available when eventStore is configured + if (extra.closeSSEStream) { + console.log(`[${extra.sessionId}] Closing SSE stream to trigger client polling...`); + extra.closeSSEStream(); + } + // Continue processing while client is disconnected + // Events are stored in eventStore and will be replayed on reconnect + await sleep(500); + await server.sendLoggingMessage({ + level: 'info', + data: 'Progress: 75% - Almost done (sent while client disconnected)...' + }, extra.sessionId); + await sleep(500); + await server.sendLoggingMessage({ + level: 'info', + data: 'Progress: 100% - Complete!' + }, extra.sessionId); + console.log(`[${extra.sessionId}] Task complete`); + return { + content: [ + { + type: 'text', + text: 'Long task completed successfully!' + } + ] + }; +}); +// Set up Express app +const app = createMcpExpressApp(); +app.use(cors()); +// Create event store for resumability +const eventStore = new InMemoryEventStore(); +// Track transports by session ID for session reuse +const transports = new Map(); +// Handle all MCP requests +app.all('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + // Reuse existing transport or create new one + let transport = sessionId ? transports.get(sessionId) : undefined; + if (!transport) { + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + eventStore, + retryInterval: 2000, // Default retry interval for priming events + onsessioninitialized: id => { + console.log(`[${id}] Session initialized`); + transports.set(id, transport); + } + }); + // Connect the MCP server to the transport + await server.connect(transport); + } + await transport.handleRequest(req, res, req.body); +}); +// Start the server +const PORT = 3001; +app.listen(PORT, () => { + console.log(`SSE Polling Example Server running on http://localhost:${PORT}/mcp`); + console.log(''); + console.log('This server demonstrates SEP-1699 SSE polling:'); + console.log('- retryInterval: 2000ms (client waits 2s before reconnecting)'); + console.log('- eventStore: InMemoryEventStore (events are persisted for replay)'); + console.log(''); + console.log('Try calling the "long-task" tool to see server-initiated disconnect in action.'); +}); +//# sourceMappingURL=ssePollingExample.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/ssePollingExample.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/ssePollingExample.js.map new file mode 100644 index 000000000..1f3c0ef61 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/ssePollingExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ssePollingExample.js","sourceRoot":"","sources":["../../../../src/examples/server/ssePollingExample.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAE/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,wBAAwB;AACxB,MAAM,MAAM,GAAG,IAAI,SAAS,CACxB;IACI,IAAI,EAAE,qBAAqB;IAC3B,OAAO,EAAE,OAAO;CACnB,EACD;IACI,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;CAChC,CACJ,CAAC;AAEF,6EAA6E;AAC7E,MAAM,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C;IACpC,CAAC;IAED,MAAM,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;AACtD,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE;IAClB,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,MAAM,CAAC,CAAC;IAClF,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,gDAAgD,CAAC,CAAC;IAC9D,OAAO,CAAC,GAAG,CAAC,+DAA+D,CAAC,CAAC;IAC7E,OAAO,CAAC,GAAG,CAAC,oEAAoE,CAAC,CAAC;IAClF,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,gFAAgF,CAAC,CAAC;AAClG,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts new file mode 100644 index 000000000..4df17831b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=standaloneSseWithGetStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map new file mode 100644 index 000000000..df60dc51b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"standaloneSseWithGetStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/standaloneSseWithGetStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js new file mode 100644 index 000000000..c5164ca59 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js @@ -0,0 +1,110 @@ +import { randomUUID } from 'node:crypto'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { isInitializeRequest } from '../../types.js'; +import { createMcpExpressApp } from '../../server/express.js'; +// Create an MCP server with implementation details +const server = new McpServer({ + name: 'resource-list-changed-notification-server', + version: '1.0.0' +}); +// Store transports by session ID to send notifications +const transports = {}; +const addResource = (name, content) => { + const uri = `https://mcp-example.com/dynamic/${encodeURIComponent(name)}`; + server.registerResource(name, uri, { mimeType: 'text/plain', description: `Dynamic resource: ${name}` }, async () => { + return { + contents: [{ uri, text: content }] + }; + }); +}; +addResource('example-resource', 'Initial content for example-resource'); +const resourceChangeInterval = setInterval(() => { + const name = randomUUID(); + addResource(name, `Content for ${name}`); +}, 5000); // Change resources every 5 seconds for testing +const app = createMcpExpressApp(); +app.post('/mcp', async (req, res) => { + console.log('Received MCP request:', req.body); + try { + // Check for existing session ID + const sessionId = req.headers['mcp-session-id']; + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && isInitializeRequest(req.body)) { + // New initialization request + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Connect the transport to the MCP server + await server.connect(transport); + // Handle the request - the onsessioninitialized callback will store the transport + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +// Handle GET requests for SSE streams (now using built-in support from StreamableHTTP) +app.get('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Establishing SSE stream for session ${sessionId}`); + const transport = transports[sessionId]; + await transport.handleRequest(req, res); +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Server listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + clearInterval(resourceChangeInterval); + await server.close(); + process.exit(0); +}); +//# sourceMappingURL=standaloneSseWithGetStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js.map new file mode 100644 index 000000000..1717f618c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"standaloneSseWithGetStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/standaloneSseWithGetStreamableHttp.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,qBA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AC;IACD,OAAO,CAAC,GAAG,CAAC,4BAA4B,IAAI,EAAE,CAAC,CAAC;AACpD,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,aAAa,CAAC,sBAAsB,CAAC,CAAC;IACtC,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;IACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/toolWithSampleServer.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/toolWithSampleServer.d.ts new file mode 100644 index 000000000..acc24b6a5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/toolWithSampleServer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=toolWithSampleServer.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/toolWithSampleServer.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/toolWithSampleServer.d.ts.map new file mode 100644 index 000000000..bd0cebcf1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/toolWithSampleServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"toolWithSampleServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/toolWithSampleServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/toolWithSampleServer.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/toolWithSampleServer.js new file mode 100644 index 000000000..0b7df6c52 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/toolWithSampleServer.js @@ -0,0 +1,48 @@ +// Run with: npx tsx src/examples/server/toolWithSampleServer.ts +import { McpServer } from '../../server/mcp.js'; +import { StdioServerTransport } from '../../server/stdio.js'; +import * as z from 'zod/v4'; +const mcpServer = new McpServer({ + name: 'tools-with-sample-server', + version: '1.0.0' +}); +// Tool that uses LLM sampling to summarize any text +mcpServer.registerTool('summarize', { + description: 'Summarize any text using an LLM', + inputSchema: { + text: z.string().describe('Text to summarize') + } +}, async ({ text }) => { + // Call the LLM through MCP sampling + const response = await mcpServer.server.createMessage({ + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please summarize the following text concisely:\n\n${text}` + } + } + ], + maxTokens: 500 + }); + // Since we're not passing tools param to createMessage, response.content is single content + return { + content: [ + { + type: 'text', + text: response.content.type === 'text' ? response.content.text : 'Unable to generate summary' + } + ] + }; +}); +async function main() { + const transport = new StdioServerTransport(); + await mcpServer.connect(transport); + console.log('MCP server is running...'); +} +main().catch(error => { + console.error('Server error:', error); + process.exit(1); +}); +//# sourceMappingURL=toolWithSampleServer.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/toolWithSampleServer.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/toolWithSampleServer.js.map new file mode 100644 index 000000000..4fc372cc3 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/server/toolWithSampleServer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"toolWithSampleServer.js","sourceRoot":"","sources":["../../../../src/examples/server/toolWithSampleServer.ts"],"names":[],"mappings":"AAAA,gEAAgE;AAEhE,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC;IAC5B,IAAI,EAAE,0BAA0B;IAChC,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,oDAAoD;AACpD,SAAS,CAAC,YAAY,CAClB,WAAW,EACX;IACI,WAAW,EAAE,iCAAiC;IAC9C,WAAW,EAAE;QACT,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,mBAAmB,CAAC;KACjD;CACJ,EACD,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE;IACf,oCAAoC;IACpC,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,MAAM,CAAC,aAAa,CAAC;QAClD,QAAQ,EAAE;YACN;gBACI,IAAI,EAAE,MAAM;gBACZ,OAAO,EAAE;oBACL,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,qDAAqD,IAAI,EAAE;iBACpE;aACJ;SACJ;QACD,SAAS,EAAE,GAAG;KACjB,CAAC,CAAC;IAEH,2FAA2F;IAC3F,OAAO;QACH,OAAO,EAAE;YACL;gBACI,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,4BAA4B;aAChG;SACJ;KACJ,CAAC;AACN,CAAC,CACJ,CAAC;AAEF,KAAK,UAAU,IAAI;IACf,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;IAC7C,MAAM,SAAS,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACnC,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;AAC5C,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/shared/inMemoryEventStore.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/shared/inMemoryEventStore.d.ts new file mode 100644 index 000000000..26ff38cf9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/shared/inMemoryEventStore.d.ts @@ -0,0 +1,31 @@ +import { JSONRPCMessage } from '../../types.js'; +import { EventStore } from '../../server/streamableHttp.js'; +/** + * Simple in-memory implementation of the EventStore interface for resumability + * This is primarily intended for examples and testing, not for production use + * where a persistent storage solution would be more appropriate. + */ +export declare class InMemoryEventStore implements EventStore { + private events; + /** + * Generates a unique event ID for a given stream ID + */ + private generateEventId; + /** + * Extracts the stream ID from an event ID + */ + private getStreamIdFromEventId; + /** + * Stores an event with a generated event ID + * Implements EventStore.storeEvent + */ + storeEvent(streamId: string, message: JSONRPCMessage): Promise; + /** + * Replays events that occurred after a specific event ID + * Implements EventStore.replayEventsAfter + */ + replayEventsAfter(lastEventId: string, { send }: { + send: (eventId: string, message: JSONRPCMessage) => Promise; + }): Promise; +} +//# sourceMappingURL=inMemoryEventStore.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/shared/inMemoryEventStore.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/shared/inMemoryEventStore.d.ts.map new file mode 100644 index 000000000..a67ee6cd1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/shared/inMemoryEventStore.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemoryEventStore.d.ts","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAE5D;;;;GAIG;AACH,qBAAa,kBAAmB,YAAW,UAAU;IACjD,OAAO,CAAC,MAAM,CAAyE;IAEvF;;OAEG;IACH,OAAO,CAAC,eAAe;IAIvB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAK9B;;;OAGG;IACG,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAM5E;;;OAGG;IACG,iBAAiB,CACnB,WAAW,EAAE,MAAM,EACnB,EAAE,IAAI,EAAE,EAAE;QAAE,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;KAAE,GAChF,OAAO,CAAC,MAAM,CAAC;CAkCrB"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/shared/inMemoryEventStore.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/shared/inMemoryEventStore.js new file mode 100644 index 000000000..35f6dbb7c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/shared/inMemoryEventStore.js @@ -0,0 +1,65 @@ +/** + * Simple in-memory implementation of the EventStore interface for resumability + * This is primarily intended for examples and testing, not for production use + * where a persistent storage solution would be more appropriate. + */ +export class InMemoryEventStore { + constructor() { + this.events = new Map(); + } + /** + * Generates a unique event ID for a given stream ID + */ + generateEventId(streamId) { + return `${streamId}_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`; + } + /** + * Extracts the stream ID from an event ID + */ + getStreamIdFromEventId(eventId) { + const parts = eventId.split('_'); + return parts.length > 0 ? parts[0] : ''; + } + /** + * Stores an event with a generated event ID + * Implements EventStore.storeEvent + */ + async storeEvent(streamId, message) { + const eventId = this.generateEventId(streamId); + this.events.set(eventId, { streamId, message }); + return eventId; + } + /** + * Replays events that occurred after a specific event ID + * Implements EventStore.replayEventsAfter + */ + async replayEventsAfter(lastEventId, { send }) { + if (!lastEventId || !this.events.has(lastEventId)) { + return ''; + } + // Extract the stream ID from the event ID + const streamId = this.getStreamIdFromEventId(lastEventId); + if (!streamId) { + return ''; + } + let foundLastEvent = false; + // Sort events by eventId for chronological ordering + const sortedEvents = [...this.events.entries()].sort((a, b) => a[0].localeCompare(b[0])); + for (const [eventId, { streamId: eventStreamId, message }] of sortedEvents) { + // Only include events from the same stream + if (eventStreamId !== streamId) { + continue; + } + // Start sending events after we find the lastEventId + if (eventId === lastEventId) { + foundLastEvent = true; + continue; + } + if (foundLastEvent) { + await send(eventId, message); + } + } + return streamId; + } +} +//# sourceMappingURL=inMemoryEventStore.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/shared/inMemoryEventStore.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/shared/inMemoryEventStore.js.map new file mode 100644 index 000000000..b9e6af66a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/examples/shared/inMemoryEventStore.js.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemoryEventStore.js","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,MAAM,OAAO,kBAAkB;IAA/B;QACY,WAAM,GAA+D,IAAI,GAAG,EAAE,CAAC;IAoE3F,CAAC;IAlEG;;OAEG;IACK,eAAe,CAAC,QAAgB;QACpC,OAAO,GAAG,QAAQ,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;IACtF,CAAC;IAED;;OAEG;IACK,sBAAsB,CAAC,OAAe;QAC1C,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACjC,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC5C,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,UAAU,CAAC,QAAgB,EAAE,OAAuB;QACtD,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,C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AAC;IACpB,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/index.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/index.d.ts new file mode 100644 index 000000000..2a8633553 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/index.d.ts @@ -0,0 +1,13 @@ +/** + * Experimental MCP SDK features. + * WARNING: These APIs are experimental and may change without notice. + * + * Import experimental features from this module: + * ```typescript + * import { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/experimental'; + * ``` + * + * @experimental + */ +export * from './tasks/index.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/index.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/index.d.ts.map new file mode 100644 index 000000000..410892aa4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/experimental/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,cAAc,kBAAkB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/index.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/index.js new file mode 100644 index 000000000..650f4e478 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/index.js @@ -0,0 +1,13 @@ +/** + * Experimental MCP SDK features. + * WARNING: These APIs are experimental and may change without notice. + * + * Import experimental features from this module: + * ```typescript + * import { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/experimental'; + * ``` + * + * @experimental + */ +export * from './tasks/index.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/index.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/index.js.map new file mode 100644 index 000000000..3639685bd --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/experimental/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,cAAc,kBAAkB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.d.ts new file mode 100644 index 000000000..9c7a92834 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.d.ts @@ -0,0 +1,121 @@ +/** + * Experimental client task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +import type { Client } from '../../client/index.js'; +import type { RequestOptions } from '../../shared/protocol.js'; +import type { ResponseMessage } from '../../shared/responseMessage.js'; +import type { AnyObjectSchema, SchemaOutput } from '../../server/zod-compat.js'; +import type { CallToolRequest, ClientRequest, Notification, Request, Result } from '../../types.js'; +import { CallToolResultSchema, type CompatibilityCallToolResultSchema } from '../../types.js'; +import type { GetTaskResult, ListTasksResult, CancelTaskResult } from './types.js'; +/** + * Experimental task features for MCP clients. + * + * Access via `client.experimental.tasks`: + * ```typescript + * const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} }); + * const task = await client.experimental.tasks.getTask(taskId); + * ``` + * + * @experimental + */ +export declare class ExperimentalClientTasks { + private readonly _client; + constructor(_client: Client); + /** + * Calls a tool and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to tool execution, allowing you to + * observe intermediate task status updates for long-running tool calls. + * Automatically validates structured output if the tool has an outputSchema. + * + * @example + * ```typescript + * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} }); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Tool execution started:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Tool status:', message.task.status); + * break; + * case 'result': + * console.log('Tool result:', message.result); + * break; + * case 'error': + * console.error('Tool error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - Tool call parameters (name and arguments) + * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema) + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + callToolStream(params: CallToolRequest['params'], resultSchema?: T, options?: RequestOptions): AsyncGenerator>, void, void>; + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + getTask(taskId: string, options?: RequestOptions): Promise; + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + getTaskResult(taskId: string, resultSchema?: T, options?: RequestOptions): Promise>; + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + listTasks(cursor?: string, options?: RequestOptions): Promise; + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + cancelTask(taskId: string, options?: RequestOptions): Promise; + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request: ClientRequest | RequestT, resultSchema: T, options?: RequestOptions): AsyncGenerator>, void, void>; +} +//# sourceMappingURL=client.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.d.ts.map new file mode 100644 index 000000000..e54158d65 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../../src/experimental/tasks/client.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAChF,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACpG,OAAO,EAAE,oBAAoB,EAAE,KAAK,iCAAiC,EAAuB,MAAM,gBAAgB,CAAC;AAEnH,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAgBnF;;;;;;;;;;GAUG;AACH,qBAAa,uBAAuB,CAChC,QAAQ,SAAS,OAAO,GAAG,OAAO,EAClC,aAAa,SAAS,YAAY,GAAG,YAAY,EACjD,OAAO,SAAS,MAAM,GAAG,MAAM;IAEnB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,MAAM,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,CAAC;IAE9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCG;IACI,cAAc,CAAC,CAAC,SAAS,OAAO,oBAAoB,GAAG,OAAO,iCAAiC,EAClG,MAAM,EAAE,eAAe,CAAC,QAAQ,CAAC,EACjC,YAAY,GAAE,CAA6B,EAC3C,OAAO,CAAC,EAAE,cAAc,GACzB,cAAc,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAyE/D;;;;;;;;OAQG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC;IAM/E;;;;;;;;;OASG;IACG,aAAa,CAAC,CAAC,SAAS,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;IAapI;;;;;;;;OAQG;IACG,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,eAAe,CAAC;IASpF;;;;;;;OAOG;IACG,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,gBAAgB,CAAC;IASrF;;;;;;;;;;;;;OAaG;IACH,aAAa,CAAC,CAAC,SAAS,eAAe,EACnC,OAAO,EAAE,aAAa,GAAG,QAAQ,EACjC,YAAY,EAAE,CAAC,EACf,OAAO,CAAC,EAAE,cAAc,GACzB,cAAc,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;CAWlE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js new file mode 100644 index 000000000..0c1d8af72 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js @@ -0,0 +1,184 @@ +/** + * Experimental client task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +import { CallToolResultSchema, McpError, ErrorCode } from '../../types.js'; +/** + * Experimental task features for MCP clients. + * + * Access via `client.experimental.tasks`: + * ```typescript + * const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} }); + * const task = await client.experimental.tasks.getTask(taskId); + * ``` + * + * @experimental + */ +export class ExperimentalClientTasks { + constructor(_client) { + this._client = _client; + } + /** + * Calls a tool and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to tool execution, allowing you to + * observe intermediate task status updates for long-running tool calls. + * Automatically validates structured output if the tool has an outputSchema. + * + * @example + * ```typescript + * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} }); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Tool execution started:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Tool status:', message.task.status); + * break; + * case 'result': + * console.log('Tool result:', message.result); + * break; + * case 'error': + * console.error('Tool error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - Tool call parameters (name and arguments) + * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema) + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + async *callToolStream(params, resultSchema = CallToolResultSchema, options) { + // Access Client's internal methods + const clientInternal = this._client; + // Add task creation parameters if server supports it and not explicitly provided + const optionsWithTask = { + ...options, + // We check if the tool is known to be a task during auto-configuration, but assume + // the caller knows what they're doing if they pass this explicitly + task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : undefined) + }; + const stream = clientInternal.requestStream({ method: 'tools/call', params }, resultSchema, optionsWithTask); + // Get the validator for this tool (if it has an output schema) + const validator = clientInternal.getToolOutputValidator(params.name); + // Iterate through the stream and validate the final result if needed + for await (const message of stream) { + // If this is a result message and the tool has an output schema, validate it + if (message.type === 'result' && validator) { + const result = message.result; + // If tool has outputSchema, it MUST return structuredContent (unless it's an error) + if (!result.structuredContent && !result.isError) { + yield { + type: 'error', + error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`) + }; + return; + } + // Only validate structured content if present (not when there's an error) + if (result.structuredContent) { + try { + // Validate the structured content against the schema + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) { + yield { + type: 'error', + error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`) + }; + return; + } + } + catch (error) { + if (error instanceof McpError) { + yield { type: 'error', error }; + return; + } + yield { + type: 'error', + error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`) + }; + return; + } + } + } + // Yield the message (either validated result or any other message type) + yield message; + } + } + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + async getTask(taskId, options) { + return this._client.getTask({ taskId }, options); + } + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + async getTaskResult(taskId, resultSchema, options) { + // Delegate to the client's underlying Protocol method + return this._client.getTaskResult({ taskId }, resultSchema, options); + } + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + async listTasks(cursor, options) { + // Delegate to the client's underlying Protocol method + return this._client.listTasks(cursor ? { cursor } : undefined, options); + } + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + async cancelTask(taskId, options) { + // Delegate to the client's underlying Protocol method + return this._client.cancelTask({ taskId }, options); + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request, resultSchema, options) { + return this._client.requestStream(request, resultSchema, options); + } +} +//# sourceMappingURL=client.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js.map new file mode 100644 index 000000000..ae79ccfdc --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/client.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAOH,OAAO,EAAE,oBAAoB,EAA0C,QAAQ,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAkBnH;;;;;;;;;;GAUG;AACH,MAAM,OAAO,uBAAuB;IAKhC,YAA6B,OAAiD;QAAjD,YAAO,GAAP,OAAO,CAA0C;IAAG,CAAC;IAElF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCG;IACH,KAAK,CAAC,CAAC,cAAc,CACjB,MAAiC,EACjC,eAAkB,oBAAyB,EAC3C,OAAwB;QAExB,mCAAmC;QACnC,MAAM,cAAc,GAAG,IAAI,CAAC,OAA8C,CAAC;QAE3E,iFAAiF;QACjF,MAAM,eAAe,GAAG;YACpB,GAAG,OAAO;YACV,mFAAmF;YACnF,mEAAmE;YACnE,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;SACnF,CAAC;QAEF,MAAM,MAAM,GAAG,cAAc,CAAC,aAAa,CAAC,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,YAAY,EAAE,eAAe,CAAC,CAAC;QAE7G,+DAA+D;QAC/D,MAAM,SAAS,GAAG,cAAc,CAAC,sBAAsB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAErE,qEAAqE;QACrE,IAAI,KAAK,EAAE,MAAM,OAAO,IAAI,MAAM,EAA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,CAAC;gBACL,CAAC;YACL,CAAC;YAED,wEAAwE;YACxE,MAAM,OAAO,CAAC;QAClB,CAAC;IACL,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAwB;QAGlD,OAAQ,IAAI,CAAC,OAAwC,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC;IACvF,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,aAAa,CAA4B,MAAc,EAAE,YAAgB,EAAE,OAAwB;QACrG,sDAAsD;QACtD,OACI,IAAI,CAAC,OAOR,CAAC,aAAa,CAAC,EAAE,MAAM,EAAE,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;IACvD,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,SAAS,CAAC,MAAe,EAAE,OAAwB;QACrD,sDAAsD;QACtD,OACI,IAAI,CAAC,OAGR,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IAC1D,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,UAAU,CAAC,MAAc,EAAE,OAAwB;QACrD,sDAAsD;QACtD,OACI,IAAI,CAAC,OAGR,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC;IAED;;;;;;;;;;;;;OAaG;IACH,aAAa,CACT,OAAiC,EACjC,YAAe,EACf,OAAwB;QAUxB,OAAQ,IAAI,CAAC,OAA8C,CAAC,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;IAC9G,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.d.ts new file mode 100644 index 000000000..f5e505f81 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.d.ts @@ -0,0 +1,47 @@ +/** + * Experimental task capability assertion helpers. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +/** + * Type representing the task requests capability structure. + * This is derived from ClientTasksCapability.requests and ServerTasksCapability.requests. + */ +interface TaskRequestsCapability { + tools?: { + call?: object; + }; + sampling?: { + createMessage?: object; + }; + elicitation?: { + create?: object; + }; +} +/** + * Asserts that task creation is supported for tools/call. + * Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability. + * + * @param requests - The task requests capability object + * @param method - The method being checked + * @param entityName - 'Server' or 'Client' for error messages + * @throws Error if the capability is not supported + * + * @experimental + */ +export declare function assertToolsCallTaskCapability(requests: TaskRequestsCapability | undefined, method: string, entityName: 'Server' | 'Client'): void; +/** + * Asserts that task creation is supported for sampling/createMessage or elicitation/create. + * Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability. + * + * @param requests - The task requests capability object + * @param method - The method being checked + * @param entityName - 'Server' or 'Client' for error messages + * @throws Error if the capability is not supported + * + * @experimental + */ +export declare function assertClientRequestTaskCapability(requests: TaskRequestsCapability | undefined, method: string, entityName: 'Server' | 'Client'): void; +export {}; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.d.ts.map new file mode 100644 index 000000000..99dc90343 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../../src/experimental/tasks/helpers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;GAGG;AACH,UAAU,sBAAsB;IAC5B,KAAK,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1B,QAAQ,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACtC,WAAW,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACrC;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,6BAA6B,CACzC,QAAQ,EAAE,sBAAsB,GAAG,SAAS,EAC5C,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,QAAQ,GAAG,QAAQ,GAChC,IAAI,CAgBN;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,iCAAiC,CAC7C,QAAQ,EAAE,sBAAsB,GAAG,SAAS,EAC5C,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,QAAQ,GAAG,QAAQ,GAChC,IAAI,CAsBN"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js new file mode 100644 index 000000000..38800311d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js @@ -0,0 +1,64 @@ +/** + * Experimental task capability assertion helpers. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +/** + * Asserts that task creation is supported for tools/call. + * Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability. + * + * @param requests - The task requests capability object + * @param method - The method being checked + * @param entityName - 'Server' or 'Client' for error messages + * @throws Error if the capability is not supported + * + * @experimental + */ +export function assertToolsCallTaskCapability(requests, method, entityName) { + if (!requests) { + throw new Error(`${entityName} does not support task creation (required for ${method})`); + } + switch (method) { + case 'tools/call': + if (!requests.tools?.call) { + throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`); + } + break; + default: + // Method doesn't support tasks, which is fine - no error + break; + } +} +/** + * Asserts that task creation is supported for sampling/createMessage or elicitation/create. + * Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability. + * + * @param requests - The task requests capability object + * @param method - The method being checked + * @param entityName - 'Server' or 'Client' for error messages + * @throws Error if the capability is not supported + * + * @experimental + */ +export function assertClientRequestTaskCapability(requests, method, entityName) { + if (!requests) { + throw new Error(`${entityName} does not support task creation (required for ${method})`); + } + switch (method) { + case 'sampling/createMessage': + if (!requests.sampling?.createMessage) { + throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`); + } + break; + case 'elicitation/create': + if (!requests.elicitation?.create) { + throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`); + } + break; + default: + // Method doesn't support tasks, which is fine - no error + break; + } +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js.map new file mode 100644 index 000000000..0cb1d79d3 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/helpers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAYH;;;;;;;;;;GAUG;AACH,MAAM,UAAU,6BAA6B,CACzC,QAA4C,EAC5C,MAAc,EACd,UAA+B;IAE/B,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,iDAAiD,MAAM,GAAG,CAAC,CAAC;IAC7F,CAAC;IAED,QAAQ,MAAM,EAAE,CAAC;QACb,KAAK,YAAY;YACb,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC;gBACxB,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,gEAAgE,MAAM,GAAG,CAAC,CAAC;YAC5G,CAAC;YACD,MAAM;QAEV;YACI,yDAAyD;YACzD,MAAM;IACd,CAAC;AACL,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,iCAAiC,CAC7C,QAA4C,EAC5C,MAAc,EACd,UAA+B;IAE/B,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,iDAAiD,MAAM,GAAG,CAAC,CAAC;IAC7F,CAAC;IAED,QAAQ,MAAM,EAAE,CAAC;QACb,KAAK,wBAAwB;YACzB,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,aAAa,EAAE,CAAC;gBACpC,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,4EAA4E,MAAM,GAAG,CAAC,CAAC;YACxH,CAAC;YACD,MAAM;QAEV,KAAK,oBAAoB;YACrB,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,MAAM,EAAE,CAAC;gBAChC,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,wEAAwE,MAAM,GAAG,CAAC,CAAC;YACpH,CAAC;YACD,MAAM;QAEV;YACI,yDAAyD;YACzD,MAAM;IACd,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/index.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/index.d.ts new file mode 100644 index 000000000..33ab79169 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/index.d.ts @@ -0,0 +1,16 @@ +/** + * Experimental task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +export * from './types.js'; +export * from './interfaces.js'; +export * from './helpers.js'; +export * from './client.js'; +export * from './server.js'; +export * from './mcp-server.js'; +export * from './stores/in-memory.js'; +export type { ResponseMessage, TaskStatusMessage, TaskCreatedMessage, ResultMessage, ErrorMessage, BaseResponseMessage } from '../../shared/responseMessage.js'; +export { takeResult, toArrayAsync } from '../../shared/responseMessage.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/index.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/index.d.ts.map new file mode 100644 index 000000000..cf117ed5f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/experimental/tasks/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,cAAc,YAAY,CAAC;AAG3B,cAAc,iBAAiB,CAAC;AAGhC,cAAc,cAAc,CAAC;AAG7B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAGhC,cAAc,uBAAuB,CAAC;AAGtC,YAAY,EACR,eAAe,EACf,iBAAiB,EACjB,kBAAkB,EAClB,aAAa,EACb,YAAY,EACZ,mBAAmB,EACtB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/index.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/index.js new file mode 100644 index 000000000..aaa84f511 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/index.js @@ -0,0 +1,20 @@ +/** + * Experimental task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +// Re-export spec types for convenience +export * from './types.js'; +// SDK implementation interfaces +export * from './interfaces.js'; +// Assertion helpers +export * from './helpers.js'; +// Wrapper classes +export * from './client.js'; +export * from './server.js'; +export * from './mcp-server.js'; +// Store implementations +export * from './stores/in-memory.js'; +export { takeResult, toArrayAsync } from '../../shared/responseMessage.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/index.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/index.js.map new file mode 100644 index 000000000..a01409c78 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,uCAAuC;AACvC,cAAc,YAAY,CAAC;AAE3B,gCAAgC;AAChC,cAAc,iBAAiB,CAAC;AAEhC,oBAAoB;AACpB,cAAc,cAAc,CAAC;AAE7B,kBAAkB;AAClB,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAEhC,wBAAwB;AACxB,cAAc,uBAAuB,CAAC;AAWtC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.d.ts new file mode 100644 index 000000000..b0bb9895c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.d.ts @@ -0,0 +1,232 @@ +/** + * Experimental task interfaces for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + */ +import { Task, RequestId, Result, JSONRPCRequest, JSONRPCNotification, JSONRPCResultResponse, JSONRPCErrorResponse, ServerRequest, ServerNotification, CallToolResult, GetTaskResult, ToolExecution, Request } from '../../types.js'; +import { CreateTaskResult } from './types.js'; +import type { RequestHandlerExtra, RequestTaskStore } from '../../shared/protocol.js'; +import type { ZodRawShapeCompat, AnySchema, ShapeOutput } from '../../server/zod-compat.js'; +/** + * Extended handler extra with task store for task creation. + * @experimental + */ +export interface CreateTaskRequestHandlerExtra extends RequestHandlerExtra { + taskStore: RequestTaskStore; +} +/** + * Extended handler extra with task ID and store for task operations. + * @experimental + */ +export interface TaskRequestHandlerExtra extends RequestHandlerExtra { + taskId: string; + taskStore: RequestTaskStore; +} +/** + * Base callback type for tool handlers. + * @experimental + */ +export type BaseToolCallback, Args extends undefined | ZodRawShapeCompat | AnySchema = undefined> = Args extends ZodRawShapeCompat ? (args: ShapeOutput, extra: ExtraT) => SendResultT | Promise : Args extends AnySchema ? (args: unknown, extra: ExtraT) => SendResultT | Promise : (extra: ExtraT) => SendResultT | Promise; +/** + * Handler for creating a task. + * @experimental + */ +export type CreateTaskRequestHandler = BaseToolCallback; +/** + * Handler for task operations (get, getResult). + * @experimental + */ +export type TaskRequestHandler = BaseToolCallback; +/** + * Interface for task-based tool handlers. + * @experimental + */ +export interface ToolTaskHandler { + createTask: CreateTaskRequestHandler; + getTask: TaskRequestHandler; + getTaskResult: TaskRequestHandler; +} +/** + * Task-specific execution configuration. + * taskSupport cannot be 'forbidden' for task-based tools. + * @experimental + */ +export type TaskToolExecution = Omit & { + taskSupport: TaskSupport extends 'forbidden' | undefined ? never : TaskSupport; +}; +/** + * Represents a message queued for side-channel delivery via tasks/result. + * + * This is a serializable data structure that can be stored in external systems. + * All fields are JSON-serializable. + */ +export type QueuedMessage = QueuedRequest | QueuedNotification | QueuedResponse | QueuedError; +export interface BaseQueuedMessage { + /** Type of message */ + type: string; + /** When the message was queued (milliseconds since epoch) */ + timestamp: number; +} +export interface QueuedRequest extends BaseQueuedMessage { + type: 'request'; + /** The actual JSONRPC request */ + message: JSONRPCRequest; +} +export interface QueuedNotification extends BaseQueuedMessage { + type: 'notification'; + /** The actual JSONRPC notification */ + message: JSONRPCNotification; +} +export interface QueuedResponse extends BaseQueuedMessage { + type: 'response'; + /** The actual JSONRPC response */ + message: JSONRPCResultResponse; +} +export interface QueuedError extends BaseQueuedMessage { + type: 'error'; + /** The actual JSONRPC error */ + message: JSONRPCErrorResponse; +} +/** + * Interface for managing per-task FIFO message queues. + * + * Similar to TaskStore, this allows pluggable queue implementations + * (in-memory, Redis, other distributed queues, etc.). + * + * Each method accepts taskId and optional sessionId parameters to enable + * a single queue instance to manage messages for multiple tasks, with + * isolation based on task ID and session ID. + * + * All methods are async to support external storage implementations. + * All data in QueuedMessage must be JSON-serializable. + * + * @experimental + */ +export interface TaskMessageQueue { + /** + * Adds a message to the end of the queue for a specific task. + * Atomically checks queue size and throws if maxSize would be exceeded. + * @param taskId The task identifier + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @param maxSize Optional maximum queue size - if specified and queue is full, throws an error + * @throws Error if maxSize is specified and would be exceeded + */ + enqueue(taskId: string, message: QueuedMessage, sessionId?: string, maxSize?: number): Promise; + /** + * Removes and returns the first message from the queue for a specific task. + * @param taskId The task identifier + * @param sessionId Optional session ID for binding the query to a specific session + * @returns The first message, or undefined if the queue is empty + */ + dequeue(taskId: string, sessionId?: string): Promise; + /** + * Removes and returns all messages from the queue for a specific task. + * Used when tasks are cancelled or failed to clean up pending messages. + * @param taskId The task identifier + * @param sessionId Optional session ID for binding the query to a specific session + * @returns Array of all messages that were in the queue + */ + dequeueAll(taskId: string, sessionId?: string): Promise; +} +/** + * Task creation options. + * @experimental + */ +export interface CreateTaskOptions { + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl?: number | null; + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval?: number; + /** + * Additional context to pass to the task store. + */ + context?: Record; +} +/** + * Interface for storing and retrieving task state and results. + * + * Similar to Transport, this allows pluggable task storage implementations + * (in-memory, database, distributed cache, etc.). + * + * @experimental + */ +export interface TaskStore { + /** + * Creates a new task with the given creation parameters and original request. + * The implementation must generate a unique taskId and createdAt timestamp. + * + * TTL Management: + * - The implementation receives the TTL suggested by the requestor via taskParams.ttl + * - The implementation MAY override the requested TTL (e.g., to enforce limits) + * - The actual TTL used MUST be returned in the Task object + * - Null TTL indicates unlimited task lifetime (no automatic cleanup) + * - Cleanup SHOULD occur automatically after TTL expires, regardless of task status + * + * @param taskParams - The task creation parameters from the request (ttl, pollInterval) + * @param requestId - The JSON-RPC request ID + * @param request - The original request that triggered task creation + * @param sessionId - Optional session ID for binding the task to a specific session + * @returns The created task object + */ + createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: Request, sessionId?: string): Promise; + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param sessionId - Optional session ID for binding the query to a specific session + * @returns The task object, or null if it does not exist + */ + getTask(taskId: string, sessionId?: string): Promise; + /** + * Stores the result of a task and sets its final status. + * + * @param taskId - The task identifier + * @param status - The final status: 'completed' for success, 'failed' for errors + * @param result - The result to store + * @param sessionId - Optional session ID for binding the operation to a specific session + */ + storeTaskResult(taskId: string, status: 'completed' | 'failed', result: Result, sessionId?: string): Promise; + /** + * Retrieves the stored result of a task. + * + * @param taskId - The task identifier + * @param sessionId - Optional session ID for binding the query to a specific session + * @returns The stored result + */ + getTaskResult(taskId: string, sessionId?: string): Promise; + /** + * Updates a task's status (e.g., to 'cancelled', 'failed', 'completed'). + * + * @param taskId - The task identifier + * @param status - The new status + * @param statusMessage - Optional diagnostic message for failed tasks or other status information + * @param sessionId - Optional session ID for binding the operation to a specific session + */ + updateTaskStatus(taskId: string, status: Task['status'], statusMessage?: string, sessionId?: string): Promise; + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @param cursor - Optional cursor for pagination + * @param sessionId - Optional session ID for binding the query to a specific session + * @returns An object containing the tasks array and an optional nextCursor + */ + listTasks(cursor?: string, sessionId?: string): Promise<{ + tasks: Task[]; + nextCursor?: string; + }>; +} +/** + * Checks if a task status represents a terminal state. + * Terminal states are those where the task has finished and will not change. + * + * @param status - The task status to check + * @returns True if the status is terminal (completed, failed, or cancelled) + * @experimental + */ +export declare function isTerminal(status: Task['status']): boolean; +//# sourceMappingURL=interfaces.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.d.ts.map new file mode 100644 index 000000000..afd1d70b0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.d.ts.map @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m/experimental/tasks/interfaces.js new file mode 100644 index 000000000..d4949de65 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js @@ -0,0 +1,16 @@ +/** + * Experimental task interfaces for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + */ +/** + * Checks if a task status represents a terminal state. + * Terminal states are those where the task has finished and will not change. + * + * @param status - The task status to check + * @returns True if the status is terminal (completed, failed, or cancelled) + * @experimental + */ +export function isTerminal(status) { + return status === 'completed' || status === 'failed' || status === 'cancelled'; +} +//# sourceMappingURL=interfaces.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js.map new file mode 100644 index 000000000..c29899029 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js.map @@ -0,0 +1 @@ +{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/interfaces.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAmRH;;;;;;;GAOG;AACH,MAAM,UAAU,UAAU,CAAC,MAAsB;IAC7C,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,WAAW,CAAC;AACnF,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.d.ts new file mode 100644 index 000000000..b3244f9d6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.d.ts @@ -0,0 +1,77 @@ +/** + * Experimental McpServer task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +import type { McpServer, RegisteredTool } from '../../server/mcp.js'; +import type { ZodRawShapeCompat, AnySchema } from '../../server/zod-compat.js'; +import type { ToolAnnotations } from '../../types.js'; +import type { ToolTaskHandler, TaskToolExecution } from './interfaces.js'; +/** + * Experimental task features for McpServer. + * + * Access via `server.experimental.tasks`: + * ```typescript + * server.experimental.tasks.registerToolTask('long-running', config, handler); + * ``` + * + * @experimental + */ +export declare class ExperimentalMcpServerTasks { + private readonly _mcpServer; + constructor(_mcpServer: McpServer); + /** + * Registers a task-based tool with a config object and handler. + * + * Task-based tools support long-running operations that can be polled for status + * and results. The handler must implement `createTask`, `getTask`, and `getTaskResult` + * methods. + * + * @example + * ```typescript + * server.experimental.tasks.registerToolTask('long-computation', { + * description: 'Performs a long computation', + * inputSchema: { input: z.string() }, + * execution: { taskSupport: 'required' } + * }, { + * createTask: async (args, extra) => { + * const task = await extra.taskStore.createTask({ ttl: 300000 }); + * startBackgroundWork(task.taskId, args); + * return { task }; + * }, + * getTask: async (args, extra) => { + * return extra.taskStore.getTask(extra.taskId); + * }, + * getTaskResult: async (args, extra) => { + * return extra.taskStore.getTaskResult(extra.taskId); + * } + * }); + * ``` + * + * @param name - The tool name + * @param config - Tool configuration (description, schemas, etc.) + * @param handler - Task handler with createTask, getTask, getTaskResult methods + * @returns RegisteredTool for managing the tool's lifecycle + * + * @experimental + */ + registerToolTask(name: string, config: { + title?: string; + description?: string; + outputSchema?: OutputArgs; + annotations?: ToolAnnotations; + execution?: TaskToolExecution; + _meta?: Record; + }, handler: ToolTaskHandler): RegisteredTool; + registerToolTask(name: string, config: { + title?: string; + description?: string; + inputSchema: InputArgs; + outputSchema?: OutputArgs; + annotations?: ToolAnnotations; + execution?: TaskToolExecution; + _meta?: Record; + }, handler: ToolTaskHandler): RegisteredTool; +} +//# sourceMappingURL=mcp-server.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.d.ts.map new file mode 100644 index 000000000..84ee9e08d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mcp-server.d.ts","sourceRoot":"","sources":["../../../../src/experimental/tasks/mcp-server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAkB,MAAM,qBAAqB,CAAC;AACrF,OAAO,KAAK,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAC/E,OAAO,KAAK,EAAE,eAAe,EAAiB,MAAM,gBAAgB,CAAC;AACrE,OAAO,KAAK,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAoB1E;;;;;;;;;GASG;AACH,qBAAa,0BAA0B;IACvB,OAAO,CAAC,QAAQ,CAAC,UAAU;gBAAV,UAAU,EAAE,SAAS;IAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAkCG;IACH,gBAAgB,CAAC,UAAU,SAAS,SAAS,GAAG,iBAAiB,GAAG,SAAS,EACzE,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE;QACJ,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,YAAY,CAAC,EAAE,UAAU,CAAC;QAC1B,WAAW,CAAC,EAAE,eAAe,CAAC;QAC9B,SAAS,CAAC,EAAE,iBAAiB,CAAC;QAC9B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACnC,EACD,OAAO,EAAE,eAAe,CAAC,SAAS,CAAC,GACpC,cAAc;IAEjB,gBAAgB,CAAC,SAAS,SAAS,iBAAiB,GAAG,SAAS,EAAE,UAAU,SAAS,SAAS,GAAG,iBAAiB,GAAG,SAAS,EAC1H,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE;QACJ,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,WAAW,EAAE,SAAS,CAAC;QACvB,YAAY,CAAC,EAAE,UAAU,CAAC;QAC1B,WAAW,CAAC,EAAE,eAAe,CAAC;QAC9B,SAAS,CAAC,EAAE,iBAAiB,CAAC;QAC9B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACnC,EACD,OAAO,EAAE,eAAe,CAAC,SAAS,CAAC,GACpC,cAAc;CAsCpB"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js new file mode 100644 index 000000000..39b9d1082 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js @@ -0,0 +1,32 @@ +/** + * Experimental McpServer task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +/** + * Experimental task features for McpServer. + * + * Access via `server.experimental.tasks`: + * ```typescript + * server.experimental.tasks.registerToolTask('long-running', config, handler); + * ``` + * + * @experimental + */ +export class ExperimentalMcpServerTasks { + constructor(_mcpServer) { + this._mcpServer = _mcpServer; + } + registerToolTask(name, config, handler) { + // Validate that taskSupport is not 'forbidden' for task-based tools + const execution = { taskSupport: 'required', ...config.execution }; + if (execution.taskSupport === 'forbidden') { + throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`); + } + // Access McpServer's internal _createRegisteredTool method + const mcpServerInternal = this._mcpServer; + return mcpServerInternal._createRegisteredTool(name, config.title, config.description, config.inputSchema, config.outputSchema, config.annotations, execution, config._meta, handler); + } +} +//# sourceMappingURL=mcp-server.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js.map new file mode 100644 index 000000000..c01a314c9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mcp-server.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/mcp-server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAyBH;;;;;;;;;GASG;AACH,MAAM,OAAO,0BAA0B;IACnC,YAA6B,UAAqB;QAArB,eAAU,GAAV,UAAU,CAAW;IAAG,CAAC;IAgEtD,gBAAgB,CAIZ,IAAY,EACZ,MAQC,EACD,OAAmC;QAEnC,oEAAoE;QACpE,MAAM,SAAS,GAAkB,EAAE,WAAW,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;QAClF,IAAI,SAAS,CAAC,WAAW,KAAK,WAAW,EAAE,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,oCAAoC,IAAI,6DAA6D,CAAC,CAAC;QAC3H,CAAC;QAED,2DAA2D;QAC3D,MAAM,iBAAiB,GAAG,IAAI,CAAC,UAA0C,CAAC;QAC1E,OAAO,iBAAiB,CAAC,qBAAqB,CAC1C,IAAI,EACJ,MAAM,CAAC,KAAK,EACZ,MAAM,CAAC,WAAW,EAClB,MAAM,CAAC,WAAW,EAClB,MAAM,CAAC,YAAY,EACnB,MAAM,CAAC,WAAW,EAClB,SAAS,EACT,MAAM,CAAC,KAAK,EACZ,OAAwD,CAC3D,CAAC;IACN,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.d.ts new file mode 100644 index 000000000..185e0bab5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.d.ts @@ -0,0 +1,83 @@ +/** + * Experimental server task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +import type { Server } from '../../server/index.js'; +import type { RequestOptions } from '../../shared/protocol.js'; +import type { ResponseMessage } from '../../shared/responseMessage.js'; +import type { AnySchema, SchemaOutput } from '../../server/zod-compat.js'; +import type { ServerRequest, Notification, Request, Result, GetTaskResult, ListTasksResult, CancelTaskResult } from '../../types.js'; +/** + * Experimental task features for low-level MCP servers. + * + * Access via `server.experimental.tasks`: + * ```typescript + * const stream = server.experimental.tasks.requestStream(request, schema, options); + * ``` + * + * For high-level server usage with task-based tools, use `McpServer.experimental.tasks` instead. + * + * @experimental + */ +export declare class ExperimentalServerTasks { + private readonly _server; + constructor(_server: Server); + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request: ServerRequest | RequestT, resultSchema: T, options?: RequestOptions): AsyncGenerator>, void, void>; + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + getTask(taskId: string, options?: RequestOptions): Promise; + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + getTaskResult(taskId: string, resultSchema?: T, options?: RequestOptions): Promise>; + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + listTasks(cursor?: string, options?: RequestOptions): Promise; + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + cancelTask(taskId: string, options?: RequestOptions): Promise; +} +//# sourceMappingURL=server.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.d.ts.map new file mode 100644 index 000000000..a1681854f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../../../src/experimental/tasks/server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAErI;;;;;;;;;;;GAWG;AACH,qBAAa,uBAAuB,CAChC,QAAQ,SAAS,OAAO,GAAG,OAAO,EAClC,aAAa,SAAS,YAAY,GAAG,YAAY,EACjD,OAAO,SAAS,MAAM,GAAG,MAAM;IAEnB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,MAAM,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,CAAC;IAE9E;;;;;;;;;;;;;OAaG;IACH,aAAa,CAAC,CAAC,SAAS,SAAS,EAC7B,OAAO,EAAE,aAAa,GAAG,QAAQ,EACjC,YAAY,EAAE,CAAC,EACf,OAAO,CAAC,EAAE,cAAc,GACzB,cAAc,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAY/D;;;;;;;;OAQG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC;IAK/E;;;;;;;;;OASG;IACG,aAAa,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;IAY9H;;;;;;;;OAQG;IACG,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,eAAe,CAAC;IAQpF;;;;;;;OAOG;IACG,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,gBAAgB,CAAC;CAOxF"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js new file mode 100644 index 000000000..3b429bb0b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js @@ -0,0 +1,89 @@ +/** + * Experimental server task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +/** + * Experimental task features for low-level MCP servers. + * + * Access via `server.experimental.tasks`: + * ```typescript + * const stream = server.experimental.tasks.requestStream(request, schema, options); + * ``` + * + * For high-level server usage with task-based tools, use `McpServer.experimental.tasks` instead. + * + * @experimental + */ +export class ExperimentalServerTasks { + constructor(_server) { + this._server = _server; + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request, resultSchema, options) { + return this._server.requestStream(request, resultSchema, options); + } + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + async getTask(taskId, options) { + return this._server.getTask({ taskId }, options); + } + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + async getTaskResult(taskId, resultSchema, options) { + return this._server.getTaskResult({ taskId }, resultSchema, options); + } + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + async listTasks(cursor, options) { + return this._server.listTasks(cursor ? { cursor } : undefined, options); + } + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + async cancelTask(taskId, options) { + return this._server.cancelTask({ taskId }, options); + } +} +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js.map new file mode 100644 index 000000000..4395efda5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAQH;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,uBAAuB;IAKhC,YAA6B,OAAiD;QAAjD,YAAO,GAAP,OAAO,CAA0C;IAAG,CAAC;IAElF;;;;;;;;;;;;;OAaG;IACH,aAAa,CACT,OAAiC,EACjC,YAAe,EACf,OAAwB;QAUxB,OAAQ,IAAI,CAAC,OAA8C,CAAC,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;IAC9G,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAwB;QAElD,OAAQ,IAAI,CAAC,OAAwC,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC;IACvF,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,aAAa,CAAsB,MAAc,EAAE,YAAgB,EAAE,OAAwB;QAC/F,OACI,IAAI,CAAC,OAOR,CAAC,aAAa,CAAC,EAAE,MAAM,EAAE,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;IACvD,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,SAAS,CAAC,MAAe,EAAE,OAAwB;QACrD,OACI,IAAI,CAAC,OAGR,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IAC1D,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,UAAU,CAAC,MAAc,EAAE,OAAwB;QACrD,OACI,IAAI,CAAC,OAGR,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/stores/in-memory.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/stores/in-memory.d.ts new file mode 100644 index 000000000..d30795e30 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/stores/in-memory.d.ts @@ -0,0 +1,94 @@ +/** + * In-memory implementations of TaskStore and TaskMessageQueue. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +import { Task, RequestId, Result, Request } from '../../../types.js'; +import { TaskStore, TaskMessageQueue, QueuedMessage, CreateTaskOptions } from '../interfaces.js'; +/** + * A simple in-memory implementation of TaskStore for demonstration purposes. + * + * This implementation stores all tasks in memory and provides automatic cleanup + * based on the ttl duration specified in the task creation parameters. + * + * Note: This is not suitable for production use as all data is lost on restart. + * For production, consider implementing TaskStore with a database or distributed cache. + * + * @experimental + */ +export declare class InMemoryTaskStore implements TaskStore { + private tasks; + private cleanupTimers; + /** + * Generates a unique task ID. + * Uses 16 bytes of random data encoded as hex (32 characters). + */ + private generateTaskId; + createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: Request, _sessionId?: string): Promise; + getTask(taskId: string, _sessionId?: string): Promise; + storeTaskResult(taskId: string, status: 'completed' | 'failed', result: Result, _sessionId?: string): Promise; + getTaskResult(taskId: string, _sessionId?: string): Promise; + updateTaskStatus(taskId: string, status: Task['status'], statusMessage?: string, _sessionId?: string): Promise; + listTasks(cursor?: string, _sessionId?: string): Promise<{ + tasks: Task[]; + nextCursor?: string; + }>; + /** + * Cleanup all timers (useful for testing or graceful shutdown) + */ + cleanup(): void; + /** + * Get all tasks (useful for debugging) + */ + getAllTasks(): Task[]; +} +/** + * A simple in-memory implementation of TaskMessageQueue for demonstration purposes. + * + * This implementation stores messages in memory, organized by task ID and optional session ID. + * Messages are stored in FIFO queues per task. + * + * Note: This is not suitable for production use in distributed systems. + * For production, consider implementing TaskMessageQueue with Redis or other distributed queues. + * + * @experimental + */ +export declare class InMemoryTaskMessageQueue implements TaskMessageQueue { + private queues; + /** + * Generates a queue key from taskId. + * SessionId is intentionally ignored because taskIds are globally unique + * and tasks need to be accessible across HTTP requests/sessions. + */ + private getQueueKey; + /** + * Gets or creates a queue for the given task and session. + */ + private getQueue; + /** + * Adds a message to the end of the queue for a specific task. + * Atomically checks queue size and throws if maxSize would be exceeded. + * @param taskId The task identifier + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @param maxSize Optional maximum queue size - if specified and queue is full, throws an error + * @throws Error if maxSize is specified and would be exceeded + */ + enqueue(taskId: string, message: QueuedMessage, sessionId?: string, maxSize?: number): Promise; + /** + * Removes and returns the first message from the queue for a specific task. + * @param taskId The task identifier + * @param sessionId Optional session ID for binding the query to a specific session + * @returns The first message, or undefined if the queue is empty + */ + dequeue(taskId: string, sessionId?: string): Promise; + /** + * Removes and returns all messages from the queue for a specific task. + * @param taskId The task identifier + * @param sessionId Optional session ID for binding the query to a specific session + * @returns Array of all messages that were in the queue + */ + dequeueAll(taskId: string, sessionId?: string): Promise; +} +//# sourceMappingURL=in-memory.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/stores/in-memory.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/stores/in-memory.d.ts.map new file mode 100644 index 000000000..1825e8751 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/stores/in-memory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"in-memory.d.ts","sourceRoot":"","sources":["../../../../../src/experimental/tasks/stores/in-memory.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,EAAE,SAAS,EAAc,gBAAgB,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAU7G;;;;;;;;;;GAUG;AACH,qBAAa,iBAAkB,YAAW,SAAS;IAC/C,OAAO,CAAC,KAAK,CAAiC;IAC9C,OAAO,CAAC,aAAa,CAAoD;IAEzE;;;OAGG;IACH,OAAO,CAAC,cAAc;IAIhB,UAAU,CAAC,UAAU,EAAE,iBAAiB,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA0CrH,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAKlE,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiCnH,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAanE,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,EAAE,aAAa,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAoCpH,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,IAAI,EAAE,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IA0BtG;;OAEG;IACH,OAAO,IAAI,IAAI;IAQf;;OAEG;IACH,WAAW,IAAI,IAAI,EAAE;CAGxB;AAED;;;;;;;;;;GAUG;AACH,qBAAa,wBAAyB,YAAW,gBAAgB;IAC7D,OAAO,CAAC,MAAM,CAAsC;IAEpD;;;;OAIG;IACH,OAAO,CAAC,WAAW;IAInB;;OAEG;IACH,OAAO,CAAC,QAAQ;IAUhB;;;;;;;;OAQG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,SAAS,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAW1G;;;;;OAKG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC;IAKrF;;;;;OAKG;IACG,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;CAMjF"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/stores/in-memory.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/stores/in-memory.js new file mode 100644 index 000000000..6458ec52f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/stores/in-memory.js @@ -0,0 +1,246 @@ +/** + * In-memory implementations of TaskStore and TaskMessageQueue. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ +import { isTerminal } from '../interfaces.js'; +import { randomBytes } from 'node:crypto'; +/** + * A simple in-memory implementation of TaskStore for demonstration purposes. + * + * This implementation stores all tasks in memory and provides automatic cleanup + * based on the ttl duration specified in the task creation parameters. + * + * Note: This is not suitable for production use as all data is lost on restart. + * For production, consider implementing TaskStore with a database or distributed cache. + * + * @experimental + */ +export class InMemoryTaskStore { + constructor() { + this.tasks = new Map(); + this.cleanupTimers = new Map(); + } + /** + * Generates a unique task ID. + * Uses 16 bytes of random data encoded as hex (32 characters). + */ + generateTaskId() { + return randomBytes(16).toString('hex'); + } + async createTask(taskParams, requestId, request, _sessionId) { + // Generate a unique task ID + const taskId = this.generateTaskId(); + // Ensure uniqueness + if (this.tasks.has(taskId)) { + throw new Error(`Task with ID ${taskId} already exists`); + } + const actualTtl = taskParams.ttl ?? null; + // Create task with generated ID and timestamps + const createdAt = new Date().toISOString(); + const task = { + taskId, + status: 'working', + ttl: actualTtl, + createdAt, + lastUpdatedAt: createdAt, + pollInterval: taskParams.pollInterval ?? 1000 + }; + this.tasks.set(taskId, { + task, + request, + requestId + }); + // Schedule cleanup if ttl is specified + // Cleanup occurs regardless of task status + if (actualTtl) { + const timer = setTimeout(() => { + this.tasks.delete(taskId); + this.cleanupTimers.delete(taskId); + }, actualTtl); + this.cleanupTimers.set(taskId, timer); + } + return task; + } + async getTask(taskId, _sessionId) { + const stored = this.tasks.get(taskId); + return stored ? { ...stored.task } : null; + } + async storeTaskResult(taskId, status, result, _sessionId) { + const stored = this.tasks.get(taskId); + if (!stored) { + throw new Error(`Task with ID ${taskId} not found`); + } + // Don't allow storing results for tasks already in terminal state + if (isTerminal(stored.task.status)) { + throw new Error(`Cannot store result for task ${taskId} in terminal status '${stored.task.status}'. Task results can only be stored once.`); + } + stored.result = result; + stored.task.status = status; + stored.task.lastUpdatedAt = new Date().toISOString(); + // Reset cleanup timer to start from now (if ttl is set) + if (stored.task.ttl) { + const existingTimer = this.cleanupTimers.get(taskId); + if (existingTimer) { + clearTimeout(existingTimer); + } + const timer = setTimeout(() => { + this.tasks.delete(taskId); + this.cleanupTimers.delete(taskId); + }, stored.task.ttl); + this.cleanupTimers.set(taskId, timer); + } + } + async getTaskResult(taskId, _sessionId) { + const stored = this.tasks.get(taskId); + if (!stored) { + throw new Error(`Task with ID ${taskId} not found`); + } + if (!stored.result) { + throw new Error(`Task ${taskId} has no result stored`); + } + return stored.result; + } + async updateTaskStatus(taskId, status, statusMessage, _sessionId) { + const stored = this.tasks.get(taskId); + if (!stored) { + throw new Error(`Task with ID ${taskId} not found`); + } + // Don't allow transitions from terminal states + if (isTerminal(stored.task.status)) { + throw new Error(`Cannot update task ${taskId} from terminal status '${stored.task.status}' to '${status}'. Terminal states (completed, failed, cancelled) cannot transition to other states.`); + } + stored.task.status = status; + if (statusMessage) { + stored.task.statusMessage = statusMessage; + } + stored.task.lastUpdatedAt = new Date().toISOString(); + // If task is in a terminal state and has ttl, start cleanup timer + if (isTerminal(status) && stored.task.ttl) { + const existingTimer = this.cleanupTimers.get(taskId); + if (existingTimer) { + clearTimeout(existingTimer); + } + const timer = setTimeout(() => { + this.tasks.delete(taskId); + this.cleanupTimers.delete(taskId); + }, stored.task.ttl); + this.cleanupTimers.set(taskId, timer); + } + } + async listTasks(cursor, _sessionId) { + const PAGE_SIZE = 10; + const allTaskIds = Array.from(this.tasks.keys()); + let startIndex = 0; + if (cursor) { + const cursorIndex = allTaskIds.indexOf(cursor); + if (cursorIndex >= 0) { + startIndex = cursorIndex + 1; + } + else { + // Invalid cursor - throw error + throw new Error(`Invalid cursor: ${cursor}`); + } + } + const pageTaskIds = allTaskIds.slice(startIndex, startIndex + PAGE_SIZE); + const tasks = pageTaskIds.map(taskId => { + const stored = this.tasks.get(taskId); + return { ...stored.task }; + }); + const nextCursor = startIndex + PAGE_SIZE < allTaskIds.length ? pageTaskIds[pageTaskIds.length - 1] : undefined; + return { tasks, nextCursor }; + } + /** + * Cleanup all timers (useful for testing or graceful shutdown) + */ + cleanup() { + for (const timer of this.cleanupTimers.values()) { + clearTimeout(timer); + } + this.cleanupTimers.clear(); + this.tasks.clear(); + } + /** + * Get all tasks (useful for debugging) + */ + getAllTasks() { + return Array.from(this.tasks.values()).map(stored => ({ ...stored.task })); + } +} +/** + * A simple in-memory implementation of TaskMessageQueue for demonstration purposes. + * + * This implementation stores messages in memory, organized by task ID and optional session ID. + * Messages are stored in FIFO queues per task. + * + * Note: This is not suitable for production use in distributed systems. + * For production, consider implementing TaskMessageQueue with Redis or other distributed queues. + * + * @experimental + */ +export class InMemoryTaskMessageQueue { + constructor() { + this.queues = new Map(); + } + /** + * Generates a queue key from taskId. + * SessionId is intentionally ignored because taskIds are globally unique + * and tasks need to be accessible across HTTP requests/sessions. + */ + getQueueKey(taskId, _sessionId) { + return taskId; + } + /** + * Gets or creates a queue for the given task and session. + */ + getQueue(taskId, sessionId) { + const key = this.getQueueKey(taskId, sessionId); + let queue = this.queues.get(key); + if (!queue) { + queue = []; + this.queues.set(key, queue); + } + return queue; + } + /** + * Adds a message to the end of the queue for a specific task. + * Atomically checks queue size and throws if maxSize would be exceeded. + * @param taskId The task identifier + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @param maxSize Optional maximum queue size - if specified and queue is full, throws an error + * @throws Error if maxSize is specified and would be exceeded + */ + async enqueue(taskId, message, sessionId, maxSize) { + const queue = this.getQueue(taskId, sessionId); + // Atomically check size and enqueue + if (maxSize !== undefined && queue.length >= maxSize) { + throw new Error(`Task message queue overflow: queue size (${queue.length}) exceeds maximum (${maxSize})`); + } + queue.push(message); + } + /** + * Removes and returns the first message from the queue for a specific task. + * @param taskId The task identifier + * @param sessionId Optional session ID for binding the query to a specific session + * @returns The first message, or undefined if the queue is empty + */ + async dequeue(taskId, sessionId) { + const queue = this.getQueue(taskId, sessionId); + return queue.shift(); + } + /** + * Removes and returns all messages from the queue for a specific task. + * @param taskId The task identifier + * @param sessionId Optional session ID for binding the query to a specific session + * @returns Array of all messages that were in the queue + */ + async dequeueAll(taskId, sessionId) { + const key = this.getQueueKey(taskId, sessionId); + const queue = this.queues.get(key) ?? []; + this.queues.delete(key); + return queue; + } +} +//# sourceMappingURL=in-memory.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/stores/in-memory.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/stores/in-memory.js.map new file mode 100644 index 000000000..12d754521 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/stores/in-memory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"in-memory.js","sourceRoot":"","sources":["../../../../../src/experimental/tasks/stores/in-memory.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAa,UAAU,EAAsD,MAAM,kBAAkB,CAAC;AAC7G,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAS1C;;;;;;;;;;GAUG;AACH,MAAM,OAAO,iBAAiB;IAA9B;QACY,UAAK,GAAG,IAAI,GAAG,EAAsB,CAAC;QACtC,kBAAa,GAAG,IAAI,GAAG,EAAyC,CAAC;IAsL7E,CAAC;IApLG;;;OAGG;IACK,cAAc;QAClB,OAAO,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,UAA6B,EAAE,SAAoB,EAAE,OAAgB,EAAE,UAAmB;QACvG,4BAA4B;QAC5B,MAAM,MAAM,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC;QAErC,oBAAoB;QACpB,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,gBAAgB,M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AAC,OAAO,CAAC,MAAc,EAAE,OAAsB,EAAE,SAAkB,EAAE,OAAgB;QACtF,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;QAE/C,oCAAoC;QACpC,IAAI,OAAO,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,IAAI,OAAO,EAAE,CAAC;YACnD,MAAM,IAAI,KAAK,CAAC,4CAA4C,KAAK,CAAC,MAAM,sBAAsB,OAAO,GAAG,CAAC,CAAC;QAC9G,CAAC;QAED,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,SAAkB;QAC5C,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;QAC/C,OAAO,KAAK,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,UAAU,CAAC,MAAc,EAAE,SAAkB;QAC/C,MAAM,GAAG,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;QAChD,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;QACzC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACxB,OAAO,KAAK,CAAC;IACjB,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/types.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/types.d.ts new file mode 100644 index 000000000..6022e19b2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/types.d.ts @@ -0,0 +1,10 @@ +/** + * Re-exports of task-related types from the MCP protocol spec. + * WARNING: These APIs are experimental and may change without notice. + * + * These types are defined in types.ts (matching the protocol spec) and + * re-exported here for convenience when working with experimental task features. + */ +export { TaskCreationParamsSchema, RelatedTaskMetadataSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema } from '../../types.js'; +export type { Task, TaskCreationParams, RelatedTaskMetadata, CreateTaskResult, TaskStatusNotificationParams, TaskStatusNotification, GetTaskRequest, GetTaskResult, GetTaskPayloadRequest, ListTasksRequest, ListTasksResult, CancelTaskRequest, CancelTaskResult } from '../../types.js'; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/types.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/types.d.ts.map new file mode 100644 index 000000000..f7b9ead05 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/experimental/tasks/types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EACH,wBAAwB,EACxB,yBAAyB,EACzB,UAAU,EACV,sBAAsB,EACtB,kCAAkC,EAClC,4BAA4B,EAC5B,oBAAoB,EACpB,mBAAmB,EACnB,2BAA2B,EAC3B,sBAAsB,EACtB,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,EACtB,2BAA2B,EAC3B,2BAA2B,EAC9B,MAAM,gBAAgB,CAAC;AAGxB,YAAY,EACR,IAAI,EACJ,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,4BAA4B,EAC5B,sBAAsB,EACtB,cAAc,EACd,aAAa,EACb,qBAAqB,EACrB,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EACnB,MAAM,gBAAgB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/types.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/types.js new file mode 100644 index 000000000..2162c093a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/types.js @@ -0,0 +1,10 @@ +/** + * Re-exports of task-related types from the MCP protocol spec. + * WARNING: These APIs are experimental and may change without notice. + * + * These types are defined in types.ts (matching the protocol spec) and + * re-exported here for convenience when working with experimental task features. + */ +// Task schemas (Zod) +export { TaskCreationParamsSchema, RelatedTaskMetadataSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema } from '../../types.js'; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/types.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/types.js.map new file mode 100644 index 000000000..f52e75e09 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/experimental/tasks/types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,qBAAqB;AACrB,OAAO,EACH,wBAAwB,EACxB,yBAAyB,EACzB,UAAU,EACV,sBAAsB,EACtB,kCAAkC,EAClC,4BAA4B,EAC5B,oBAAoB,EACpB,mBAAmB,EACnB,2BAA2B,EAC3B,sBAAsB,EACtB,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,EACtB,2BAA2B,EAC3B,2BAA2B,EAC9B,MAAM,gBAAgB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.d.ts new file mode 100644 index 000000000..32a931a86 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.d.ts @@ -0,0 +1,31 @@ +import { Transport } from './shared/transport.js'; +import { JSONRPCMessage, RequestId } from './types.js'; +import { AuthInfo } from './server/auth/types.js'; +/** + * In-memory transport for creating clients and servers that talk to each other within the same process. + */ +export declare class InMemoryTransport implements Transport { + private _otherTransport?; + private _messageQueue; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: { + authInfo?: AuthInfo; + }) => void; + sessionId?: string; + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. + */ + static createLinkedPair(): [InMemoryTransport, InMemoryTransport]; + start(): Promise; + close(): Promise; + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + send(message: JSONRPCMessage, options?: { + relatedRequestId?: RequestId; + authInfo?: AuthInfo; + }): Promise; +} +//# sourceMappingURL=inMemory.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.d.ts.map new file mode 100644 index 000000000..46bc74be1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemory.d.ts","sourceRoot":"","sources":["../../src/inMemory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAOlD;;GAEG;AACH,qBAAa,iBAAkB,YAAW,SAAS;IAC/C,OAAO,CAAC,eAAe,CAAC,CAAoB;IAC5C,OAAO,CAAC,aAAa,CAAuB;IAE5C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAAK,IAAI,CAAC;IAC/E,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,MAAM,CAAC,gBAAgB,IAAI,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;IAQ3D,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAQtB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAO5B;;;OAGG;IACG,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAC;QAAC,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAWtH"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.js new file mode 100644 index 000000000..62d86a291 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.js @@ -0,0 +1,47 @@ +/** + * In-memory transport for creating clients and servers that talk to each other within the same process. + */ +export class InMemoryTransport { + constructor() { + this._messageQueue = []; + } + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. + */ + static createLinkedPair() { + const clientTransport = new InMemoryTransport(); + const serverTransport = new InMemoryTransport(); + clientTransport._otherTransport = serverTransport; + serverTransport._otherTransport = clientTransport; + return [clientTransport, serverTransport]; + } + async start() { + // Process any messages that were queued before start was called + while (this._messageQueue.length > 0) { + const queuedMessage = this._messageQueue.shift(); + this.onmessage?.(queuedMessage.message, queuedMessage.extra); + } + } + async close() { + const other = this._otherTransport; + this._otherTransport = undefined; + await other?.close(); + this.onclose?.(); + } + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + async send(message, options) { + if (!this._otherTransport) { + throw new Error('Not connected'); + } + if (this._otherTransport.onmessage) { + this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); + } + else { + this._otherTransport._messageQueue.push({ message, extra: { authInfo: options?.authInfo } }); + } + } +} +//# sourceMappingURL=inMemory.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.js.map new file mode 100644 index 000000000..60ededdda --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/inMemory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemory.js","sourceRoot":"","sources":["../../src/inMemory.ts"],"names":[],"mappings":"AASA;;GAEG;AACH,MAAM,OAAO,iBAAiB;IAA9B;QAEY,kBAAa,GAAoB,EAAE,CAAC;IAgDhD,CAAC;IAzCG;;OAEG;IACH,MAAM,CAAC,gBAAgB;QACnB,MAAM,eAAe,GAAG,IAAI,iBAAiB,EAAE,CAAC;QAChD,MAAM,eAAe,GAAG,IAAI,iBAAiB,EAAE,CAAC;QAChD,eAAe,CAAC,eAAe,GAAG,eAAe,CAAC;QAClD,eAAe,CAAC,eAAe,GAAG,eAAe,CAAC;QAClD,OAAO,CAAC,eAAe,EAAE,eAAe,CAAC,CAAC;IAC9C,CAAC;IAED,KAAK,CAAC,KAAK;QACP,gEAAgE;QAChE,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACnC,MAAM,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,EAAG,CAAC;YAClD,IAAI,CAAC,SAAS,EAAE,CAAC,aAAa,CAAC,OAAO,EAAE,aAAa,CAAC,KAAK,CAAC,CAAC;QACjE,CAAC;IACL,CAAC;IAED,KAAK,CAAC,KAAK;QACP,MAAM,KAAK,GAAG,IAAI,CAAC,eAAe,CAAC;QACnC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,MAAM,KAAK,EAAE,KAAK,EAAE,CAAC;QACrB,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;IACrB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,IAAI,CAAC,OAAuB,EAAE,OAA+D;QAC/F,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;QACrC,CAAC;QAED,IAAI,IAAI,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC7E,CAAC;aAAM,CAAC;YACJ,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;QACjG,CAAC;IACL,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/package.json b/node_modules/@modelcontextprotocol/sdk/dist/esm/package.json new file mode 100644 index 000000000..6990891ff --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/clients.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/clients.d.ts new file mode 100644 index 000000000..be6899a19 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/clients.d.ts @@ -0,0 +1,19 @@ +import { OAuthClientInformationFull } from '../../shared/auth.js'; +/** + * Stores information about registered OAuth clients for this server. + */ +export interface OAuthRegisteredClientsStore { + /** + * Returns information about a registered client, based on its ID. + */ + getClient(clientId: string): OAuthClientInformationFull | undefined | Promise; + /** + * Registers a new client with the server. The client ID and secret will be automatically generated by the library. A modified version of the client information can be returned to reflect specific values enforced by the server. + * + * NOTE: Implementations should NOT delete expired client secrets in-place. Auth middleware provided by this library will automatically check the `client_secret_expires_at` field and reject requests with expired secrets. Any custom logic for authenticating clients should check the `client_secret_expires_at` field as well. + * + * If unimplemented, dynamic client registration is unsupported. + */ + registerClient?(client: Omit): OAuthClientInformationFull | Promise; +} +//# sourceMappingURL=clients.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/clients.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/clients.d.ts.map new file mode 100644 index 000000000..ab3851db3 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/clients.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clients.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/clients.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAElE;;GAEG;AACH,MAAM,WAAW,2BAA2B;IACxC;;OAEG;IACH,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,0BAA0B,GAAG,SAAS,GAAG,OAAO,CAAC,0BAA0B,GAAG,SAAS,CAAC,CAAC;IAEtH;;;;;;OAMG;IACH,cAAc,CAAC,CACX,MAAM,EAAE,IAAI,CAAC,0BAA0B,EAAE,WAAW,GAAG,qBAAqB,CAAC,GAC9E,0BAA0B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;CACvE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/clients.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/clients.js new file mode 100644 index 000000000..6181a5709 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/clients.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=clients.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/clients.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/clients.js.map new file mode 100644 index 000000000..021010442 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/clients.js.map @@ -0,0 +1 @@ +{"version":3,"file":"clients.js","sourceRoot":"","sources":["../../../../src/server/auth/clients.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.d.ts new file mode 100644 index 000000000..7fddf954c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.d.ts @@ -0,0 +1,148 @@ +import { OAuthErrorResponse } from '../../shared/auth.js'; +/** + * Base class for all OAuth errors + */ +export declare class OAuthError extends Error { + readonly errorUri?: string | undefined; + static errorCode: string; + constructor(message: string, errorUri?: string | undefined); + /** + * Converts the error to a standard OAuth error response object + */ + toResponseObject(): OAuthErrorResponse; + get errorCode(): string; +} +/** + * Invalid request error - The request is missing a required parameter, + * includes an invalid parameter value, includes a parameter more than once, + * or is otherwise malformed. + */ +export declare class InvalidRequestError extends OAuthError { + static errorCode: string; +} +/** + * Invalid client error - Client authentication failed (e.g., unknown client, no client + * authentication included, or unsupported authentication method). + */ +export declare class InvalidClientError extends OAuthError { + static errorCode: string; +} +/** + * Invalid grant error - The provided authorization grant or refresh token is + * invalid, expired, revoked, does not match the redirection URI used in the + * authorization request, or was issued to another client. + */ +export declare class InvalidGrantError extends OAuthError { + static errorCode: string; +} +/** + * Unauthorized client error - The authenticated client is not authorized to use + * this authorization grant type. + */ +export declare class UnauthorizedClientError extends OAuthError { + static errorCode: string; +} +/** + * Unsupported grant type error - The authorization grant type is not supported + * by the authorization server. + */ +export declare class UnsupportedGrantTypeError extends OAuthError { + static errorCode: string; +} +/** + * Invalid scope error - The requested scope is invalid, unknown, malformed, or + * exceeds the scope granted by the resource owner. + */ +export declare class InvalidScopeError extends OAuthError { + static errorCode: string; +} +/** + * Access denied error - The resource owner or authorization server denied the request. + */ +export declare class AccessDeniedError extends OAuthError { + static errorCode: string; +} +/** + * Server error - The authorization server encountered an unexpected condition + * that prevented it from fulfilling the request. + */ +export declare class ServerError extends OAuthError { + static errorCode: string; +} +/** + * Temporarily unavailable error - The authorization server is currently unable to + * handle the request due to a temporary overloading or maintenance of the server. + */ +export declare class TemporarilyUnavailableError extends OAuthError { + static errorCode: string; +} +/** + * Unsupported response type error - The authorization server does not support + * obtaining an authorization code using this method. + */ +export declare class UnsupportedResponseTypeError extends OAuthError { + static errorCode: string; +} +/** + * Unsupported token type error - The authorization server does not support + * the requested token type. + */ +export declare class UnsupportedTokenTypeError extends OAuthError { + static errorCode: string; +} +/** + * Invalid token error - The access token provided is expired, revoked, malformed, + * or invalid for other reasons. + */ +export declare class InvalidTokenError extends OAuthError { + static errorCode: string; +} +/** + * Method not allowed error - The HTTP method used is not allowed for this endpoint. + * (Custom, non-standard error) + */ +export declare class MethodNotAllowedError extends OAuthError { + static errorCode: string; +} +/** + * Too many requests error - Rate limit exceeded. + * (Custom, non-standard error based on RFC 6585) + */ +export declare class TooManyRequestsError extends OAuthError { + static errorCode: string; +} +/** + * Invalid client metadata error - The client metadata is invalid. + * (Custom error for dynamic client registration - RFC 7591) + */ +export declare class InvalidClientMetadataError extends OAuthError { + static errorCode: string; +} +/** + * Insufficient scope error - The request requires higher privileges than provided by the access token. + */ +export declare class InsufficientScopeError extends OAuthError { + static errorCode: string; +} +/** + * Invalid target error - The requested resource is invalid, missing, unknown, or malformed. + * (Custom error for resource indicators - RFC 8707) + */ +export declare class InvalidTargetError extends OAuthError { + static errorCode: string; +} +/** + * A utility class for defining one-off error codes + */ +export declare class CustomOAuthError extends OAuthError { + private readonly customErrorCode; + constructor(customErrorCode: string, message: string, errorUri?: string); + get errorCode(): string; +} +/** + * A full list of all OAuthErrors, enabling parsing from error responses + */ +export declare const OAUTH_ERRORS: { + readonly [x: string]: typeof InvalidRequestError; +}; +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.d.ts.map new file mode 100644 index 000000000..5c0e99202 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D;;GAEG;AACH,qBAAa,UAAW,SAAQ,KAAK;aAKb,QAAQ,CAAC,EAAE,MAAM;IAJrC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC;gBAGrB,OAAO,EAAE,MAAM,EACC,QAAQ,CAAC,EAAE,MAAM,YAAA;IAMrC;;OAEG;IACH,gBAAgB,IAAI,kBAAkB;IAatC,IAAI,SAAS,IAAI,MAAM,CAEtB;CACJ;AAED;;;;GAIG;AACH,qBAAa,mBAAoB,SAAQ,UAAU;IAC/C,MAAM,CAAC,SAAS,SAAqB;CACxC;AAED;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,UAAU;IAC9C,MAAM,CAAC,SAAS,SAAoB;CACvC;AAED;;;;GAIG;AACH,qBAAa,iBAAkB,SAAQ,UAAU;IAC7C,MAAM,CAAC,SAAS,SAAmB;CACtC;AAED;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,UAAU;IACnD,MAAM,CAAC,SAAS,SAAyB;CAC5C;AAED;;;GAGG;AACH,qBAAa,yBAA0B,SAAQ,UAAU;IACrD,MAAM,CAAC,SAAS,SAA4B;CAC/C;AAED;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,UAAU;IAC7C,MAAM,CAAC,SAAS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extprotocol/sdk/dist/esm/server/auth/errors.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js new file mode 100644 index 000000000..7106ab98a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js @@ -0,0 +1,180 @@ +/** + * Base class for all OAuth errors + */ +export class OAuthError extends Error { + constructor(message, errorUri) { + super(message); + this.errorUri = errorUri; + this.name = this.constructor.name; + } + /** + * Converts the error to a standard OAuth error response object + */ + toResponseObject() { + const response = { + error: this.errorCode, + error_description: this.message + }; + if (this.errorUri) { + response.error_uri = this.errorUri; + } + return response; + } + get errorCode() { + return this.constructor.errorCode; + } +} +/** + * Invalid request error - The request is missing a required parameter, + * includes an invalid parameter value, includes a parameter more than once, + * or is otherwise malformed. + */ +export class InvalidRequestError extends OAuthError { +} +InvalidRequestError.errorCode = 'invalid_request'; +/** + * Invalid client error - Client authentication failed (e.g., unknown client, no client + * authentication included, or unsupported authentication method). + */ +export class InvalidClientError extends OAuthError { +} +InvalidClientError.errorCode = 'invalid_client'; +/** + * Invalid grant error - The provided authorization grant or refresh token is + * invalid, expired, revoked, does not match the redirection URI used in the + * authorization request, or was issued to another client. + */ +export class InvalidGrantError extends OAuthError { +} +InvalidGrantError.errorCode = 'invalid_grant'; +/** + * Unauthorized client error - The authenticated client is not authorized to use + * this authorization grant type. + */ +export class UnauthorizedClientError extends OAuthError { +} +UnauthorizedClientError.errorCode = 'unauthorized_client'; +/** + * Unsupported grant type error - The authorization grant type is not supported + * by the authorization server. + */ +export class UnsupportedGrantTypeError extends OAuthError { +} +UnsupportedGrantTypeError.errorCode = 'unsupported_grant_type'; +/** + * Invalid scope error - The requested scope is invalid, unknown, malformed, or + * exceeds the scope granted by the resource owner. + */ +export class InvalidScopeError extends OAuthError { +} +InvalidScopeError.errorCode = 'invalid_scope'; +/** + * Access denied error - The resource owner or authorization server denied the request. + */ +export class AccessDeniedError extends OAuthError { +} +AccessDeniedError.errorCode = 'access_denied'; +/** + * Server error - The authorization server encountered an unexpected condition + * that prevented it from fulfilling the request. + */ +export class ServerError extends OAuthError { +} +ServerError.errorCode = 'server_error'; +/** + * Temporarily unavailable error - The authorization server is currently unable to + * handle the request due to a temporary overloading or maintenance of the server. + */ +export class TemporarilyUnavailableError extends OAuthError { +} +TemporarilyUnavailableError.errorCode = 'temporarily_unavailable'; +/** + * Unsupported response type error - The authorization server does not support + * obtaining an authorization code using this method. + */ +export class UnsupportedResponseTypeError extends OAuthError { +} +UnsupportedResponseTypeError.errorCode = 'unsupported_response_type'; +/** + * Unsupported token type error - The authorization server does not support + * the requested token type. + */ +export class UnsupportedTokenTypeError extends OAuthError { +} +UnsupportedTokenTypeError.errorCode = 'unsupported_token_type'; +/** + * Invalid token error - The access token provided is expired, revoked, malformed, + * or invalid for other reasons. + */ +export class InvalidTokenError extends OAuthError { +} +InvalidTokenError.errorCode = 'invalid_token'; +/** + * Method not allowed error - The HTTP method used is not allowed for this endpoint. + * (Custom, non-standard error) + */ +export class MethodNotAllowedError extends OAuthError { +} +MethodNotAllowedError.errorCode = 'method_not_allowed'; +/** + * Too many requests error - Rate limit exceeded. + * (Custom, non-standard error based on RFC 6585) + */ +export class TooManyRequestsError extends OAuthError { +} +TooManyRequestsError.errorCode = 'too_many_requests'; +/** + * Invalid client metadata error - The client metadata is invalid. + * (Custom error for dynamic client registration - RFC 7591) + */ +export class InvalidClientMetadataError extends OAuthError { +} +InvalidClientMetadataError.errorCode = 'invalid_client_metadata'; +/** + * Insufficient scope error - The request requires higher privileges than provided by the access token. + */ +export class InsufficientScopeError extends OAuthError { +} +InsufficientScopeError.errorCode = 'insufficient_scope'; +/** + * Invalid target error - The requested resource is invalid, missing, unknown, or malformed. + * (Custom error for resource indicators - RFC 8707) + */ +export class InvalidTargetError extends OAuthError { +} +InvalidTargetError.errorCode = 'invalid_target'; +/** + * A utility class for defining one-off error codes + */ +export class CustomOAuthError extends OAuthError { + constructor(customErrorCode, message, errorUri) { + super(message, errorUri); + this.customErrorCode = customErrorCode; + } + get errorCode() { + return this.customErrorCode; + } +} +/** + * A full list of all OAuthErrors, enabling parsing from error responses + */ +export const OAUTH_ERRORS = { + [InvalidRequestError.errorCode]: InvalidRequestError, + [InvalidClientError.errorCode]: InvalidClientError, + [InvalidGrantError.errorCode]: InvalidGrantError, + [UnauthorizedClientError.errorCode]: UnauthorizedClientError, + [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError, + [InvalidScopeError.errorCode]: InvalidScopeError, + [AccessDeniedError.errorCode]: AccessDeniedError, + [ServerError.errorCode]: ServerError, + [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError, + [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError, + [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError, + [InvalidTokenError.errorCode]: InvalidTokenError, + [MethodNotAllowedError.errorCode]: MethodNotAllowedError, + [TooManyRequestsError.errorCode]: TooManyRequestsError, + [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError, + [InsufficientScopeError.errorCode]: InsufficientScopeError, + [InvalidTargetError.errorCode]: InvalidTargetError +}; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js.map new file mode 100644 index 000000000..1461367c6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../src/server/auth/errors.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,OAAO,UAAW,SAAQ,KAAK;IAGjC,YACI,OAAe,EACC,QAAiB;QAEjC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,aAAQ,GAAR,QAAQ,CAAS;QAGjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;IACtC,CAAC;IAED;;OAEG;IACH,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AS,CAAC,EAAE,iBAAiB;IAChD,CAAC,iBAAiB,CAAC,SAAS,CAAC,EAAE,iBAAiB;IAChD,CAAC,WAAW,CAAC,SAAS,CAAC,EAAE,WAAW;IACpC,CAAC,2BAA2B,CAAC,SAAS,CAAC,EAAE,2BAA2B;IACpE,CAAC,4BAA4B,CAAC,SAAS,CAAC,EAAE,4BAA4B;IACtE,CAAC,yBAAyB,CAAC,SAAS,CAAC,EAAE,yBAAyB;IAChE,CAAC,iBAAiB,CAAC,SAAS,CAAC,EAAE,iBAAiB;IAChD,CAAC,qBAAqB,CAAC,SAAS,CAAC,EAAE,qBAAqB;IACxD,CAAC,oBAAoB,CAAC,SAAS,CAAC,EAAE,oBAAoB;IACtD,CAAC,0BAA0B,CAAC,SAAS,CAAC,EAAE,0BAA0B;IAClE,CAAC,sBAAsB,CAAC,SAAS,CAAC,EAAE,sBAAsB;IAC1D,CAAC,kBAAkB,CAAC,SAAS,CAAC,EAAE,kBAAkB;CAC5C,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/authorize.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/authorize.d.ts new file mode 100644 index 000000000..38e9829bd --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/authorize.d.ts @@ -0,0 +1,13 @@ +import { RequestHandler } from 'express'; +import { OAuthServerProvider } from '../provider.js'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type AuthorizationHandlerOptions = { + provider: OAuthServerProvider; + /** + * Rate limiting configuration for the authorization endpoint. + * Set to false to disable rate limiting for this endpoint. + */ + rateLimit?: Partial | false; +}; +export declare function authorizationHandler({ provider, rateLimit: rateLimitConfig }: AuthorizationHandlerOptions): RequestHandler; +//# sourceMappingURL=authorize.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/authorize.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/authorize.d.ts.map new file mode 100644 index 000000000..b06798834 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/authorize.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/authorize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,2BAA2B,GAAG;IACtC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAqBF,wBAAgB,oBAAoB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,2BAA2B,GAAG,cAAc,CAgH1H"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/authorize.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/authorize.js new file mode 100644 index 000000000..e29f09438 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/authorize.js @@ -0,0 +1,138 @@ +import * as z from 'zod/v4'; +import express from 'express'; +import { rateLimit } from 'express-rate-limit'; +import { allowedMethods } from '../middleware/allowedMethods.js'; +import { InvalidRequestError, InvalidClientError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; +// Parameters that must be validated in order to issue redirects. +const ClientAuthorizationParamsSchema = z.object({ + client_id: z.string(), + redirect_uri: z + .string() + .optional() + .refine(value => value === undefined || URL.canParse(value), { message: 'redirect_uri must be a valid URL' }) +}); +// Parameters that must be validated for a successful authorization request. Failure can be reported to the redirect URI. +const RequestAuthorizationParamsSchema = z.object({ + response_type: z.literal('code'), + code_challenge: z.string(), + code_challenge_method: z.literal('S256'), + scope: z.string().optional(), + state: z.string().optional(), + resource: z.string().url().optional() +}); +export function authorizationHandler({ provider, rateLimit: rateLimitConfig }) { + // Create a router to apply middleware + const router = express.Router(); + router.use(allowedMethods(['GET', 'POST'])); + router.use(express.urlencoded({ extended: false })); + // Apply rate limiting unless explicitly disabled + if (rateLimitConfig !== false) { + router.use(rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, // 100 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new TooManyRequestsError('You have exceeded the rate limit for authorization requests').toResponseObject(), + ...rateLimitConfig + })); + } + router.all('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + // In the authorization flow, errors are split into two categories: + // 1. Pre-redirect errors (direct response with 400) + // 2. Post-redirect errors (redirect with error parameters) + // Phase 1: Validate client_id and redirect_uri. Any errors here must be direct responses. + let client_id, redirect_uri, client; + try { + const result = ClientAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); + if (!result.success) { + throw new InvalidRequestError(result.error.message); + } + client_id = result.data.client_id; + redirect_uri = result.data.redirect_uri; + client = await provider.clientsStore.getClient(client_id); + if (!client) { + throw new InvalidClientError('Invalid client_id'); + } + if (redirect_uri !== undefined) { + if (!client.redirect_uris.includes(redirect_uri)) { + throw new InvalidRequestError('Unregistered redirect_uri'); + } + } + else if (client.redirect_uris.length === 1) { + redirect_uri = client.redirect_uris[0]; + } + else { + throw new InvalidRequestError('redirect_uri must be specified when client has multiple registered URIs'); + } + } + catch (error) { + // Pre-redirect errors - return direct response + // + // These don't need to be JSON encoded, as they'll be displayed in a user + // agent, but OTOH they all represent exceptional situations (arguably, + // "programmer error"), so presenting a nice HTML page doesn't help the + // user anyway. + if (error instanceof OAuthError) { + const status = error instanceof ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + return; + } + // Phase 2: Validate other parameters. Any errors here should go into redirect responses. + let state; + try { + // Parse and validate authorization parameters + const parseResult = RequestAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); + if (!parseResult.success) { + throw new InvalidRequestError(parseResult.error.message); + } + const { scope, code_challenge, resource } = parseResult.data; + state = parseResult.data.state; + // Validate scopes + let requestedScopes = []; + if (scope !== undefined) { + requestedScopes = scope.split(' '); + } + // All validation passed, proceed with authorization + await provider.authorize(client, { + state, + scopes: requestedScopes, + redirectUri: redirect_uri, + codeChallenge: code_challenge, + resource: resource ? new URL(resource) : undefined + }, res); + } + catch (error) { + // Post-redirect errors - redirect with error parameters + if (error instanceof OAuthError) { + res.redirect(302, createErrorRedirect(redirect_uri, error, state)); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.redirect(302, createErrorRedirect(redirect_uri, serverError, state)); + } + } + }); + return router; +} +/** + * Helper function to create redirect URL with error parameters + */ +function createErrorRedirect(redirectUri, error, state) { + const errorUrl = new URL(redirectUri); + errorUrl.searchParams.set('error', error.errorCode); + errorUrl.searchParams.set('error_description', error.message); + if (error.errorUri) { + errorUrl.searchParams.set('error_uri', error.errorUri); + } + if (state) { + errorUrl.searchParams.set('state', state); + } + return errorUrl.href; +} +//# sourceMappingURL=authorize.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/authorize.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/authorize.js.map new file mode 100644 index 000000000..6911f9a38 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/authorize.js.map @@ -0,0 +1 @@ +{"version":3,"file":"authorize.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/authorize.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EAAE,SAAS,EAA+B,M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,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;GAEG;AACH,SAAS,mBAAmB,CAAC,WAAmB,EAAE,KAAiB,EAAE,KAAc;IAC/E,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;IACtC,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IACpD,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,mBAAmB,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;IAC9D,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;QACjB,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,WAAW,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC3D,CAAC;IACD,IAAI,KAAK,EAAE,CAAC;QACR,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/metadata.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/metadata.d.ts new file mode 100644 index 000000000..4d0328617 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/metadata.d.ts @@ -0,0 +1,4 @@ +import { RequestHandler } from 'express'; +import { OAuthMetadata, OAuthProtectedResourceMetadata } from '../../../shared/auth.js'; +export declare function metadataHandler(metadata: OAuthMetadata | OAuthProtectedResourceMetadata): RequestHandler; +//# sourceMappingURL=metadata.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/metadata.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/metadata.d.ts.map new file mode 100644 index 000000000..55e3a50dc --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/metadata.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/metadata.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,8BAA8B,EAAE,MAAM,yBAAyB,CAAC;AAIxF,wBAAgB,eAAe,CAAC,QAAQ,EAAE,aAAa,GAAG,8BAA8B,GAAG,cAAc,CAaxG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/metadata.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/metadata.js new file mode 100644 index 000000000..94dadb709 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/metadata.js @@ -0,0 +1,15 @@ +import express from 'express'; +import cors from 'cors'; +import { allowedMethods } from '../middleware/allowedMethods.js'; +export function metadataHandler(metadata) { + // Nested router so we can configure middleware and restrict HTTP method + const router = express.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use(cors()); + router.use(allowedMethods(['GET', 'OPTIONS'])); + router.get('/', (req, res) => { + res.status(200).json(metadata); + }); + return router; +} +//# sourceMappingURL=metadata.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/metadata.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/metadata.js.map new file mode 100644 index 000000000..625ed947d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/metadata.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/metadata.ts"],"names":[],"mappings":"AAAA,OAAO,OAA2B,MAAM,SAAS,CAAC;AAElD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAEjE,MAAM,UAAU,eAAe,CAAC,QAAwD;IACpF,wEAAwE;IACxE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAEhC,kFAAkF;IAClF,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;IAEnB,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;IAC/C,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;QACzB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACnC,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/register.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/register.d.ts new file mode 100644 index 000000000..e9add2845 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/register.d.ts @@ -0,0 +1,29 @@ +import { RequestHandler } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type ClientRegistrationHandlerOptions = { + /** + * A store used to save information about dynamically registered OAuth clients. + */ + clientsStore: OAuthRegisteredClientsStore; + /** + * The number of seconds after which to expire issued client secrets, or 0 to prevent expiration of client secrets (not recommended). + * + * If not set, defaults to 30 days. + */ + clientSecretExpirySeconds?: number; + /** + * Rate limiting configuration for the client registration endpoint. + * Set to false to disable rate limiting for this endpoint. + * Registration endpoints are particularly sensitive to abuse and should be rate limited. + */ + rateLimit?: Partial | false; + /** + * Whether to generate a client ID before calling the client registration endpoint. + * + * If not set, defaults to true. + */ + clientIdGeneration?: boolean; +}; +export declare function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds, rateLimit: rateLimitConfig, clientIdGeneration }: ClientRegistrationHandlerOptions): RequestHandler; +//# sourceMappingURL=register.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/register.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/register.d.ts.map new file mode 100644 index 000000000..a38ebdb89 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/register.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/register.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAIlD,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,gCAAgC,GAAG;IAC3C;;OAEG;IACH,YAAY,EAAE,2BAA2B,CAAC;IAE1C;;;;OAIG;IACH,yBAAyB,CAAC,EAAE,MAAM,CAAC;IAEnC;;;;OAIG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;IAE9C;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAChC,CAAC;AAIF,wBAAgB,yBAAyB,CAAC,EACtC,YAAY,EACZ,yBAAgE,EAChE,SAAS,EAAE,eAAe,EAC1B,kBAAyB,EAC5B,EAAE,gCAAgC,GAAG,cAAc,CA0EnD"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/register.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/register.js new file mode 100644 index 000000000..ef6c44d51 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/register.js @@ -0,0 +1,71 @@ +import express from 'express'; +import { OAuthClientMetadataSchema } from '../../../shared/auth.js'; +import crypto from 'node:crypto'; +import cors from 'cors'; +import { rateLimit } from 'express-rate-limit'; +import { allowedMethods } from '../middleware/allowedMethods.js'; +import { InvalidClientMetadataError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; +const DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS = 30 * 24 * 60 * 60; // 30 days +export function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds = DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS, rateLimit: rateLimitConfig, clientIdGeneration = true }) { + if (!clientsStore.registerClient) { + throw new Error('Client registration store does not support registering clients'); + } + // Nested router so we can configure middleware and restrict HTTP method + const router = express.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use(cors()); + router.use(allowedMethods(['POST'])); + router.use(express.json()); + // Apply rate limiting unless explicitly disabled - stricter limits for registration + if (rateLimitConfig !== false) { + router.use(rateLimit({ + windowMs: 60 * 60 * 1000, // 1 hour + max: 20, // 20 requests per hour - stricter as registration is sensitive + standardHeaders: true, + legacyHeaders: false, + message: new TooManyRequestsError('You have exceeded the rate limit for client registration requests').toResponseObject(), + ...rateLimitConfig + })); + } + router.post('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + try { + const parseResult = OAuthClientMetadataSchema.safeParse(req.body); + if (!parseResult.success) { + throw new InvalidClientMetadataError(parseResult.error.message); + } + const clientMetadata = parseResult.data; + const isPublicClient = clientMetadata.token_endpoint_auth_method === 'none'; + // Generate client credentials + const clientSecret = isPublicClient ? undefined : crypto.randomBytes(32).toString('hex'); + const clientIdIssuedAt = Math.floor(Date.now() / 1000); + // Calculate client secret expiry time + const clientsDoExpire = clientSecretExpirySeconds > 0; + const secretExpiryTime = clientsDoExpire ? clientIdIssuedAt + clientSecretExpirySeconds : 0; + const clientSecretExpiresAt = isPublicClient ? undefined : secretExpiryTime; + let clientInfo = { + ...clientMetadata, + client_secret: clientSecret, + client_secret_expires_at: clientSecretExpiresAt + }; + if (clientIdGeneration) { + clientInfo.client_id = crypto.randomUUID(); + clientInfo.client_id_issued_at = clientIdIssuedAt; + } + clientInfo = await clientsStore.registerClient(clientInfo); + res.status(201).json(clientInfo); + } + catch (error) { + if (error instanceof OAuthError) { + const status = error instanceof ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }); + return router; +} +//# sourceMappingURL=register.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/register.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/register.js.map new file mode 100644 index 000000000..3f4c082f0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/register.js.map @@ -0,0 +1 @@ +{"version":3,"file":"register.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/register.ts"],"names":[],"mappings":"AAAA,OAAO,OAA2B,MAAM,SAAS,CAAC;AAClD,OAAO,EAA8B,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAChG,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,SAAS,EAA+B,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,0BAA0B,EAAE,WAAW,EAAE,oBAAoB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AA8BzG,MAAM,oCAAoC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,UAAU;AAE1E,MAAM,UAAU,yBAAyB,CAAC,EACtC,YAAY,EACZ,yBAAyB,GAAG,oCAAoC,EAChE,SAAS,EAAE,eAAe,EAC1B,kBAAkB,GAAG,IAAI,EACM;IAC/B,IAAI,CAAC,YAAY,CAAC,cAAc,EAAE,CAAC;QAC/B,MAAM,IAAI,KAAK,CAAC,gEAA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AAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/revoke.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/revoke.d.ts new file mode 100644 index 000000000..2be32bb3c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/revoke.d.ts @@ -0,0 +1,13 @@ +import { OAuthServerProvider } from '../provider.js'; +import { RequestHandler } from 'express'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type RevocationHandlerOptions = { + provider: OAuthServerProvider; + /** + * Rate limiting configuration for the token revocation endpoint. + * Set to false to disable rate limiting for this endpoint. + */ + rateLimit?: Partial | false; +}; +export declare function revocationHandler({ provider, rateLimit: rateLimitConfig }: RevocationHandlerOptions): RequestHandler; +//# sourceMappingURL=revoke.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/revoke.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/revoke.d.ts.map new file mode 100644 index 000000000..fb13cf19f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/revoke.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"revoke.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/revoke.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAIlD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,wBAAwB,GAAG;IACnC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,wBAAwB,GAAG,cAAc,CA4DpH"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/revoke.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/revoke.js new file mode 100644 index 000000000..68f5284dd --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/revoke.js @@ -0,0 +1,59 @@ +import express from 'express'; +import cors from 'cors'; +import { authenticateClient } from '../middleware/clientAuth.js'; +import { OAuthTokenRevocationRequestSchema } from '../../../shared/auth.js'; +import { rateLimit } from 'express-rate-limit'; +import { allowedMethods } from '../middleware/allowedMethods.js'; +import { InvalidRequestError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; +export function revocationHandler({ provider, rateLimit: rateLimitConfig }) { + if (!provider.revokeToken) { + throw new Error('Auth provider does not support revoking tokens'); + } + // Nested router so we can configure middleware and restrict HTTP method + const router = express.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use(cors()); + router.use(allowedMethods(['POST'])); + router.use(express.urlencoded({ extended: false })); + // Apply rate limiting unless explicitly disabled + if (rateLimitConfig !== false) { + router.use(rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 50, // 50 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new TooManyRequestsError('You have exceeded the rate limit for token revocation requests').toResponseObject(), + ...rateLimitConfig + })); + } + // Authenticate and extract client details + router.use(authenticateClient({ clientsStore: provider.clientsStore })); + router.post('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + try { + const parseResult = OAuthTokenRevocationRequestSchema.safeParse(req.body); + if (!parseResult.success) { + throw new InvalidRequestError(parseResult.error.message); + } + const client = req.client; + if (!client) { + // This should never happen + throw new ServerError('Internal Server Error'); + } + await provider.revokeToken(client, parseResult.data); + res.status(200).json({}); + } + catch (error) { + if (error instanceof OAuthError) { + const status = error instanceof ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }); + return router; +} +//# sourceMappingURL=revoke.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/revoke.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/revoke.js.map new file mode 100644 index 000000000..e1a0b1db9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/revoke.js.map @@ -0,0 +1 @@ +{"version":3,"file":"revoke.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/revoke.ts"],"names":[],"mappings":"AACA,OAAO,OAA2B,MAAM,SAAS,CAAC;AAClD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,iCAAiC,EAAE,MAAM,yBAAyB,CAAC;AAC5E,OAAO,EAAE,SAAS,EAA+B,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,oBAAoB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAWlG,MAAM,UAAU,iBAAiB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAA4B;IAChG,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACtE,CAAC;IAED,wEAAwE;IACxE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC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B,MAAM,IAAI,WAAW,CAAC,uBAAuB,CAAC,CAAC;YACnD,CAAC;YAED,MAAM,QAAQ,CAAC,WAAY,CAAC,MAAM,EAAE,WAAW,CAAC,IAAI,CAAC,CAAC;YACtD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC7B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,UAAU,EAAE,CAAC;gBAC9B,MAAM,MAAM,GAAG,KAAK,YAAY,WAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;gBACxD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,WAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/token.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/token.d.ts new file mode 100644 index 000000000..24d1c8783 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/token.d.ts @@ -0,0 +1,13 @@ +import { RequestHandler } from 'express'; +import { OAuthServerProvider } from '../provider.js'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type TokenHandlerOptions = { + provider: OAuthServerProvider; + /** + * Rate limiting configuration for the token endpoint. + * Set to false to disable rate limiting for this endpoint. + */ + rateLimit?: Partial | false; +}; +export declare function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHandlerOptions): RequestHandler; +//# sourceMappingURL=token.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/token.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/token.d.ts.map new file mode 100644 index 000000000..68189b0b2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/token.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/token.ts"],"names":[],"mappings":"AACA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAIrD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAW5E,MAAM,MAAM,mBAAmB,GAAG;IAC9B,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAmBF,wBAAgB,YAAY,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,mBAAmB,GAAG,cAAc,CA+G1G"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/token.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/token.js new file mode 100644 index 000000000..b413c499e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/token.js @@ -0,0 +1,107 @@ +import * as z from 'zod/v4'; +import express from 'express'; +import cors from 'cors'; +import { verifyChallenge } from 'pkce-challenge'; +import { authenticateClient } from '../middleware/clientAuth.js'; +import { rateLimit } from 'express-rate-limit'; +import { allowedMethods } from '../middleware/allowedMethods.js'; +import { InvalidRequestError, InvalidGrantError, UnsupportedGrantTypeError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; +const TokenRequestSchema = z.object({ + grant_type: z.string() +}); +const AuthorizationCodeGrantSchema = z.object({ + code: z.string(), + code_verifier: z.string(), + redirect_uri: z.string().optional(), + resource: z.string().url().optional() +}); +const RefreshTokenGrantSchema = z.object({ + refresh_token: z.string(), + scope: z.string().optional(), + resource: z.string().url().optional() +}); +export function tokenHandler({ provider, rateLimit: rateLimitConfig }) { + // Nested router so we can configure middleware and restrict HTTP method + const router = express.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use(cors()); + router.use(allowedMethods(['POST'])); + router.use(express.urlencoded({ extended: false })); + // Apply rate limiting unless explicitly disabled + if (rateLimitConfig !== false) { + router.use(rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 50, // 50 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new TooManyRequestsError('You have exceeded the rate limit for token requests').toResponseObject(), + ...rateLimitConfig + })); + } + // Authenticate and extract client details + router.use(authenticateClient({ clientsStore: provider.clientsStore })); + router.post('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + try { + const parseResult = TokenRequestSchema.safeParse(req.body); + if (!parseResult.success) { + throw new InvalidRequestError(parseResult.error.message); + } + const { grant_type } = parseResult.data; + const client = req.client; + if (!client) { + // This should never happen + throw new ServerError('Internal Server Error'); + } + switch (grant_type) { + case 'authorization_code': { + const parseResult = AuthorizationCodeGrantSchema.safeParse(req.body); + if (!parseResult.success) { + throw new InvalidRequestError(parseResult.error.message); + } + const { code, code_verifier, redirect_uri, resource } = parseResult.data; + const skipLocalPkceValidation = provider.skipLocalPkceValidation; + // Perform local PKCE validation unless explicitly skipped + // (e.g. to validate code_verifier in upstream server) + if (!skipLocalPkceValidation) { + const codeChallenge = await provider.challengeForAuthorizationCode(client, code); + if (!(await verifyChallenge(code_verifier, codeChallenge))) { + throw new InvalidGrantError('code_verifier does not match the challenge'); + } + } + // Passes the code_verifier to the provider if PKCE validation didn't occur locally + const tokens = await provider.exchangeAuthorizationCode(client, code, skipLocalPkceValidation ? code_verifier : undefined, redirect_uri, resource ? new URL(resource) : undefined); + res.status(200).json(tokens); + break; + } + case 'refresh_token': { + const parseResult = RefreshTokenGrantSchema.safeParse(req.body); + if (!parseResult.success) { + throw new InvalidRequestError(parseResult.error.message); + } + const { refresh_token, scope, resource } = parseResult.data; + const scopes = scope?.split(' '); + const tokens = await provider.exchangeRefreshToken(client, refresh_token, scopes, resource ? new URL(resource) : undefined); + res.status(200).json(tokens); + break; + } + // Additional auth methods will not be added on the server side of the SDK. + case 'client_credentials': + default: + throw new UnsupportedGrantTypeError('The grant type is not supported by this authorization server.'); + } + } + catch (error) { + if (error instanceof OAuthError) { + const status = error instanceof ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }); + return router; +} +//# sourceMappingURL=token.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/token.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/token.js.map new file mode 100644 index 000000000..07f182a25 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/handlers/token.js.map @@ -0,0 +1 @@ +{"version":3,"file":"token.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/token.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,OAA2B,MAAM,SAAS,CAAC;AAElD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,SAAS,EAA+B,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EACH,mBAAmB,EACnB,iBAAiB,EACjB,yBAAyB,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,CAAC;oBAE5D,MAAM,MAAM,GAAG,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;oBACjC,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,oBAAoB,CAC9C,MAAM,EACN,aAAa,EACb,MAAM,EACN,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAC3C,CAAC;oBACF,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;oBAC7B,MAAM;gBACV,CAAC;gBACD,2EAA2E;gBAC3E,KAAK,oBAAoB,CAAC;gBAC1B;oBACI,MAAM,IAAI,yBAAyB,CAAC,+DAA+D,CAAC,CAAC;YAC7G,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,UAAU,EAAE,CAAC;gBAC9B,MAAM,MAAM,GAAG,KAAK,YAAY,WAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;gBACxD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,WAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/allowedMethods.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/allowedMethods.d.ts new file mode 100644 index 000000000..ee6037e0d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/allowedMethods.d.ts @@ -0,0 +1,9 @@ +import { RequestHandler } from 'express'; +/** + * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. + * + * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) + * @returns Express middleware that returns a 405 error if method not in allowed list + */ +export declare function allowedMethods(allowedMethods: string[]): RequestHandler; +//# sourceMappingURL=allowedMethods.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/allowedMethods.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/allowedMethods.d.ts.map new file mode 100644 index 000000000..d3de93e24 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/allowedMethods.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"allowedMethods.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/allowedMethods.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzC;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,cAAc,EAAE,MAAM,EAAE,GAAG,cAAc,CAUvE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/allowedMethods.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/allowedMethods.js new file mode 100644 index 000000000..af2ba0892 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/allowedMethods.js @@ -0,0 +1,18 @@ +import { MethodNotAllowedError } from '../errors.js'; +/** + * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. + * + * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) + * @returns Express middleware that returns a 405 error if method not in allowed list + */ +export function allowedMethods(allowedMethods) { + return (req, res, next) => { + if (allowedMethods.includes(req.method)) { + next(); + return; + } + const error = new MethodNotAllowedError(`The method ${req.method} is not allowed for this endpoint`); + res.status(405).set('Allow', allowedMethods.join(', ')).json(error.toResponseObject()); + }; +} +//# sourceMappingURL=allowedMethods.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/allowedMethods.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/allowedMethods.js.map new file mode 100644 index 000000000..c41097986 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/allowedMethods.js.map @@ -0,0 +1 @@ +{"version":3,"file":"allowedMethods.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/allowedMethods.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAErD;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,cAAwB;IACnD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACtB,IAAI,cAAc,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YACtC,IAAI,EAAE,CAAC;YACP,OAAO;QACX,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,qBAAqB,CAAC,cAAc,GAAG,CAAC,MAAM,mCAAmC,CAAC,CAAC;QACrG,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;IAC3F,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/bearerAuth.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/bearerAuth.d.ts new file mode 100644 index 000000000..10730758b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/bearerAuth.d.ts @@ -0,0 +1,35 @@ +import { RequestHandler } from 'express'; +import { OAuthTokenVerifier } from '../provider.js'; +import { AuthInfo } from '../types.js'; +export type BearerAuthMiddlewareOptions = { + /** + * A provider used to verify tokens. + */ + verifier: OAuthTokenVerifier; + /** + * Optional scopes that the token must have. + */ + requiredScopes?: string[]; + /** + * Optional resource metadata URL to include in WWW-Authenticate header. + */ + resourceMetadataUrl?: string; +}; +declare module 'express-serve-static-core' { + interface Request { + /** + * Information about the validated access token, if the `requireBearerAuth` middleware was used. + */ + auth?: AuthInfo; + } +} +/** + * Middleware that requires a valid Bearer token in the Authorization header. + * + * This will validate the token with the auth provider and add the resulting auth info to the request object. + * + * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header + * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. + */ +export declare function requireBearerAuth({ verifier, requiredScopes, resourceMetadataUrl }: BearerAuthMiddlewareOptions): RequestHandler; +//# sourceMappingURL=bearerAuth.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/bearerAuth.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/bearerAuth.d.ts.map new file mode 100644 index 000000000..c9d939f3b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/bearerAuth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bearerAuth.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/bearerAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,MAAM,MAAM,2BAA2B,GAAG;IACtC;;OAEG;IACH,QAAQ,EAAE,kBAAkB,CAAC;IAE7B;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAE1B;;OAEG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF,OAAO,QAAQ,2BAA2B,CAAC;IACvC,UAAU,OAAO;QACb;;WAEG;QACH,IAAI,CAAC,EAAE,QAAQ,CAAC;KACnB;CACJ;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAmB,EAAE,mBAAmB,EAAE,EAAE,2BAA2B,GAAG,cAAc,CA8DrI"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/bearerAuth.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/bearerAuth.js new file mode 100644 index 000000000..0c527b4f4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/bearerAuth.js @@ -0,0 +1,72 @@ +import { InsufficientScopeError, InvalidTokenError, OAuthError, ServerError } from '../errors.js'; +/** + * Middleware that requires a valid Bearer token in the Authorization header. + * + * This will validate the token with the auth provider and add the resulting auth info to the request object. + * + * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header + * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. + */ +export function requireBearerAuth({ verifier, requiredScopes = [], resourceMetadataUrl }) { + return async (req, res, next) => { + try { + const authHeader = req.headers.authorization; + if (!authHeader) { + throw new InvalidTokenError('Missing Authorization header'); + } + const [type, token] = authHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !token) { + throw new InvalidTokenError("Invalid Authorization header format, expected 'Bearer TOKEN'"); + } + const authInfo = await verifier.verifyAccessToken(token); + // Check if token has the required scopes (if any) + if (requiredScopes.length > 0) { + const hasAllScopes = requiredScopes.every(scope => authInfo.scopes.includes(scope)); + if (!hasAllScopes) { + throw new InsufficientScopeError('Insufficient scope'); + } + } + // Check if the token is set to expire or if it is expired + if (typeof authInfo.expiresAt !== 'number' || isNaN(authInfo.expiresAt)) { + throw new InvalidTokenError('Token has no expiration time'); + } + else if (authInfo.expiresAt < Date.now() / 1000) { + throw new InvalidTokenError('Token has expired'); + } + req.auth = authInfo; + next(); + } + catch (error) { + // Build WWW-Authenticate header parts + const buildWwwAuthHeader = (errorCode, message) => { + let header = `Bearer error="${errorCode}", error_description="${message}"`; + if (requiredScopes.length > 0) { + header += `, scope="${requiredScopes.join(' ')}"`; + } + if (resourceMetadataUrl) { + header += `, resource_metadata="${resourceMetadataUrl}"`; + } + return header; + }; + if (error instanceof InvalidTokenError) { + res.set('WWW-Authenticate', buildWwwAuthHeader(error.errorCode, error.message)); + res.status(401).json(error.toResponseObject()); + } + else if (error instanceof InsufficientScopeError) { + res.set('WWW-Authenticate', buildWwwAuthHeader(error.errorCode, error.message)); + res.status(403).json(error.toResponseObject()); + } + else if (error instanceof ServerError) { + res.status(500).json(error.toResponseObject()); + } + else if (error instanceof OAuthError) { + res.status(400).json(error.toResponseObject()); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }; +} +//# sourceMappingURL=bearerAuth.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/bearerAuth.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/bearerAuth.js.map new file mode 100644 index 000000000..d8d0179b7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/bearerAuth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bearerAuth.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/bearerAuth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AA8BlG;;;;;;;GAOG;AACH,MAAM,UAAU,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAc,GAAG,EAAE,EAAE,mBAAmB,EAA+B;IACjH,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;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AM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACnD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,WAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/clientAuth.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/clientAuth.d.ts new file mode 100644 index 000000000..837f95fd2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/clientAuth.d.ts @@ -0,0 +1,19 @@ +import { RequestHandler } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { OAuthClientInformationFull } from '../../../shared/auth.js'; +export type ClientAuthenticationMiddlewareOptions = { + /** + * A store used to read information about registered OAuth clients. + */ + clientsStore: OAuthRegisteredClientsStore; +}; +declare module 'express-serve-static-core' { + interface Request { + /** + * The authenticated client for this request, if the `authenticateClient` middleware was used. + */ + client?: OAuthClientInformationFull; + } +} +export declare function authenticateClient({ clientsStore }: ClientAuthenticationMiddlewareOptions): RequestHandler; +//# sourceMappingURL=clientAuth.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/clientAuth.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/clientAuth.d.ts.map new file mode 100644 index 000000000..5455132c9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/clientAuth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clientAuth.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/clientAuth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AAGrE,MAAM,MAAM,qCAAqC,GAAG;IAChD;;OAEG;IACH,YAAY,EAAE,2BAA2B,CAAC;CAC7C,CAAC;AAOF,OAAO,QAAQ,2BAA2B,CAAC;IACvC,UAAU,OAAO;QACb;;WAEG;QACH,MAAM,CAAC,EAAE,0BAA0B,CAAC;KACvC;CACJ;AAED,wBAAgB,kBAAkB,CAAC,EAAE,YAAY,EAAE,EAAE,qCAAqC,GAAG,cAAc,CAoC1G"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/clientAuth.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/clientAuth.js new file mode 100644 index 000000000..cce72a2d2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/clientAuth.js @@ -0,0 +1,45 @@ +import * as z from 'zod/v4'; +import { InvalidRequestError, InvalidClientError, ServerError, OAuthError } from '../errors.js'; +const ClientAuthenticatedRequestSchema = z.object({ + client_id: z.string(), + client_secret: z.string().optional() +}); +export function authenticateClient({ clientsStore }) { + return async (req, res, next) => { + try { + const result = ClientAuthenticatedRequestSchema.safeParse(req.body); + if (!result.success) { + throw new InvalidRequestError(String(result.error)); + } + const { client_id, client_secret } = result.data; + const client = await clientsStore.getClient(client_id); + if (!client) { + throw new InvalidClientError('Invalid client_id'); + } + if (client.client_secret) { + if (!client_secret) { + throw new InvalidClientError('Client secret is required'); + } + if (client.client_secret !== client_secret) { + throw new InvalidClientError('Invalid client_secret'); + } + if (client.client_secret_expires_at && client.client_secret_expires_at < Math.floor(Date.now() / 1000)) { + throw new InvalidClientError('Client secret has expired'); + } + } + req.client = client; + next(); + } + catch (error) { + if (error instanceof OAuthError) { + const status = error instanceof ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }; +} +//# sourceMappingURL=clientAuth.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/clientAuth.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/clientAuth.js.map new file mode 100644 index 000000000..5023c023b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/middleware/clientAuth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"clientAuth.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/clientAuth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAI5B,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAShG,MAAM,gCAAgC,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9C,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACvC,CAAC,CAAC;AAWH,MAAM,UAAU,kBAAkB,CAAC,EAAE,YAAY,EAAyC;IACtF,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC5B,IAAI,CAAC;YACD,MAAM,MAAM,GAAG,gCAAgC,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YACpE,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;gBAClB,MAAM,IAAI,mBAAmB,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;YACxD,CAAC;YACD,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC;YACjD,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC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modules/@modelcontextprotocol/sdk/dist/esm/server/auth/provider.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/provider.d.ts new file mode 100644 index 000000000..3e4eca392 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/provider.d.ts @@ -0,0 +1,68 @@ +import { Response } from 'express'; +import { OAuthRegisteredClientsStore } from './clients.js'; +import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../shared/auth.js'; +import { AuthInfo } from './types.js'; +export type AuthorizationParams = { + state?: string; + scopes?: string[]; + codeChallenge: string; + redirectUri: string; + resource?: URL; +}; +/** + * Implements an end-to-end OAuth server. + */ +export interface OAuthServerProvider { + /** + * A store used to read information about registered OAuth clients. + */ + get clientsStore(): OAuthRegisteredClientsStore; + /** + * Begins the authorization flow, which can either be implemented by this server itself or via redirection to a separate authorization server. + * + * This server must eventually issue a redirect with an authorization response or an error response to the given redirect URI. Per OAuth 2.1: + * - In the successful case, the redirect MUST include the `code` and `state` (if present) query parameters. + * - In the error case, the redirect MUST include the `error` query parameter, and MAY include an optional `error_description` query parameter. + */ + authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; + /** + * Returns the `codeChallenge` that was used when the indicated authorization began. + */ + challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; + /** + * Exchanges an authorization code for an access token. + */ + exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; + /** + * Exchanges a refresh token for an access token. + */ + exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; + /** + * Verifies an access token and returns information about it. + */ + verifyAccessToken(token: string): Promise; + /** + * Revokes an access or refresh token. If unimplemented, token revocation is not supported (not recommended). + * + * If the given token is invalid or already revoked, this method should do nothing. + */ + revokeToken?(client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest): Promise; + /** + * Whether to skip local PKCE validation. + * + * If true, the server will not perform PKCE validation locally and will pass the code_verifier to the upstream server. + * + * NOTE: This should only be true if the upstream server is performing the actual PKCE validation. + */ + skipLocalPkceValidation?: boolean; +} +/** + * Slim implementation useful for token verification + */ +export interface OAuthTokenVerifier { + /** + * Verifies an access token and returns information about it. + */ + verifyAccessToken(token: string): Promise; +} +//# sourceMappingURL=provider.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/provider.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/provider.d.ts.map new file mode 100644 index 000000000..d1a4bfff0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,2BAA2B,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC5G,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,MAAM,MAAM,mBAAmB,GAAG;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,GAAG,CAAC;CAClB,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAChC;;OAEG;IACH,IAAI,YAAY,IAAI,2BAA2B,CAAC;IAEhD;;;;;;OAMG;IACH,SAAS,CAAC,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzG;;OAEG;IACH,6BAA6B,CAAC,MAAM,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAE9G;;OAEG;IACH,yBAAyB,CACrB,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EACzB,YAAY,CAAC,EAAE,MAAM,EACrB,WAAW,CAAC,EAAE,MAAM,EACpB,QAAQ,CAAC,EAAE,GAAG,GACf,OAAO,CAAC,WAAW,CAAC,CAAC;IAExB;;OAEG;IACH,oBAAoB,CAAC,MAAM,EAAE,0BAA0B,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,EAAE,QAAQ,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IAExI;;OAEG;IACH,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAEpD;;;;OAIG;IACH,WAAW,CAAC,CAAC,MAAM,EAAE,0BAA0B,EAAE,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtG;;;;;;OAMG;IACH,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACrC;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IAC/B;;OAEG;IACH,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACvD"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/provider.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/provider.js new file mode 100644 index 000000000..be31058cd --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/provider.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=provider.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/provider.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/provider.js.map new file mode 100644 index 000000000..b968414aa --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../../src/server/auth/provider.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/providers/proxyProvider.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/providers/proxyProvider.d.ts new file mode 100644 index 000000000..ee6f35081 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/providers/proxyProvider.d.ts @@ -0,0 +1,49 @@ +import { Response } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../../shared/auth.js'; +import { AuthInfo } from '../types.js'; +import { AuthorizationParams, OAuthServerProvider } from '../provider.js'; +import { FetchLike } from '../../../shared/transport.js'; +export type ProxyEndpoints = { + authorizationUrl: string; + tokenUrl: string; + revocationUrl?: string; + registrationUrl?: string; +}; +export type ProxyOptions = { + /** + * Individual endpoint URLs for proxying specific OAuth operations + */ + endpoints: ProxyEndpoints; + /** + * Function to verify access tokens and return auth info + */ + verifyAccessToken: (token: string) => Promise; + /** + * Function to fetch client information from the upstream server + */ + getClient: (clientId: string) => Promise; + /** + * Custom fetch implementation used for all network requests. + */ + fetch?: FetchLike; +}; +/** + * Implements an OAuth server that proxies requests to another OAuth server. + */ +export declare class ProxyOAuthServerProvider implements OAuthServerProvider { + protected readonly _endpoints: ProxyEndpoints; + protected readonly _verifyAccessToken: (token: string) => Promise; + protected readonly _getClient: (clientId: string) => Promise; + protected readonly _fetch?: FetchLike; + skipLocalPkceValidation: boolean; + revokeToken?: (client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest) => Promise; + constructor(options: ProxyOptions); + get clientsStore(): OAuthRegisteredClientsStore; + authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; + challengeForAuthorizationCode(_client: OAuthClientInformationFull, _authorizationCode: string): Promise; + exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; + exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; + verifyAccessToken(token: string): Promise; +} +//# sourceMappingURL=proxyProvider.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/providers/proxyProvider.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/providers/proxyProvider.d.ts.map new file mode 100644 index 000000000..124c105fa --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/providers/proxyProvider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"proxyProvider.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/providers/proxyProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EACH,0BAA0B,EAE1B,2BAA2B,EAC3B,WAAW,EAEd,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE1E,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAEzD,MAAM,MAAM,cAAc,GAAG;IACzB,gBAAgB,EAAE,MAAM,CAAC;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACvB;;OAEG;IACH,SAAS,EAAE,cAAc,CAAC;IAE1B;;OAEG;IACH,iBAAiB,E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WAAW,CAAC;IAwCjB,oBAAoB,CACtB,MAAM,EAAE,0BAA0B,EAClC,YAAY,EAAE,MAAM,EACpB,MAAM,CAAC,EAAE,MAAM,EAAE,EACjB,QAAQ,CAAC,EAAE,GAAG,GACf,OAAO,CAAC,WAAW,CAAC;IAoCjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAG5D"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/providers/proxyProvider.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/providers/proxyProvider.js new file mode 100644 index 000000000..fef1ff5ba --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/providers/proxyProvider.js @@ -0,0 +1,155 @@ +import { OAuthClientInformationFullSchema, OAuthTokensSchema } from '../../../shared/auth.js'; +import { ServerError } from '../errors.js'; +/** + * Implements an OAuth server that proxies requests to another OAuth server. + */ +export class ProxyOAuthServerProvider { + constructor(options) { + this.skipLocalPkceValidation = true; + this._endpoints = options.endpoints; + this._verifyAccessToken = options.verifyAccessToken; + this._getClient = options.getClient; + this._fetch = options.fetch; + if (options.endpoints?.revocationUrl) { + this.revokeToken = async (client, request) => { + const revocationUrl = this._endpoints.revocationUrl; + if (!revocationUrl) { + throw new Error('No revocation endpoint configured'); + } + const params = new URLSearchParams(); + params.set('token', request.token); + params.set('client_id', client.client_id); + if (client.client_secret) { + params.set('client_secret', client.client_secret); + } + if (request.token_type_hint) { + params.set('token_type_hint', request.token_type_hint); + } + const response = await (this._fetch ?? fetch)(revocationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: params.toString() + }); + await response.body?.cancel(); + if (!response.ok) { + throw new ServerError(`Token revocation failed: ${response.status}`); + } + }; + } + } + get clientsStore() { + const registrationUrl = this._endpoints.registrationUrl; + return { + getClient: this._getClient, + ...(registrationUrl && { + registerClient: async (client) => { + const response = await (this._fetch ?? fetch)(registrationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(client) + }); + if (!response.ok) { + await response.body?.cancel(); + throw new ServerError(`Client registration failed: ${response.status}`); + } + const data = await response.json(); + return OAuthClientInformationFullSchema.parse(data); + } + }) + }; + } + async authorize(client, params, res) { + // Start with required OAuth parameters + const targetUrl = new URL(this._endpoints.authorizationUrl); + const searchParams = new URLSearchParams({ + client_id: client.client_id, + response_type: 'code', + redirect_uri: params.redirectUri, + code_challenge: params.codeChallenge, + code_challenge_method: 'S256' + }); + // Add optional standard OAuth parameters + if (params.state) + searchParams.set('state', params.state); + if (params.scopes?.length) + searchParams.set('scope', params.scopes.join(' ')); + if (params.resource) + searchParams.set('resource', params.resource.href); + targetUrl.search = searchParams.toString(); + res.redirect(targetUrl.toString()); + } + async challengeForAuthorizationCode(_client, _authorizationCode) { + // In a proxy setup, we don't store the code challenge ourselves + // Instead, we proxy the token request and let the upstream server validate it + return ''; + } + async exchangeAuthorizationCode(client, authorizationCode, codeVerifier, redirectUri, resource) { + const params = new URLSearchParams({ + grant_type: 'authorization_code', + client_id: client.client_id, + code: authorizationCode + }); + if (client.client_secret) { + params.append('client_secret', client.client_secret); + } + if (codeVerifier) { + params.append('code_verifier', codeVerifier); + } + if (redirectUri) { + params.append('redirect_uri', redirectUri); + } + if (resource) { + params.append('resource', resource.href); + } + const response = await (this._fetch ?? fetch)(this._endpoints.tokenUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: params.toString() + }); + if (!response.ok) { + await response.body?.cancel(); + throw new ServerError(`Token exchange failed: ${response.status}`); + } + const data = await response.json(); + return OAuthTokensSchema.parse(data); + } + async exchangeRefreshToken(client, refreshToken, scopes, resource) { + const params = new URLSearchParams({ + grant_type: 'refresh_token', + client_id: client.client_id, + refresh_token: refreshToken + }); + if (client.client_secret) { + params.set('client_secret', client.client_secret); + } + if (scopes?.length) { + params.set('scope', scopes.join(' ')); + } + if (resource) { + params.set('resource', resource.href); + } + const response = await (this._fetch ?? fetch)(this._endpoints.tokenUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: params.toString() + }); + if (!response.ok) { + await response.body?.cancel(); + throw new ServerError(`Token refresh failed: ${response.status}`); + } + const data = await response.json(); + return OAuthTokensSchema.parse(data); + } + async verifyAccessToken(token) { + return this._verifyAccessToken(token); + } +} +//# sourceMappingURL=proxyProvider.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/providers/proxyProvider.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/providers/proxyProvider.js.map new file mode 100644 index 000000000..b77ac3087 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/providers/proxyProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"proxyProvider.js","sourceRoot":"","sources":["../../../../../src/server/auth/providers/proxyProvider.ts"],"names":[],"mappings":"AAEA,OAAO,EAEH,gCAAgC,EAGhC,iBAAiB,EACpB,MAAM,yBAAyB,CAAC;AAGjC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAgC3C;;GAEG;AACH,MAAM,OAAO,wBAAwB;IAUjC,YAAY,OAAqB;QAJjC,4BAAuB,GAAG,IAAI,CAAC;QAK3B,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC;QACpC,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,iBAAiB,CAAC;QACpD,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC;QACpC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC;QAC5B,IAAI,OAAO,CAAC,SAAS,EAAE,aAAa,EAAE,CAAC;YACnC,IAAI,CAAC,WAAW,GAAG,KAAK,EAAE,MAAkC,EAAE,OAAoC,EAAE,EAAE;gBAClG,MAAM,aAAa,GAAG,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;gB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tD;YACD,IAAI,EAAE,MAAM,CAAC,QAAQ,EAAE;SAC1B,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACf,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC;YAC9B,MAAM,IAAI,WAAW,CAAC,yBAAyB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;QACtE,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,OAAO,iBAAiB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,iBAAiB,CAAC,KAAa;QACjC,OAAO,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/router.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/router.d.ts new file mode 100644 index 000000000..43dabde7d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/router.d.ts @@ -0,0 +1,101 @@ +import express, { RequestHandler } from 'express'; +import { ClientRegistrationHandlerOptions } from './handlers/register.js'; +import { TokenHandlerOptions } from './handlers/token.js'; +import { AuthorizationHandlerOptions } from './handlers/authorize.js'; +import { RevocationHandlerOptions } from './handlers/revoke.js'; +import { OAuthServerProvider } from './provider.js'; +import { OAuthMetadata } from '../../shared/auth.js'; +export type AuthRouterOptions = { + /** + * A provider implementing the actual authorization logic for this router. + */ + provider: OAuthServerProvider; + /** + * The authorization server's issuer identifier, which is a URL that uses the "https" scheme and has no query or fragment components. + */ + issuerUrl: URL; + /** + * The base URL of the authorization server to use for the metadata endpoints. + * + * If not provided, the issuer URL will be used as the base URL. + */ + baseUrl?: URL; + /** + * An optional URL of a page containing human-readable information that developers might want or need to know when using the authorization server. + */ + serviceDocumentationUrl?: URL; + /** + * An optional list of scopes supported by this authorization server + */ + scopesSupported?: string[]; + /** + * The resource name to be displayed in protected resource metadata + */ + resourceName?: string; + /** + * The URL of the protected resource (RS) whose metadata we advertise. + * If not provided, falls back to `baseUrl` and then to `issuerUrl` (AS=RS). + */ + resourceServerUrl?: URL; + authorizationOptions?: Omit; + clientRegistrationOptions?: Omit; + revocationOptions?: Omit; + tokenOptions?: Omit; +}; +export declare const createOAuthMetadata: (options: { + provider: OAuthServerProvider; + issuerUrl: URL; + baseUrl?: URL; + serviceDocumentationUrl?: URL; + scopesSupported?: string[]; +}) => OAuthMetadata; +/** + * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). + * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. + * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. + * + * By default, rate limiting is applied to all endpoints to prevent abuse. + * + * This router MUST be installed at the application root, like so: + * + * const app = express(); + * app.use(mcpAuthRouter(...)); + */ +export declare function mcpAuthRouter(options: AuthRouterOptions): RequestHandler; +export type AuthMetadataOptions = { + /** + * OAuth Metadata as would be returned from the authorization server + * this MCP server relies on + */ + oauthMetadata: OAuthMetadata; + /** + * The url of the MCP server, for use in protected resource metadata + */ + resourceServerUrl: URL; + /** + * The url for documentation for the MCP server + */ + serviceDocumentationUrl?: URL; + /** + * An optional list of scopes supported by this MCP server + */ + scopesSupported?: string[]; + /** + * An optional resource name to display in resource metadata + */ + resourceName?: string; +}; +export declare function mcpAuthMetadataRouter(options: AuthMetadataOptions): express.Router; +/** + * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL + * from a given server URL. This replaces the path with the standard metadata endpoint. + * + * @param serverUrl - The base URL of the protected resource server + * @returns The URL for the OAuth protected resource metadata endpoint + * + * @example + * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) + * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' + */ +export declare function getOAuthProtectedResourceMetadataUrl(serverUrl: URL): string; +//# sourceMappingURL=router.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/router.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/router.d.ts.map new file mode 100644 index 000000000..615cb964b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/router.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAA6B,gCAAgC,EAAE,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAgB,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAwB,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAC5F,OAAO,EAAqB,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,aAAa,EAAkC,MAAM,sBAAsB,CAAC;AAUrF,MAAM,MAAM,iBAAiB,GAAG;IAC5B;;OAEG;IACH,QAAQ,EAAE,mBAAmB,CAAC;IAE9B;;OAEG;IACH,SAAS,EAAE,GAAG,CAAC;IAEf;;;;OAIG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;IAEd;;OAEG;IACH,uBAAuB,CAAC,EAAE,GAAG,CAAC;IAE9B;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAE3B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;OAGG;IACH,iBAAiB,CAAC,EAAE,GAAG,CAAC;IAGxB,oBAAoB,CAAC,EAAE,IAAI,CAAC,2BAA2B,EAAE,UAAU,CAAC,CAAC;IACrE,yBAAyB,CAAC,EAAE,IAAI,CAAC,gCAAgC,EAAE,cAAc,CAAC,CAAC;IACnF,iBAAiB,CAAC,EAAE,IAAI,CAAC,wBAAwB,EAAE,UAAU,CAAC,CAAC;IAC/D,YAAY,CAAC,EAAE,IAAI,CAAC,mBAAmB,EAAE,UAAU,CAAC,CAAC;CACxD,CAAC;AAeF,eAAO,MAAM,mBAAmB,YAAa;IACzC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,SAAS,EAAE,GAAG,CAAC;IACf,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,uBAAuB,CAAC,EAAE,GAAG,CAAC;IAC9B,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;CAC9B,KAAG,aAgCH,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,iBAAiB,GAAG,cAAc,CAyCxE;AAED,MAAM,MAAM,mBAAmB,GAAG;IAC9B;;;OAGG;IACH,aAAa,EAAE,aAAa,CAAC;IAE7B;;OAEG;IACH,iBAAiB,EAAE,GAAG,CAAC;IAEvB;;OAEG;IACH,uBAAuB,CAAC,EAAE,GAAG,CAAC;IAE9B;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAE3B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,MAAM,CAuBlF;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,oCAAoC,CAAC,SAAS,EAAE,GAAG,GAAG,MAAM,CAI3E"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/router.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/router.js new file mode 100644 index 000000000..c33a542fc --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/router.js @@ -0,0 +1,118 @@ +import express from 'express'; +import { clientRegistrationHandler } from './handlers/register.js'; +import { tokenHandler } from './handlers/token.js'; +import { authorizationHandler } from './handlers/authorize.js'; +import { revocationHandler } from './handlers/revoke.js'; +import { metadataHandler } from './handlers/metadata.js'; +// Check for dev mode flag that allows HTTP issuer URLs (for development/testing only) +const allowInsecureIssuerUrl = process.env.MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL === 'true' || process.env.MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL === '1'; +if (allowInsecureIssuerUrl) { + // eslint-disable-next-line no-console + console.warn('MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL is enabled - HTTP issuer URLs are allowed. Do not use in production.'); +} +const checkIssuerUrl = (issuer) => { + // Technically RFC 8414 does not permit a localhost HTTPS exemption, but this will be necessary for ease of testing + if (issuer.protocol !== 'https:' && issuer.hostname !== 'localhost' && issuer.hostname !== '127.0.0.1' && !allowInsecureIssuerUrl) { + throw new Error('Issuer URL must be HTTPS'); + } + if (issuer.hash) { + throw new Error(`Issuer URL must not have a fragment: ${issuer}`); + } + if (issuer.search) { + throw new Error(`Issuer URL must not have a query string: ${issuer}`); + } +}; +export const createOAuthMetadata = (options) => { + const issuer = options.issuerUrl; + const baseUrl = options.baseUrl; + checkIssuerUrl(issuer); + const authorization_endpoint = '/authorize'; + const token_endpoint = '/token'; + const registration_endpoint = options.provider.clientsStore.registerClient ? '/register' : undefined; + const revocation_endpoint = options.provider.revokeToken ? '/revoke' : undefined; + const metadata = { + issuer: issuer.href, + service_documentation: options.serviceDocumentationUrl?.href, + authorization_endpoint: new URL(authorization_endpoint, baseUrl || issuer).href, + response_types_supported: ['code'], + code_challenge_methods_supported: ['S256'], + token_endpoint: new URL(token_endpoint, baseUrl || issuer).href, + token_endpoint_auth_methods_supported: ['client_secret_post', 'none'], + grant_types_supported: ['authorization_code', 'refresh_token'], + scopes_supported: options.scopesSupported, + revocation_endpoint: revocation_endpoint ? new URL(revocation_endpoint, baseUrl || issuer).href : undefined, + revocation_endpoint_auth_methods_supported: revocation_endpoint ? ['client_secret_post'] : undefined, + registration_endpoint: registration_endpoint ? new URL(registration_endpoint, baseUrl || issuer).href : undefined + }; + return metadata; +}; +/** + * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). + * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. + * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. + * + * By default, rate limiting is applied to all endpoints to prevent abuse. + * + * This router MUST be installed at the application root, like so: + * + * const app = express(); + * app.use(mcpAuthRouter(...)); + */ +export function mcpAuthRouter(options) { + const oauthMetadata = createOAuthMetadata(options); + const router = express.Router(); + router.use(new URL(oauthMetadata.authorization_endpoint).pathname, authorizationHandler({ provider: options.provider, ...options.authorizationOptions })); + router.use(new URL(oauthMetadata.token_endpoint).pathname, tokenHandler({ provider: options.provider, ...options.tokenOptions })); + router.use(mcpAuthMetadataRouter({ + oauthMetadata, + // Prefer explicit RS; otherwise fall back to AS baseUrl, then to issuer (back-compat) + resourceServerUrl: options.resourceServerUrl ?? options.baseUrl ?? new URL(oauthMetadata.issuer), + serviceDocumentationUrl: options.serviceDocumentationUrl, + scopesSupported: options.scopesSupported, + resourceName: options.resourceName + })); + if (oauthMetadata.registration_endpoint) { + router.use(new URL(oauthMetadata.registration_endpoint).pathname, clientRegistrationHandler({ + clientsStore: options.provider.clientsStore, + ...options.clientRegistrationOptions + })); + } + if (oauthMetadata.revocation_endpoint) { + router.use(new URL(oauthMetadata.revocation_endpoint).pathname, revocationHandler({ provider: options.provider, ...options.revocationOptions })); + } + return router; +} +export function mcpAuthMetadataRouter(options) { + checkIssuerUrl(new URL(options.oauthMetadata.issuer)); + const router = express.Router(); + const protectedResourceMetadata = { + resource: options.resourceServerUrl.href, + authorization_servers: [options.oauthMetadata.issuer], + scopes_supported: options.scopesSupported, + resource_name: options.resourceName, + resource_documentation: options.serviceDocumentationUrl?.href + }; + // Serve PRM at the path-specific URL per RFC 9728 + const rsPath = new URL(options.resourceServerUrl.href).pathname; + router.use(`/.well-known/oauth-protected-resource${rsPath === '/' ? '' : rsPath}`, metadataHandler(protectedResourceMetadata)); + // Always add this for OAuth Authorization Server metadata per RFC 8414 + router.use('/.well-known/oauth-authorization-server', metadataHandler(options.oauthMetadata)); + return router; +} +/** + * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL + * from a given server URL. This replaces the path with the standard metadata endpoint. + * + * @param serverUrl - The base URL of the protected resource server + * @returns The URL for the OAuth protected resource metadata endpoint + * + * @example + * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) + * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' + */ +export function getOAuthProtectedResourceMetadataUrl(serverUrl) { + const u = new URL(serverUrl.href); + const rsPath = u.pathname && u.pathname !== '/' ? u.pathname : ''; + return new URL(`/.well-known/oauth-protected-resource${rsPath}`, u).href; +} +//# sourceMappingURL=router.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/router.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/router.js.map new file mode 100644 index 000000000..6487fb0f4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/router.js.map @@ -0,0 +1 @@ +{"version":3,"file":"router.js","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":"AAAA,OAAO,OAA2B,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,yBAAyB,EAAoC,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAE,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAE,oBAAoB,EAA+B,MAAM,yBAAyB,CAAC;AAC5F,OAAO,EAAE,iBAAiB,EAA4B,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAIzD,sFAAsF;AACtF,MAAM,sBAAsB,GACxB,OAAO,CAAC,GAAG,CAAC,yCAAyC,KAAK,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,yCAAyC,KAAK,GAAG,CAAC;AACtI,IAAI,sBAAsB,EAAE,CAAC;IACzB,sCAAsC;I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AyB,GAAmC;QAC9D,QAAQ,EAAE,OAAO,CAAC,iBAAiB,CAAC,IAAI;QAExC,qBAAqB,EAAE,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC;QAErD,gBAAgB,EAAE,OAAO,CAAC,eAAe;QACzC,aAAa,EAAE,OAAO,CAAC,YAAY;QACnC,sBAAsB,EAAE,OAAO,CAAC,uBAAuB,EAAE,IAAI;KAChE,CAAC;IAEF,kDAAkD;IAClD,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC;IAChE,MAAM,CAAC,GAAG,CAAC,wCAAwC,MAAM,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,eAAe,CAAC,yBAAyB,CAAC,CAAC,CAAC;IAE/H,uEAAuE;IACvE,MAAM,CAAC,GAAG,CAAC,yCAAyC,EAAE,eAAe,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC;IAE9F,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,oCAAoC,CAAC,SAAc;IAC/D,MAAM,CAAC,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IAClC,MAAM,MAAM,GAAG,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,QAAQ,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;IAClE,OAAO,IAAI,GAAG,CAAC,wCAAwC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAC7E,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/types.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/types.d.ts new file mode 100644 index 000000000..05ec8485a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/types.d.ts @@ -0,0 +1,32 @@ +/** + * Information about a validated access token, provided to request handlers. + */ +export interface AuthInfo { + /** + * The access token. + */ + token: string; + /** + * The client ID associated with this token. + */ + clientId: string; + /** + * Scopes associated with this token. + */ + scopes: string[]; + /** + * When the token expires (in seconds since epoch). + */ + expiresAt?: number; + /** + * The RFC 8707 resource server identifier for which this token is valid. + * If set, this MUST match the MCP server's resource identifier (minus hash fragment). + */ + resource?: URL; + /** + * Additional data associated with the token. + * This field should be used for any additional data that needs to be attached to the auth info. + */ + extra?: Record; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/types.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/types.d.ts.map new file mode 100644 index 000000000..021e94740 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,QAAQ;IACrB;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,MAAM,EAAE,MAAM,EAAE,CAAC;IAEjB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,GAAG,CAAC;IAEf;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/types.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/types.js new file mode 100644 index 000000000..718fd38ae --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/types.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/types.js.map new file mode 100644 index 000000000..0d8063dee --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/server/auth/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.d.ts new file mode 100644 index 000000000..1b3159ac8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.d.ts @@ -0,0 +1,38 @@ +import { AnySchema, SchemaInput } from './zod-compat.js'; +export declare const COMPLETABLE_SYMBOL: unique symbol; +export type CompleteCallback = (value: SchemaInput, context?: { + arguments?: Record; +}) => SchemaInput[] | Promise[]>; +export type CompletableMeta = { + complete: CompleteCallback; +}; +export type CompletableSchema = T & { + [COMPLETABLE_SYMBOL]: CompletableMeta; +}; +/** + * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. + * Works with both Zod v3 and v4 schemas. + */ +export declare function completable(schema: T, complete: CompleteCallback): CompletableSchema; +/** + * Checks if a schema is completable (has completion metadata). + */ +export declare function isCompletable(schema: unknown): schema is CompletableSchema; +/** + * Gets the completer callback from a completable schema, if it exists. + */ +export declare function getCompleter(schema: T): CompleteCallback | undefined; +/** + * Unwraps a completable schema to get the underlying schema. + * For backward compatibility with code that called `.unwrap()`. + */ +export declare function unwrapCompletable(schema: CompletableSchema): T; +export declare enum McpZodTypeKind { + Completable = "McpCompletable" +} +export interface CompletableDef { + type: T; + complete: CompleteCallback; + typeName: McpZodTypeKind.Completable; +} +//# sourceMappingURL=completable.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.d.ts.map new file mode 100644 index 000000000..83ea2f1e2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"completable.d.ts","sourceRoot":"","sources":["../../../src/server/completable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEzD,eAAO,MAAM,kBAAkB,EAAE,OAAO,MAAsC,CAAC;AAE/E,MAAM,MAAM,gBAAgB,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,IAAI,CAC5D,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,EACrB,OAAO,CAAC,EAAE;IACN,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACtC,KACA,WAAW,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;AAElD,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,IAAI;IAC3D,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,iBAAiB,CAAC,CAAC,SAAS,SAAS,IAAI,CAAC,GAAG;IACrD,CAAC,kBAAkB,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC;CAC5C,CAAC;AAEF;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,CAAC,EAAE,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAQ/G;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,IAAI,iBAAiB,CAAC,SAAS,CAAC,CAErF;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,CAAC,GAAG,gBAAgB,CAAC,CAAC,CAAC,GAAG,SAAS,CAG5F;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,CAEtF;AAID,oBAAY,cAAc;IACtB,WAAW,mBAAmB;CACjC;AAED,MAAM,WAAW,cAAc,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS;IAC3D,IAAI,EAAE,CAAC,CAAC;IACR,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;IAC9B,QAAQ,EAAE,cAAc,CAAC,WAAW,CAAC;CACxC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js new file mode 100644 index 000000000..827f7d419 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js @@ -0,0 +1,41 @@ +export const COMPLETABLE_SYMBOL = Symbol.for('mcp.completable'); +/** + * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. + * Works with both Zod v3 and v4 schemas. + */ +export function completable(schema, complete) { + Object.defineProperty(schema, COMPLETABLE_SYMBOL, { + value: { complete }, + enumerable: false, + writable: false, + configurable: false + }); + return schema; +} +/** + * Checks if a schema is completable (has completion metadata). + */ +export function isCompletable(schema) { + return !!schema && typeof schema === 'object' && COMPLETABLE_SYMBOL in schema; +} +/** + * Gets the completer callback from a completable schema, if it exists. + */ +export function getCompleter(schema) { + const meta = schema[COMPLETABLE_SYMBOL]; + return meta?.complete; +} +/** + * Unwraps a completable schema to get the underlying schema. + * For backward compatibility with code that called `.unwrap()`. + */ +export function unwrapCompletable(schema) { + return schema; +} +// Legacy exports for backward compatibility +// These types are deprecated but kept for existing code +export var McpZodTypeKind; +(function (McpZodTypeKind) { + McpZodTypeKind["Completable"] = "McpCompletable"; +})(McpZodTypeKind || (McpZodTypeKind = {})); +//# sourceMappingURL=completable.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js.map new file mode 100644 index 000000000..a5ae859b1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"completable.js","sourceRoot":"","sources":["../../../src/server/completable.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,kBAAkB,GAAkB,MAAM,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;AAiB/E;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAsB,MAAS,EAAE,QAA6B;IACrF,MAAM,CAAC,cAAc,CAAC,MAAgB,EAAE,kBAAkB,EAAE;QACxD,KAAK,EAAE,EAAE,QAAQ,EAAwB;QACzC,UAAU,EAAE,KAAK;QACjB,QAAQ,EAAE,KAAK;QACf,YAAY,EAAE,KAAK;KACtB,CAAC,CAAC;IACH,OAAO,MAA8B,CAAC;AAC1C,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,MAAe;IACzC,OAAO,CAAC,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,kBAAkB,IAAK,MAAiB,CAAC;AAC9F,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,YAAY,CAAsB,MAAS;IACvD,MAAM,IAAI,GAAI,MAAmE,CAAC,kBAAkB,CAAC,CAAC;IACtG,OAAO,IAAI,EAAE,QAA2C,CAAC;AAC7D,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAsB,MAA4B;IAC/E,OAAO,MAAM,CAAC;AAClB,CAAC;AAED,4CAA4C;AAC5C,wDAAwD;AACxD,MAAM,CAAN,IAAY,cAEX;AAFD,WAAY,cAAc;IACtB,gDAA8B,CAAA;AAClC,CAAC,EAFW,cAAc,KAAd,cAAc,QAEzB"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.d.ts new file mode 100644 index 000000000..7746e823b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.d.ts @@ -0,0 +1,45 @@ +import { Express } from 'express'; +/** + * Options for creating an MCP Express application. + */ +export interface CreateMcpExpressAppOptions { + /** + * The hostname to bind to. Defaults to '127.0.0.1'. + * When set to '127.0.0.1', 'localhost', or '::1', DNS rebinding protection is automatically enabled. + */ + host?: string; + /** + * List of allowed hostnames for DNS rebinding protection. + * If provided, host header validation will be applied using this list. + * For IPv6, provide addresses with brackets (e.g., '[::1]'). + * + * This is useful when binding to '0.0.0.0' or '::' but still wanting + * to restrict which hostnames are allowed. + */ + allowedHosts?: string[]; +} +/** + * Creates an Express application pre-configured for MCP servers. + * + * When the host is '127.0.0.1', 'localhost', or '::1' (the default is '127.0.0.1'), + * DNS rebinding protection middleware is automatically applied to protect against + * DNS rebinding attacks on localhost servers. + * + * @param options - Configuration options + * @returns A configured Express application + * + * @example + * ```typescript + * // Basic usage - defaults to 127.0.0.1 with DNS rebinding protection + * const app = createMcpExpressApp(); + * + * // Custom host - DNS rebinding protection only applied for localhost hosts + * const app = createMcpExpressApp({ host: '0.0.0.0' }); // No automatic DNS rebinding protection + * const app = createMcpExpressApp({ host: 'localhost' }); // DNS rebinding protection enabled + * + * // Custom allowed hosts for non-localhost binding + * const app = createMcpExpressApp({ host: '0.0.0.0', allowedHosts: ['myapp.local', 'localhost'] }); + * ``` + */ +export declare function createMcpExpressApp(options?: CreateMcpExpressAppOptions): Express; +//# sourceMappingURL=express.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.d.ts.map new file mode 100644 index 000000000..5f607a9a9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"express.d.ts","sourceRoot":"","sources":["../../../src/server/express.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAG3C;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACvC;;;OAGG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd;;;;;;;OAOG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CAC3B;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,0BAA+B,GAAG,OAAO,CA0BrF"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.js new file mode 100644 index 000000000..a23a57bf7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.js @@ -0,0 +1,50 @@ +import express from 'express'; +import { hostHeaderValidation, localhostHostValidation } from './middleware/hostHeaderValidation.js'; +/** + * Creates an Express application pre-configured for MCP servers. + * + * When the host is '127.0.0.1', 'localhost', or '::1' (the default is '127.0.0.1'), + * DNS rebinding protection middleware is automatically applied to protect against + * DNS rebinding attacks on localhost servers. + * + * @param options - Configuration options + * @returns A configured Express application + * + * @example + * ```typescript + * // Basic usage - defaults to 127.0.0.1 with DNS rebinding protection + * const app = createMcpExpressApp(); + * + * // Custom host - DNS rebinding protection only applied for localhost hosts + * const app = createMcpExpressApp({ host: '0.0.0.0' }); // No automatic DNS rebinding protection + * const app = createMcpExpressApp({ host: 'localhost' }); // DNS rebinding protection enabled + * + * // Custom allowed hosts for non-localhost binding + * const app = createMcpExpressApp({ host: '0.0.0.0', allowedHosts: ['myapp.local', 'localhost'] }); + * ``` + */ +export function createMcpExpressApp(options = {}) { + const { host = '127.0.0.1', allowedHosts } = options; + const app = express(); + app.use(express.json()); + // If allowedHosts is explicitly provided, use that for validation + if (allowedHosts) { + app.use(hostHeaderValidation(allowedHosts)); + } + else { + // Apply DNS rebinding protection automatically for localhost hosts + const localhostHosts = ['127.0.0.1', 'localhost', '::1']; + if (localhostHosts.includes(host)) { + app.use(localhostHostValidation()); + } + else if (host === '0.0.0.0' || host === '::') { + // Warn when binding to all interfaces without DNS rebinding protection + // eslint-disable-next-line no-console + console.warn(`Warning: Server is binding to ${host} without DNS rebinding protection. ` + + 'Consider using the allowedHosts option to restrict allowed hosts, ' + + 'or use authentication to protect your server.'); + } + } + return app; +} +//# sourceMappingURL=express.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.js.map new file mode 100644 index 000000000..0ebc4c88c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.js.map @@ -0,0 +1 @@ +{"version":3,"file":"express.js","sourceRoot":"","sources":["../../../src/server/express.ts"],"names":[],"mappings":"AAAA,OAAO,OAAoB,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,sCAAsC,CAAC;AAuBrG;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,mBAAmB,CAAC,UAAsC,EAAE;IACxE,MAAM,EAAE,IAAI,GAAG,WAAW,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC;IAErD,MAAM,GAAG,GAAG,OAAO,EAAE,CAAC;IACtB,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IAExB,kEAAkE;IAClE,IAAI,YAAY,EAAE,CAAC;QACf,GAAG,CAAC,GAAG,CAAC,oBAAoB,CAAC,YAAY,CAAC,CAAC,CAAC;IAChD,CAAC;SAAM,CAAC;QACJ,mEAAmE;QACnE,MAAM,cAAc,GAAG,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC;QACzD,IAAI,cAAc,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YAChC,GAAG,CAAC,GAAG,CAAC,uBAAuB,EAAE,CAAC,CAAC;QACvC,CAAC;aAAM,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YAC7C,uEAAuE;YACvE,sCAAsC;YACtC,OAAO,CAAC,IAAI,CACR,iCAAiC,IAAI,qCAAqC;gBACtE,oEAAoE;gBACpE,+CAA+C,CACtD,CAAC;QACN,CAAC;IACL,CAAC;IAED,OAAO,GAAG,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.d.ts new file mode 100644 index 000000000..cfa236eb0 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.d.ts @@ -0,0 +1,196 @@ +import { Protocol, type NotificationOptions, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; +import { type ClientCapabilities, type CreateMessageRequest, type CreateMessageResult, type CreateMessageResultWithTools, type CreateMessageRequestParamsBase, type CreateMessageRequestParamsWithTools, type ElicitRequestFormParams, type ElicitRequestURLParams, type ElicitResult, type Implementation, type ListRootsRequest, type LoggingMessageNotification, type ResourceUpdatedNotification, type ServerCapabilities, type ServerNotification, type ServerRequest, type ServerResult, type Request, type Notification, type Result } from '../types.js'; +import type { jsonSchemaValidator } from '../validation/types.js'; +import { AnyObjectSchema, SchemaOutput } from './zod-compat.js'; +import { RequestHandlerExtra } from '../shared/protocol.js'; +import { ExperimentalServerTasks } from '../experimental/tasks/server.js'; +export type ServerOptions = ProtocolOptions & { + /** + * Capabilities to advertise as being supported by this server. + */ + capabilities?: ServerCapabilities; + /** + * Optional instructions describing how to use the server and its features. + */ + instructions?: string; + /** + * JSON Schema validator for elicitation response validation. + * + * The validator is used to validate user input returned from elicitation + * requests against the requested schema. + * + * @default AjvJsonSchemaValidator + * + * @example + * ```typescript + * // ajv (default) + * const server = new Server( + * { name: 'my-server', version: '1.0.0' }, + * { + * capabilities: {} + * jsonSchemaValidator: new AjvJsonSchemaValidator() + * } + * ); + * + * // @cfworker/json-schema + * const server = new Server( + * { name: 'my-server', version: '1.0.0' }, + * { + * capabilities: {}, + * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() + * } + * ); + * ``` + */ + jsonSchemaValidator?: jsonSchemaValidator; +}; +/** + * An MCP server on top of a pluggable transport. + * + * This server will automatically respond to the initialization flow as initiated from the client. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed server + * const server = new Server({ + * name: "CustomServer", + * version: "1.0.0" + * }) + * ``` + * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. + */ +export declare class Server extends Protocol { + private _serverInfo; + private _clientCapabilities?; + private _clientVersion?; + private _capabilities; + private _instructions?; + private _jsonSchemaValidator; + private _experimental?; + /** + * Callback for when initialization has fully completed (i.e., the client has sent an `initialized` notification). + */ + oninitialized?: () => void; + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo: Implementation, options?: ServerOptions); + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental(): { + tasks: ExperimentalServerTasks; + }; + private _loggingLevels; + private readonly LOG_LEVEL_SEVERITY; + private isMessageIgnored; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities: ServerCapabilities): void; + /** + * Override request handler registration to enforce server-side validation for tools/call. + */ + setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => ServerResult | ResultT | Promise): void; + protected assertCapabilityForMethod(method: RequestT['method']): void; + protected assertNotificationCapability(method: (ServerNotification | NotificationT)['method']): void; + protected assertRequestHandlerCapability(method: string): void; + protected assertTaskCapability(method: string): void; + protected assertTaskHandlerCapability(method: string): void; + private _oninitialize; + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + */ + getClientCapabilities(): ClientCapabilities | undefined; + /** + * After initialization has completed, this will be populated with information about the client's name and version. + */ + getClientVersion(): Implementation | undefined; + private getCapabilities; + ping(): Promise<{ + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + /** + * Request LLM sampling from the client (without tools). + * Returns single content block for backwards compatibility. + */ + createMessage(params: CreateMessageRequestParamsBase, options?: RequestOptions): Promise; + /** + * Request LLM sampling from the client with tool support. + * Returns content that may be a single block or array (for parallel tool calls). + */ + createMessage(params: CreateMessageRequestParamsWithTools, options?: RequestOptions): Promise; + /** + * Request LLM sampling from the client. + * When tools may or may not be present, returns the union type. + */ + createMessage(params: CreateMessageRequest['params'], options?: RequestOptions): Promise; + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + */ + elicitInput(params: ElicitRequestFormParams | ElicitRequestURLParams, options?: RequestOptions): Promise; + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId: string, options?: NotificationOptions): () => Promise; + listRoots(params?: ListRootsRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + roots: { + uri: string; + name?: string | undefined; + _meta?: Record | undefined; + }[]; + _meta?: { + [x: string]: unknown; + progressToken?: string | number | undefined; + "io.modelcontextprotocol/related-task"?: { + taskId: string; + } | undefined; + } | undefined; + }>; + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise; + sendResourceUpdated(params: ResourceUpdatedNotification['params']): Promise; + sendResourceListChanged(): Promise; + sendToolListChanged(): Promise; + sendPromptListChanged(): Promise; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.d.ts.map new file mode 100644 index 000000000..fe0fa6589 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,KAAK,mBAAmB,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACzI,OAAO,EACH,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EAExB,KAAK,4BAA4B,EAEjC,KAAK,8BAA8B,EACnC,KAAK,mCAAmC,EACxC,KAAK,uBAAuB,EAC5B,KAAK,sBAAsB,EAC3B,KAAK,YAAY,EAIjB,KAAK,cAAc,EAMnB,KAAK,gBAAgB,EAIrB,KAAK,0BAA0B,EAE/B,KAAK,2BAA2B,EAChC,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,YAAY,EAQjB,KAAK,OAAO,EACZ,KAAK,YAAY,EACjB,KAAK,MAAM,EACd,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EAAkB,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAClF,O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,aAAa,CACf,MAAM,EAAE,oBAAoB,CAAC,QAAQ,CAAC,EACtC,OAAO,CAAC,EAAE,cAAc,GACzB,OAAO,CAAC,mBAAmB,GAAG,4BAA4B,CAAC;IAwD9D;;;;;;OAMG;IACG,WAAW,CAAC,MAAM,EAAE,uBAAuB,GAAG,sBAAsB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC;IAgD5H;;;;;;;OAOG;IACH,mCAAmC,CAAC,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC;IAiBxG,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;IAI7E;;;;;;OAMG;IACG,kBAAkB,CAAC,MAAM,EAAE,0BAA0B,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC,EAAE,MAAM;IAQnF,mBAAmB,CAAC,MAAM,EAAE,2BAA2B,CAAC,QAAQ,CAAC;IAOjE,uBAAuB;IAMvB,mBAAmB;IAInB,qBAAqB;CAG9B"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js new file mode 100644 index 000000000..51d060e59 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js @@ -0,0 +1,440 @@ +import { mergeCapabilities, Protocol } from '../shared/protocol.js'; +import { CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitResultSchema, EmptyResultSchema, ErrorCode, InitializedNotificationSchema, InitializeRequestSchema, LATEST_PROTOCOL_VERSION, ListRootsResultSchema, LoggingLevelSchema, McpError, SetLevelRequestSchema, SUPPORTED_PROTOCOL_VERSIONS, CallToolRequestSchema, CallToolResultSchema, CreateTaskResultSchema } from '../types.js'; +import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; +import { getObjectShape, isZ4Schema, safeParse } from './zod-compat.js'; +import { ExperimentalServerTasks } from '../experimental/tasks/server.js'; +import { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js'; +/** + * An MCP server on top of a pluggable transport. + * + * This server will automatically respond to the initialization flow as initiated from the client. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed server + * const server = new Server({ + * name: "CustomServer", + * version: "1.0.0" + * }) + * ``` + * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. + */ +export class Server extends Protocol { + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + super(options); + this._serverInfo = _serverInfo; + // Map log levels by session id + this._loggingLevels = new Map(); + // Map LogLevelSchema to severity index + this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); + // Is a message with the given level ignored in the log level set for the given session id? + this.isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + this._capabilities = options?.capabilities ?? {}; + this._instructions = options?.instructions; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + this.setRequestHandler(InitializeRequestSchema, request => this._oninitialize(request)); + this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.()); + if (this._capabilities.logging) { + this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { + const transportSessionId = extra.sessionId || extra.requestInfo?.headers['mcp-session-id'] || undefined; + const { level } = request.params; + const parseResult = LoggingLevelSchema.safeParse(level); + if (parseResult.success) { + this._loggingLevels.set(transportSessionId, parseResult.data); + } + return {}; + }); + } + } + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental() { + if (!this._experimental) { + this._experimental = { + tasks: new ExperimentalServerTasks(this) + }; + } + return this._experimental; + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error('Cannot register capabilities after connecting to transport'); + } + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + } + /** + * Override request handler registration to enforce server-side validation for tools/call. + */ + setRequestHandler(requestSchema, handler) { + const shape = getObjectShape(requestSchema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + // Extract literal value using type-safe property access + let methodValue; + if (isZ4Schema(methodSchema)) { + const v4Schema = methodSchema; + const v4Def = v4Schema._zod?.def; + methodValue = v4Def?.value ?? v4Schema.value; + } + else { + const v3Schema = methodSchema; + const legacyDef = v3Schema._def; + methodValue = legacyDef?.value ?? v3Schema.value; + } + if (typeof methodValue !== 'string') { + throw new Error('Schema method literal must be a string'); + } + const method = methodValue; + if (method === 'tools/call') { + const wrappedHandler = async (request, extra) => { + const validatedRequest = safeParse(CallToolRequestSchema, request); + if (!validatedRequest.success) { + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + const result = await Promise.resolve(handler(request, extra)); + // When task creation is requested, validate and return CreateTaskResult + if (params.task) { + const taskValidationResult = safeParse(CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error + ? taskValidationResult.error.message + : String(taskValidationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + // For non-task requests, validate against CallToolResultSchema + const validationResult = safeParse(CallToolResultSchema, result); + if (!validationResult.success) { + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`); + } + return validationResult.data; + }; + // Install the wrapped handler + return super.setRequestHandler(requestSchema, wrappedHandler); + } + // Other handlers use default behavior + return super.setRequestHandler(requestSchema, handler); + } + assertCapabilityForMethod(method) { + switch (method) { + case 'sampling/createMessage': + if (!this._clientCapabilities?.sampling) { + throw new Error(`Client does not support sampling (required for ${method})`); + } + break; + case 'elicitation/create': + if (!this._clientCapabilities?.elicitation) { + throw new Error(`Client does not support elicitation (required for ${method})`); + } + break; + case 'roots/list': + if (!this._clientCapabilities?.roots) { + throw new Error(`Client does not support listing roots (required for ${method})`); + } + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertNotificationCapability(method) { + switch (method) { + case 'notifications/message': + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'notifications/resources/updated': + case 'notifications/resources/list_changed': + if (!this._capabilities.resources) { + throw new Error(`Server does not support notifying about resources (required for ${method})`); + } + break; + case 'notifications/tools/list_changed': + if (!this._capabilities.tools) { + throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); + } + break; + case 'notifications/prompts/list_changed': + if (!this._capabilities.prompts) { + throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); + } + break; + case 'notifications/elicitation/complete': + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error(`Client does not support URL elicitation (required for ${method})`); + } + break; + case 'notifications/cancelled': + // Cancellation notifications are always allowed + break; + case 'notifications/progress': + // Progress notifications are always allowed + break; + } + } + assertRequestHandlerCapability(method) { + // Task handlers are registered in Protocol constructor before _capabilities is initialized + // Skip capability check for task methods during initialization + if (!this._capabilities) { + return; + } + switch (method) { + case 'completion/complete': + if (!this._capabilities.completions) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case 'logging/setLevel': + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'prompts/get': + case 'prompts/list': + if (!this._capabilities.prompts) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case 'resources/list': + case 'resources/templates/list': + case 'resources/read': + if (!this._capabilities.resources) { + throw new Error(`Server does not support resources (required for ${method})`); + } + break; + case 'tools/call': + case 'tools/list': + if (!this._capabilities.tools) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case 'tasks/get': + case 'tasks/list': + case 'tasks/result': + case 'tasks/cancel': + if (!this._capabilities.tasks) { + throw new Error(`Server does not support tasks capability (required for ${method})`); + } + break; + case 'ping': + case 'initialize': + // No specific capability required for these methods + break; + } + } + assertTaskCapability(method) { + assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, 'Client'); + } + assertTaskHandlerCapability(method) { + // Task handlers are registered in Protocol constructor before _capabilities is initialized + // Skip capability check for task methods during initialization + if (!this._capabilities) { + return; + } + assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, 'Server'); + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...(this._instructions && { instructions: this._instructions }) + }; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + */ + getClientVersion() { + return this._clientVersion; + } + getCapabilities() { + return this._capabilities; + } + async ping() { + return this.request({ method: 'ping' }, EmptyResultSchema); + } + // Implementation + async createMessage(params, options) { + // Capability check - only required when tools/toolChoice are provided + if (params.tools || params.toolChoice) { + if (!this._clientCapabilities?.sampling?.tools) { + throw new Error('Client does not support sampling tools capability.'); + } + } + // Message structure validation - always validate tool_use/tool_result pairs. + // These may appear even without tools/toolChoice in the current request when + // a previous sampling request returned tool_use and this is a follow-up with results. + if (params.messages.length > 0) { + const lastMessage = params.messages[params.messages.length - 1]; + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some(c => c.type === 'tool_result'); + const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined; + const previousContent = previousMessage + ? Array.isArray(previousMessage.content) + ? previousMessage.content + : [previousMessage.content] + : []; + const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use'); + if (hasToolResults) { + if (lastContent.some(c => c.type !== 'tool_result')) { + throw new Error('The last message must contain only tool_result content if any is present'); + } + if (!hasPreviousToolUse) { + throw new Error('tool_result blocks are not matching any tool_use from the previous message'); + } + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id)); + const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) { + throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match'); + } + } + } + // Use different schemas based on whether tools are provided + if (params.tools) { + return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultWithToolsSchema, options); + } + return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options); + } + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + */ + async elicitInput(params, options) { + const mode = (params.mode ?? 'form'); + switch (mode) { + case 'url': { + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error('Client does not support url elicitation.'); + } + const urlParams = params; + return this.request({ method: 'elicitation/create', params: urlParams }, ElicitResultSchema, options); + } + case 'form': { + if (!this._clientCapabilities?.elicitation?.form) { + throw new Error('Client does not support form elicitation.'); + } + const formParams = params.mode === 'form' ? params : { ...params, mode: 'form' }; + const result = await this.request({ method: 'elicitation/create', params: formParams }, ElicitResultSchema, options); + if (result.action === 'accept' && result.content && formParams.requestedSchema) { + try { + const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); + const validationResult = validator(result.content); + if (!validationResult.valid) { + throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } + } + catch (error) { + if (error instanceof McpError) { + throw error; + } + throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); + } + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)'); + } + return () => this.notification({ + method: 'notifications/elicitation/complete', + params: { + elicitationId + } + }, options); + } + async listRoots(params, options) { + return this.request({ method: 'roots/list', params }, ListRootsResultSchema, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging) { + if (!this.isMessageIgnored(params.level, sessionId)) { + return this.notification({ method: 'notifications/message', params }); + } + } + } + async sendResourceUpdated(params) { + return this.notification({ + method: 'notifications/resources/updated', + params + }); + } + async sendResourceListChanged() { + return this.notification({ + method: 'notifications/resources/list_changed' + }); + } + async sendToolListChanged() { + return this.notification({ method: 'notifications/tools/list_changed' }); + } + async sendPromptListChanged() { + return this.notification({ method: 'notifications/prompts/list_changed' }); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js.map new file mode 100644 index 000000000..bd943512f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAuE,MAAM,uBAAuB,CAAC;AACzI,OAAO,EAIH,yBAAyB,EAEzB,kCAAkC,EAMlC,kBAAkB,EAClB,iBAAiB,EACjB,SAAS,EAET,6BAA6B,EAE7B,uBAAuB,EAEvB,uBAAuB,EAEvB,qBAAqB,EAErB,kBAAkB,EAElB,QAAQ,EAMR,qBAAqB,EACrB,2BAA2B,EAG3B,qBAAqB,EACrB,oBAAoB,EACpB,sBAAsB,EAIzB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAEvE,OAAO,EAEH,cAAc,EACd,UAAU,EACV,SAAS,EAIZ,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAC1E,OAAO,EAAE,6BAA6B,EAAE,iCAAiC,EAAE,MAAM,kCAAkC,CAAC;AA6CpH;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,OAAO,MAIX,SAAQ,QAA8F;IAapG;;OAEG;IACH,YACY,WAA2B,EACnC,OAAuB;QAEvB,KAAK,CAAC,OAAO,CAAC,CAAC;QAHP,gBAAW,GAAX,WAAW,CAAgB;QAyCvC,+BAA+B;QACvB,mBAAc,GAAG,IAAI,GAAG,EAAoC,CAAC;QAErE,uCAAuC;QACtB,uBAAkB,GAAG,IAAI,GAAG,CAAC,kBAAkB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;Q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CAAkC,EAAE,CAAC,CAAC;IAC7E,CAAC;IAED,KAAK,CAAC,qBAAqB;QACvB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,oCAAoC,EAAE,CAAC,CAAC;IAC/E,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.d.ts new file mode 100644 index 000000000..1bc0c6829 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.d.ts @@ -0,0 +1,364 @@ +import { Server, ServerOptions } from './index.js'; +import { AnySchema, AnyObjectSchema, ZodRawShapeCompat, SchemaOutput, ShapeOutput } from './zod-compat.js'; +import { Implementation, CallToolResult, Resource, ListResourcesResult, GetPromptResult, ReadResourceResult, ServerRequest, ServerNotification, ToolAnnotations, LoggingMessageNotification, Result, ToolExecution } from '../types.js'; +import { UriTemplate, Variables } from '../shared/uriTemplate.js'; +import { RequestHandlerExtra } from '../shared/protocol.js'; +import { Transport } from '../shared/transport.js'; +import { ExperimentalMcpServerTasks } from '../experimental/tasks/mcp-server.js'; +import type { ToolTaskHandler } from '../experimental/tasks/interfaces.js'; +/** + * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. + * For advanced usage (like sending notifications or setting custom request handlers), use the underlying + * Server instance available via the `server` property. + */ +export declare class McpServer { + /** + * The underlying Server instance, useful for advanced operations like sending notifications. + */ + readonly server: Server; + private _registeredResources; + private _registeredResourceTemplates; + private _registeredTools; + private _registeredPrompts; + private _experimental?; + constructor(serverInfo: Implementation, options?: ServerOptions); + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental(): { + tasks: ExperimentalMcpServerTasks; + }; + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + connect(transport: Transport): Promise; + /** + * Closes the connection. + */ + close(): Promise; + private _toolHandlersInitialized; + private setToolRequestHandlers; + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + private createToolError; + /** + * Validates tool input arguments against the tool's input schema. + */ + private validateToolInput; + /** + * Validates tool output against the tool's output schema. + */ + private validateToolOutput; + /** + * Executes a tool handler (either regular or task-based). + */ + private executeToolHandler; + /** + * Handles automatic task polling for tools with taskSupport 'optional'. + */ + private handleAutomaticTaskPolling; + private _completionHandlerInitialized; + private setCompletionRequestHandler; + private handlePromptCompletion; + private handleResourceCompletion; + private _resourceHandlersInitialized; + private setResourceRequestHandlers; + private _promptHandlersInitialized; + private setPromptRequestHandlers; + /** + * Registers a resource `name` at a fixed URI, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, uri: string, readCallback: ReadResourceCallback): RegisteredResource; + /** + * Registers a resource `name` at a fixed URI with metadata, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, uri: string, metadata: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; + /** + * Registers a resource `name` with a template pattern, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, template: ResourceTemplate, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; + /** + * Registers a resource `name` with a template pattern and metadata, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, template: ResourceTemplate, metadata: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; + /** + * Registers a resource with a config object and callback. + * For static resources, use a URI string. For dynamic resources, use a ResourceTemplate. + */ + registerResource(name: string, uriOrTemplate: string, config: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; + registerResource(name: string, uriOrTemplate: ResourceTemplate, config: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; + private _createRegisteredResource; + private _createRegisteredResourceTemplate; + private _createRegisteredPrompt; + private _createRegisteredTool; + /** + * Registers a zero-argument tool `name`, which will run the given function when the client calls it. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, cb: ToolCallback): RegisteredTool; + /** + * Registers a zero-argument tool `name` (with a description) which will run the given function when the client calls it. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, description: string, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool taking either a parameter schema for validation or annotations for additional metadata. + * This unified overload handles both `tool(name, paramsSchema, cb)` and `tool(name, annotations, cb)` cases. + * + * Note: We use a union type for the second parameter because TypeScript cannot reliably disambiguate + * between ToolAnnotations and ZodRawShapeCompat during overload resolution, as both are plain object types. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool `name` (with a description) taking either parameter schema or annotations. + * This unified overload handles both `tool(name, description, paramsSchema, cb)` and + * `tool(name, description, annotations, cb)` cases. + * + * Note: We use a union type for the third parameter because TypeScript cannot reliably disambiguate + * between ToolAnnotations and ZodRawShapeCompat during overload resolution, as both are plain object types. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, description: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool with both parameter schema and annotations. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool with description, parameter schema, and annotations. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, description: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool with a config object and callback. + */ + registerTool(name: string, config: { + title?: string; + description?: string; + inputSchema?: InputArgs; + outputSchema?: OutputArgs; + annotations?: ToolAnnotations; + _meta?: Record; + }, cb: ToolCallback): RegisteredTool; + /** + * Registers a zero-argument prompt `name`, which will run the given function when the client calls it. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a zero-argument prompt `name` (with a description) which will run the given function when the client calls it. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, description: string, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a prompt `name` accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a prompt `name` (with a description) accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, description: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a prompt with a config object and callback. + */ + registerPrompt(name: string, config: { + title?: string; + description?: string; + argsSchema?: Args; + }, cb: PromptCallback): RegisteredPrompt; + /** + * Checks if the server is connected to a transport. + * @returns True if the server is connected + */ + isConnected(): boolean; + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise; + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged(): void; + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged(): void; + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged(): void; +} +/** + * A callback to complete one variable within a resource template's URI template. + */ +export type CompleteResourceTemplateCallback = (value: string, context?: { + arguments?: Record; +}) => string[] | Promise; +/** + * A resource template combines a URI pattern with optional functionality to enumerate + * all resources matching that pattern. + */ +export declare class ResourceTemplate { + private _callbacks; + private _uriTemplate; + constructor(uriTemplate: string | UriTemplate, _callbacks: { + /** + * A callback to list all resources matching this template. This is required to specified, even if `undefined`, to avoid accidentally forgetting resource listing. + */ + list: ListResourcesCallback | undefined; + /** + * An optional callback to autocomplete variables within the URI template. Useful for clients and users to discover possible values. + */ + complete?: { + [variable: string]: CompleteResourceTemplateCallback; + }; + }); + /** + * Gets the URI template pattern. + */ + get uriTemplate(): UriTemplate; + /** + * Gets the list callback, if one was provided. + */ + get listCallback(): ListResourcesCallback | undefined; + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable: string): CompleteResourceTemplateCallback | undefined; +} +export type BaseToolCallback, Args extends undefined | ZodRawShapeCompat | AnySchema> = Args extends ZodRawShapeCompat ? (args: ShapeOutput, extra: Extra) => SendResultT | Promise : Args extends AnySchema ? (args: SchemaOutput, extra: Extra) => SendResultT | Promise : (extra: Extra) => SendResultT | Promise; +/** + * Callback for a tool handler registered with Server.tool(). + * + * Parameters will include tool arguments, if applicable, as well as other request handler context. + * + * The callback should return: + * - `structuredContent` if the tool has an outputSchema defined + * - `content` if the tool does not have an outputSchema + * - Both fields are optional but typically one should be provided + */ +export type ToolCallback = BaseToolCallback, Args>; +/** + * Supertype that can handle both regular tools (simple callback) and task-based tools (task handler object). + */ +export type AnyToolHandler = ToolCallback | ToolTaskHandler; +export type RegisteredTool = { + title?: string; + description?: string; + inputSchema?: AnySchema; + outputSchema?: AnySchema; + annotations?: ToolAnnotations; + execution?: ToolExecution; + _meta?: Record; + handler: AnyToolHandler; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string | null; + title?: string; + description?: string; + paramsSchema?: InputArgs; + outputSchema?: OutputArgs; + annotations?: ToolAnnotations; + _meta?: Record; + callback?: ToolCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +/** + * Additional, optional information for annotating a resource. + */ +export type ResourceMetadata = Omit; +/** + * Callback to list all resources matching a given template. + */ +export type ListResourcesCallback = (extra: RequestHandlerExtra) => ListResourcesResult | Promise; +/** + * Callback to read a resource at a given URI. + */ +export type ReadResourceCallback = (uri: URL, extra: RequestHandlerExtra) => ReadResourceResult | Promise; +export type RegisteredResource = { + name: string; + title?: string; + metadata?: ResourceMetadata; + readCallback: ReadResourceCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string; + title?: string; + uri?: string | null; + metadata?: ResourceMetadata; + callback?: ReadResourceCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +/** + * Callback to read a resource at a given URI, following a filled-in URI template. + */ +export type ReadResourceTemplateCallback = (uri: URL, variables: Variables, extra: RequestHandlerExtra) => ReadResourceResult | Promise; +export type RegisteredResourceTemplate = { + resourceTemplate: ResourceTemplate; + title?: string; + metadata?: ResourceMetadata; + readCallback: ReadResourceTemplateCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string | null; + title?: string; + template?: ResourceTemplate; + metadata?: ResourceMetadata; + callback?: ReadResourceTemplateCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +type PromptArgsRawShape = ZodRawShapeCompat; +export type PromptCallback = Args extends PromptArgsRawShape ? (args: ShapeOutput, extra: RequestHandlerExtra) => GetPromptResult | Promise : (extra: RequestHandlerExtra) => GetPromptResult | Promise; +export type RegisteredPrompt = { + title?: string; + description?: string; + argsSchema?: AnyObjectSchema; + callback: PromptCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string | null; + title?: string; + description?: string; + argsSchema?: Args; + callback?: PromptCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +export {}; +//# sourceMappingURL=mcp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.d.ts.map new file mode 100644 index 000000000..0b460bb2a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../../src/server/mcp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACH,SAAS,EACT,eAAe,EACf,iBAAiB,EACjB,YA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,UAAU,CAAC,EAAE,eAAe,CAAC;IAC7B,QAAQ,EAAE,cAAc,CAAC,SAAS,GAAG,kBAAkB,CAAC,CAAC;IACzD,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,IAAI,IAAI,CAAC;IACf,OAAO,IAAI,IAAI,CAAC;IAChB,MAAM,CAAC,IAAI,SAAS,kBAAkB,EAAE,OAAO,EAAE;QAC7C,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QACrB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,UAAU,CAAC,EAAE,IAAI,CAAC;QAClB,QAAQ,CAAC,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;QAChC,OAAO,CAAC,EAAE,OAAO,CAAC;KACrB,GAAG,IAAI,CAAC;IACT,MAAM,IAAI,IAAI,CAAC;CAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js new file mode 100644 index 000000000..23639ce55 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js @@ -0,0 +1,913 @@ +import { Server } from './index.js'; +import { normalizeObjectSchema, safeParseAsync, getObjectShape, objectFromShape, getParseErrorMessage, getSchemaDescription, isSchemaOptional, getLiteralValue } from './zod-compat.js'; +import { toJsonSchemaCompat } from './zod-json-schema-compat.js'; +import { McpError, ErrorCode, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ListPromptsRequestSchema, GetPromptRequestSchema, CompleteRequestSchema, assertCompleteRequestPrompt, assertCompleteRequestResourceTemplate } from '../types.js'; +import { isCompletable, getCompleter } from './completable.js'; +import { UriTemplate } from '../shared/uriTemplate.js'; +import { validateAndWarnToolName } from '../shared/toolNameValidation.js'; +import { ExperimentalMcpServerTasks } from '../experimental/tasks/mcp-server.js'; +import { ZodOptional } from 'zod'; +/** + * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. + * For advanced usage (like sending notifications or setting custom request handlers), use the underlying + * Server instance available via the `server` property. + */ +export class McpServer { + constructor(serverInfo, options) { + this._registeredResources = {}; + this._registeredResourceTemplates = {}; + this._registeredTools = {}; + this._registeredPrompts = {}; + this._toolHandlersInitialized = false; + this._completionHandlerInitialized = false; + this._resourceHandlersInitialized = false; + this._promptHandlersInitialized = false; + this.server = new Server(serverInfo, options); + } + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental() { + if (!this._experimental) { + this._experimental = { + tasks: new ExperimentalMcpServerTasks(this) + }; + } + return this._experimental; + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport) { + return await this.server.connect(transport); + } + /** + * Closes the connection. + */ + async close() { + await this.server.close(); + } + setToolRequestHandlers() { + if (this._toolHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)); + this.server.registerCapabilities({ + tools: { + listChanged: true + } + }); + this.server.setRequestHandler(ListToolsRequestSchema, () => ({ + tools: Object.entries(this._registeredTools) + .filter(([, tool]) => tool.enabled) + .map(([name, tool]) => { + const toolDefinition = { + name, + title: tool.title, + description: tool.description, + inputSchema: (() => { + const obj = normalizeObjectSchema(tool.inputSchema); + return obj + ? toJsonSchemaCompat(obj, { + strictUnions: true, + pipeStrategy: 'input' + }) + : EMPTY_OBJECT_JSON_SCHEMA; + })(), + annotations: tool.annotations, + execution: tool.execution, + _meta: tool._meta + }; + if (tool.outputSchema) { + const obj = normalizeObjectSchema(tool.outputSchema); + if (obj) { + toolDefinition.outputSchema = toJsonSchemaCompat(obj, { + strictUnions: true, + pipeStrategy: 'output' + }); + } + } + return toolDefinition; + }) + })); + this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { + try { + const tool = this._registeredTools[request.params.name]; + if (!tool) { + throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); + } + if (!tool.enabled) { + throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); + } + const isTaskRequest = !!request.params.task; + const taskSupport = tool.execution?.taskSupport; + const isTaskHandler = 'createTask' in tool.handler; + // Validate task hint configuration + if ((taskSupport === 'required' || taskSupport === 'optional') && !isTaskHandler) { + throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`); + } + // Handle taskSupport 'required' without task augmentation + if (taskSupport === 'required' && !isTaskRequest) { + throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`); + } + // Handle taskSupport 'optional' without task augmentation - automatic polling + if (taskSupport === 'optional' && !isTaskRequest && isTaskHandler) { + return await this.handleAutomaticTaskPolling(tool, request, extra); + } + // Normal execution path + const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); + const result = await this.executeToolHandler(tool, args, extra); + // Return CreateTaskResult immediately for task requests + if (isTaskRequest) { + return result; + } + // Validate output schema for non-task requests + await this.validateToolOutput(tool, result, request.params.name); + return result; + } + catch (error) { + if (error instanceof McpError) { + if (error.code === ErrorCode.UrlElicitationRequired) { + throw error; // Return the error to the caller without wrapping in CallToolResult + } + } + return this.createToolError(error instanceof Error ? error.message : String(error)); + } + }); + this._toolHandlersInitialized = true; + } + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + createToolError(errorMessage) { + return { + content: [ + { + type: 'text', + text: errorMessage + } + ], + isError: true + }; + } + /** + * Validates tool input arguments against the tool's input schema. + */ + async validateToolInput(tool, args, toolName) { + if (!tool.inputSchema) { + return undefined; + } + // Try to normalize to object schema first (for raw shapes and object schemas) + // If that fails, use the schema directly (for union/intersection/etc) + const inputObj = normalizeObjectSchema(tool.inputSchema); + const schemaToParse = inputObj ?? tool.inputSchema; + const parseResult = await safeParseAsync(schemaToParse, args); + if (!parseResult.success) { + const error = 'error' in parseResult ? parseResult.error : 'Unknown error'; + const errorMessage = getParseErrorMessage(error); + throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`); + } + return parseResult.data; + } + /** + * Validates tool output against the tool's output schema. + */ + async validateToolOutput(tool, result, toolName) { + if (!tool.outputSchema) { + return; + } + // Only validate CallToolResult, not CreateTaskResult + if (!('content' in result)) { + return; + } + if (result.isError) { + return; + } + if (!result.structuredContent) { + throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); + } + // if the tool has an output schema, validate structured content + const outputObj = normalizeObjectSchema(tool.outputSchema); + const parseResult = await safeParseAsync(outputObj, result.structuredContent); + if (!parseResult.success) { + const error = 'error' in parseResult ? parseResult.error : 'Unknown error'; + const errorMessage = getParseErrorMessage(error); + throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`); + } + } + /** + * Executes a tool handler (either regular or task-based). + */ + async executeToolHandler(tool, args, extra) { + const handler = tool.handler; + const isTaskHandler = 'createTask' in handler; + if (isTaskHandler) { + if (!extra.taskStore) { + throw new Error('No task store provided.'); + } + const taskExtra = { ...extra, taskStore: extra.taskStore }; + if (tool.inputSchema) { + const typedHandler = handler; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return await Promise.resolve(typedHandler.createTask(args, taskExtra)); + } + else { + const typedHandler = handler; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return await Promise.resolve(typedHandler.createTask(taskExtra)); + } + } + if (tool.inputSchema) { + const typedHandler = handler; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return await Promise.resolve(typedHandler(args, extra)); + } + else { + const typedHandler = handler; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return await Promise.resolve(typedHandler(extra)); + } + } + /** + * Handles automatic task polling for tools with taskSupport 'optional'. + */ + async handleAutomaticTaskPolling(tool, request, extra) { + if (!extra.taskStore) { + throw new Error('No task store provided for task-capable tool.'); + } + // Validate input and create task + const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); + const handler = tool.handler; + const taskExtra = { ...extra, taskStore: extra.taskStore }; + const createTaskResult = args // undefined only if tool.inputSchema is undefined + ? await Promise.resolve(handler.createTask(args, taskExtra)) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + await Promise.resolve(handler.createTask(taskExtra)); + // Poll until completion + const taskId = createTaskResult.task.taskId; + let task = createTaskResult.task; + const pollInterval = task.pollInterval ?? 5000; + while (task.status !== 'completed' && task.status !== 'failed' && task.status !== 'cancelled') { + await new Promise(resolve => setTimeout(resolve, pollInterval)); + const updatedTask = await extra.taskStore.getTask(taskId); + if (!updatedTask) { + throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`); + } + task = updatedTask; + } + // Return the final result + return (await extra.taskStore.getTaskResult(taskId)); + } + setCompletionRequestHandler() { + if (this._completionHandlerInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)); + this.server.registerCapabilities({ + completions: {} + }); + this.server.setRequestHandler(CompleteRequestSchema, async (request) => { + switch (request.params.ref.type) { + case 'ref/prompt': + assertCompleteRequestPrompt(request); + return this.handlePromptCompletion(request, request.params.ref); + case 'ref/resource': + assertCompleteRequestResourceTemplate(request); + return this.handleResourceCompletion(request, request.params.ref); + default: + throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); + } + }); + this._completionHandlerInitialized = true; + } + async handlePromptCompletion(request, ref) { + const prompt = this._registeredPrompts[ref.name]; + if (!prompt) { + throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); + } + if (!prompt.enabled) { + throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); + } + if (!prompt.argsSchema) { + return EMPTY_COMPLETION_RESULT; + } + const promptShape = getObjectShape(prompt.argsSchema); + const field = promptShape?.[request.params.argument.name]; + if (!isCompletable(field)) { + return EMPTY_COMPLETION_RESULT; + } + const completer = getCompleter(field); + if (!completer) { + return EMPTY_COMPLETION_RESULT; + } + const suggestions = await completer(request.params.argument.value, request.params.context); + return createCompletionResult(suggestions); + } + async handleResourceCompletion(request, ref) { + const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri); + if (!template) { + if (this._registeredResources[ref.uri]) { + // Attempting to autocomplete a fixed resource URI is not an error in the spec (but probably should be). + return EMPTY_COMPLETION_RESULT; + } + throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); + } + const completer = template.resourceTemplate.completeCallback(request.params.argument.name); + if (!completer) { + return EMPTY_COMPLETION_RESULT; + } + const suggestions = await completer(request.params.argument.value, request.params.context); + return createCompletionResult(suggestions); + } + setResourceRequestHandlers() { + if (this._resourceHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)); + this.server.registerCapabilities({ + resources: { + listChanged: true + } + }); + this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => { + const resources = Object.entries(this._registeredResources) + .filter(([_, resource]) => resource.enabled) + .map(([uri, resource]) => ({ + uri, + name: resource.name, + ...resource.metadata + })); + const templateResources = []; + for (const template of Object.values(this._registeredResourceTemplates)) { + if (!template.resourceTemplate.listCallback) { + continue; + } + const result = await template.resourceTemplate.listCallback(extra); + for (const resource of result.resources) { + templateResources.push({ + ...template.metadata, + // the defined resource metadata should override the template metadata if present + ...resource + }); + } + } + return { resources: [...resources, ...templateResources] }; + }); + this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => { + const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ + name, + uriTemplate: template.resourceTemplate.uriTemplate.toString(), + ...template.metadata + })); + return { resourceTemplates }; + }); + this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { + const uri = new URL(request.params.uri); + // First check for exact resource match + const resource = this._registeredResources[uri.toString()]; + if (resource) { + if (!resource.enabled) { + throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`); + } + return resource.readCallback(uri, extra); + } + // Then check templates + for (const template of Object.values(this._registeredResourceTemplates)) { + const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); + if (variables) { + return template.readCallback(uri, variables, extra); + } + } + throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`); + }); + this._resourceHandlersInitialized = true; + } + setPromptRequestHandlers() { + if (this._promptHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)); + this.server.registerCapabilities({ + prompts: { + listChanged: true + } + }); + this.server.setRequestHandler(ListPromptsRequestSchema, () => ({ + prompts: Object.entries(this._registeredPrompts) + .filter(([, prompt]) => prompt.enabled) + .map(([name, prompt]) => { + return { + name, + title: prompt.title, + description: prompt.description, + arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined + }; + }) + })); + this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => { + const prompt = this._registeredPrompts[request.params.name]; + if (!prompt) { + throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); + } + if (!prompt.enabled) { + throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); + } + if (prompt.argsSchema) { + const argsObj = normalizeObjectSchema(prompt.argsSchema); + const parseResult = await safeParseAsync(argsObj, request.params.arguments); + if (!parseResult.success) { + const error = 'error' in parseResult ? parseResult.error : 'Unknown error'; + const errorMessage = getParseErrorMessage(error); + throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`); + } + const args = parseResult.data; + const cb = prompt.callback; + return await Promise.resolve(cb(args, extra)); + } + else { + const cb = prompt.callback; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return await Promise.resolve(cb(extra)); + } + }); + this._promptHandlersInitialized = true; + } + resource(name, uriOrTemplate, ...rest) { + let metadata; + if (typeof rest[0] === 'object') { + metadata = rest.shift(); + } + const readCallback = rest[0]; + if (typeof uriOrTemplate === 'string') { + if (this._registeredResources[uriOrTemplate]) { + throw new Error(`Resource ${uriOrTemplate} is already registered`); + } + const registeredResource = this._createRegisteredResource(name, undefined, uriOrTemplate, metadata, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } + else { + if (this._registeredResourceTemplates[name]) { + throw new Error(`Resource template ${name} is already registered`); + } + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + registerResource(name, uriOrTemplate, config, readCallback) { + if (typeof uriOrTemplate === 'string') { + if (this._registeredResources[uriOrTemplate]) { + throw new Error(`Resource ${uriOrTemplate} is already registered`); + } + const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } + else { + if (this._registeredResourceTemplates[name]) { + throw new Error(`Resource template ${name} is already registered`); + } + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + _createRegisteredResource(name, title, uri, metadata, readCallback) { + const registeredResource = { + name, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResource.update({ enabled: false }), + enable: () => registeredResource.update({ enabled: true }), + remove: () => registeredResource.update({ uri: null }), + update: updates => { + if (typeof updates.uri !== 'undefined' && updates.uri !== uri) { + delete this._registeredResources[uri]; + if (updates.uri) + this._registeredResources[updates.uri] = registeredResource; + } + if (typeof updates.name !== 'undefined') + registeredResource.name = updates.name; + if (typeof updates.title !== 'undefined') + registeredResource.title = updates.title; + if (typeof updates.metadata !== 'undefined') + registeredResource.metadata = updates.metadata; + if (typeof updates.callback !== 'undefined') + registeredResource.readCallback = updates.callback; + if (typeof updates.enabled !== 'undefined') + registeredResource.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResources[uri] = registeredResource; + return registeredResource; + } + _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { + const registeredResourceTemplate = { + resourceTemplate: template, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResourceTemplate.update({ enabled: false }), + enable: () => registeredResourceTemplate.update({ enabled: true }), + remove: () => registeredResourceTemplate.update({ name: null }), + update: updates => { + if (typeof updates.name !== 'undefined' && updates.name !== name) { + delete this._registeredResourceTemplates[name]; + if (updates.name) + this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; + } + if (typeof updates.title !== 'undefined') + registeredResourceTemplate.title = updates.title; + if (typeof updates.template !== 'undefined') + registeredResourceTemplate.resourceTemplate = updates.template; + if (typeof updates.metadata !== 'undefined') + registeredResourceTemplate.metadata = updates.metadata; + if (typeof updates.callback !== 'undefined') + registeredResourceTemplate.readCallback = updates.callback; + if (typeof updates.enabled !== 'undefined') + registeredResourceTemplate.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResourceTemplates[name] = registeredResourceTemplate; + // If the resource template has any completion callbacks, enable completions capability + const variableNames = template.uriTemplate.variableNames; + const hasCompleter = Array.isArray(variableNames) && variableNames.some(v => !!template.completeCallback(v)); + if (hasCompleter) { + this.setCompletionRequestHandler(); + } + return registeredResourceTemplate; + } + _createRegisteredPrompt(name, title, description, argsSchema, callback) { + const registeredPrompt = { + title, + description, + argsSchema: argsSchema === undefined ? undefined : objectFromShape(argsSchema), + callback, + enabled: true, + disable: () => registeredPrompt.update({ enabled: false }), + enable: () => registeredPrompt.update({ enabled: true }), + remove: () => registeredPrompt.update({ name: null }), + update: updates => { + if (typeof updates.name !== 'undefined' && updates.name !== name) { + delete this._registeredPrompts[name]; + if (updates.name) + this._registeredPrompts[updates.name] = registeredPrompt; + } + if (typeof updates.title !== 'undefined') + registeredPrompt.title = updates.title; + if (typeof updates.description !== 'undefined') + registeredPrompt.description = updates.description; + if (typeof updates.argsSchema !== 'undefined') + registeredPrompt.argsSchema = objectFromShape(updates.argsSchema); + if (typeof updates.callback !== 'undefined') + registeredPrompt.callback = updates.callback; + if (typeof updates.enabled !== 'undefined') + registeredPrompt.enabled = updates.enabled; + this.sendPromptListChanged(); + } + }; + this._registeredPrompts[name] = registeredPrompt; + // If any argument uses a Completable schema, enable completions capability + if (argsSchema) { + const hasCompletable = Object.values(argsSchema).some(field => { + const inner = field instanceof ZodOptional ? field._def?.innerType : field; + return isCompletable(inner); + }); + if (hasCompletable) { + this.setCompletionRequestHandler(); + } + } + return registeredPrompt; + } + _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) { + // Validate tool name according to SEP specification + validateAndWarnToolName(name); + const registeredTool = { + title, + description, + inputSchema: getZodSchemaObject(inputSchema), + outputSchema: getZodSchemaObject(outputSchema), + annotations, + execution, + _meta, + handler: handler, + enabled: true, + disable: () => registeredTool.update({ enabled: false }), + enable: () => registeredTool.update({ enabled: true }), + remove: () => registeredTool.update({ name: null }), + update: updates => { + if (typeof updates.name !== 'undefined' && updates.name !== name) { + if (typeof updates.name === 'string') { + validateAndWarnToolName(updates.name); + } + delete this._registeredTools[name]; + if (updates.name) + this._registeredTools[updates.name] = registeredTool; + } + if (typeof updates.title !== 'undefined') + registeredTool.title = updates.title; + if (typeof updates.description !== 'undefined') + registeredTool.description = updates.description; + if (typeof updates.paramsSchema !== 'undefined') + registeredTool.inputSchema = objectFromShape(updates.paramsSchema); + if (typeof updates.outputSchema !== 'undefined') + registeredTool.outputSchema = objectFromShape(updates.outputSchema); + if (typeof updates.callback !== 'undefined') + registeredTool.handler = updates.callback; + if (typeof updates.annotations !== 'undefined') + registeredTool.annotations = updates.annotations; + if (typeof updates._meta !== 'undefined') + registeredTool._meta = updates._meta; + if (typeof updates.enabled !== 'undefined') + registeredTool.enabled = updates.enabled; + this.sendToolListChanged(); + } + }; + this._registeredTools[name] = registeredTool; + this.setToolRequestHandlers(); + this.sendToolListChanged(); + return registeredTool; + } + /** + * tool() implementation. Parses arguments passed to overrides defined above. + */ + tool(name, ...rest) { + if (this._registeredTools[name]) { + throw new Error(`Tool ${name} is already registered`); + } + let description; + let inputSchema; + let outputSchema; + let annotations; + // Tool properties are passed as separate arguments, with omissions allowed. + // Support for this style is frozen as of protocol version 2025-03-26. Future additions + // to tool definition should *NOT* be added. + if (typeof rest[0] === 'string') { + description = rest.shift(); + } + // Handle the different overload combinations + if (rest.length > 1) { + // We have at least one more arg before the callback + const firstArg = rest[0]; + if (isZodRawShapeCompat(firstArg)) { + // We have a params schema as the first arg + inputSchema = rest.shift(); + // Check if the next arg is potentially annotations + if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShapeCompat(rest[0])) { + // Case: tool(name, paramsSchema, annotations, cb) + // Or: tool(name, description, paramsSchema, annotations, cb) + annotations = rest.shift(); + } + } + else if (typeof firstArg === 'object' && firstArg !== null) { + // Not a ZodRawShapeCompat, so must be annotations in this position + // Case: tool(name, annotations, cb) + // Or: tool(name, description, annotations, cb) + annotations = rest.shift(); + } + } + const callback = rest[0]; + return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, undefined, callback); + } + /** + * Registers a tool with a config object and callback. + */ + registerTool(name, config, cb) { + if (this._registeredTools[name]) { + throw new Error(`Tool ${name} is already registered`); + } + const { title, description, inputSchema, outputSchema, annotations, _meta } = config; + return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, _meta, cb); + } + prompt(name, ...rest) { + if (this._registeredPrompts[name]) { + throw new Error(`Prompt ${name} is already registered`); + } + let description; + if (typeof rest[0] === 'string') { + description = rest.shift(); + } + let argsSchema; + if (rest.length > 1) { + argsSchema = rest.shift(); + } + const cb = rest[0]; + const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Registers a prompt with a config object and callback. + */ + registerPrompt(name, config, cb) { + if (this._registeredPrompts[name]) { + throw new Error(`Prompt ${name} is already registered`); + } + const { title, description, argsSchema } = config; + const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Checks if the server is connected to a transport. + * @returns True if the server is connected + */ + isConnected() { + return this.server.transport !== undefined; + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + async sendLoggingMessage(params, sessionId) { + return this.server.sendLoggingMessage(params, sessionId); + } + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged() { + if (this.isConnected()) { + this.server.sendResourceListChanged(); + } + } + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged() { + if (this.isConnected()) { + this.server.sendToolListChanged(); + } + } + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged() { + if (this.isConnected()) { + this.server.sendPromptListChanged(); + } + } +} +/** + * A resource template combines a URI pattern with optional functionality to enumerate + * all resources matching that pattern. + */ +export class ResourceTemplate { + constructor(uriTemplate, _callbacks) { + this._callbacks = _callbacks; + this._uriTemplate = typeof uriTemplate === 'string' ? new UriTemplate(uriTemplate) : uriTemplate; + } + /** + * Gets the URI template pattern. + */ + get uriTemplate() { + return this._uriTemplate; + } + /** + * Gets the list callback, if one was provided. + */ + get listCallback() { + return this._callbacks.list; + } + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable) { + return this._callbacks.complete?.[variable]; + } +} +const EMPTY_OBJECT_JSON_SCHEMA = { + type: 'object', + properties: {} +}; +/** + * Checks if a value looks like a Zod schema by checking for parse/safeParse methods. + */ +function isZodTypeLike(value) { + return (value !== null && + typeof value === 'object' && + 'parse' in value && + typeof value.parse === 'function' && + 'safeParse' in value && + typeof value.safeParse === 'function'); +} +/** + * Checks if an object is a Zod schema instance (v3 or v4). + * + * Zod schemas have internal markers: + * - v3: `_def` property + * - v4: `_zod` property + * + * This includes transformed schemas like z.preprocess(), z.transform(), z.pipe(). + */ +function isZodSchemaInstance(obj) { + return '_def' in obj || '_zod' in obj || isZodTypeLike(obj); +} +/** + * Checks if an object is a "raw shape" - a plain object where values are Zod schemas. + * + * Raw shapes are used as shorthand: `{ name: z.string() }` instead of `z.object({ name: z.string() })`. + * + * IMPORTANT: This must NOT match actual Zod schema instances (like z.preprocess, z.pipe), + * which have internal properties that could be mistaken for schema values. + */ +function isZodRawShapeCompat(obj) { + if (typeof obj !== 'object' || obj === null) { + return false; + } + // If it's already a Zod schema instance, it's NOT a raw shape + if (isZodSchemaInstance(obj)) { + return false; + } + // Empty objects are valid raw shapes (tools with no parameters) + if (Object.keys(obj).length === 0) { + return true; + } + // A raw shape has at least one property that is a Zod schema + return Object.values(obj).some(isZodTypeLike); +} +/** + * Converts a provided Zod schema to a Zod object if it is a ZodRawShapeCompat, + * otherwise returns the schema as is. + */ +function getZodSchemaObject(schema) { + if (!schema) { + return undefined; + } + if (isZodRawShapeCompat(schema)) { + return objectFromShape(schema); + } + return schema; +} +function promptArgumentsFromSchema(schema) { + const shape = getObjectShape(schema); + if (!shape) + return []; + return Object.entries(shape).map(([name, field]) => { + // Get description - works for both v3 and v4 + const description = getSchemaDescription(field); + // Check if optional - works for both v3 and v4 + const isOptional = isSchemaOptional(field); + return { + name, + description, + required: !isOptional + }; + }); +} +function getMethodValue(schema) { + const shape = getObjectShape(schema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + // Extract literal value - works for both v3 and v4 + const value = getLiteralValue(methodSchema); + if (typeof value === 'string') { + return value; + } + throw new Error('Schema method literal must be a string'); +} +function createCompletionResult(suggestions) { + return { + completion: { + values: suggestions.slice(0, 100), + total: suggestions.length, + hasMore: suggestions.length > 100 + } + }; +} +const EMPTY_COMPLETION_RESULT = { + completion: { + values: [], + hasMore: false + } +}; +//# sourceMappingURL=mcp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js.map new file mode 100644 index 000000000..162f7e2aa --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mcp.js","sourceRoot":"","sources":["../../../src/server/mcp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAiB,MAAM,YAAY,CAAC;AACnD,OAAO,EAMH,qBAAqB,EACrB,cAAc,EACd,cAAc,EACd,eAAe,EACf,oBAAoB,EACpB,oBAAoB,EACpB,gBAAgB,EAChB,eAAe,EAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAKH,QAAQ,EACR,SAAS,EAOT,kCAAkC,EAClC,yBAAyB,EACzB,sBAAsB,EACtB,qBAAqB,EACrB,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EAcrB,2BAA2B,EAC3B,qCAAqC,EAGxC,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAa,MAAM,0BAA0B,CAAC;AAIlE,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAC1E,OAAO,EAAE,0BAA0B,EAAE,MAAM,qCAAqC,CAAC;AAEjF,OAAO,EAAE,WAAW,EAAE,MAAM,KAAK,CAAC;AAElC;;;;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W,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC;YACjC,KAAK,EAAE,WAAW,CAAC,MAAM;YACzB,OAAO,EAAE,WAAW,CAAC,MAAM,GAAG,GAAG;SACpC;KACJ,CAAC;AACN,CAAC;AAED,MAAM,uBAAuB,GAAmB;IAC5C,UAAU,EAAE;QACR,MAAM,EAAE,EAAE;QACV,OAAO,EAAE,KAAK;KACjB;CACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/middleware/hostHeaderValidation.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/middleware/hostHeaderValidation.d.ts new file mode 100644 index 000000000..cb526d8fa --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/middleware/hostHeaderValidation.d.ts @@ -0,0 +1,32 @@ +import { RequestHandler } from 'express'; +/** + * Express middleware for DNS rebinding protection. + * Validates Host header hostname (port-agnostic) against an allowed list. + * + * This is particularly important for servers without authorization or HTTPS, + * such as localhost servers or development servers. DNS rebinding attacks can + * bypass same-origin policy by manipulating DNS to point a domain to a + * localhost address, allowing malicious websites to access your local server. + * + * @param allowedHostnames - List of allowed hostnames (without ports). + * For IPv6, provide the address with brackets (e.g., '[::1]'). + * @returns Express middleware function + * + * @example + * ```typescript + * const middleware = hostHeaderValidation(['localhost', '127.0.0.1', '[::1]']); + * app.use(middleware); + * ``` + */ +export declare function hostHeaderValidation(allowedHostnames: string[]): RequestHandler; +/** + * Convenience middleware for localhost DNS rebinding protection. + * Allows only localhost, 127.0.0.1, and [::1] (IPv6 localhost) hostnames. + * + * @example + * ```typescript + * app.use(localhostHostValidation()); + * ``` + */ +export declare function localhostHostValidation(): RequestHandler; +//# sourceMappingURL=hostHeaderValidation.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/middleware/hostHeaderValidation.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/middleware/hostHeaderValidation.d.ts.map new file mode 100644 index 000000000..c550324ec --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/middleware/hostHeaderValidation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hostHeaderValidation.d.ts","sourceRoot":"","sources":["../../../../src/server/middleware/hostHeaderValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmC,cAAc,EAAE,MAAM,SAAS,CAAC;AAE1E;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,oBAAoB,CAAC,gBAAgB,EAAE,MAAM,EAAE,GAAG,cAAc,CA4C/E;AAED;;;;;;;;GAQG;AACH,wBAAgB,uBAAuB,IAAI,cAAc,CAExD"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/middleware/hostHeaderValidation.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/middleware/hostHeaderValidation.js new file mode 100644 index 000000000..79922a27b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/middleware/hostHeaderValidation.js @@ -0,0 +1,76 @@ +/** + * Express middleware for DNS rebinding protection. + * Validates Host header hostname (port-agnostic) against an allowed list. + * + * This is particularly important for servers without authorization or HTTPS, + * such as localhost servers or development servers. DNS rebinding attacks can + * bypass same-origin policy by manipulating DNS to point a domain to a + * localhost address, allowing malicious websites to access your local server. + * + * @param allowedHostnames - List of allowed hostnames (without ports). + * For IPv6, provide the address with brackets (e.g., '[::1]'). + * @returns Express middleware function + * + * @example + * ```typescript + * const middleware = hostHeaderValidation(['localhost', '127.0.0.1', '[::1]']); + * app.use(middleware); + * ``` + */ +export function hostHeaderValidation(allowedHostnames) { + return (req, res, next) => { + const hostHeader = req.headers.host; + if (!hostHeader) { + res.status(403).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Missing Host header' + }, + id: null + }); + return; + } + // Use URL API to parse hostname (handles IPv4, IPv6, and regular hostnames) + let hostname; + try { + hostname = new URL(`http://${hostHeader}`).hostname; + } + catch { + res.status(403).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: `Invalid Host header: ${hostHeader}` + }, + id: null + }); + return; + } + if (!allowedHostnames.includes(hostname)) { + res.status(403).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: `Invalid Host: ${hostname}` + }, + id: null + }); + return; + } + next(); + }; +} +/** + * Convenience middleware for localhost DNS rebinding protection. + * Allows only localhost, 127.0.0.1, and [::1] (IPv6 localhost) hostnames. + * + * @example + * ```typescript + * app.use(localhostHostValidation()); + * ``` + */ +export function localhostHostValidation() { + return hostHeaderValidation(['localhost', '127.0.0.1', '[::1]']); +} +//# sourceMappingURL=hostHeaderValidation.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/middleware/hostHeaderValidation.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/middleware/hostHeaderValidation.js.map new file mode 100644 index 000000000..f04fdfd1d --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/middleware/hostHeaderValidation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hostHeaderValidation.js","sourceRoot":"","sources":["../../../../src/server/middleware/hostHeaderValidation.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,oBAAoB,CAAC,gBAA0B;IAC3D,OAAO,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;QACvD,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC;QACpC,IAAI,CAAC,UAAU,EAAE,CAAC;YACd,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACjB,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE;oBACH,IAAI,EAAE,CAAC,KAAK;oBACZ,OAAO,EAAE,qBAAqB;iBACjC;gBACD,EAAE,EAAE,IAAI;aACX,CAAC,CAAC;YACH,OAAO;QACX,CAAC;QAED,4EAA4E;QAC5E,IAAI,QAAgB,CAAC;QACrB,IAAI,CAAC;YACD,QAAQ,GAAG,IAAI,GAAG,CAAC,UAAU,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC;QACxD,CAAC;QAAC,MAAM,CAAC;YACL,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACjB,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE;oBACH,IAAI,EAAE,CAAC,KAAK;oBACZ,OAAO,EAAE,wBAAwB,UAAU,EAAE;iBAChD;gBACD,EAAE,EAAE,IAAI;aACX,CAAC,CAAC;YACH,OAAO;QACX,CAAC;QAED,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;YACvC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACjB,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE;oBACH,IAAI,EAAE,CAAC,KAAK;oBACZ,OAAO,EAAE,iBAAiB,QAAQ,EAAE;iBACvC;gBACD,EAAE,EAAE,IAAI;aACX,CAAC,CAAC;YACH,OAAO;QACX,CAAC;QACD,IAAI,EAAE,CAAC;IACX,CAAC,CAAC;AACN,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,uBAAuB;IACnC,OAAO,oBAAoB,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC,CAAC;AACrE,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.d.ts new file mode 100644 index 000000000..7fa42a58f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.d.ts @@ -0,0 +1,82 @@ +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage, MessageExtraInfo } from '../types.js'; +import { AuthInfo } from './auth/types.js'; +/** + * Configuration options for SSEServerTransport. + */ +export interface SSEServerTransportOptions { + /** + * List of allowed host header values for DNS rebinding protection. + * If not specified, host validation is disabled. + * @deprecated Use the `hostHeaderValidation` middleware from `@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js` instead, + * or use `createMcpExpressApp` from `@modelcontextprotocol/sdk/server/express.js` which includes localhost protection by default. + */ + allowedHosts?: string[]; + /** + * List of allowed origin header values for DNS rebinding protection. + * If not specified, origin validation is disabled. + * @deprecated Use the `hostHeaderValidation` middleware from `@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js` instead, + * or use `createMcpExpressApp` from `@modelcontextprotocol/sdk/server/express.js` which includes localhost protection by default. + */ + allowedOrigins?: string[]; + /** + * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). + * Default is false for backwards compatibility. + * @deprecated Use the `hostHeaderValidation` middleware from `@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js` instead, + * or use `createMcpExpressApp` from `@modelcontextprotocol/sdk/server/express.js` which includes localhost protection by default. + */ + enableDnsRebindingProtection?: boolean; +} +/** + * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. + * + * This transport is only available in Node.js environments. + * @deprecated SSEServerTransport is deprecated. Use StreamableHTTPServerTransport instead. + */ +export declare class SSEServerTransport implements Transport { + private _endpoint; + private res; + private _sseResponse?; + private _sessionId; + private _options; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; + /** + * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. + */ + constructor(_endpoint: string, res: ServerResponse, options?: SSEServerTransportOptions); + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + private validateRequestHeaders; + /** + * Handles the initial SSE connection request. + * + * This should be called when a GET request is made to establish the SSE stream. + */ + start(): Promise; + /** + * Handles incoming POST messages. + * + * This should be called when a POST request is made to send a message to the server. + */ + handlePostMessage(req: IncomingMessage & { + auth?: AuthInfo; + }, res: ServerResponse, parsedBody?: unknown): Promise; + /** + * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. + */ + handleMessage(message: unknown, extra?: MessageExtraInfo): Promise; + close(): Promise; + send(message: JSONRPCMessage): Promise; + /** + * Returns the session ID for this transport. + * + * This can be used to route incoming POST requests. + */ + get sessionId(): string; +} +//# sourceMappingURL=sse.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.d.ts.map new file mode 100644 index 000000000..c94a521d2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../../src/server/sse.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAwB,gBAAgB,EAAe,MAAM,aAAa,CAAC;AAGlG,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAK3C;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACtC;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IAExB;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAE1B;;;;;OAKG;IACH,4BAA4B,CAAC,EAAE,OAAO,CAAC;CAC1C;AAED;;;;;GAKG;AACH,qBAAa,kBAAmB,YAAW,SAAS;IAY5C,OAAO,CAAC,SAAS;IACjB,OAAO,CAAC,GAAG;IAZf,OAAO,CAAC,YAAY,CAAC,CAAiB;IACtC,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,QAAQ,CAA4B;IAC5C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAExE;;OAEG;gBAES,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,cAAc,EAC3B,OAAO,CAAC,EAAE,yBAAyB;IAMvC;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAyB9B;;;;OAIG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA8B5B;;;;OAIG;IACG,iBAAiB,CAAC,GAAG,EAAE,eAAe,GAAG;QAAE,IAAI,CAAC,EAAE,QAAQ,CAAA;KAAE,EAAE,GAAG,EAAE,cAAc,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IA+C7H;;OAEG;IACG,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;IAYxE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAMtB,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAQlD;;;;OAIG;IACH,IAAI,SAAS,IAAI,MAAM,CAEtB;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.js new file mode 100644 index 000000000..5d0cd8d89 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.js @@ -0,0 +1,158 @@ +import { randomUUID } from 'node:crypto'; +import { JSONRPCMessageSchema } from '../types.js'; +import getRawBody from 'raw-body'; +import contentType from 'content-type'; +import { URL } from 'node:url'; +const MAXIMUM_MESSAGE_SIZE = '4mb'; +/** + * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. + * + * This transport is only available in Node.js environments. + * @deprecated SSEServerTransport is deprecated. Use StreamableHTTPServerTransport instead. + */ +export class SSEServerTransport { + /** + * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. + */ + constructor(_endpoint, res, options) { + this._endpoint = _endpoint; + this.res = res; + this._sessionId = randomUUID(); + this._options = options || { enableDnsRebindingProtection: false }; + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + validateRequestHeaders(req) { + // Skip validation if protection is not enabled + if (!this._options.enableDnsRebindingProtection) { + return undefined; + } + // Validate Host header if allowedHosts is configured + if (this._options.allowedHosts && this._options.allowedHosts.length > 0) { + const hostHeader = req.headers.host; + if (!hostHeader || !this._options.allowedHosts.includes(hostHeader)) { + return `Invalid Host header: ${hostHeader}`; + } + } + // Validate Origin header if allowedOrigins is configured + if (this._options.allowedOrigins && this._options.allowedOrigins.length > 0) { + const originHeader = req.headers.origin; + if (originHeader && !this._options.allowedOrigins.includes(originHeader)) { + return `Invalid Origin header: ${originHeader}`; + } + } + return undefined; + } + /** + * Handles the initial SSE connection request. + * + * This should be called when a GET request is made to establish the SSE stream. + */ + async start() { + if (this._sseResponse) { + throw new Error('SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.'); + } + this.res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }); + // Send the endpoint event + // Use a dummy base URL because this._endpoint is relative. + // This allows using URL/URLSearchParams for robust parameter handling. + const dummyBase = 'http://localhost'; // Any valid base works + const endpointUrl = new URL(this._endpoint, dummyBase); + endpointUrl.searchParams.set('sessionId', this._sessionId); + // Reconstruct the relative URL string (pathname + search + hash) + const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash; + this.res.write(`event: endpoint\ndata: ${relativeUrlWithSession}\n\n`); + this._sseResponse = this.res; + this.res.on('close', () => { + this._sseResponse = undefined; + this.onclose?.(); + }); + } + /** + * Handles incoming POST messages. + * + * This should be called when a POST request is made to send a message to the server. + */ + async handlePostMessage(req, res, parsedBody) { + if (!this._sseResponse) { + const message = 'SSE connection not established'; + res.writeHead(500).end(message); + throw new Error(message); + } + // Validate request headers for DNS rebinding protection + const validationError = this.validateRequestHeaders(req); + if (validationError) { + res.writeHead(403).end(validationError); + this.onerror?.(new Error(validationError)); + return; + } + const authInfo = req.auth; + const requestInfo = { headers: req.headers }; + let body; + try { + const ct = contentType.parse(req.headers['content-type'] ?? ''); + if (ct.type !== 'application/json') { + throw new Error(`Unsupported content-type: ${ct.type}`); + } + body = + parsedBody ?? + (await getRawBody(req, { + limit: MAXIMUM_MESSAGE_SIZE, + encoding: ct.parameters.charset ?? 'utf-8' + })); + } + catch (error) { + res.writeHead(400).end(String(error)); + this.onerror?.(error); + return; + } + try { + await this.handleMessage(typeof body === 'string' ? JSON.parse(body) : body, { requestInfo, authInfo }); + } + catch { + res.writeHead(400).end(`Invalid message: ${body}`); + return; + } + res.writeHead(202).end('Accepted'); + } + /** + * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. + */ + async handleMessage(message, extra) { + let parsedMessage; + try { + parsedMessage = JSONRPCMessageSchema.parse(message); + } + catch (error) { + this.onerror?.(error); + throw error; + } + this.onmessage?.(parsedMessage, extra); + } + async close() { + this._sseResponse?.end(); + this._sseResponse = undefined; + this.onclose?.(); + } + async send(message) { + if (!this._sseResponse) { + throw new Error('Not connected'); + } + this._sseResponse.write(`event: message\ndata: ${JSON.stringify(message)}\n\n`); + } + /** + * Returns the session ID for this transport. + * + * This can be used to route incoming POST requests. + */ + get sessionId() { + return this._sessionId; + } +} +//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.js.map new file mode 100644 index 000000000..55ad8aa97 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.js.map @@ -0,0 +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EAAE,EAAE,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,OAAuB;QAC9B,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;QACrC,CAAC;QAED,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,yBAAyB,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpF,CAAC;IAED;;;;OAIG;IACH,IAAI,SAAS;QACT,OAAO,IAAI,CAAC,UAAU,CAAC;IAC3B,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.d.ts new file mode 100644 index 000000000..83af57219 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.d.ts @@ -0,0 +1,28 @@ +import { Readable, Writable } from 'node:stream'; +import { JSONRPCMessage } from '../types.js'; +import { Transport } from '../shared/transport.js'; +/** + * Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout. + * + * This transport is only available in Node.js environments. + */ +export declare class StdioServerTransport implements Transport { + private _stdin; + private _stdout; + private _readBuffer; + private _started; + constructor(_stdin?: Readable, _stdout?: Writable); + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + _ondata: (chunk: Buffer) => void; + _onerror: (error: Error) => void; + /** + * Starts listening for messages on stdin. + */ + start(): Promise; + private processReadBuffer; + close(): Promise; + send(message: JSONRPCMessage): Promise; +} +//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.d.ts.map new file mode 100644 index 000000000..fdd2dfe48 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/server/stdio.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,SAAS;IAK9C,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IALnB,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,QAAQ,CAAS;gBAGb,MAAM,GAAE,QAAwB,EAChC,OAAO,GAAE,QAAyB;IAG9C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;IAG9C,OAAO,UAAW,MAAM,UAGtB;IACF,QAAQ,UAAW,KAAK,UAEtB;IAEF;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAY5B,OAAO,CAAC,iBAAiB;IAenB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAkB5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAU/C"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js new file mode 100644 index 000000000..727fe70a5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js @@ -0,0 +1,75 @@ +import process from 'node:process'; +import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; +/** + * Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout. + * + * This transport is only available in Node.js environments. + */ +export class StdioServerTransport { + constructor(_stdin = process.stdin, _stdout = process.stdout) { + this._stdin = _stdin; + this._stdout = _stdout; + this._readBuffer = new ReadBuffer(); + this._started = false; + // Arrow functions to bind `this` properly, while maintaining function identity. + this._ondata = (chunk) => { + this._readBuffer.append(chunk); + this.processReadBuffer(); + }; + this._onerror = (error) => { + this.onerror?.(error); + }; + } + /** + * Starts listening for messages on stdin. + */ + async start() { + if (this._started) { + throw new Error('StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.'); + } + this._started = true; + this._stdin.on('data', this._ondata); + this._stdin.on('error', this._onerror); + } + processReadBuffer() { + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + this.onmessage?.(message); + } + catch (error) { + this.onerror?.(error); + } + } + } + async close() { + // Remove our event listeners first + this._stdin.off('data', this._ondata); + this._stdin.off('error', this._onerror); + // Check if we were the only data listener + const remainingDataListeners = this._stdin.listenerCount('data'); + if (remainingDataListeners === 0) { + // Only pause stdin if we were the only listener + // This prevents interfering with other parts of the application that might be using stdin + this._stdin.pause(); + } + // Clear the buffer and notify closure + this._readBuffer.clear(); + this.onclose?.(); + } + send(message) { + return new Promise(resolve => { + const json = serializeMessage(message); + if (this._stdout.write(json)) { + resolve(); + } + else { + this._stdout.once('drain', resolve); + } + }); + } +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js.map new file mode 100644 index 000000000..307a74403 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/server/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,cAAc,CAAC;AAEnC,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAIlE;;;;GAIG;AACH,MAAM,OAAO,oBAAo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,CAAC;QACL,CAAC;IACL,CAAC;IAED,KAAK,CAAC,KAAK;QACP,mCAAmC;QACnC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACtC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;QAExC,0CAA0C;QAC1C,MAAM,sBAAsB,GAAG,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;QACjE,IAAI,sBAAsB,KAAK,CAAC,EAAE,CAAC;YAC/B,gDAAgD;YAChD,0FAA0F;YAC1F,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACxB,CAAC;QAED,sCAAsC;QACtC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;IACrB,CAAC;IAED,IAAI,CAAC,OAAuB;QACxB,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;YACzB,MAAM,IAAI,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;YACvC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC3B,OAAO,EAAE,CAAC;YACd,CAAC;iBAAM,CAAC;gBACJ,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.d.ts new file mode 100644 index 000000000..5d5564bd1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.d.ts @@ -0,0 +1,122 @@ +/** + * Node.js HTTP Streamable HTTP Server Transport + * + * This is a thin wrapper around `WebStandardStreamableHTTPServerTransport` that provides + * compatibility with Node.js HTTP server (IncomingMessage/ServerResponse). + * + * For web-standard environments (Cloudflare Workers, Deno, Bun), use `WebStandardStreamableHTTPServerTransport` directly. + */ +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Transport } from '../shared/transport.js'; +import { AuthInfo } from './auth/types.js'; +import { MessageExtraInfo, JSONRPCMessage, RequestId } from '../types.js'; +import { WebStandardStreamableHTTPServerTransportOptions, EventStore, StreamId, EventId } from './webStandardStreamableHttp.js'; +export type { EventStore, StreamId, EventId }; +/** + * Configuration options for StreamableHTTPServerTransport + * + * This is an alias for WebStandardStreamableHTTPServerTransportOptions for backward compatibility. + */ +export type StreamableHTTPServerTransportOptions = WebStandardStreamableHTTPServerTransportOptions; +/** + * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It supports both SSE streaming and direct HTTP responses. + * + * This is a wrapper around `WebStandardStreamableHTTPServerTransport` that provides Node.js HTTP compatibility. + * It uses the `@hono/node-server` library to convert between Node.js HTTP and Web Standard APIs. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: () => randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Using with pre-parsed request body + * app.post('/mcp', (req, res) => { + * transport.handleRequest(req, res, req.body); + * }); + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +export declare class StreamableHTTPServerTransport implements Transport { + private _webStandardTransport; + private _requestListener; + private _requestContext; + constructor(options?: StreamableHTTPServerTransportOptions); + /** + * Gets the session ID for this transport instance. + */ + get sessionId(): string | undefined; + /** + * Sets callback for when the transport is closed. + */ + set onclose(handler: (() => void) | undefined); + get onclose(): (() => void) | undefined; + /** + * Sets callback for transport errors. + */ + set onerror(handler: ((error: Error) => void) | undefined); + get onerror(): ((error: Error) => void) | undefined; + /** + * Sets callback for incoming messages. + */ + set onmessage(handler: ((message: JSONRPCMessage, extra?: MessageExtraInfo) => void) | undefined); + get onmessage(): ((message: JSONRPCMessage, extra?: MessageExtraInfo) => void) | undefined; + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + start(): Promise; + /** + * Closes the transport and all active connections. + */ + close(): Promise; + /** + * Sends a JSON-RPC message through the transport. + */ + send(message: JSONRPCMessage, options?: { + relatedRequestId?: RequestId; + }): Promise; + /** + * Handles an incoming HTTP request, whether GET or POST. + * + * This method converts Node.js HTTP objects to Web Standard Request/Response + * and delegates to the underlying WebStandardStreamableHTTPServerTransport. + * + * @param req - Node.js IncomingMessage, optionally with auth property from middleware + * @param res - Node.js ServerResponse + * @param parsedBody - Optional pre-parsed body from body-parser middleware + */ + handleRequest(req: IncomingMessage & { + auth?: AuthInfo; + }, res: ServerResponse, parsedBody?: unknown): Promise; + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId: RequestId): void; + /** + * Close the standalone GET SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream(): void; +} +//# sourceMappingURL=streamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.d.ts.map new file mode 100644 index 000000000..f9e54b43e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.d.ts","sourceRoot":"","sources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,KAAK,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC,GAAG,SAAS,EAE/F;IAED,IAAI,SAAS,IAAI,CAAC,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC,GAAG,SAAS,CAEzF;IAED;;;OAGG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B;;OAEG;IACG,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAI9F;;;;;;;;;OASG;IACG,aAAa,CAAC,GAAG,EAAE,eAAe,GAAG;QAAE,IAAI,CAAC,EAAE,QAAQ,CAAA;KAAE,EAAE,GAAG,EAAE,cAAc,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAuBzH;;;;OAIG;IACH,cAAc,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI;IAI1C;;;OAGG;IACH,wBAAwB,IAAI,IAAI;CAGnC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js new file mode 100644 index 000000000..143ee17c1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js @@ -0,0 +1,161 @@ +/** + * Node.js HTTP Streamable HTTP Server Transport + * + * This is a thin wrapper around `WebStandardStreamableHTTPServerTransport` that provides + * compatibility with Node.js HTTP server (IncomingMessage/ServerResponse). + * + * For web-standard environments (Cloudflare Workers, Deno, Bun), use `WebStandardStreamableHTTPServerTransport` directly. + */ +import { getRequestListener } from '@hono/node-server'; +import { WebStandardStreamableHTTPServerTransport } from './webStandardStreamableHttp.js'; +/** + * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It supports both SSE streaming and direct HTTP responses. + * + * This is a wrapper around `WebStandardStreamableHTTPServerTransport` that provides Node.js HTTP compatibility. + * It uses the `@hono/node-server` library to convert between Node.js HTTP and Web Standard APIs. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: () => randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Using with pre-parsed request body + * app.post('/mcp', (req, res) => { + * transport.handleRequest(req, res, req.body); + * }); + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +export class StreamableHTTPServerTransport { + constructor(options = {}) { + // Store auth and parsedBody per request for passing through to handleRequest + this._requestContext = new WeakMap(); + this._webStandardTransport = new WebStandardStreamableHTTPServerTransport(options); + // Create a request listener that wraps the web standard transport + // getRequestListener converts Node.js HTTP to Web Standard and properly handles SSE streaming + // overrideGlobalObjects: false prevents Hono from overwriting global Response, which would + // break frameworks like Next.js whose response classes extend the native Response + this._requestListener = getRequestListener(async (webRequest) => { + // Get context if available (set during handleRequest) + const context = this._requestContext.get(webRequest); + return this._webStandardTransport.handleRequest(webRequest, { + authInfo: context?.authInfo, + parsedBody: context?.parsedBody + }); + }, { overrideGlobalObjects: false }); + } + /** + * Gets the session ID for this transport instance. + */ + get sessionId() { + return this._webStandardTransport.sessionId; + } + /** + * Sets callback for when the transport is closed. + */ + set onclose(handler) { + this._webStandardTransport.onclose = handler; + } + get onclose() { + return this._webStandardTransport.onclose; + } + /** + * Sets callback for transport errors. + */ + set onerror(handler) { + this._webStandardTransport.onerror = handler; + } + get onerror() { + return this._webStandardTransport.onerror; + } + /** + * Sets callback for incoming messages. + */ + set onmessage(handler) { + this._webStandardTransport.onmessage = handler; + } + get onmessage() { + return this._webStandardTransport.onmessage; + } + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start() { + return this._webStandardTransport.start(); + } + /** + * Closes the transport and all active connections. + */ + async close() { + return this._webStandardTransport.close(); + } + /** + * Sends a JSON-RPC message through the transport. + */ + async send(message, options) { + return this._webStandardTransport.send(message, options); + } + /** + * Handles an incoming HTTP request, whether GET or POST. + * + * This method converts Node.js HTTP objects to Web Standard Request/Response + * and delegates to the underlying WebStandardStreamableHTTPServerTransport. + * + * @param req - Node.js IncomingMessage, optionally with auth property from middleware + * @param res - Node.js ServerResponse + * @param parsedBody - Optional pre-parsed body from body-parser middleware + */ + async handleRequest(req, res, parsedBody) { + // Store context for this request to pass through auth and parsedBody + // We need to intercept the request creation to attach this context + const authInfo = req.auth; + // Create a custom handler that includes our context + // overrideGlobalObjects: false prevents Hono from overwriting global Response, which would + // break frameworks like Next.js whose response classes extend the native Response + const handler = getRequestListener(async (webRequest) => { + return this._webStandardTransport.handleRequest(webRequest, { + authInfo, + parsedBody + }); + }, { overrideGlobalObjects: false }); + // Delegate to the request listener which handles all the Node.js <-> Web Standard conversion + // including proper SSE streaming support + await handler(req, res); + } + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId) { + this._webStandardTransport.closeSSEStream(requestId); + } + /** + * Close the standalone GET SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream() { + this._webStandardTransport.closeStandaloneSSEStream(); + } +} +//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js.map new file mode 100644 index 000000000..b03f1f2a1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.js","sourceRoot":"","sources":["../../../src/server/streamableHttp.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAIvD,OAAO,EACH,wCAAwC,EAK3C,MAAM,gCAAgC,CAAC;AAYxC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,MAAM,OAAO,6BAA6B;IAMtC,YAAY,UAAgD,EAAE;QAH9D,6EAA6E;QACrE,oBAAe,GAAoE,IAAI,OAAO,EAAE,CAAC;QAGrG,IAAI,CAAC,qBAAqB,GAAG,IAAI,wCAAwC,CAAC,OAAO,CAAC,CAAC;QAEnF,kEAAkE;QAClE,8FAA8F;QAC9F,2FAA2F;QAC3F,kFAAkF;QAClF,IAAI,CAAC,gBAAgB,GAAG,kBAAkB,CACtC,KAAK,EAAE,UAAmB,EAAE,EAAE;YAC1B,sDAAsD;YACtD,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YACrD,OAAO,IAAI,CAAC,qBAAqB,CAAC,aAAa,CAAC,UAAU,EAAE;gBACxD,QAAQ,EAAE,OAAO,EAAE,QAAQ;gBAC3B,UAAU,EAAE,OAAO,EAAE,UAAU;aAClC,CAAC,CAAC;QACP,CAAC,EACD,EAAE,qBAAqB,EAAE,KAAK,EAAE,CACnC,CAAC;IACN,CAAC;IAED;;OAEG;IACH,IAAI,SAAS;QACT,OAAO,IAAI,CAAC,qBAAqB,CAAC,SAAS,CAAC;IAChD,CAAC;IAED;;OAEG;IACH,IAAI,OAAO,CAAC,OAAiC;QACzC,IAAI,CAAC,qBAAqB,CAAC,OAAO,GAAG,OAAO,CAAC;IACjD,CAAC;IAED,IAAI,OA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AAK,EAAE,CACnC,CAAC;QAEF,6FAA6F;QAC7F,yCAAyC;QACzC,MAAM,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IAC5B,CAAC;IAED;;;;OAIG;IACH,cAAc,CAAC,SAAoB;QAC/B,IAAI,CAAC,qBAAqB,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;IACzD,CAAC;IAED;;;OAGG;IACH,wBAAwB;QACpB,IAAI,CAAC,qBAAqB,CAAC,wBAAwB,EAAE,CAAC;IAC1D,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.d.ts new file mode 100644 index 000000000..d8f3ca64b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.d.ts @@ -0,0 +1,267 @@ +/** + * Web Standards Streamable HTTP Server Transport + * + * This is the core transport implementation using Web Standard APIs (Request, Response, ReadableStream). + * It can run on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. + * + * For Node.js Express/HTTP compatibility, use `StreamableHTTPServerTransport` which wraps this transport. + */ +import { Transport } from '../shared/transport.js'; +import { AuthInfo } from './auth/types.js'; +import { MessageExtraInfo, JSONRPCMessage, RequestId } from '../types.js'; +export type StreamId = string; +export type EventId = string; +/** + * Interface for resumability support via event storage + */ +export interface EventStore { + /** + * Stores an event for later retrieval + * @param streamId ID of the stream the event belongs to + * @param message The JSON-RPC message to store + * @returns The generated event ID for the stored event + */ + storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise; + /** + * Get the stream ID associated with a given event ID. + * @param eventId The event ID to look up + * @returns The stream ID, or undefined if not found + * + * Optional: If not provided, the SDK will use the streamId returned by + * replayEventsAfter for stream mapping. + */ + getStreamIdForEventId?(eventId: EventId): Promise; + replayEventsAfter(lastEventId: EventId, { send }: { + send: (eventId: EventId, message: JSONRPCMessage) => Promise; + }): Promise; +} +/** + * Configuration options for WebStandardStreamableHTTPServerTransport + */ +export interface WebStandardStreamableHTTPServerTransportOptions { + /** + * Function that generates a session ID for the transport. + * The session ID SHOULD be globally unique and cryptographically secure (e.g., a securely generated UUID, a JWT, or a cryptographic hash) + * + * If not provided, session management is disabled (stateless mode). + */ + sessionIdGenerator?: () => string; + /** + * A callback for session initialization events + * This is called when the server initializes a new session. + * Useful in cases when you need to register multiple mcp sessions + * and need to keep track of them. + * @param sessionId The generated session ID + */ + onsessioninitialized?: (sessionId: string) => void | Promise; + /** + * A callback for session close events + * This is called when the server closes a session due to a DELETE request. + * Useful in cases when you need to clean up resources associated with the session. + * Note that this is different from the transport closing, if you are handling + * HTTP requests from multiple nodes you might want to close each + * WebStandardStreamableHTTPServerTransport after a request is completed while still keeping the + * session open/running. + * @param sessionId The session ID that was closed + */ + onsessionclosed?: (sessionId: string) => void | Promise; + /** + * If true, the server will return JSON responses instead of starting an SSE stream. + * This can be useful for simple request/response scenarios without streaming. + * Default is false (SSE streams are preferred). + */ + enableJsonResponse?: boolean; + /** + * Event store for resumability support + * If provided, resumability will be enabled, allowing clients to reconnect and resume messages + */ + eventStore?: EventStore; + /** + * List of allowed host header values for DNS rebinding protection. + * If not specified, host validation is disabled. + * @deprecated Use external middleware for host validation instead. + */ + allowedHosts?: string[]; + /** + * List of allowed origin header values for DNS rebinding protection. + * If not specified, origin validation is disabled. + * @deprecated Use external middleware for origin validation instead. + */ + allowedOrigins?: string[]; + /** + * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). + * Default is false for backwards compatibility. + * @deprecated Use external middleware for DNS rebinding protection instead. + */ + enableDnsRebindingProtection?: boolean; + /** + * Retry interval in milliseconds to suggest to clients in SSE retry field. + * When set, the server will send a retry field in SSE priming events to control + * client reconnection timing for polling behavior. + */ + retryInterval?: number; +} +/** + * Options for handling a request + */ +export interface HandleRequestOptions { + /** + * Pre-parsed request body. If provided, the transport will use this instead of parsing req.json(). + * Useful when using body-parser middleware that has already parsed the body. + */ + parsedBody?: unknown; + /** + * Authentication info from middleware. If provided, will be passed to message handlers. + */ + authInfo?: AuthInfo; +} +/** + * Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification + * using Web Standard APIs (Request, Response, ReadableStream). + * + * This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new WebStandardStreamableHTTPServerTransport({ + * sessionIdGenerator: () => crypto.randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new WebStandardStreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Hono.js usage + * app.all('/mcp', async (c) => { + * return transport.handleRequest(c.req.raw); + * }); + * + * // Cloudflare Workers usage + * export default { + * async fetch(request: Request): Promise { + * return transport.handleRequest(request); + * } + * }; + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +export declare class WebStandardStreamableHTTPServerTransport implements Transport { + private sessionIdGenerator; + private _started; + private _streamMapping; + private _requestToStreamMapping; + private _requestResponseMap; + private _initialized; + private _enableJsonResponse; + private _standaloneSseStreamId; + private _eventStore?; + private _onsessioninitialized?; + private _onsessionclosed?; + private _allowedHosts?; + private _allowedOrigins?; + private _enableDnsRebindingProtection; + private _retryInterval?; + sessionId?: string; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; + constructor(options?: WebStandardStreamableHTTPServerTransportOptions); + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + start(): Promise; + /** + * Helper to create a JSON error response + */ + private createJsonErrorResponse; + /** + * Validates request headers for DNS rebinding protection. + * @returns Error response if validation fails, undefined if validation passes. + */ + private validateRequestHeaders; + /** + * Handles an incoming HTTP request, whether GET, POST, or DELETE + * Returns a Response object (Web Standard) + */ + handleRequest(req: Request, options?: HandleRequestOptions): Promise; + /** + * Writes a priming event to establish resumption capability. + * Only sends if eventStore is configured (opt-in for resumability) and + * the client's protocol version supports empty SSE data (>= 2025-11-25). + */ + private writePrimingEvent; + /** + * Handles GET requests for SSE stream + */ + private handleGetRequest; + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + private replayEvents; + /** + * Writes an event to an SSE stream via controller with proper formatting + */ + private writeSSEEvent; + /** + * Handles unsupported requests (PUT, PATCH, etc.) + */ + private handleUnsupportedRequest; + /** + * Handles POST requests containing JSON-RPC messages + */ + private handlePostRequest; + /** + * Handles DELETE requests to terminate sessions + */ + private handleDeleteRequest; + /** + * Validates session ID for non-initialization requests. + * Returns Response error if invalid, undefined otherwise + */ + private validateSession; + /** + * Validates the MCP-Protocol-Version header on incoming requests. + * + * For initialization: Version negotiation handles unknown versions gracefully + * (server responds with its supported version). + * + * For subsequent requests with MCP-Protocol-Version header: + * - Accept if in supported list + * - 400 if unsupported + * + * For HTTP requests without the MCP-Protocol-Version header: + * - Accept and default to the version negotiated at initialization + */ + private validateProtocolVersion; + close(): Promise; + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId: RequestId): void; + /** + * Close the standalone GET SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream(): void; + send(message: JSONRPCMessage, options?: { + relatedRequestId?: RequestId; + }): Promise; +} +//# sourceMappingURL=webStandardStreamableHttp.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.d.ts.map new file mode 100644 index 000000000..49c1aed78 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webStandardStreamableHttp.d.ts","sourceRoot":"","sources":["../../../src/server/webStandardStreamableHttp.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EACH,gBAAgB,EAMhB,cAAc,EAEd,SAAS,EAGZ,MAAM,aAAa,CAAC;AAErB,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC;AAC9B,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC;AAE7B;;GAEG;AACH,MAAM,WAAW,UAAU;IACvB;;;;;OAKG;IACH,UAAU,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAE1E;;;;;;;OAOG;IACH,qBAAqB,CAAC,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC,CAAC;IAExE,iBAAiB,CACb,WAAW,EAAE,OAAO,EACpB,EACI,IAAI,EACP,EAAE;QACC,IAAI,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KACtE,GACF,OAAO,CAAC,QAAQ,CAAC,CAAC;CACxB;AAgBD;;GAEG;AACH,MAAM,WAAW,+CAA+C;IAC5D;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,MAAM,MAAM,CAAC;IAElC;;;;;;OAMG;IACH,oBAAoB,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnE;;;;;;;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;IACnB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC;gBAE5D,OAAO,GAAE,+CAAoD;IAYzE;;;OAGG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAO5B;;OAEG;IACH,OAAO,CAAC,uBAAuB;IA0B/B;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IA6B9B;;;OAGG;IACG,aAAa,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAmBpF;;;;OAIG;YACW,iBAAiB;IA0B/B;;OAEG;YACW,gBAAgB;IA2E9B;;;OAGG;YACW,YAAY;IAgF1B;;OAEG;IACH,OAAO,CAAC,aAAa;IAoBrB;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAoBhC;;OAEG;YACW,iBAAiB;IA8M/B;;OAEG;YACW,mBAAmB;IAejC;;;OAGG;IACH,OAAO,CAAC,eAAe;IA0BvB;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,uBAAuB;IAazB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAY5B;;;;OAIG;IACH,cAAc,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI;IAU1C;;;OAGG;IACH,wBAAwB,IAAI,IAAI;IAO1B,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAiGjG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js new file mode 100644 index 000000000..f87830f0c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js @@ -0,0 +1,725 @@ +/** + * Web Standards Streamable HTTP Server Transport + * + * This is the core transport implementation using Web Standard APIs (Request, Response, ReadableStream). + * It can run on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. + * + * For Node.js Express/HTTP compatibility, use `StreamableHTTPServerTransport` which wraps this transport. + */ +import { isInitializeRequest, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema, SUPPORTED_PROTOCOL_VERSIONS, DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from '../types.js'; +/** + * Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification + * using Web Standard APIs (Request, Response, ReadableStream). + * + * This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new WebStandardStreamableHTTPServerTransport({ + * sessionIdGenerator: () => crypto.randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new WebStandardStreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Hono.js usage + * app.all('/mcp', async (c) => { + * return transport.handleRequest(c.req.raw); + * }); + * + * // Cloudflare Workers usage + * export default { + * async fetch(request: Request): Promise { + * return transport.handleRequest(request); + * } + * }; + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +export class WebStandardStreamableHTTPServerTransport { + constructor(options = {}) { + this._started = false; + this._streamMapping = new Map(); + this._requestToStreamMapping = new Map(); + this._requestResponseMap = new Map(); + this._initialized = false; + this._enableJsonResponse = false; + this._standaloneSseStreamId = '_GET_stream'; + this.sessionIdGenerator = options.sessionIdGenerator; + this._enableJsonResponse = options.enableJsonResponse ?? false; + this._eventStore = options.eventStore; + this._onsessioninitialized = options.onsessioninitialized; + this._onsessionclosed = options.onsessionclosed; + this._allowedHosts = options.allowedHosts; + this._allowedOrigins = options.allowedOrigins; + this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; + this._retryInterval = options.retryInterval; + } + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start() { + if (this._started) { + throw new Error('Transport already started'); + } + this._started = true; + } + /** + * Helper to create a JSON error response + */ + createJsonErrorResponse(status, code, message, options) { + const error = { code, message }; + if (options?.data !== undefined) { + error.data = options.data; + } + return new Response(JSON.stringify({ + jsonrpc: '2.0', + error, + id: null + }), { + status, + headers: { + 'Content-Type': 'application/json', + ...options?.headers + } + }); + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error response if validation fails, undefined if validation passes. + */ + validateRequestHeaders(req) { + // Skip validation if protection is not enabled + if (!this._enableDnsRebindingProtection) { + return undefined; + } + // Validate Host header if allowedHosts is configured + if (this._allowedHosts && this._allowedHosts.length > 0) { + const hostHeader = req.headers.get('host'); + if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { + const error = `Invalid Host header: ${hostHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32000, error); + } + } + // Validate Origin header if allowedOrigins is configured + if (this._allowedOrigins && this._allowedOrigins.length > 0) { + const originHeader = req.headers.get('origin'); + if (originHeader && !this._allowedOrigins.includes(originHeader)) { + const error = `Invalid Origin header: ${originHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32000, error); + } + } + return undefined; + } + /** + * Handles an incoming HTTP request, whether GET, POST, or DELETE + * Returns a Response object (Web Standard) + */ + async handleRequest(req, options) { + // Validate request headers for DNS rebinding protection + const validationError = this.validateRequestHeaders(req); + if (validationError) { + return validationError; + } + switch (req.method) { + case 'POST': + return this.handlePostRequest(req, options); + case 'GET': + return this.handleGetRequest(req); + case 'DELETE': + return this.handleDeleteRequest(req); + default: + return this.handleUnsupportedRequest(); + } + } + /** + * Writes a priming event to establish resumption capability. + * Only sends if eventStore is configured (opt-in for resumability) and + * the client's protocol version supports empty SSE data (>= 2025-11-25). + */ + async writePrimingEvent(controller, encoder, streamId, protocolVersion) { + if (!this._eventStore) { + return; + } + // Priming events have empty data which older clients cannot handle. + // Only send priming events to clients with protocol version >= 2025-11-25 + // which includes the fix for handling empty SSE data. + if (protocolVersion < '2025-11-25') { + return; + } + const primingEventId = await this._eventStore.storeEvent(streamId, {}); + let primingEvent = `id: ${primingEventId}\ndata: \n\n`; + if (this._retryInterval !== undefined) { + primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; + } + controller.enqueue(encoder.encode(primingEvent)); + } + /** + * Handles GET requests for SSE stream + */ + async handleGetRequest(req) { + // The client MUST include an Accept header, listing text/event-stream as a supported content type. + const acceptHeader = req.headers.get('accept'); + if (!acceptHeader?.includes('text/event-stream')) { + return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept text/event-stream'); + } + // If an Mcp-Session-Id is returned by the server during initialization, + // clients using the Streamable HTTP transport MUST include it + // in the Mcp-Session-Id header on all of their subsequent HTTP requests. + const sessionError = this.validateSession(req); + if (sessionError) { + return sessionError; + } + const protocolError = this.validateProtocolVersion(req); + if (protocolError) { + return protocolError; + } + // Handle resumability: check for Last-Event-ID header + if (this._eventStore) { + const lastEventId = req.headers.get('last-event-id'); + if (lastEventId) { + return this.replayEvents(lastEventId); + } + } + // Check if there's already an active standalone SSE stream for this session + if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) { + // Only one GET SSE stream is allowed per session + return this.createJsonErrorResponse(409, -32000, 'Conflict: Only one SSE stream is allowed per session'); + } + const encoder = new TextEncoder(); + let streamController; + // Create a ReadableStream with a controller we can use to push SSE events + const readable = new ReadableStream({ + start: controller => { + streamController = controller; + }, + cancel: () => { + // Stream was cancelled by client + this._streamMapping.delete(this._standaloneSseStreamId); + } + }); + const headers = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }; + // After initialization, always include the session ID if we have one + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + // Store the stream mapping with the controller for pushing data + this._streamMapping.set(this._standaloneSseStreamId, { + controller: streamController, + encoder, + cleanup: () => { + this._streamMapping.delete(this._standaloneSseStreamId); + try { + streamController.close(); + } + catch { + // Controller might already be closed + } + } + }); + return new Response(readable, { headers }); + } + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + async replayEvents(lastEventId) { + if (!this._eventStore) { + return this.createJsonErrorResponse(400, -32000, 'Event store not configured'); + } + try { + // If getStreamIdForEventId is available, use it for conflict checking + let streamId; + if (this._eventStore.getStreamIdForEventId) { + streamId = await this._eventStore.getStreamIdForEventId(lastEventId); + if (!streamId) { + return this.createJsonErrorResponse(400, -32000, 'Invalid event ID format'); + } + // Check conflict with the SAME streamId we'll use for mapping + if (this._streamMapping.get(streamId) !== undefined) { + return this.createJsonErrorResponse(409, -32000, 'Conflict: Stream already has an active connection'); + } + } + const headers = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }; + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + // Create a ReadableStream with controller for SSE + const encoder = new TextEncoder(); + let streamController; + const readable = new ReadableStream({ + start: controller => { + streamController = controller; + }, + cancel: () => { + // Stream was cancelled by client + // Cleanup will be handled by the mapping + } + }); + // Replay events - returns the streamId for backwards compatibility + const replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { + send: async (eventId, message) => { + const success = this.writeSSEEvent(streamController, encoder, message, eventId); + if (!success) { + this.onerror?.(new Error('Failed replay events')); + try { + streamController.close(); + } + catch { + // Controller might already be closed + } + } + } + }); + this._streamMapping.set(replayedStreamId, { + controller: streamController, + encoder, + cleanup: () => { + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } + catch { + // Controller might already be closed + } + } + }); + return new Response(readable, { headers }); + } + catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(500, -32000, 'Error replaying events'); + } + } + /** + * Writes an event to an SSE stream via controller with proper formatting + */ + writeSSEEvent(controller, encoder, message, eventId) { + try { + let eventData = `event: message\n`; + // Include event ID if provided - this is important for resumability + if (eventId) { + eventData += `id: ${eventId}\n`; + } + eventData += `data: ${JSON.stringify(message)}\n\n`; + controller.enqueue(encoder.encode(eventData)); + return true; + } + catch { + return false; + } + } + /** + * Handles unsupported requests (PUT, PATCH, etc.) + */ + handleUnsupportedRequest() { + return new Response(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + }), { + status: 405, + headers: { + Allow: 'GET, POST, DELETE', + 'Content-Type': 'application/json' + } + }); + } + /** + * Handles POST requests containing JSON-RPC messages + */ + async handlePostRequest(req, options) { + try { + // Validate the Accept header + const acceptHeader = req.headers.get('accept'); + // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types. + if (!acceptHeader?.includes('application/json') || !acceptHeader.includes('text/event-stream')) { + return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept both application/json and text/event-stream'); + } + const ct = req.headers.get('content-type'); + if (!ct || !ct.includes('application/json')) { + return this.createJsonErrorResponse(415, -32000, 'Unsupported Media Type: Content-Type must be application/json'); + } + // Build request info from headers + const requestInfo = { + headers: Object.fromEntries(req.headers.entries()) + }; + let rawMessage; + if (options?.parsedBody !== undefined) { + rawMessage = options.parsedBody; + } + else { + try { + rawMessage = await req.json(); + } + catch { + return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON'); + } + } + let messages; + // handle batch and single messages + try { + if (Array.isArray(rawMessage)) { + messages = rawMessage.map(msg => JSONRPCMessageSchema.parse(msg)); + } + else { + messages = [JSONRPCMessageSchema.parse(rawMessage)]; + } + } + catch { + return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON-RPC message'); + } + // Check if this is an initialization request + // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/ + const isInitializationRequest = messages.some(isInitializeRequest); + if (isInitializationRequest) { + // If it's a server with session management and the session ID is already set we should reject the request + // to avoid re-initialization. + if (this._initialized && this.sessionId !== undefined) { + return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Server already initialized'); + } + if (messages.length > 1) { + return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Only one initialization request is allowed'); + } + this.sessionId = this.sessionIdGenerator?.(); + this._initialized = true; + // If we have a session ID and an onsessioninitialized handler, call it immediately + // This is needed in cases where the server needs to keep track of multiple sessions + if (this.sessionId && this._onsessioninitialized) { + await Promise.resolve(this._onsessioninitialized(this.sessionId)); + } + } + if (!isInitializationRequest) { + // If an Mcp-Session-Id is returned by the server during initialization, + // clients using the Streamable HTTP transport MUST include it + // in the Mcp-Session-Id header on all of their subsequent HTTP requests. + const sessionError = this.validateSession(req); + if (sessionError) { + return sessionError; + } + // Mcp-Protocol-Version header is required for all requests after initialization. + const protocolError = this.validateProtocolVersion(req); + if (protocolError) { + return protocolError; + } + } + // check if it contains requests + const hasRequests = messages.some(isJSONRPCRequest); + if (!hasRequests) { + // if it only contains notifications or responses, return 202 + for (const message of messages) { + this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo }); + } + return new Response(null, { status: 202 }); + } + // The default behavior is to use SSE streaming + // but in some cases server will return JSON responses + const streamId = crypto.randomUUID(); + // Extract protocol version for priming event decision. + // For initialize requests, get from request params. + // For other requests, get from header (already validated). + const initRequest = messages.find(m => isInitializeRequest(m)); + const clientProtocolVersion = initRequest + ? initRequest.params.protocolVersion + : (req.headers.get('mcp-protocol-version') ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION); + if (this._enableJsonResponse) { + // For JSON response mode, return a Promise that resolves when all responses are ready + return new Promise(resolve => { + this._streamMapping.set(streamId, { + resolveJson: resolve, + cleanup: () => { + this._streamMapping.delete(streamId); + } + }); + for (const message of messages) { + if (isJSONRPCRequest(message)) { + this._requestToStreamMapping.set(message.id, streamId); + } + } + for (const message of messages) { + this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo }); + } + }); + } + // SSE streaming mode - use ReadableStream with controller for more reliable data pushing + const encoder = new TextEncoder(); + let streamController; + const readable = new ReadableStream({ + start: controller => { + streamController = controller; + }, + cancel: () => { + // Stream was cancelled by client + this._streamMapping.delete(streamId); + } + }); + const headers = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive' + }; + // After initialization, always include the session ID if we have one + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + // Store the response for this request to send messages back through this connection + // We need to track by request ID to maintain the connection + for (const message of messages) { + if (isJSONRPCRequest(message)) { + this._streamMapping.set(streamId, { + controller: streamController, + encoder, + cleanup: () => { + this._streamMapping.delete(streamId); + try { + streamController.close(); + } + catch { + // Controller might already be closed + } + } + }); + this._requestToStreamMapping.set(message.id, streamId); + } + } + // Write priming event if event store is configured (after mapping is set up) + await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); + // handle each message + for (const message of messages) { + // Build closeSSEStream callback for requests when eventStore is configured + // AND client supports resumability (protocol version >= 2025-11-25). + // Old clients can't resume if the stream is closed early because they + // didn't receive a priming event with an event ID. + let closeSSEStream; + let closeStandaloneSSEStream; + if (isJSONRPCRequest(message) && this._eventStore && clientProtocolVersion >= '2025-11-25') { + closeSSEStream = () => { + this.closeSSEStream(message.id); + }; + closeStandaloneSSEStream = () => { + this.closeStandaloneSSEStream(); + }; + } + this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo, closeSSEStream, closeStandaloneSSEStream }); + } + // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses + // This will be handled by the send() method when responses are ready + return new Response(readable, { status: 200, headers }); + } + catch (error) { + // return JSON-RPC formatted error + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, 'Parse error', { data: String(error) }); + } + } + /** + * Handles DELETE requests to terminate sessions + */ + async handleDeleteRequest(req) { + const sessionError = this.validateSession(req); + if (sessionError) { + return sessionError; + } + const protocolError = this.validateProtocolVersion(req); + if (protocolError) { + return protocolError; + } + await Promise.resolve(this._onsessionclosed?.(this.sessionId)); + await this.close(); + return new Response(null, { status: 200 }); + } + /** + * Validates session ID for non-initialization requests. + * Returns Response error if invalid, undefined otherwise + */ + validateSession(req) { + if (this.sessionIdGenerator === undefined) { + // If the sessionIdGenerator ID is not set, the session management is disabled + // and we don't need to validate the session ID + return undefined; + } + if (!this._initialized) { + // If the server has not been initialized yet, reject all requests + return this.createJsonErrorResponse(400, -32000, 'Bad Request: Server not initialized'); + } + const sessionId = req.headers.get('mcp-session-id'); + if (!sessionId) { + // Non-initialization requests without a session ID should return 400 Bad Request + return this.createJsonErrorResponse(400, -32000, 'Bad Request: Mcp-Session-Id header is required'); + } + if (sessionId !== this.sessionId) { + // Reject requests with invalid session ID with 404 Not Found + return this.createJsonErrorResponse(404, -32001, 'Session not found'); + } + return undefined; + } + /** + * Validates the MCP-Protocol-Version header on incoming requests. + * + * For initialization: Version negotiation handles unknown versions gracefully + * (server responds with its supported version). + * + * For subsequent requests with MCP-Protocol-Version header: + * - Accept if in supported list + * - 400 if unsupported + * + * For HTTP requests without the MCP-Protocol-Version header: + * - Accept and default to the version negotiated at initialization + */ + validateProtocolVersion(req) { + const protocolVersion = req.headers.get('mcp-protocol-version'); + if (protocolVersion !== null && !SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) { + return this.createJsonErrorResponse(400, -32000, `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})`); + } + return undefined; + } + async close() { + // Close all SSE connections + this._streamMapping.forEach(({ cleanup }) => { + cleanup(); + }); + this._streamMapping.clear(); + // Clear any pending responses + this._requestResponseMap.clear(); + this.onclose?.(); + } + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId) { + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) + return; + const stream = this._streamMapping.get(streamId); + if (stream) { + stream.cleanup(); + } + } + /** + * Close the standalone GET SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream() { + const stream = this._streamMapping.get(this._standaloneSseStreamId); + if (stream) { + stream.cleanup(); + } + } + async send(message, options) { + let requestId = options?.relatedRequestId; + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + // If the message is a response, use the request ID from the message + requestId = message.id; + } + // Check if this message should be sent on the standalone SSE stream (no request ID) + // Ignore notifications from tools (which have relatedRequestId set) + // Those will be sent via dedicated response SSE streams + if (requestId === undefined) { + // For standalone SSE streams, we can only send requests and notifications + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request'); + } + // Generate and store event ID if event store is provided + // Store even if stream is disconnected so events can be replayed on reconnect + let eventId; + if (this._eventStore) { + // Stores the event and gets the generated event ID + eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); + } + const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); + if (standaloneSse === undefined) { + // Stream is disconnected - event is stored for replay, nothing more to do + return; + } + // Send the message to the standalone SSE stream + if (standaloneSse.controller && standaloneSse.encoder) { + this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); + } + return; + } + // Get the response for this request + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) { + throw new Error(`No connection established for request ID: ${String(requestId)}`); + } + const stream = this._streamMapping.get(streamId); + if (!this._enableJsonResponse && stream?.controller && stream?.encoder) { + // For SSE responses, generate event ID if event store is provided + let eventId; + if (this._eventStore) { + eventId = await this._eventStore.storeEvent(streamId, message); + } + // Write the event to the response stream + this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); + } + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._requestResponseMap.set(requestId, message); + const relatedIds = Array.from(this._requestToStreamMapping.entries()) + .filter(([_, sid]) => sid === streamId) + .map(([id]) => id); + // Check if we have responses for all requests using this connection + const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id)); + if (allResponsesReady) { + if (!stream) { + throw new Error(`No connection established for request ID: ${String(requestId)}`); + } + if (this._enableJsonResponse && stream.resolveJson) { + // All responses ready, send as JSON + const headers = { + 'Content-Type': 'application/json' + }; + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + const responses = relatedIds.map(id => this._requestResponseMap.get(id)); + if (responses.length === 1) { + stream.resolveJson(new Response(JSON.stringify(responses[0]), { status: 200, headers })); + } + else { + stream.resolveJson(new Response(JSON.stringify(responses), { status: 200, headers })); + } + } + else { + // End the SSE stream + stream.cleanup(); + } + // Clean up + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + } + } + } +} +//# sourceMappingURL=webStandardStreamableHttp.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js.map new file mode 100644 index 000000000..8868c1f97 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webStandardStreamableHttp.js","sourceRoot":"","sources":["../../../src/server/webStandardStreamableHttp.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,EAGH,mBAAmB,EACnB,sBAAsB,EACtB,gBAAgB,EAChB,uBAAuB,EAEvB,oBAAoB,EAEpB,2BAA2B,EAC3B,mCAAmC,EACtC,MAAM,aAAa,CAAC;AA8IrB;;;;;;;;;;;;;;;;;;;;;;;;;;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C,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;oBAC7F,CAAC;yBAAM,CAAC;wBACJ,MAAM,CAAC,WAAW,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;oBAC1F,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACJ,qBAAqB;oBACrB,MAAM,CAAC,OAAO,EAAE,CAAC;gBACrB,CAAC;gBACD,WAAW;gBACX,KAAK,MAAM,EAAE,IAAI,UAAU,EAAE,CAAC;oBAC1B,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;oBACpC,IAAI,CAAC,uBAAuB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAC5C,CAAC;YACL,CAAC;QACL,CAAC;IACL,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.d.ts new file mode 100644 index 000000000..c3a5b60ee --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.d.ts @@ -0,0 +1,84 @@ +import type * as z3 from 'zod/v3'; +import type * as z4 from 'zod/v4/core'; +export type AnySchema = z3.ZodTypeAny | z4.$ZodType; +export type AnyObjectSchema = z3.AnyZodObject | z4.$ZodObject | AnySchema; +export type ZodRawShapeCompat = Record; +export interface ZodV3Internal { + _def?: { + typeName?: string; + value?: unknown; + values?: unknown[]; + shape?: Record | (() => Record); + description?: string; + }; + shape?: Record | (() => Record); + value?: unknown; +} +export interface ZodV4Internal { + _zod?: { + def?: { + type?: string; + value?: unknown; + values?: unknown[]; + shape?: Record | (() => Record); + }; + }; + value?: unknown; +} +export type SchemaOutput = S extends z3.ZodTypeAny ? z3.infer : S extends z4.$ZodType ? z4.output : never; +export type SchemaInput = S extends z3.ZodTypeAny ? z3.input : S extends z4.$ZodType ? z4.input : never; +/** + * Infers the output type from a ZodRawShapeCompat (raw shape object). + * Maps over each key in the shape and infers the output type from each schema. + */ +export type ShapeOutput = { + [K in keyof Shape]: SchemaOutput; +}; +export declare function isZ4Schema(s: AnySchema): s is z4.$ZodType; +export declare function objectFromShape(shape: ZodRawShapeCompat): AnyObjectSchema; +export declare function safeParse(schema: S, data: unknown): { + success: true; + data: SchemaOutput; +} | { + success: false; + error: unknown; +}; +export declare function safeParseAsync(schema: S, data: unknown): Promise<{ + success: true; + data: SchemaOutput; +} | { + success: false; + error: unknown; +}>; +export declare function getObjectShape(schema: AnyObjectSchema | undefined): Record | undefined; +/** + * Normalizes a schema to an object schema. Handles both: + * - Already-constructed object schemas (v3 or v4) + * - Raw shapes that need to be wrapped into object schemas + */ +export declare function normalizeObjectSchema(schema: AnySchema | ZodRawShapeCompat | undefined): AnyObjectSchema | undefined; +/** + * Safely extracts an error message from a parse result error. + * Zod errors can have different structures, so we handle various cases. + */ +export declare function getParseErrorMessage(error: unknown): string; +/** + * Gets the description from a schema, if available. + * Works with both Zod v3 and v4. + * + * Both versions expose a `.description` getter that returns the description + * from their respective internal storage (v3: _def, v4: globalRegistry). + */ +export declare function getSchemaDescription(schema: AnySchema): string | undefined; +/** + * Checks if a schema is optional. + * Works with both Zod v3 and v4. + */ +export declare function isSchemaOptional(schema: AnySchema): boolean; +/** + * Gets the literal value from a schema, if it's a literal schema. + * Works with both Zod v3 and v4. + * Returns undefined if the schema is not a literal or the value cannot be determined. + */ +export declare function getLiteralValue(schema: AnySchema): unknown; +//# sourceMappingURL=zod-compat.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.d.ts.map new file mode 100644 index 000000000..a2ccd51c7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-compat.d.ts","sourceRoot":"","sources":["../../../src/server/zod-compat.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,KAAK,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAMvC,MAAM,MAAM,SAAS,GAAG,EAAE,CAAC,UAAU,GAAG,EAAE,CAAC,QAAQ,CAAC;AACpD,MAAM,MAAM,eAAe,GAAG,EAAE,CAAC,YAAY,GAAG,EAAE,CAAC,UAAU,GAAG,SAAS,CAAC;AAC1E,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAI1D,MAAM,WAAW,aAAa;IAC1B,IAAI,CAAC,EAAE;QACH,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,KAAK,CAAC,EAAE,OAAO,CAAC;QAChB,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;QACnB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;QACtE,WAAW,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;IACF,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;IACtE,KAAK,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,aAAa;IAC1B,IAAI,CAAC,EAAE;QACH,GAAG,CAAC,EAAE;YACF,IAAI,CAAC,EAAE,MAAM,CAAC;YACd,KAAK,CAAC,EAAE,OAAO,CAAC;YAChB,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;YACnB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAA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AAO,GACd,OAAO,CAAC;IAAE,OAAO,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC,CASxF;AAGD,wBAAgB,cAAc,CAAC,MAAM,EAAE,eAAe,GAAG,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,SAAS,CAyBzG;AAGD;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,SAAS,GAAG,iBAAiB,GAAG,SAAS,GAAG,eAAe,GAAG,SAAS,CAiDpH;AAGD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAoB3D;AAGD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,GAAG,SAAS,CAE1E;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAW3D;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAwB1D"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js new file mode 100644 index 000000000..be30a2230 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js @@ -0,0 +1,209 @@ +// zod-compat.ts +// ---------------------------------------------------- +// Unified types + helpers to accept Zod v3 and v4 (Mini) +// ---------------------------------------------------- +import * as z3rt from 'zod/v3'; +import * as z4mini from 'zod/v4-mini'; +// --- Runtime detection --- +export function isZ4Schema(s) { + // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3 + const schema = s; + return !!schema._zod; +} +// --- Schema construction --- +export function objectFromShape(shape) { + const values = Object.values(shape); + if (values.length === 0) + return z4mini.object({}); // default to v4 Mini + const allV4 = values.every(isZ4Schema); + const allV3 = values.every(s => !isZ4Schema(s)); + if (allV4) + return z4mini.object(shape); + if (allV3) + return z3rt.object(shape); + throw new Error('Mixed Zod versions detected in object shape.'); +} +// --- Unified parsing --- +export function safeParse(schema, data) { + if (isZ4Schema(schema)) { + // Mini exposes top-level safeParse + const result = z4mini.safeParse(schema, data); + return result; + } + const v3Schema = schema; + const result = v3Schema.safeParse(data); + return result; +} +export async function safeParseAsync(schema, data) { + if (isZ4Schema(schema)) { + // Mini exposes top-level safeParseAsync + const result = await z4mini.safeParseAsync(schema, data); + return result; + } + const v3Schema = schema; + const result = await v3Schema.safeParseAsync(data); + return result; +} +// --- Shape extraction --- +export function getObjectShape(schema) { + if (!schema) + return undefined; + // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape` + let rawShape; + if (isZ4Schema(schema)) { + const v4Schema = schema; + rawShape = v4Schema._zod?.def?.shape; + } + else { + const v3Schema = schema; + rawShape = v3Schema.shape; + } + if (!rawShape) + return undefined; + if (typeof rawShape === 'function') { + try { + return rawShape(); + } + catch { + return undefined; + } + } + return rawShape; +} +// --- Schema normalization --- +/** + * Normalizes a schema to an object schema. Handles both: + * - Already-constructed object schemas (v3 or v4) + * - Raw shapes that need to be wrapped into object schemas + */ +export function normalizeObjectSchema(schema) { + if (!schema) + return undefined; + // First check if it's a raw shape (Record) + // Raw shapes don't have _def or _zod properties and aren't schemas themselves + if (typeof schema === 'object') { + // Check if it's actually a ZodRawShapeCompat (not a schema instance) + // by checking if it lacks schema-like internal properties + const asV3 = schema; + const asV4 = schema; + // If it's not a schema instance (no _def or _zod), it might be a raw shape + if (!asV3._def && !asV4._zod) { + // Check if all values are schemas (heuristic to confirm it's a raw shape) + const values = Object.values(schema); + if (values.length > 0 && + values.every(v => typeof v === 'object' && + v !== null && + (v._def !== undefined || + v._zod !== undefined || + typeof v.parse === 'function'))) { + return objectFromShape(schema); + } + } + } + // If we get here, it should be an AnySchema (not a raw shape) + // Check if it's already an object schema + if (isZ4Schema(schema)) { + // Check if it's a v4 object + const v4Schema = schema; + const def = v4Schema._zod?.def; + if (def && (def.type === 'object' || def.shape !== undefined)) { + return schema; + } + } + else { + // Check if it's a v3 object + const v3Schema = schema; + if (v3Schema.shape !== undefined) { + return schema; + } + } + return undefined; +} +// --- Error message extraction --- +/** + * Safely extracts an error message from a parse result error. + * Zod errors can have different structures, so we handle various cases. + */ +export function getParseErrorMessage(error) { + if (error && typeof error === 'object') { + // Try common error structures + if ('message' in error && typeof error.message === 'string') { + return error.message; + } + if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) { + const firstIssue = error.issues[0]; + if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) { + return String(firstIssue.message); + } + } + // Fallback: try to stringify the error + try { + return JSON.stringify(error); + } + catch { + return String(error); + } + } + return String(error); +} +// --- Schema metadata access --- +/** + * Gets the description from a schema, if available. + * Works with both Zod v3 and v4. + * + * Both versions expose a `.description` getter that returns the description + * from their respective internal storage (v3: _def, v4: globalRegistry). + */ +export function getSchemaDescription(schema) { + return schema.description; +} +/** + * Checks if a schema is optional. + * Works with both Zod v3 and v4. + */ +export function isSchemaOptional(schema) { + if (isZ4Schema(schema)) { + const v4Schema = schema; + return v4Schema._zod?.def?.type === 'optional'; + } + const v3Schema = schema; + // v3 has isOptional() method + if (typeof schema.isOptional === 'function') { + return schema.isOptional(); + } + return v3Schema._def?.typeName === 'ZodOptional'; +} +/** + * Gets the literal value from a schema, if it's a literal schema. + * Works with both Zod v3 and v4. + * Returns undefined if the schema is not a literal or the value cannot be determined. + */ +export function getLiteralValue(schema) { + if (isZ4Schema(schema)) { + const v4Schema = schema; + const def = v4Schema._zod?.def; + if (def) { + // Try various ways to get the literal value + if (def.value !== undefined) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + } + const v3Schema = schema; + const def = v3Schema._def; + if (def) { + if (def.value !== undefined) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + // Fallback: check for direct value property (some Zod versions) + const directValue = schema.value; + if (directValue !== undefined) + return directValue; + return undefined; +} +//# sourceMappingURL=zod-compat.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js.map new file mode 100644 index 000000000..42b83f9d7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-compat.js","sourceRoot":"","sources":["../../../src/server/zod-compat.ts"],"names":[],"mappings":"AAAA,gBAAgB;AAChB,uDAAuD;AACvD,yDAAyD;AACzD,uDAAuD;AAKvD,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC/B,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AA8CtC,4BAA4B;AAC5B,MAAM,UAAU,UAAU,CAAC,CAAY;IACnC,6DAA6D;IAC7D,MAAM,MAAM,GAAG,CAA6B,CAAC;IAC7C,OAAO,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;AACzB,CAAC;AAED,8BAA8B;AAC9B,MAAM,UAAU,eAAe,CAAC,KAAwB;IACpD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,qBAAqB;IAExE,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACvC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;IAEhD,IAAI,KAAK;QAAE,OAAO,MAAM,CAAC,MAAM,CAAC,KAAoC,CAAC,CAAC;IACt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gBACrD,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACzB,CAAC;QACL,CAAC;IACL,CAAC;IACD,MAAM,QAAQ,GAAG,MAAkC,CAAC;IACpD,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC;IAC1B,IAAI,GAAG,EAAE,CAAC;QACN,IAAI,GAAG,CAAC,KAAK,KAAK,SAAS;YAAE,OAAO,GAAG,CAAC,KAAK,CAAC;QAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrD,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QACzB,CAAC;IACL,CAAC;IACD,gEAAgE;IAChE,MAAM,WAAW,GAAI,MAA8B,CAAC,KAAK,CAAC;IAC1D,IAAI,WAAW,KAAK,SAAS;QAAE,OAAO,WAAW,CAAC;IAClD,OAAO,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.d.ts new file mode 100644 index 000000000..3a04452b4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.d.ts @@ -0,0 +1,12 @@ +import { AnySchema, AnyObjectSchema } from './zod-compat.js'; +type JsonSchema = Record; +type CommonOpts = { + strictUnions?: boolean; + pipeStrategy?: 'input' | 'output'; + target?: 'jsonSchema7' | 'draft-7' | 'jsonSchema2019-09' | 'draft-2020-12'; +}; +export declare function toJsonSchemaCompat(schema: AnyObjectSchema, opts?: CommonOpts): JsonSchema; +export declare function getMethodLiteral(schema: AnyObjectSchema): string; +export declare function parseWithCompat(schema: AnySchema, data: unknown): unknown; +export {}; +//# sourceMappingURL=zod-json-schema-compat.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.d.ts.map new file mode 100644 index 000000000..0b851bf50 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-json-schema-compat.d.ts","sourceRoot":"","sources":["../../../src/server/zod-json-schema-compat.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,SAAS,EAAE,eAAe,EAA0D,MAAM,iBAAiB,CAAC;AAGrH,KAAK,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAG1C,KAAK,UAAU,GAAG;IACd,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;IAClC,MAAM,CAAC,EAAE,aAAa,GAAG,SAAS,GAAG,mBAAmB,GAAG,eAAe,CAAC;CAC9E,CAAC;AASF,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAczF;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,eAAe,GAAG,MAAM,CAahE;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAMzE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js new file mode 100644 index 000000000..62f7fd0ef --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js @@ -0,0 +1,51 @@ +// zod-json-schema-compat.ts +// ---------------------------------------------------- +// JSON Schema conversion for both Zod v3 and Zod v4 (Mini) +// v3 uses your vendored converter; v4 uses Mini's toJSONSchema +// ---------------------------------------------------- +import * as z4mini from 'zod/v4-mini'; +import { getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js'; +import { zodToJsonSchema } from 'zod-to-json-schema'; +function mapMiniTarget(t) { + if (!t) + return 'draft-7'; + if (t === 'jsonSchema7' || t === 'draft-7') + return 'draft-7'; + if (t === 'jsonSchema2019-09' || t === 'draft-2020-12') + return 'draft-2020-12'; + return 'draft-7'; // fallback +} +export function toJsonSchemaCompat(schema, opts) { + if (isZ4Schema(schema)) { + // v4 branch — use Mini's built-in toJSONSchema + return z4mini.toJSONSchema(schema, { + target: mapMiniTarget(opts?.target), + io: opts?.pipeStrategy ?? 'input' + }); + } + // v3 branch — use vendored converter + return zodToJsonSchema(schema, { + strictUnions: opts?.strictUnions ?? true, + pipeStrategy: opts?.pipeStrategy ?? 'input' + }); +} +export function getMethodLiteral(schema) { + const shape = getObjectShape(schema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + const value = getLiteralValue(methodSchema); + if (typeof value !== 'string') { + throw new Error('Schema method literal must be a string'); + } + return value; +} +export function parseWithCompat(schema, data) { + const result = safeParse(schema, data); + if (!result.success) { + throw result.error; + } + return result.data; +} +//# sourceMappingURL=zod-json-schema-compat.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js.map new file mode 100644 index 000000000..70169ff25 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-json-schema-compat.js","sourceRoot":"","sources":["../../../src/server/zod-json-schema-compat.ts"],"names":[],"mappings":"AAAA,4BAA4B;AAC5B,uDAAuD;AACvD,2DAA2D;AAC3D,+DAA+D;AAC/D,uDAAuD;AAKvD,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AAEtC,OAAO,EAA8B,cAAc,EAAE,SAAS,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I,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAC9D,CAAC;IAED,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,MAAiB,EAAE,IAAa;IAC5D,MAAM,MAAM,GAAG,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACvC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QAClB,MAAM,MAAM,CAAC,KAAK,CAAC;IACvB,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC;AACvB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.d.ts new file mode 100644 index 000000000..c966e30e7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.d.ts @@ -0,0 +1,23 @@ +/** + * Utilities for handling OAuth resource URIs. + */ +/** + * Converts a server URL to a resource URL by removing the fragment. + * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". + * Keeps everything else unchanged (scheme, domain, port, path, query). + */ +export declare function resourceUrlFromServerUrl(url: URL | string): URL; +/** + * Checks if a requested resource URL matches a configured resource URL. + * A requested resource matches if it has the same scheme, domain, port, + * and its path starts with the configured resource's path. + * + * @param requestedResource The resource URL being requested + * @param configuredResource The resource URL that has been configured + * @returns true if the requested resource matches the configured resource, false otherwise + */ +export declare function checkResourceAllowed({ requestedResource, configuredResource }: { + requestedResource: URL | string; + configuredResource: URL | string; +}): boolean; +//# sourceMappingURL=auth-utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.d.ts.map new file mode 100644 index 000000000..30873de55 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-utils.d.ts","sourceRoot":"","sources":["../../../src/shared/auth-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,GAAG,GAAG,CAI/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,EACjC,iBAAiB,EACjB,kBAAkB,EACrB,EAAE;IACC,iBAAiB,EAAE,GAAG,GAAG,MAAM,CAAC;IAChC,kBAAkB,EAAE,GAAG,GAAG,MAAM,CAAC;CACpC,GAAG,OAAO,CAwBV"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js new file mode 100644 index 000000000..1883885e4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js @@ -0,0 +1,44 @@ +/** + * Utilities for handling OAuth resource URIs. + */ +/** + * Converts a server URL to a resource URL by removing the fragment. + * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". + * Keeps everything else unchanged (scheme, domain, port, path, query). + */ +export function resourceUrlFromServerUrl(url) { + const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href); + resourceURL.hash = ''; // Remove fragment + return resourceURL; +} +/** + * Checks if a requested resource URL matches a configured resource URL. + * A requested resource matches if it has the same scheme, domain, port, + * and its path starts with the configured resource's path. + * + * @param requestedResource The resource URL being requested + * @param configuredResource The resource URL that has been configured + * @returns true if the requested resource matches the configured resource, false otherwise + */ +export function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href); + // Compare the origin (scheme, domain, and port) + if (requested.origin !== configured.origin) { + return false; + } + // Handle cases like requested=/foo and configured=/foo/ + if (requested.pathname.length < configured.pathname.length) { + return false; + } + // Check if the requested path starts with the configured path + // Ensure both paths end with / for proper comparison + // This ensures that if we have paths like "/api" and "/api/users", + // we properly detect that "/api/users" is a subpath of "/api" + // By adding a trailing slash if missing, we avoid false positives + // where paths like "/api123" would incorrectly match "/api" + const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/'; + const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/'; + return requestedPath.startsWith(configuredPath); +} +//# sourceMappingURL=auth-utils.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js.map new file mode 100644 index 000000000..3ced5af40 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-utils.js","sourceRoot":"","sources":["../../../src/shared/auth-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CAAC,GAAiB;IACtD,MAAM,WAAW,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC/E,WAAW,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,kBAAkB;IACzC,OAAO,WAAW,CAAC;AACvB,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAAC,EACjC,iBAAiB,EACjB,kBAAkB,EAIrB;IACG,MAAM,SAAS,GAAG,OAAO,iBAAiB,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACvH,MAAM,UAAU,GAAG,OAAO,kBAAkB,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IAE3H,gDAAgD;IAChD,IAAI,SAAS,CAAC,MAAM,KAAK,UAAU,CAAC,MAAM,EAAE,CAAC;QACzC,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,wDAAwD;IACxD,IAAI,SAAS,CAAC,QAAQ,CAAC,MAAM,GAAG,UAAU,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QACzD,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,8DAA8D;IAC9D,qDAAqD;IACrD,mEAAmE;IACnE,8DAA8D;IAC9D,kEAAkE;IAClE,4DAA4D;IAC5D,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,GAAG,GAAG,CAAC;IACvG,MAAM,cAAc,GAAG,UAAU,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,GAAG,GAAG,CAAC;IAE3G,OAAO,aAAa,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;AACpD,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.d.ts new file mode 100644 index 000000000..4e47be12b --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.d.ts @@ -0,0 +1,240 @@ +import * as z from 'zod/v4'; +/** + * Reusable URL validation that disallows javascript: scheme + */ +export declare const SafeUrlSchema: z.ZodURL; +/** + * RFC 9728 OAuth Protected Resource Metadata + */ +export declare const OAuthProtectedResourceMetadataSchema: z.ZodObject<{ + resource: z.ZodString; + authorization_servers: z.ZodOptional>; + jwks_uri: z.ZodOptional; + scopes_supported: z.ZodOptional>; + bearer_methods_supported: z.ZodOptional>; + resource_signing_alg_values_supported: z.ZodOptional>; + resource_name: z.ZodOptional; + resource_documentation: z.ZodOptional; + resource_policy_uri: z.ZodOptional; + resource_tos_uri: z.ZodOptional; + tls_client_certificate_bound_access_tokens: z.ZodOptional; + authorization_details_types_supported: z.ZodOptional>; + dpop_signing_alg_values_supported: z.ZodOptional>; + dpop_bound_access_tokens_required: z.ZodOptional; +}, z.core.$loose>; +/** + * RFC 8414 OAuth 2.0 Authorization Server Metadata + */ +export declare const OAuthMetadataSchema: z.ZodObject<{ + issuer: z.ZodString; + authorization_endpoint: z.ZodURL; + token_endpoint: z.ZodURL; + registration_endpoint: z.ZodOptional; + scopes_supported: z.ZodOptional>; + response_types_supported: z.ZodArray; + response_modes_supported: z.ZodOptional>; + grant_types_supported: z.ZodOptional>; + token_endpoint_auth_methods_supported: z.ZodOptional>; + token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + service_documentation: z.ZodOptional; + revocation_endpoint: z.ZodOptional; + revocation_endpoint_auth_methods_supported: z.ZodOptional>; + revocation_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + introspection_endpoint: z.ZodOptional; + introspection_endpoint_auth_methods_supported: z.ZodOptional>; + introspection_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + code_challenge_methods_supported: z.ZodOptional>; + client_id_metadata_document_supported: z.ZodOptional; +}, z.core.$loose>; +/** + * OpenID Connect Discovery 1.0 Provider Metadata + * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +export declare const OpenIdProviderMetadataSchema: z.ZodObject<{ + issuer: z.ZodString; + authorization_endpoint: z.ZodURL; + token_endpoint: z.ZodURL; + userinfo_endpoint: z.ZodOptional; + jwks_uri: z.ZodURL; + registration_endpoint: z.ZodOptional; + scopes_supported: z.ZodOptional>; + response_types_supported: z.ZodArray; + response_modes_supported: z.ZodOptional>; + grant_types_supported: z.ZodOptional>; + acr_values_supported: z.ZodOptional>; + subject_types_supported: z.ZodArray; + id_token_signing_alg_values_supported: z.ZodArray; + id_token_encryption_alg_values_supported: z.ZodOptional>; + id_token_encryption_enc_values_supported: z.ZodOptional>; + userinfo_signing_alg_values_supported: z.ZodOptional>; + userinfo_encryption_alg_values_supported: z.ZodOptional>; + userinfo_encryption_enc_values_supported: z.ZodOptional>; + request_object_signing_alg_values_supported: z.ZodOptional>; + request_object_encryption_alg_values_supported: z.ZodOptional>; + request_object_encryption_enc_values_supported: z.ZodOptional>; + token_endpoint_auth_methods_supported: z.ZodOptional>; + token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + display_values_supported: z.ZodOptional>; + claim_types_supported: z.ZodOptional>; + claims_supported: z.ZodOptional>; + service_documentation: z.ZodOptional; + claims_locales_supported: z.ZodOptional>; + ui_locales_supported: z.ZodOptional>; + claims_parameter_supported: z.ZodOptional; + request_parameter_supported: z.ZodOptional; + request_uri_parameter_supported: z.ZodOptional; + require_request_uri_registration: z.ZodOptional; + op_policy_uri: z.ZodOptional; + op_tos_uri: z.ZodOptional; + client_id_metadata_document_supported: z.ZodOptional; +}, z.core.$loose>; +/** + * OpenID Connect Discovery metadata that may include OAuth 2.0 fields + * This schema represents the real-world scenario where OIDC providers + * return a mix of OpenID Connect and OAuth 2.0 metadata fields + */ +export declare const OpenIdProviderDiscoveryMetadataSchema: z.ZodObject<{ + code_challenge_methods_supported: z.ZodOptional>; + issuer: z.ZodString; + authorization_endpoint: z.ZodURL; + token_endpoint: z.ZodURL; + userinfo_endpoint: z.ZodOptional; + jwks_uri: z.ZodURL; + registration_endpoint: z.ZodOptional; + scopes_supported: z.ZodOptional>; + response_types_supported: z.ZodArray; + response_modes_supported: z.ZodOptional>; + grant_types_supported: z.ZodOptional>; + acr_values_supported: z.ZodOptional>; + subject_types_supported: z.ZodArray; + id_token_signing_alg_values_supported: z.ZodArray; + id_token_encryption_alg_values_supported: z.ZodOptional>; + id_token_encryption_enc_values_supported: z.ZodOptional>; + userinfo_signing_alg_values_supported: z.ZodOptional>; + userinfo_encryption_alg_values_supported: z.ZodOptional>; + userinfo_encryption_enc_values_supported: z.ZodOptional>; + request_object_signing_alg_values_supported: z.ZodOptional>; + request_object_encryption_alg_values_supported: z.ZodOptional>; + request_object_encryption_enc_values_supported: z.ZodOptional>; + token_endpoint_auth_methods_supported: z.ZodOptional>; + token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + display_values_supported: z.ZodOptional>; + claim_types_supported: z.ZodOptional>; + claims_supported: z.ZodOptional>; + service_documentation: z.ZodOptional; + claims_locales_supported: z.ZodOptional>; + ui_locales_supported: z.ZodOptional>; + claims_parameter_supported: z.ZodOptional; + request_parameter_supported: z.ZodOptional; + request_uri_parameter_supported: z.ZodOptional; + require_request_uri_registration: z.ZodOptional; + op_policy_uri: z.ZodOptional; + op_tos_uri: z.ZodOptional; + client_id_metadata_document_supported: z.ZodOptional; +}, z.core.$strip>; +/** + * OAuth 2.1 token response + */ +export declare const OAuthTokensSchema: z.ZodObject<{ + access_token: z.ZodString; + id_token: z.ZodOptional; + token_type: z.ZodString; + expires_in: z.ZodOptional>; + scope: z.ZodOptional; + refresh_token: z.ZodOptional; +}, z.core.$strip>; +/** + * OAuth 2.1 error response + */ +export declare const OAuthErrorResponseSchema: z.ZodObject<{ + error: z.ZodString; + error_description: z.ZodOptional; + error_uri: z.ZodOptional; +}, z.core.$strip>; +/** + * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri + */ +export declare const OptionalSafeUrlSchema: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata + */ +export declare const OAuthClientMetadataSchema: z.ZodObject<{ + redirect_uris: z.ZodArray; + token_endpoint_auth_method: z.ZodOptional; + grant_types: z.ZodOptional>; + response_types: z.ZodOptional>; + client_name: z.ZodOptional; + client_uri: z.ZodOptional; + logo_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + scope: z.ZodOptional; + contacts: z.ZodOptional>; + tos_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + policy_uri: z.ZodOptional; + jwks_uri: z.ZodOptional; + jwks: z.ZodOptional; + software_id: z.ZodOptional; + software_version: z.ZodOptional; + software_statement: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration client information + */ +export declare const OAuthClientInformationSchema: z.ZodObject<{ + client_id: z.ZodString; + client_secret: z.ZodOptional; + client_id_issued_at: z.ZodOptional; + client_secret_expires_at: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) + */ +export declare const OAuthClientInformationFullSchema: z.ZodObject<{ + redirect_uris: z.ZodArray; + token_endpoint_auth_method: z.ZodOptional; + grant_types: z.ZodOptional>; + response_types: z.ZodOptional>; + client_name: z.ZodOptional; + client_uri: z.ZodOptional; + logo_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + scope: z.ZodOptional; + contacts: z.ZodOptional>; + tos_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + policy_uri: z.ZodOptional; + jwks_uri: z.ZodOptional; + jwks: z.ZodOptional; + software_id: z.ZodOptional; + software_version: z.ZodOptional; + software_statement: z.ZodOptional; + client_id: z.ZodString; + client_secret: z.ZodOptional; + client_id_issued_at: z.ZodOptional; + client_secret_expires_at: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration error response + */ +export declare const OAuthClientRegistrationErrorSchema: z.ZodObject<{ + error: z.ZodString; + error_description: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7009 OAuth 2.0 Token Revocation request + */ +export declare const OAuthTokenRevocationRequestSchema: z.ZodObject<{ + token: z.ZodString; + token_type_hint: z.ZodOptional; +}, z.core.$strip>; +export type OAuthMetadata = z.infer; +export type OpenIdProviderMetadata = z.infer; +export type OpenIdProviderDiscoveryMetadata = z.infer; +export type OAuthTokens = z.infer; +export type OAuthErrorResponse = z.infer; +export type OAuthClientMetadata = z.infer; +export type OAuthClientInformation = z.infer; +export type OAuthClientInformationFull = z.infer; +export type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull; +export type OAuthClientRegistrationError = z.infer; +export type OAuthTokenRevocationRequest = z.infer; +export type OAuthProtectedResourceMetadata = z.infer; +export type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscoveryMetadata; +//# sourceMappingURL=auth.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.d.ts.map new file mode 100644 index 000000000..031a88fb9 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/shared/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B;;GAEG;AACH,eAAO,MAAM,aAAa,UAmBrB,CAAC;AAEN;;GAEG;AACH,eAAO,MAAM,oCAAoC;;;;;;;;;;;;;;;iBAe/C,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;iBAoB9B,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqCvC,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,qCAAqC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAKhD,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;iBASlB,CAAC;AAEb;;GAEG;AACH,eAAO,MAAM,wBAAwB;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AG,CAAC,CAAC,KAAK,CAAC,OAAO,iCAAiC,CAAC,CAAC;AAC5F,MAAM,MAAM,8BAA8B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oCAAoC,CAAC,CAAC;AAGlG,MAAM,MAAM,2BAA2B,GAAG,aAAa,GAAG,+BAA+B,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js new file mode 100644 index 000000000..04f38eb88 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js @@ -0,0 +1,198 @@ +import * as z from 'zod/v4'; +/** + * Reusable URL validation that disallows javascript: scheme + */ +export const SafeUrlSchema = z + .url() + .superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'URL must be parseable', + fatal: true + }); + return z.NEVER; + } +}) + .refine(url => { + const u = new URL(url); + return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:'; +}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' }); +/** + * RFC 9728 OAuth Protected Resource Metadata + */ +export const OAuthProtectedResourceMetadataSchema = z.looseObject({ + resource: z.string().url(), + authorization_servers: z.array(SafeUrlSchema).optional(), + jwks_uri: z.string().url().optional(), + scopes_supported: z.array(z.string()).optional(), + bearer_methods_supported: z.array(z.string()).optional(), + resource_signing_alg_values_supported: z.array(z.string()).optional(), + resource_name: z.string().optional(), + resource_documentation: z.string().optional(), + resource_policy_uri: z.string().url().optional(), + resource_tos_uri: z.string().url().optional(), + tls_client_certificate_bound_access_tokens: z.boolean().optional(), + authorization_details_types_supported: z.array(z.string()).optional(), + dpop_signing_alg_values_supported: z.array(z.string()).optional(), + dpop_bound_access_tokens_required: z.boolean().optional() +}); +/** + * RFC 8414 OAuth 2.0 Authorization Server Metadata + */ +export const OAuthMetadataSchema = z.looseObject({ + issuer: z.string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: z.array(z.string()).optional(), + response_types_supported: z.array(z.string()), + response_modes_supported: z.array(z.string()).optional(), + grant_types_supported: z.array(z.string()).optional(), + token_endpoint_auth_methods_supported: z.array(z.string()).optional(), + token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + introspection_endpoint: z.string().optional(), + introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + code_challenge_methods_supported: z.array(z.string()).optional(), + client_id_metadata_document_supported: z.boolean().optional() +}); +/** + * OpenID Connect Discovery 1.0 Provider Metadata + * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +export const OpenIdProviderMetadataSchema = z.looseObject({ + issuer: z.string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: z.array(z.string()).optional(), + response_types_supported: z.array(z.string()), + response_modes_supported: z.array(z.string()).optional(), + grant_types_supported: z.array(z.string()).optional(), + acr_values_supported: z.array(z.string()).optional(), + subject_types_supported: z.array(z.string()), + id_token_signing_alg_values_supported: z.array(z.string()), + id_token_encryption_alg_values_supported: z.array(z.string()).optional(), + id_token_encryption_enc_values_supported: z.array(z.string()).optional(), + userinfo_signing_alg_values_supported: z.array(z.string()).optional(), + userinfo_encryption_alg_values_supported: z.array(z.string()).optional(), + userinfo_encryption_enc_values_supported: z.array(z.string()).optional(), + request_object_signing_alg_values_supported: z.array(z.string()).optional(), + request_object_encryption_alg_values_supported: z.array(z.string()).optional(), + request_object_encryption_enc_values_supported: z.array(z.string()).optional(), + token_endpoint_auth_methods_supported: z.array(z.string()).optional(), + token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + display_values_supported: z.array(z.string()).optional(), + claim_types_supported: z.array(z.string()).optional(), + claims_supported: z.array(z.string()).optional(), + service_documentation: z.string().optional(), + claims_locales_supported: z.array(z.string()).optional(), + ui_locales_supported: z.array(z.string()).optional(), + claims_parameter_supported: z.boolean().optional(), + request_parameter_supported: z.boolean().optional(), + request_uri_parameter_supported: z.boolean().optional(), + require_request_uri_registration: z.boolean().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: z.boolean().optional() +}); +/** + * OpenID Connect Discovery metadata that may include OAuth 2.0 fields + * This schema represents the real-world scenario where OIDC providers + * return a mix of OpenID Connect and OAuth 2.0 metadata fields + */ +export const OpenIdProviderDiscoveryMetadataSchema = z.object({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ + code_challenge_methods_supported: true + }).shape +}); +/** + * OAuth 2.1 token response + */ +export const OAuthTokensSchema = z + .object({ + access_token: z.string(), + id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect + token_type: z.string(), + expires_in: z.coerce.number().optional(), + scope: z.string().optional(), + refresh_token: z.string().optional() +}) + .strip(); +/** + * OAuth 2.1 error response + */ +export const OAuthErrorResponseSchema = z.object({ + error: z.string(), + error_description: z.string().optional(), + error_uri: z.string().optional() +}); +/** + * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri + */ +export const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined)); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata + */ +export const OAuthClientMetadataSchema = z + .object({ + redirect_uris: z.array(SafeUrlSchema), + token_endpoint_auth_method: z.string().optional(), + grant_types: z.array(z.string()).optional(), + response_types: z.array(z.string()).optional(), + client_name: z.string().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: z.string().optional(), + contacts: z.array(z.string()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: z.string().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: z.any().optional(), + software_id: z.string().optional(), + software_version: z.string().optional(), + software_statement: z.string().optional() +}) + .strip(); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration client information + */ +export const OAuthClientInformationSchema = z + .object({ + client_id: z.string(), + client_secret: z.string().optional(), + client_id_issued_at: z.number().optional(), + client_secret_expires_at: z.number().optional() +}) + .strip(); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) + */ +export const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration error response + */ +export const OAuthClientRegistrationErrorSchema = z + .object({ + error: z.string(), + error_description: z.string().optional() +}) + .strip(); +/** + * RFC 7009 OAuth 2.0 Token Revocation request + */ +export const OAuthTokenRevocationRequestSchema = z + .object({ + token: z.string(), + token_type_hint: z.string().optional() +}) + .strip(); +//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js.map new file mode 100644 index 000000000..d529c24a6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/shared/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC;KACzB,GAAG,EAAE;KACL,WAAW,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;IACtB,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,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4B,CAAC,CAAC;AAE9G;;GAEG;AACH,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAC;KAC9C,MAAM,CAAC;IACJ,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;IACjB,iBAAiB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAC3C,CAAC;KACD,KAAK,EAAE,CAAC;AAEb;;GAEG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,CAAC;KAC7C,MAAM,CAAC;IACJ,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;IACjB,eAAe,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACzC,CAAC;KACD,KAAK,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/metadataUtils.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/metadataUtils.d.ts new file mode 100644 index 000000000..9dff76dae --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/metadataUtils.d.ts @@ -0,0 +1,16 @@ +import { BaseMetadata } from '../types.js'; +/** + * Utilities for working with BaseMetadata objects. + */ +/** + * Gets the display name for an object with BaseMetadata. + * For tools, the precedence is: title → annotations.title → name + * For other objects: title → name + * This implements the spec requirement: "if no title is provided, name should be used for display purposes" + */ +export declare function getDisplayName(metadata: BaseMetadata | (BaseMetadata & { + annotations?: { + title?: string; + }; +})): string; +//# sourceMappingURL=metadataUtils.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/metadataUtils.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/metadataUtils.d.ts.map new file mode 100644 index 000000000..9d9929c54 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/metadataUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metadataUtils.d.ts","sourceRoot":"","sources":["../../../src/shared/metadataUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C;;GAEG;AAEH;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,YAAY,GAAG,CAAC,YAAY,GAAG;IAAE,WAAW,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAAC,GAAG,MAAM,CAarH"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/metadataUtils.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/metadataUtils.js new file mode 100644 index 000000000..6d450c089 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/metadataUtils.js @@ -0,0 +1,22 @@ +/** + * Utilities for working with BaseMetadata objects. + */ +/** + * Gets the display name for an object with BaseMetadata. + * For tools, the precedence is: title → annotations.title → name + * For other objects: title → name + * This implements the spec requirement: "if no title is provided, name should be used for display purposes" + */ +export function getDisplayName(metadata) { + // First check for title (not undefined and not empty string) + if (metadata.title !== undefined && metadata.title !== '') { + return metadata.title; + } + // Then check for annotations.title (only present in Tool objects) + if ('annotations' in metadata && metadata.annotations?.title) { + return metadata.annotations.title; + } + // Finally fall back to name + return metadata.name; +} +//# sourceMappingURL=metadataUtils.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/metadataUtils.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/metadataUtils.js.map new file mode 100644 index 000000000..d78868ebb --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/metadataUtils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metadataUtils.js","sourceRoot":"","sources":["../../../src/shared/metadataUtils.ts"],"names":[],"mappings":"AAEA;;GAEG;AAEH;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,QAA8E;IACzG,6DAA6D;IAC7D,IAAI,QAAQ,CAAC,KAAK,KAAK,SAAS,IAAI,QAAQ,CAAC,KAAK,KAAK,EAAE,EAAE,CAAC;QACxD,OAAO,QAAQ,CAAC,KAAK,CAAC;IAC1B,CAAC;IAED,kEAAkE;IAClE,IAAI,aAAa,IAAI,QAAQ,IAAI,QAAQ,CAAC,WAAW,EAAE,KAAK,EAAE,CAAC;QAC3D,OAAO,QAAQ,CAAC,WAAW,CAAC,KAAK,CAAC;IACtC,CAAC;IAED,4BAA4B;IAC5B,OAAO,QAAQ,CAAC,IAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.d.ts new file mode 100644 index 000000000..808bfedf7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.d.ts @@ -0,0 +1,443 @@ +import { AnySchema, AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js'; +import { ClientCapabilities, GetTaskRequest, GetTaskPayloadRequest, ListTasksResultSchema, CancelTaskResultSchema, JSONRPCRequest, Progress, RequestId, Result, ServerCapabilities, RequestMeta, RequestInfo, GetTaskResult, TaskCreationParams, RelatedTaskMetadata, Task, Request, Notification } from '../types.js'; +import { Transport, TransportSendOptions } from './transport.js'; +import { AuthInfo } from '../server/auth/types.js'; +import { TaskStore, TaskMessageQueue, CreateTaskOptions } from '../experimental/tasks/interfaces.js'; +import { ResponseMessage } from './responseMessage.js'; +/** + * Callback for progress notifications. + */ +export type ProgressCallback = (progress: Progress) => void; +/** + * Additional initialization options. + */ +export type ProtocolOptions = { + /** + * Whether to restrict emitted requests to only those that the remote side has indicated that they can handle, through their advertised capabilities. + * + * Note that this DOES NOT affect checking of _local_ side capabilities, as it is considered a logic error to mis-specify those. + * + * Currently this defaults to false, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to true. + */ + enforceStrictCapabilities?: boolean; + /** + * An array of notification method names that should be automatically debounced. + * Any notifications with a method in this list will be coalesced if they + * occur in the same tick of the event loop. + * e.g., ['notifications/tools/list_changed'] + */ + debouncedNotificationMethods?: string[]; + /** + * Optional task storage implementation. If provided, enables task-related request handlers + * and provides task storage capabilities to request handlers. + */ + taskStore?: TaskStore; + /** + * Optional task message queue implementation for managing server-initiated messages + * that will be delivered through the tasks/result response stream. + */ + taskMessageQueue?: TaskMessageQueue; + /** + * Default polling interval (in milliseconds) for task status checks when no pollInterval + * is provided by the server. Defaults to 5000ms if not specified. + */ + defaultTaskPollInterval?: number; + /** + * Maximum number of messages that can be queued per task for side-channel delivery. + * If undefined, the queue size is unbounded. + * When the limit is exceeded, the TaskMessageQueue implementation's enqueue() method + * will throw an error. It's the implementation's responsibility to handle overflow + * appropriately (e.g., by failing the task, dropping messages, etc.). + */ + maxTaskQueueSize?: number; +}; +/** + * The default request timeout, in miliseconds. + */ +export declare const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; +/** + * Options that can be given per request. + */ +export type RequestOptions = { + /** + * If set, requests progress notifications from the remote end (if supported). When progress notifications are received, this callback will be invoked. + * + * For task-augmented requests: progress notifications continue after CreateTaskResult is returned and stop automatically when the task reaches a terminal status. + */ + onprogress?: ProgressCallback; + /** + * Can be used to cancel an in-flight request. This will cause an AbortError to be raised from request(). + */ + signal?: AbortSignal; + /** + * A timeout (in milliseconds) for this request. If exceeded, an McpError with code `RequestTimeout` will be raised from request(). + * + * If not specified, `DEFAULT_REQUEST_TIMEOUT_MSEC` will be used as the timeout. + */ + timeout?: number; + /** + * If true, receiving a progress notification will reset the request timeout. + * This is useful for long-running operations that send periodic progress updates. + * Default: false + */ + resetTimeoutOnProgress?: boolean; + /** + * Maximum total time (in milliseconds) to wait for a response. + * If exceeded, an McpError with code `RequestTimeout` will be raised, regardless of progress notifications. + * If not specified, there is no maximum total timeout. + */ + maxTotalTimeout?: number; + /** + * If provided, augments the request with task creation parameters to enable call-now, fetch-later execution patterns. + */ + task?: TaskCreationParams; + /** + * If provided, associates this request with a related task. + */ + relatedTask?: RelatedTaskMetadata; +} & TransportSendOptions; +/** + * Options that can be given per notification. + */ +export type NotificationOptions = { + /** + * May be used to indicate to the transport which incoming request to associate this outgoing notification with. + */ + relatedRequestId?: RequestId; + /** + * If provided, associates this notification with a related task. + */ + relatedTask?: RelatedTaskMetadata; +}; +/** + * Options that can be given per request. + */ +export type TaskRequestOptions = Omit; +/** + * Request-scoped TaskStore interface. + */ +export interface RequestTaskStore { + /** + * Creates a new task with the given creation parameters. + * The implementation generates a unique taskId and createdAt timestamp. + * + * @param taskParams - The task creation parameters from the request + * @returns The created task object + */ + createTask(taskParams: CreateTaskOptions): Promise; + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @returns The task object + * @throws If the task does not exist + */ + getTask(taskId: string): Promise; + /** + * Stores the result of a task and sets its final status. + * + * @param taskId - The task identifier + * @param status - The final status: 'completed' for success, 'failed' for errors + * @param result - The result to store + */ + storeTaskResult(taskId: string, status: 'completed' | 'failed', result: Result): Promise; + /** + * Retrieves the stored result of a task. + * + * @param taskId - The task identifier + * @returns The stored result + */ + getTaskResult(taskId: string): Promise; + /** + * Updates a task's status (e.g., to 'cancelled', 'failed', 'completed'). + * + * @param taskId - The task identifier + * @param status - The new status + * @param statusMessage - Optional diagnostic message for failed tasks or other status information + */ + updateTaskStatus(taskId: string, status: Task['status'], statusMessage?: string): Promise; + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @param cursor - Optional cursor for pagination + * @returns An object containing the tasks array and an optional nextCursor + */ + listTasks(cursor?: string): Promise<{ + tasks: Task[]; + nextCursor?: string; + }>; +} +/** + * Extra data given to request handlers. + */ +export type RequestHandlerExtra = { + /** + * An abort signal used to communicate if the request was cancelled from the sender's side. + */ + signal: AbortSignal; + /** + * Information about a validated access token, provided to request handlers. + */ + authInfo?: AuthInfo; + /** + * The session ID from the transport, if available. + */ + sessionId?: string; + /** + * Metadata from the original request. + */ + _meta?: RequestMeta; + /** + * The JSON-RPC ID of the request being handled. + * This can be useful for tracking or logging purposes. + */ + requestId: RequestId; + taskId?: string; + taskStore?: RequestTaskStore; + taskRequestedTtl?: number | null; + /** + * The original HTTP request. + */ + requestInfo?: RequestInfo; + /** + * Sends a notification that relates to the current request being handled. + * + * This is used by certain transports to correctly associate related messages. + */ + sendNotification: (notification: SendNotificationT) => Promise; + /** + * Sends a request that relates to the current request being handled. + * + * This is used by certain transports to correctly associate related messages. + */ + sendRequest: (request: SendRequestT, resultSchema: U, options?: TaskRequestOptions) => Promise>; + /** + * Closes the SSE stream for this request, triggering client reconnection. + * Only available when using StreamableHTTPServerTransport with eventStore configured. + * Use this to implement polling behavior during long-running operations. + */ + closeSSEStream?: () => void; + /** + * Closes the standalone GET SSE stream, triggering client reconnection. + * Only available when using StreamableHTTPServerTransport with eventStore configured. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream?: () => void; +}; +/** + * Implements MCP protocol framing on top of a pluggable transport, including + * features like request/response linking, notifications, and progress. + */ +export declare abstract class Protocol { + private _options?; + private _transport?; + private _requestMessageId; + private _requestHandlers; + private _requestHandlerAbortControllers; + private _notificationHandlers; + private _responseHandlers; + private _progressHandlers; + private _timeoutInfo; + private _pendingDebouncedNotifications; + private _taskProgressTokens; + private _taskStore?; + private _taskMessageQueue?; + private _requestResolvers; + /** + * Callback for when the connection is closed for any reason. + * + * This is invoked when close() is called as well. + */ + onclose?: () => void; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror?: (error: Error) => void; + /** + * A handler to invoke for any request types that do not have their own handler installed. + */ + fallbackRequestHandler?: (request: JSONRPCRequest, extra: RequestHandlerExtra) => Promise; + /** + * A handler to invoke for any notification types that do not have their own handler installed. + */ + fallbackNotificationHandler?: (notification: Notification) => Promise; + constructor(_options?: ProtocolOptions | undefined); + private _oncancel; + private _setupTimeout; + private _resetTimeout; + private _cleanupTimeout; + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + connect(transport: Transport): Promise; + private _onclose; + private _onerror; + private _onnotification; + private _onrequest; + private _onprogress; + private _onresponse; + get transport(): Transport | undefined; + /** + * Closes the connection. + */ + close(): Promise; + /** + * A method to check if a capability is supported by the remote side, for the given method to be called. + * + * This should be implemented by subclasses. + */ + protected abstract assertCapabilityForMethod(method: SendRequestT['method']): void; + /** + * A method to check if a notification is supported by the local side, for the given method to be sent. + * + * This should be implemented by subclasses. + */ + protected abstract assertNotificationCapability(method: SendNotificationT['method']): void; + /** + * A method to check if a request handler is supported by the local side, for the given method to be handled. + * + * This should be implemented by subclasses. + */ + protected abstract assertRequestHandlerCapability(method: string): void; + /** + * A method to check if task creation is supported for the given request method. + * + * This should be implemented by subclasses. + */ + protected abstract assertTaskCapability(method: string): void; + /** + * A method to check if task handler is supported by the local side, for the given method to be handled. + * + * This should be implemented by subclasses. + */ + protected abstract assertTaskHandlerCapability(method: string): void; + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * @example + * ```typescript + * const stream = protocol.requestStream(request, resultSchema, options); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @experimental Use `client.experimental.tasks.requestStream()` to access this method. + */ + protected requestStream(request: SendRequestT, resultSchema: T, options?: RequestOptions): AsyncGenerator>, void, void>; + /** + * Sends a request and waits for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request: SendRequestT, resultSchema: T, options?: RequestOptions): Promise>; + /** + * Gets the current status of a task. + * + * @experimental Use `client.experimental.tasks.getTask()` to access this method. + */ + protected getTask(params: GetTaskRequest['params'], options?: RequestOptions): Promise; + /** + * Retrieves the result of a completed task. + * + * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. + */ + protected getTaskResult(params: GetTaskPayloadRequest['params'], resultSchema: T, options?: RequestOptions): Promise>; + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @experimental Use `client.experimental.tasks.listTasks()` to access this method. + */ + protected listTasks(params?: { + cursor?: string; + }, options?: RequestOptions): Promise>; + /** + * Cancels a specific task. + * + * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. + */ + protected cancelTask(params: { + taskId: string; + }, options?: RequestOptions): Promise>; + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + notification(notification: SendNotificationT, options?: NotificationOptions): Promise; + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => SendResultT | Promise): void; + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method: string): void; + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method: string): void; + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema: T, handler: (notification: SchemaOutput) => void | Promise): void; + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method: string): void; + /** + * Cleans up the progress handler associated with a task. + * This should be called when a task reaches a terminal status. + */ + private _cleanupTaskProgressHandler; + /** + * Enqueues a task-related message for side-channel delivery via tasks/result. + * @param taskId The task ID to associate the message with + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) + * + * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle + * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer + * simply propagates the error. + */ + private _enqueueTaskMessage; + /** + * Clears the message queue for a task and rejects any pending request resolvers. + * @param taskId The task ID whose queue should be cleared + * @param sessionId Optional session ID for binding the operation to a specific session + */ + private _clearTaskQueue; + /** + * Waits for a task update (new messages or status change) with abort signal support. + * Uses polling to check for updates at the task's configured poll interval. + * @param taskId The task ID to wait for + * @param signal Abort signal to cancel the wait + * @returns Promise that resolves when an update occurs or rejects if aborted + */ + private _waitForTaskUpdate; + private requestTaskStore; +} +export declare function mergeCapabilities(base: ServerCapabilities, additional: Partial): ServerCapabilities; +export declare function mergeCapabilities(base: ClientCapabilities, additional: Partial): ClientCapabilities; +//# sourceMappingURL=protocol.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.d.ts.map new file mode 100644 index 000000000..b669a018a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../../src/shared/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,YAAY,EAAa,MAAM,yBAAyB,CAAC;AAC9F,OAAO,EAEH,kBAAkB,EAGlB,cAAc,EAGd,qBAAqB,EAGrB,qBAAqB,EAErB,sBAAsB,EAOtB,cAAc,EAId,QAAQ,EAIR,SAAS,EACT,MAAM,EACN,kBAAkB,EAClB,WAAW,EAEX,WAAW,EACX,aAAa,EACb,kBAAkB,EAClB,mBAAmB,EAEnB,IAAI,EAGJ,OAAO,EACP,YAAY,EAGf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAc,SAAS,EAAE,gBAAgB,EAAiB,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAEhI,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEvD;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,CA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AAO,EAAE,CACL,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,EACxB,KAAK,EAAE,mBAAmB,CAAC,YAAY,EAAE,iBAAiB,CAAC,KAC1D,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,GACxC,IAAI;IAUP;;OAEG;IACH,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI1C;;OAEG;IACH,0BAA0B,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAMhD;;;;OAIG;IACH,sBAAsB,CAAC,CAAC,SAAS,eAAe,EAC5C,kBAAkB,EAAE,CAAC,EACrB,OAAO,EAAE,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GACjE,IAAI;IAQP;;OAEG;IACH,yBAAyB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI/C;;;OAGG;IACH,OAAO,CAAC,2BAA2B;IAQnC;;;;;;;;;;OAUG;YACW,mBAAmB;IAUjC;;;;OAIG;YACW,eAAe;IAqB7B;;;;;;OAMG;YACW,kBAAkB;IAiChC,OAAO,CAAC,gBAAgB;CAwF3B;AAMD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,kBAAkB,CAAC;AACzH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,kBAAkB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js new file mode 100644 index 000000000..02388a39e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js @@ -0,0 +1,1086 @@ +import { safeParse } from '../server/zod-compat.js'; +import { CancelledNotificationSchema, CreateTaskResultSchema, ErrorCode, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCNotification, McpError, PingRequestSchema, ProgressNotificationSchema, RELATED_TASK_META_KEY, TaskStatusNotificationSchema, isTaskAugmentedRequestParams } from '../types.js'; +import { isTerminal } from '../experimental/tasks/interfaces.js'; +import { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js'; +/** + * The default request timeout, in miliseconds. + */ +export const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; +/** + * Implements MCP protocol framing on top of a pluggable transport, including + * features like request/response linking, notifications, and progress. + */ +export class Protocol { + constructor(_options) { + this._options = _options; + this._requestMessageId = 0; + this._requestHandlers = new Map(); + this._requestHandlerAbortControllers = new Map(); + this._notificationHandlers = new Map(); + this._responseHandlers = new Map(); + this._progressHandlers = new Map(); + this._timeoutInfo = new Map(); + this._pendingDebouncedNotifications = new Set(); + // Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult + this._taskProgressTokens = new Map(); + this._requestResolvers = new Map(); + this.setNotificationHandler(CancelledNotificationSchema, notification => { + this._oncancel(notification); + }); + this.setNotificationHandler(ProgressNotificationSchema, notification => { + this._onprogress(notification); + }); + this.setRequestHandler(PingRequestSchema, + // Automatic pong by default. + _request => ({})); + // Install task handlers if TaskStore is provided + this._taskStore = _options?.taskStore; + this._taskMessageQueue = _options?.taskMessageQueue; + if (this._taskStore) { + this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found'); + } + // Per spec: tasks/get responses SHALL NOT include related-task metadata + // as the taskId parameter is the source of truth + // @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else + return { + ...task + }; + }); + this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { + const handleTaskResult = async () => { + const taskId = request.params.taskId; + // Deliver queued messages + if (this._taskMessageQueue) { + let queuedMessage; + while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) { + // Handle response and error messages by routing them to the appropriate resolver + if (queuedMessage.type === 'response' || queuedMessage.type === 'error') { + const message = queuedMessage.message; + const requestId = message.id; + // Lookup resolver in _requestResolvers map + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + // Remove resolver from map after invocation + this._requestResolvers.delete(requestId); + // Invoke resolver with response or error + if (queuedMessage.type === 'response') { + resolver(message); + } + else { + // Convert JSONRPCError to McpError + const errorMessage = message; + const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data); + resolver(error); + } + } + else { + // Handle missing resolver gracefully with error logging + const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error'; + this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); + } + // Continue to next message + continue; + } + // Send the message on the response stream by passing the relatedRequestId + // This tells the transport to write the message to the tasks/result response stream + await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); + } + } + // Now check task status + const task = await this._taskStore.getTask(taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); + } + // Block if task is not terminal (we've already delivered all queued messages above) + if (!isTerminal(task.status)) { + // Wait for status change or new messages + await this._waitForTaskUpdate(taskId, extra.signal); + // After waking up, recursively call to deliver any new messages or result + return await handleTaskResult(); + } + // If task is terminal, return the result + if (isTerminal(task.status)) { + const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); + this._clearTaskQueue(taskId); + return { + ...result, + _meta: { + ...result._meta, + [RELATED_TASK_META_KEY]: { + taskId: taskId + } + } + }; + } + return await handleTaskResult(); + }; + return await handleTaskResult(); + }); + this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { + try { + const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); + // @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else + return { + tasks, + nextCursor, + _meta: {} + }; + } + catch (error) { + throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`); + } + }); + this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { + try { + // Get the current task to check if it's in a terminal state, in case the implementation is not atomic + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); + } + // Reject cancellation of terminal tasks + if (isTerminal(task.status)) { + throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); + } + await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId); + this._clearTaskQueue(request.params.taskId); + const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!cancelledTask) { + // Task was deleted during cancellation (e.g., cleanup happened) + throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); + } + return { + _meta: {}, + ...cancelledTask + }; + } + catch (error) { + // Re-throw McpError as-is + if (error instanceof McpError) { + throw error; + } + throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`); + } + }); + } + } + async _oncancel(notification) { + if (!notification.params.requestId) { + return; + } + // Handle request cancellation + const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); + controller?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) + return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport) { + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + _onclose?.(); + this._onclose(); + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error) => { + _onerror?.(error); + this._onerror(error); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._onresponse(message); + } + else if (isJSONRPCRequest(message)) { + this._onrequest(message, extra); + } + else if (isJSONRPCNotification(message)) { + this._onnotification(message); + } + else { + this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); + } + }; + await this._transport.start(); + } + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = new Map(); + this._progressHandlers.clear(); + this._taskProgressTokens.clear(); + this._pendingDebouncedNotifications.clear(); + const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed'); + this._transport = undefined; + this.onclose?.(); + for (const handler of responseHandlers.values()) { + handler(error); + } + } + _onerror(error) { + this.onerror?.(error); + } + _onnotification(notification) { + const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; + // Ignore notifications not being subscribed to. + if (handler === undefined) { + return; + } + // Starting with Promise.resolve() puts any synchronous errors into the monad as well. + Promise.resolve() + .then(() => handler(notification)) + .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`))); + } + _onrequest(request, extra) { + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + // Capture the current transport at request time to ensure responses go to the correct client + const capturedTransport = this._transport; + // Extract taskId from request metadata if present (needed early for method not found case) + const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; + if (handler === undefined) { + const errorResponse = { + jsonrpc: '2.0', + id: request.id, + error: { + code: ErrorCode.MethodNotFound, + message: 'Method not found' + } + }; + // Queue or send the error response based on whether this is a task-related request + if (relatedTaskId && this._taskMessageQueue) { + this._enqueueTaskMessage(relatedTaskId, { + type: 'error', + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`))); + } + else { + capturedTransport + ?.send(errorResponse) + .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`))); + } + return; + } + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined; + const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined; + const fullExtra = { + signal: abortController.signal, + sessionId: capturedTransport?.sessionId, + _meta: request.params?._meta, + sendNotification: async (notification) => { + // Include related-task metadata if this request is part of a task + const notificationOptions = { relatedRequestId: request.id }; + if (relatedTaskId) { + notificationOptions.relatedTask = { taskId: relatedTaskId }; + } + await this.notification(notification, notificationOptions); + }, + sendRequest: async (r, resultSchema, options) => { + // Include related-task metadata if this request is part of a task + const requestOptions = { ...options, relatedRequestId: request.id }; + if (relatedTaskId && !requestOptions.relatedTask) { + requestOptions.relatedTask = { taskId: relatedTaskId }; + } + // Set task status to input_required when sending a request within a task context + // Use the taskId from options (explicit) or fall back to relatedTaskId (inherited) + const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; + if (effectiveTaskId && taskStore) { + await taskStore.updateTaskStatus(effectiveTaskId, 'input_required'); + } + return await this.request(r, resultSchema, requestOptions); + }, + authInfo: extra?.authInfo, + requestId: request.id, + requestInfo: extra?.requestInfo, + taskId: relatedTaskId, + taskStore: taskStore, + taskRequestedTtl: taskCreationParams?.ttl, + closeSSEStream: extra?.closeSSEStream, + closeStandaloneSSEStream: extra?.closeStandaloneSSEStream + }; + // Starting with Promise.resolve() puts any synchronous errors into the monad as well. + Promise.resolve() + .then(() => { + // If this request asked for task creation, check capability first + if (taskCreationParams) { + // Check if the request method supports task creation + this.assertTaskHandlerCapability(request.method); + } + }) + .then(() => handler(request, fullExtra)) + .then(async (result) => { + if (abortController.signal.aborted) { + // Request was cancelled + return; + } + const response = { + result, + jsonrpc: '2.0', + id: request.id + }; + // Queue or send the response based on whether this is a task-related request + if (relatedTaskId && this._taskMessageQueue) { + await this._enqueueTaskMessage(relatedTaskId, { + type: 'response', + message: response, + timestamp: Date.now() + }, capturedTransport?.sessionId); + } + else { + await capturedTransport?.send(response); + } + }, async (error) => { + if (abortController.signal.aborted) { + // Request was cancelled + return; + } + const errorResponse = { + jsonrpc: '2.0', + id: request.id, + error: { + code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError, + message: error.message ?? 'Internal error', + ...(error['data'] !== undefined && { data: error['data'] }) + } + }; + // Queue or send the error response based on whether this is a task-related request + if (relatedTaskId && this._taskMessageQueue) { + await this._enqueueTaskMessage(relatedTaskId, { + type: 'error', + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId); + } + else { + await capturedTransport?.send(errorResponse); + } + }) + .catch(error => this._onerror(new Error(`Failed to send response: ${error}`))) + .finally(() => { + this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { + try { + this._resetTimeout(messageId); + } + catch (error) { + // Clean up if maxTotalTimeout was exceeded + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error); + return; + } + } + handler(params); + } + _onresponse(response) { + const messageId = Number(response.id); + // Check if this is a response to a queued request + const resolver = this._requestResolvers.get(messageId); + if (resolver) { + this._requestResolvers.delete(messageId); + if (isJSONRPCResultResponse(response)) { + resolver(response); + } + else { + const error = new McpError(response.error.code, response.error.message, response.error.data); + resolver(error); + } + return; + } + const handler = this._responseHandlers.get(messageId); + if (handler === undefined) { + this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + // Keep progress handler alive for CreateTaskResult responses + let isTaskResponse = false; + if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') { + const result = response.result; + if (result.task && typeof result.task === 'object') { + const task = result.task; + if (typeof task.taskId === 'string') { + isTaskResponse = true; + this._taskProgressTokens.set(task.taskId, messageId); + } + } + } + if (!isTaskResponse) { + this._progressHandlers.delete(messageId); + } + if (isJSONRPCResultResponse(response)) { + handler(response); + } + else { + const error = McpError.fromError(response.error.code, response.error.message, response.error.data); + handler(error); + } + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * @example + * ```typescript + * const stream = protocol.requestStream(request, resultSchema, options); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @experimental Use `client.experimental.tasks.requestStream()` to access this method. + */ + async *requestStream(request, resultSchema, options) { + const { task } = options ?? {}; + // For non-task requests, just yield the result + if (!task) { + try { + const result = await this.request(request, resultSchema, options); + yield { type: 'result', result }; + } + catch (error) { + yield { + type: 'error', + error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error)) + }; + } + return; + } + // For task-augmented requests, we need to poll for status + // First, make the request to create the task + let taskId; + try { + // Send the request and get the CreateTaskResult + const createResult = await this.request(request, CreateTaskResultSchema, options); + // Extract taskId from the result + if (createResult.task) { + taskId = createResult.task.taskId; + yield { type: 'taskCreated', task: createResult.task }; + } + else { + throw new McpError(ErrorCode.InternalError, 'Task creation did not return a task'); + } + // Poll for task completion + while (true) { + // Get current task status + const task = await this.getTask({ taskId }, options); + yield { type: 'taskStatus', task }; + // Check if task is terminal + if (isTerminal(task.status)) { + if (task.status === 'completed') { + // Get the final result + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: 'result', result }; + } + else if (task.status === 'failed') { + yield { + type: 'error', + error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) + }; + } + else if (task.status === 'cancelled') { + yield { + type: 'error', + error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) + }; + } + return; + } + // When input_required, call tasks/result to deliver queued messages + // (elicitation, sampling) via SSE and block until terminal + if (task.status === 'input_required') { + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: 'result', result }; + return; + } + // Wait before polling again + const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000; + await new Promise(resolve => setTimeout(resolve, pollInterval)); + // Check if cancelled + options?.signal?.throwIfAborted(); + } + } + catch (error) { + yield { + type: 'error', + error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error)) + }; + } + } + /** + * Sends a request and waits for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; + // Send the request + return new Promise((resolve, reject) => { + const earlyReject = (error) => { + reject(error); + }; + if (!this._transport) { + earlyReject(new Error('Not connected')); + return; + } + if (this._options?.enforceStrictCapabilities === true) { + try { + this.assertCapabilityForMethod(request.method); + // If task creation is requested, also check task capabilities + if (task) { + this.assertTaskCapability(request.method); + } + } + catch (e) { + earlyReject(e); + return; + } + } + options?.signal?.throwIfAborted(); + const messageId = this._requestMessageId++; + const jsonrpcRequest = { + ...request, + jsonrpc: '2.0', + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...(request.params?._meta || {}), + progressToken: messageId + } + }; + } + // Augment with task creation parameters if provided + if (task) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + task: task + }; + } + // Augment with related task metadata if relatedTask is provided + if (relatedTask) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + _meta: { + ...(jsonrpcRequest.params?._meta || {}), + [RELATED_TASK_META_KEY]: relatedTask + } + }; + } + const cancel = (reason) => { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._transport + ?.send({ + jsonrpc: '2.0', + method: 'notifications/cancelled', + params: { + requestId: messageId, + reason: String(reason) + } + }, { relatedRequestId, resumptionToken, onresumptiontoken }) + .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`))); + // Wrap the reason in an McpError if it isn't already + const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)); + reject(error); + }; + this._responseHandlers.set(messageId, response => { + if (options?.signal?.aborted) { + return; + } + if (response instanceof Error) { + return reject(response); + } + try { + const parseResult = safeParse(resultSchema, response.result); + if (!parseResult.success) { + // Type guard: if success is false, error is guaranteed to exist + reject(parseResult.error); + } + else { + resolve(parseResult.data); + } + } + catch (error) { + reject(error); + } + }); + options?.signal?.addEventListener('abort', () => { + cancel(options?.signal?.reason); + }); + const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + // Queue request if related to a task + const relatedTaskId = relatedTask?.taskId; + if (relatedTaskId) { + // Store the response resolver for this request so responses can be routed back + const responseResolver = (response) => { + const handler = this._responseHandlers.get(messageId); + if (handler) { + handler(response); + } + else { + // Log error when resolver is missing, but don't fail + this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); + } + }; + this._requestResolvers.set(messageId, responseResolver); + this._enqueueTaskMessage(relatedTaskId, { + type: 'request', + message: jsonrpcRequest, + timestamp: Date.now() + }).catch(error => { + this._cleanupTimeout(messageId); + reject(error); + }); + // Don't send through transport - queued messages are delivered via tasks/result only + // This prevents duplicate delivery for bidirectional transports + } + else { + // No related task - send through transport normally + this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => { + this._cleanupTimeout(messageId); + reject(error); + }); + } + }); + } + /** + * Gets the current status of a task. + * + * @experimental Use `client.experimental.tasks.getTask()` to access this method. + */ + async getTask(params, options) { + // @ts-expect-error SendRequestT cannot directly contain GetTaskRequest, but we ensure all type instantiations contain it anyways + return this.request({ method: 'tasks/get', params }, GetTaskResultSchema, options); + } + /** + * Retrieves the result of a completed task. + * + * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. + */ + async getTaskResult(params, resultSchema, options) { + // @ts-expect-error SendRequestT cannot directly contain GetTaskPayloadRequest, but we ensure all type instantiations contain it anyways + return this.request({ method: 'tasks/result', params }, resultSchema, options); + } + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @experimental Use `client.experimental.tasks.listTasks()` to access this method. + */ + async listTasks(params, options) { + // @ts-expect-error SendRequestT cannot directly contain ListTasksRequest, but we ensure all type instantiations contain it anyways + return this.request({ method: 'tasks/list', params }, ListTasksResultSchema, options); + } + /** + * Cancels a specific task. + * + * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. + */ + async cancelTask(params, options) { + // @ts-expect-error SendRequestT cannot directly contain CancelTaskRequest, but we ensure all type instantiations contain it anyways + return this.request({ method: 'tasks/cancel', params }, CancelTaskResultSchema, options); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + if (!this._transport) { + throw new Error('Not connected'); + } + this.assertNotificationCapability(notification.method); + // Queue notification if related to a task + const relatedTaskId = options?.relatedTask?.taskId; + if (relatedTaskId) { + // Build the JSONRPC notification with metadata + const jsonrpcNotification = { + ...notification, + jsonrpc: '2.0', + params: { + ...notification.params, + _meta: { + ...(notification.params?._meta || {}), + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + await this._enqueueTaskMessage(relatedTaskId, { + type: 'notification', + message: jsonrpcNotification, + timestamp: Date.now() + }); + // Don't send through transport - queued messages are delivered via tasks/result only + // This prevents duplicate delivery for bidirectional transports + return; + } + const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; + // A notification can only be debounced if it's in the list AND it's "simple" + // (i.e., has no parameters and no related request ID or related task that could be lost). + const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask; + if (canDebounce) { + // If a notification of this type is already scheduled, do nothing. + if (this._pendingDebouncedNotifications.has(notification.method)) { + return; + } + // Mark this notification type as pending. + this._pendingDebouncedNotifications.add(notification.method); + // Schedule the actual send to happen in the next microtask. + // This allows all synchronous calls in the current event loop tick to be coalesced. + Promise.resolve().then(() => { + // Un-mark the notification so the next one can be scheduled. + this._pendingDebouncedNotifications.delete(notification.method); + // SAFETY CHECK: If the connection was closed while this was pending, abort. + if (!this._transport) { + return; + } + let jsonrpcNotification = { + ...notification, + jsonrpc: '2.0' + }; + // Augment with related task metadata if relatedTask is provided + if (options?.relatedTask) { + jsonrpcNotification = { + ...jsonrpcNotification, + params: { + ...jsonrpcNotification.params, + _meta: { + ...(jsonrpcNotification.params?._meta || {}), + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + // Send the notification, but don't await it here to avoid blocking. + // Handle potential errors with a .catch(). + this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error)); + }); + // Return immediately. + return; + } + let jsonrpcNotification = { + ...notification, + jsonrpc: '2.0' + }; + // Augment with related task metadata if relatedTask is provided + if (options?.relatedTask) { + jsonrpcNotification = { + ...jsonrpcNotification, + params: { + ...jsonrpcNotification.params, + _meta: { + ...(jsonrpcNotification.params?._meta || {}), + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + await this._transport.send(jsonrpcNotification, options); + } + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema, handler) { + const method = getMethodLiteral(requestSchema); + this.assertRequestHandlerCapability(method); + this._requestHandlers.set(method, (request, extra) => { + const parsed = parseWithCompat(requestSchema, request); + return Promise.resolve(handler(parsed, extra)); + }); + } + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) { + throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + } + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema, handler) { + const method = getMethodLiteral(notificationSchema); + this._notificationHandlers.set(method, notification => { + const parsed = parseWithCompat(notificationSchema, notification); + return Promise.resolve(handler(parsed)); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } + /** + * Cleans up the progress handler associated with a task. + * This should be called when a task reaches a terminal status. + */ + _cleanupTaskProgressHandler(taskId) { + const progressToken = this._taskProgressTokens.get(taskId); + if (progressToken !== undefined) { + this._progressHandlers.delete(progressToken); + this._taskProgressTokens.delete(taskId); + } + } + /** + * Enqueues a task-related message for side-channel delivery via tasks/result. + * @param taskId The task ID to associate the message with + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) + * + * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle + * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer + * simply propagates the error. + */ + async _enqueueTaskMessage(taskId, message, sessionId) { + // Task message queues are only used when taskStore is configured + if (!this._taskStore || !this._taskMessageQueue) { + throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured'); + } + const maxQueueSize = this._options?.maxTaskQueueSize; + await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize); + } + /** + * Clears the message queue for a task and rejects any pending request resolvers. + * @param taskId The task ID whose queue should be cleared + * @param sessionId Optional session ID for binding the operation to a specific session + */ + async _clearTaskQueue(taskId, sessionId) { + if (this._taskMessageQueue) { + // Reject any pending request resolvers + const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); + for (const message of messages) { + if (message.type === 'request' && isJSONRPCRequest(message.message)) { + // Extract request ID from the message + const requestId = message.message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + resolver(new McpError(ErrorCode.InternalError, 'Task cancelled or completed')); + this._requestResolvers.delete(requestId); + } + else { + // Log error when resolver is missing during cleanup for better observability + this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); + } + } + } + } + } + /** + * Waits for a task update (new messages or status change) with abort signal support. + * Uses polling to check for updates at the task's configured poll interval. + * @param taskId The task ID to wait for + * @param signal Abort signal to cancel the wait + * @returns Promise that resolves when an update occurs or rejects if aborted + */ + async _waitForTaskUpdate(taskId, signal) { + // Get the task's poll interval, falling back to default + let interval = this._options?.defaultTaskPollInterval ?? 1000; + try { + const task = await this._taskStore?.getTask(taskId); + if (task?.pollInterval) { + interval = task.pollInterval; + } + } + catch { + // Use default interval if task lookup fails + } + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled')); + return; + } + // Wait for the poll interval, then resolve so caller can check for updates + const timeoutId = setTimeout(resolve, interval); + // Clean up timeout and reject if aborted + signal.addEventListener('abort', () => { + clearTimeout(timeoutId); + reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled')); + }, { once: true }); + }); + } + requestTaskStore(request, sessionId) { + const taskStore = this._taskStore; + if (!taskStore) { + throw new Error('No task store configured'); + } + return { + createTask: async (taskParams) => { + if (!request) { + throw new Error('No request provided'); + } + return await taskStore.createTask(taskParams, request.id, { + method: request.method, + params: request.params + }, sessionId); + }, + getTask: async (taskId) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found'); + } + return task; + }, + storeTaskResult: async (taskId, status, result) => { + await taskStore.storeTaskResult(taskId, status, result, sessionId); + // Get updated task state and send notification + const task = await taskStore.getTask(taskId, sessionId); + if (task) { + const notification = TaskStatusNotificationSchema.parse({ + method: 'notifications/tasks/status', + params: task + }); + await this.notification(notification); + if (isTerminal(task.status)) { + this._cleanupTaskProgressHandler(taskId); + // Don't clear queue here - it will be cleared after delivery via tasks/result + } + } + }, + getTaskResult: taskId => { + return taskStore.getTaskResult(taskId, sessionId); + }, + updateTaskStatus: async (taskId, status, statusMessage) => { + // Check if task exists + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); + } + // Don't allow transitions from terminal states + if (isTerminal(task.status)) { + throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); + } + await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); + // Get updated task state and send notification + const updatedTask = await taskStore.getTask(taskId, sessionId); + if (updatedTask) { + const notification = TaskStatusNotificationSchema.parse({ + method: 'notifications/tasks/status', + params: updatedTask + }); + await this.notification(notification); + if (isTerminal(updatedTask.status)) { + this._cleanupTaskProgressHandler(taskId); + // Don't clear queue here - it will be cleared after delivery via tasks/result + } + } + }, + listTasks: cursor => { + return taskStore.listTasks(cursor, sessionId); + } + }; + } +} +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +export function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === undefined) + continue; + const baseValue = result[k]; + if (isPlainObject(baseValue) && isPlainObject(addValue)) { + result[k] = { ...baseValue, ...addValue }; + } + else { + result[k] = addValue; + } + } + return result; +} +//# sourceMappingURL=protocol.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js.map new file mode 100644 index 000000000..a4d0ad378 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js.map @@ -0,0 +1 @@ +{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../../src/shared/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4C,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAC9F,OAAO,EACH,2BAA2B,EAE3B,sBAAsB,EACtB,SAAS,EAET,oBAAoB,EACpB,mBAAmB,EAEnB,2BAA2B,EAC3B,sBAAsB,EACtB,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,EACtB,sBAAsB,EACtB,gBAAgB,EAChB,uBAAuB,EACvB,qBAAqB,EAKrB,QAAQ,EACR,iBAAiB,EAGjB,0BAA0B,EAC1B,qBAAqB,EAarB,4BAA4B,EAI5B,4BAA4B,EAC/B,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,UAAU,EAAiE,MAAM,qCAAqC,CAAC;AAChI,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAoDxF;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAkNlD;;;GAGG;AACH,MAAM,OAAgB,QAAQ;IA8C1B,YAAoB,QAA0B;QAA1B,aA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aAAa,CAAC,SAAS,CAAC,IAAI,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC;YACtD,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,GAAI,SAAqC,EAAE,GAAI,QAAoC,EAAiB,CAAC;QACvH,CAAC;aAAM,CAAC;YACJ,MAAM,CAAC,CAAC,CAAC,GAAG,QAAuB,CAAC;QACxC,CAAC;IACL,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/responseMessage.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/responseMessage.d.ts new file mode 100644 index 000000000..84354bdb7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/responseMessage.d.ts @@ -0,0 +1,45 @@ +import { Result, Task, McpError } from '../types.js'; +/** + * Base message type + */ +export interface BaseResponseMessage { + type: string; +} +/** + * Task status update message + */ +export interface TaskStatusMessage extends BaseResponseMessage { + type: 'taskStatus'; + task: Task; +} +/** + * Task created message (first message for task-augmented requests) + */ +export interface TaskCreatedMessage extends BaseResponseMessage { + type: 'taskCreated'; + task: Task; +} +/** + * Final result message (terminal) + */ +export interface ResultMessage extends BaseResponseMessage { + type: 'result'; + result: T; +} +/** + * Error message (terminal) + */ +export interface ErrorMessage extends BaseResponseMessage { + type: 'error'; + error: McpError; +} +/** + * Union type representing all possible messages that can be yielded during request processing. + * Note: Progress notifications are handled through the existing onprogress callback mechanism. + * Side-channeled messages (server requests/notifications) are handled through registered handlers. + */ +export type ResponseMessage = TaskStatusMessage | TaskCreatedMessage | ResultMessage | ErrorMessage; +export type AsyncGeneratorValue = T extends AsyncGenerator ? U : never; +export declare function toArrayAsync>(it: T): Promise[]>; +export declare function takeResult>>(it: U): Promise; +//# sourceMappingURL=responseMessage.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/responseMessage.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/responseMessage.d.ts.map new file mode 100644 index 000000000..65d93bb50 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/responseMessage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"responseMessage.d.ts","sourceRoot":"","sources":["../../../src/shared/responseMessage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAErD;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAChC,IAAI,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAkB,SAAQ,mBAAmB;IAC1D,IAAI,EAAE,YAAY,CAAC;IACnB,IAAI,EAAE,IAAI,CAAC;CACd;AAED;;GAEG;AACH,MAAM,WAAW,kBAAmB,SAAQ,mBAAmB;IAC3D,IAAI,EAAE,aAAa,CAAC;IACpB,IAAI,EAAE,IAAI,CAAC;CACd;AAED;;GAEG;AACH,MAAM,WAAW,aAAa,CAAC,CAAC,SAAS,MAAM,CAAE,SAAQ,mBAAmB;IACxE,IAAI,EAAE,QAAQ,CAAC;IACf,MAAM,EAAE,CAAC,CAAC;CACb;AAED;;GAEG;AACH,MAAM,WAAW,YAAa,SAAQ,mBAAmB;IACrD,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EAAE,QAAQ,CAAC;CACnB;AAED;;;;GAIG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,MAAM,IAAI,iBAAiB,GAAG,kBAAkB,GAAG,aAAa,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC;AAEzH,MAAM,MAAM,mBAAmB,CAAC,CAAC,IAAI,CAAC,SAAS,cAAc,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAEnF,wBAAsB,YAAY,CAAC,CAAC,SAAS,cAAc,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC,CAAC,EAAE,CAAC,CAO9G;AAED,wBAAsB,UAAU,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,cAAc,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAUlH"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/responseMessage.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/responseMessage.js new file mode 100644 index 000000000..d29e8a450 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/responseMessage.js @@ -0,0 +1,19 @@ +export async function toArrayAsync(it) { + const arr = []; + for await (const o of it) { + arr.push(o); + } + return arr; +} +export async function takeResult(it) { + for await (const o of it) { + if (o.type === 'result') { + return o.result; + } + else if (o.type === 'error') { + throw o.error; + } + } + throw new Error('No result in stream.'); +} +//# sourceMappingURL=responseMessage.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/responseMessage.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/responseMessage.js.map new file mode 100644 index 000000000..eca1ceccb --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/responseMessage.js.map @@ -0,0 +1 @@ +{"version":3,"file":"responseMessage.js","sourceRoot":"","sources":["../../../src/shared/responseMessage.ts"],"names":[],"mappings":"AAkDA,MAAM,CAAC,KAAK,UAAU,YAAY,CAAoC,EAAK;IACvE,MAAM,GAAG,GAA6B,EAAE,CAAC;IACzC,IAAI,KAAK,EAAE,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;QACvB,GAAG,CAAC,IAAI,CAAC,CAA2B,CAAC,CAAC;IAC1C,CAAC;IAED,OAAO,GAAG,CAAC;AACf,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,UAAU,CAAiE,EAAK;IAClG,IAAI,KAAK,EAAE,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;QACvB,IAAI,CAAC,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACtB,OAAO,CAAC,CAAC,MAAM,CAAC;QACpB,CAAC;aAAM,IAAI,CAAC,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;YAC5B,MAAM,CAAC,CAAC,KAAK,CAAC;QAClB,CAAC;IACL,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;AAC5C,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.d.ts new file mode 100644 index 000000000..0830a48bc --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.d.ts @@ -0,0 +1,13 @@ +import { JSONRPCMessage } from '../types.js'; +/** + * Buffers a continuous stdio stream into discrete JSON-RPC messages. + */ +export declare class ReadBuffer { + private _buffer?; + append(chunk: Buffer): void; + readMessage(): JSONRPCMessage | null; + clear(): void; +} +export declare function deserializeMessage(line: string): JSONRPCMessage; +export declare function serializeMessage(message: JSONRPCMessage): string; +//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.d.ts.map new file mode 100644 index 000000000..8f97f2ab1 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/shared/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAEnE;;GAEG;AACH,qBAAa,UAAU;IACnB,OAAO,CAAC,OAAO,CAAC,CAAS;IAEzB,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAI3B,WAAW,IAAI,cAAc,GAAG,IAAI;IAepC,KAAK,IAAI,IAAI;CAGhB;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,CAE/D;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM,CAEhE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js new file mode 100644 index 000000000..30f299f5a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js @@ -0,0 +1,31 @@ +import { JSONRPCMessageSchema } from '../types.js'; +/** + * Buffers a continuous stdio stream into discrete JSON-RPC messages. + */ +export class ReadBuffer { + append(chunk) { + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + if (!this._buffer) { + return null; + } + const index = this._buffer.indexOf('\n'); + if (index === -1) { + return null; + } + const line = this._buffer.toString('utf8', 0, index).replace(/\r$/, ''); + this._buffer = this._buffer.subarray(index + 1); + return deserializeMessage(line); + } + clear() { + this._buffer = undefined; + } +} +export function deserializeMessage(line) { + return JSONRPCMessageSchema.parse(JSON.parse(line)); +} +export function serializeMessage(message) { + return JSON.stringify(message) + '\n'; +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js.map new file mode 100644 index 000000000..19fdf08d8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/shared/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnE;;GAEG;AACH,MAAM,OAAO,UAAU;IAGnB,MAAM,CAAC,KAAa;QAChB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC/E,CAAC;IAED,WAAW;QACP,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAChB,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACzC,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE,CAAC;YACf,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACxE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QAChD,OAAO,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;IAED,KAAK;QACD,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;IAC7B,CAAC;CACJ;AAED,MAAM,UAAU,kBAAkB,CAAC,IAAY;IAC3C,OAAO,oBAAoB,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,OAAuB;IACpD,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.d.ts new file mode 100644 index 000000000..3cf94bf78 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.d.ts @@ -0,0 +1,31 @@ +/** + * Tool name validation utilities according to SEP: Specify Format for Tool Names + * + * Tool names SHOULD be between 1 and 128 characters in length (inclusive). + * Tool names are case-sensitive. + * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits + * (0-9), underscore (_), dash (-), and dot (.). + * Tool names SHOULD NOT contain spaces, commas, or other special characters. + */ +/** + * Validates a tool name according to the SEP specification + * @param name - The tool name to validate + * @returns An object containing validation result and any warnings + */ +export declare function validateToolName(name: string): { + isValid: boolean; + warnings: string[]; +}; +/** + * Issues warnings for non-conforming tool names + * @param name - The tool name that triggered the warnings + * @param warnings - Array of warning messages + */ +export declare function issueToolNameWarning(name: string, warnings: string[]): void; +/** + * Validates a tool name and issues warnings for non-conforming names + * @param name - The tool name to validate + * @returns true if the name is valid, false otherwise + */ +export declare function validateAndWarnToolName(name: string): boolean; +//# sourceMappingURL=toolNameValidation.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.d.ts.map new file mode 100644 index 000000000..d81f0156e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"toolNameValidation.d.ts","sourceRoot":"","sources":["../../../src/shared/toolNameValidation.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAOH;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG;IAC5C,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACtB,CA0DA;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAY3E;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAO7D"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js new file mode 100644 index 000000000..34b6d19c5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js @@ -0,0 +1,92 @@ +/** + * Tool name validation utilities according to SEP: Specify Format for Tool Names + * + * Tool names SHOULD be between 1 and 128 characters in length (inclusive). + * Tool names are case-sensitive. + * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits + * (0-9), underscore (_), dash (-), and dot (.). + * Tool names SHOULD NOT contain spaces, commas, or other special characters. + */ +/** + * Regular expression for valid tool names according to SEP-986 specification + */ +const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; +/** + * Validates a tool name according to the SEP specification + * @param name - The tool name to validate + * @returns An object containing validation result and any warnings + */ +export function validateToolName(name) { + const warnings = []; + // Check length + if (name.length === 0) { + return { + isValid: false, + warnings: ['Tool name cannot be empty'] + }; + } + if (name.length > 128) { + return { + isValid: false, + warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] + }; + } + // Check for specific problematic patterns (these are warnings, not validation failures) + if (name.includes(' ')) { + warnings.push('Tool name contains spaces, which may cause parsing issues'); + } + if (name.includes(',')) { + warnings.push('Tool name contains commas, which may cause parsing issues'); + } + // Check for potentially confusing patterns (leading/trailing dashes, dots, slashes) + if (name.startsWith('-') || name.endsWith('-')) { + warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts'); + } + if (name.startsWith('.') || name.endsWith('.')) { + warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts'); + } + // Check for invalid characters + if (!TOOL_NAME_REGEX.test(name)) { + const invalidChars = name + .split('') + .filter(char => !/[A-Za-z0-9._-]/.test(char)) + .filter((char, index, arr) => arr.indexOf(char) === index); // Remove duplicates + warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c => `"${c}"`).join(', ')}`, 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)'); + return { + isValid: false, + warnings + }; + } + return { + isValid: true, + warnings + }; +} +/** + * Issues warnings for non-conforming tool names + * @param name - The tool name that triggered the warnings + * @param warnings - Array of warning messages + */ +export function issueToolNameWarning(name, warnings) { + if (warnings.length > 0) { + console.warn(`Tool name validation warning for "${name}":`); + for (const warning of warnings) { + console.warn(` - ${warning}`); + } + console.warn('Tool registration will proceed, but this may cause compatibility issues.'); + console.warn('Consider updating the tool name to conform to the MCP tool naming standard.'); + console.warn('See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.'); + } +} +/** + * Validates a tool name and issues warnings for non-conforming names + * @param name - The tool name to validate + * @returns true if the name is valid, false otherwise + */ +export function validateAndWarnToolName(name) { + const result = validateToolName(name); + // Always issue warnings for any validation issues (both invalid names and warnings) + issueToolNameWarning(name, result.warnings); + return result.isValid; +} +//# sourceMappingURL=toolNameValidation.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js.map new file mode 100644 index 000000000..9fdfcea84 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"toolNameValidation.js","sourceRoot":"","sources":["../../../src/shared/toolNameValidation.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;GAEG;AACH,MAAM,eAAe,GAAG,yBAAyB,CAAC;AAElD;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY;IAIzC,MAAM,QAAQ,GAAa,EAAE,CAAC;IAE9B,eAAe;IACf,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpB,OAAO;YACH,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE,CAAC,2BAA2B,CAAC;SAC1C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AY,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EACtF,8EAA8E,CACjF,CAAC;QAEF,OAAO;YACH,OAAO,EAAE,KAAK;YACd,QAAQ;SACX,CAAC;IACN,CAAC;IAED,OAAO;QACH,OAAO,EAAE,IAAI;QACb,QAAQ;KACX,CAAC;AACN,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAAC,IAAY,EAAE,QAAkB;IACjE,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACtB,OAAO,CAAC,IAAI,CAAC,qCAAqC,IAAI,IAAI,CAAC,CAAC;QAC5D,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;YAC7B,OAAO,CAAC,IAAI,CAAC,OAAO,OAAO,EAAE,CAAC,CAAC;QACnC,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,0EAA0E,CAAC,CAAC;QACzF,OAAO,CAAC,IAAI,CAAC,6EAA6E,CAAC,CAAC;QAC5F,OAAO,CAAC,IAAI,CACR,oIAAoI,CACvI,CAAC;IACN,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CAAC,IAAY;IAChD,MAAM,MAAM,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAEtC,oFAAoF;IACpF,oBAAoB,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;IAE5C,OAAO,MAAM,CAAC,OAAO,CAAC;AAC1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.d.ts new file mode 100644 index 000000000..1bd95efb4 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.d.ts @@ -0,0 +1,89 @@ +import { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types.js'; +export type FetchLike = (url: string | URL, init?: RequestInit) => Promise; +/** + * Normalizes HeadersInit to a plain Record for manipulation. + * Handles Headers objects, arrays of tuples, and plain objects. + */ +export declare function normalizeHeaders(headers: HeadersInit | undefined): Record; +/** + * Creates a fetch function that includes base RequestInit options. + * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. + * + * @param baseFetch - The base fetch function to wrap (defaults to global fetch) + * @param baseInit - The base RequestInit to merge with each request + * @returns A wrapped fetch function that merges base options with call-specific options + */ +export declare function createFetchWithInit(baseFetch?: FetchLike, baseInit?: RequestInit): FetchLike; +/** + * Options for sending a JSON-RPC message. + */ +export type TransportSendOptions = { + /** + * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. + */ + relatedRequestId?: RequestId; + /** + * The resumption token used to continue long-running requests that were interrupted. + * + * This allows clients to reconnect and continue from where they left off, if supported by the transport. + */ + resumptionToken?: string; + /** + * A callback that is invoked when the resumption token changes, if supported by the transport. + * + * This allows clients to persist the latest token for potential reconnection. + */ + onresumptiontoken?: (token: string) => void; +}; +/** + * Describes the minimal contract for an MCP transport that a client or server can communicate over. + */ +export interface Transport { + /** + * Starts processing messages on the transport, including any connection steps that might need to be taken. + * + * This method should only be called after callbacks are installed, or else messages may be lost. + * + * NOTE: This method should not be called explicitly when using Client, Server, or Protocol classes, as they will implicitly call start(). + */ + start(): Promise; + /** + * Sends a JSON-RPC message (request or response). + * + * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. + */ + send(message: JSONRPCMessage, options?: TransportSendOptions): Promise; + /** + * Closes the connection. + */ + close(): Promise; + /** + * Callback for when the connection is closed for any reason. + * + * This should be invoked when close() is called as well. + */ + onclose?: () => void; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror?: (error: Error) => void; + /** + * Callback for when a message (request or response) is received over the connection. + * + * Includes the requestInfo and authInfo if the transport is authenticated. + * + * The requestInfo can be used to get the original request information (headers, etc.) + */ + onmessage?: (message: T, extra?: MessageExtraInfo) => void; + /** + * The session ID generated for this connection. + */ + sessionId?: string; + /** + * Sets the protocol version used for the connection (called when the initialize response is received). + */ + setProtocolVersion?: (version: string) => void; +} +//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.d.ts.map new file mode 100644 index 000000000..7a3d837df --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../src/shared/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE1E,MAAM,MAAM,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAErF;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAYzF;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,GAAE,SAAiB,EAAE,QAAQ,CAAC,EAAE,WAAW,GAAG,SAAS,CAenG;AAED;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG;IAC/B;;OAEG;IACH,gBAAgB,CAAC,EAAE,SAAS,CAAC;IAE7B;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;CAC/C,CAAC;AACF;;GAEG;AACH,MAAM,WAAW,SAAS;IACtB;;;;;;OAMG;IACH,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvB;;;;OAIG;IACH,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE7E;;OAEG;IACH,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IAErB;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAEjC;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,CAAC,CAAC,SAAS,cAAc,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAErF;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,kBAAkB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CAClD"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js new file mode 100644 index 000000000..ce25e23c2 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js @@ -0,0 +1,39 @@ +/** + * Normalizes HeadersInit to a plain Record for manipulation. + * Handles Headers objects, arrays of tuples, and plain objects. + */ +export function normalizeHeaders(headers) { + if (!headers) + return {}; + if (headers instanceof Headers) { + return Object.fromEntries(headers.entries()); + } + if (Array.isArray(headers)) { + return Object.fromEntries(headers); + } + return { ...headers }; +} +/** + * Creates a fetch function that includes base RequestInit options. + * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. + * + * @param baseFetch - The base fetch function to wrap (defaults to global fetch) + * @param baseInit - The base RequestInit to merge with each request + * @returns A wrapped fetch function that merges base options with call-specific options + */ +export function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) { + return baseFetch; + } + // Return a wrapped fetch that merges base RequestInit with call-specific init + return async (url, init) => { + const mergedInit = { + ...baseInit, + ...init, + // Headers need special handling - merge instead of replace + headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers + }; + return baseFetch(url, mergedInit); + }; +} +//# sourceMappingURL=transport.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js.map new file mode 100644 index 000000000..790e11d8a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../src/shared/transport.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAgC;IAC7D,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC;IAExB,IAAI,OAAO,YAAY,OAAO,EAAE,CAAC;QAC7B,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IACjD,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,EAAE,GAAI,OAAkC,EAAE,CAAC;AACtD,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,mBAAmB,CAAC,YAAuB,KAAK,EAAE,QAAsB;IACpF,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,8EAA8E;IAC9E,OAAO,KAAK,EAAE,GAAiB,EAAE,IAAkB,EAAqB,EAAE;QACtE,MAAM,UAAU,GAAgB;YAC5B,GAAG,QAAQ;YACX,GAAG,IAAI;YACP,2DAA2D;YAC3D,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,gBAAgB,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO;SAC3H,CAAC;QACF,OAAO,SAAS,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;IACtC,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.d.ts new file mode 100644 index 000000000..175e329b6 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.d.ts @@ -0,0 +1,25 @@ +export type Variables = Record; +export declare class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like {foo} or {?bar}. + */ + static isTemplate(str: string): boolean; + private static validateLength; + private readonly template; + private readonly parts; + get variableNames(): string[]; + constructor(template: string); + toString(): string; + private parse; + private getOperator; + private getNames; + private encodeValue; + private expandPart; + expand(variables: Variables): string; + private escapeRegExp; + private partToRegExp; + match(uri: string): Variables | null; +} +//# sourceMappingURL=uriTemplate.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.d.ts.map new file mode 100644 index 000000000..052e91851 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"uriTemplate.d.ts","sourceRoot":"","sources":["../../../src/shared/uriTemplate.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;AAO1D,qBAAa,WAAW;IACpB;;;;OAIG;IACH,MAAM,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAMvC,OAAO,CAAC,MAAM,CAAC,cAAc;IAK7B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAyF;IAE/G,IAAI,aAAa,IAAI,MAAM,EAAE,CAE5B;gBAEW,QAAQ,EAAE,MAAM;IAM5B,QAAQ,IAAI,MAAM;IAIlB,OAAO,CAAC,KAAK;IA8Cb,OAAO,CAAC,WAAW;IAKnB,OAAO,CAAC,QAAQ;IAShB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,UAAU;IAsDlB,MAAM,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM;IA4BpC,OAAO,CAAC,YAAY;IAIpB,OAAO,CAAC,YAAY;IAkDpB,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;CAuCvC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.js new file mode 100644 index 000000000..8247f631e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.js @@ -0,0 +1,239 @@ +// Claude-authored implementation of RFC 6570 URI Templates +const MAX_TEMPLATE_LENGTH = 1000000; // 1MB +const MAX_VARIABLE_LENGTH = 1000000; // 1MB +const MAX_TEMPLATE_EXPRESSIONS = 10000; +const MAX_REGEX_LENGTH = 1000000; // 1MB +export class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like {foo} or {?bar}. + */ + static isTemplate(str) { + // Look for any sequence of characters between curly braces + // that isn't just whitespace + return /\{[^}\s]+\}/.test(str); + } + static validateLength(str, max, context) { + if (str.length > max) { + throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); + } + } + get variableNames() { + return this.parts.flatMap(part => (typeof part === 'string' ? [] : part.names)); + } + constructor(template) { + UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, 'Template'); + this.template = template; + this.parts = this.parse(template); + } + toString() { + return this.template; + } + parse(template) { + const parts = []; + let currentText = ''; + let i = 0; + let expressionCount = 0; + while (i < template.length) { + if (template[i] === '{') { + if (currentText) { + parts.push(currentText); + currentText = ''; + } + const end = template.indexOf('}', i); + if (end === -1) + throw new Error('Unclosed template expression'); + expressionCount++; + if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) { + throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); + } + const expr = template.slice(i + 1, end); + const operator = this.getOperator(expr); + const exploded = expr.includes('*'); + const names = this.getNames(expr); + const name = names[0]; + // Validate variable name length + for (const name of names) { + UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); + } + parts.push({ name, operator, names, exploded }); + i = end + 1; + } + else { + currentText += template[i]; + i++; + } + } + if (currentText) { + parts.push(currentText); + } + return parts; + } + getOperator(expr) { + const operators = ['+', '#', '.', '/', '?', '&']; + return operators.find(op => expr.startsWith(op)) || ''; + } + getNames(expr) { + const operator = this.getOperator(expr); + return expr + .slice(operator.length) + .split(',') + .map(name => name.replace('*', '').trim()) + .filter(name => name.length > 0); + } + encodeValue(value, operator) { + UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, 'Variable value'); + if (operator === '+' || operator === '#') { + return encodeURI(value); + } + return encodeURIComponent(value); + } + expandPart(part, variables) { + if (part.operator === '?' || part.operator === '&') { + const pairs = part.names + .map(name => { + const value = variables[name]; + if (value === undefined) + return ''; + const encoded = Array.isArray(value) + ? value.map(v => this.encodeValue(v, part.operator)).join(',') + : this.encodeValue(value.toString(), part.operator); + return `${name}=${encoded}`; + }) + .filter(pair => pair.length > 0); + if (pairs.length === 0) + return ''; + const separator = part.operator === '?' ? '?' : '&'; + return separator + pairs.join('&'); + } + if (part.names.length > 1) { + const values = part.names.map(name => variables[name]).filter(v => v !== undefined); + if (values.length === 0) + return ''; + return values.map(v => (Array.isArray(v) ? v[0] : v)).join(','); + } + const value = variables[part.name]; + if (value === undefined) + return ''; + const values = Array.isArray(value) ? value : [value]; + const encoded = values.map(v => this.encodeValue(v, part.operator)); + switch (part.operator) { + case '': + return encoded.join(','); + case '+': + return encoded.join(','); + case '#': + return '#' + encoded.join(','); + case '.': + return '.' + encoded.join('.'); + case '/': + return '/' + encoded.join('/'); + default: + return encoded.join(','); + } + } + expand(variables) { + let result = ''; + let hasQueryParam = false; + for (const part of this.parts) { + if (typeof part === 'string') { + result += part; + continue; + } + const expanded = this.expandPart(part, variables); + if (!expanded) + continue; + // Convert ? to & if we already have a query parameter + if ((part.operator === '?' || part.operator === '&') && hasQueryParam) { + result += expanded.replace('?', '&'); + } + else { + result += expanded; + } + if (part.operator === '?' || part.operator === '&') { + hasQueryParam = true; + } + } + return result; + } + escapeRegExp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + } + partToRegExp(part) { + const patterns = []; + // Validate variable name length for matching + for (const name of part.names) { + UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); + } + if (part.operator === '?' || part.operator === '&') { + for (let i = 0; i < part.names.length; i++) { + const name = part.names[i]; + const prefix = i === 0 ? '\\' + part.operator : '&'; + patterns.push({ + pattern: prefix + this.escapeRegExp(name) + '=([^&]+)', + name + }); + } + return patterns; + } + let pattern; + const name = part.name; + switch (part.operator) { + case '': + pattern = part.exploded ? '([^/,]+(?:,[^/,]+)*)' : '([^/,]+)'; + break; + case '+': + case '#': + pattern = '(.+)'; + break; + case '.': + pattern = '\\.([^/,]+)'; + break; + case '/': + pattern = '/' + (part.exploded ? '([^/,]+(?:,[^/,]+)*)' : '([^/,]+)'); + break; + default: + pattern = '([^/]+)'; + } + patterns.push({ pattern, name }); + return patterns; + } + match(uri) { + UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, 'URI'); + let pattern = '^'; + const names = []; + for (const part of this.parts) { + if (typeof part === 'string') { + pattern += this.escapeRegExp(part); + } + else { + const patterns = this.partToRegExp(part); + for (const { pattern: partPattern, name } of patterns) { + pattern += partPattern; + names.push({ name, exploded: part.exploded }); + } + } + } + pattern += '$'; + UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, 'Generated regex pattern'); + const regex = new RegExp(pattern); + const match = uri.match(regex); + if (!match) + return null; + const result = {}; + for (let i = 0; i < names.length; i++) { + const { name, exploded } = names[i]; + const value = match[i + 1]; + const cleanName = name.replace('*', ''); + if (exploded && value.includes(',')) { + result[cleanName] = value.split(','); + } + else { + result[cleanName] = value; + } + } + return result; + } +} +//# sourceMappingURL=uriTemplate.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.js.map new file mode 100644 index 000000000..d47e01ba8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uriTemplate.js","sourceRoot":"","sources":["../../../src/shared/uriTemplate.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAI3D,MAAM,mBAAmB,GAAG,OAAO,CAAC,CAAC,MAAM;AAC3C,MAAM,mBAAmB,GAAG,OAAO,CAAC,CAAC,MAAM;AAC3C,MAAM,wBAAwB,GAAG,KAAK,CAAC;AACvC,MAAM,gBAAgB,GAAG,OAAO,CAAC,CAAC,MAAM;AAExC,MAAM,OAAO,WAAW;IACpB;;;;OAIG;IACH,MAAM,CAAC,UAAU,CAAC,GAAW;QACzB,2DAA2D;QAC3D,6BAA6B;QAC7B,OAAO,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACnC,CAAC;IAEO,MAAM,CAAC,cAAc,CAAC,GAAW,EAAE,GAAW,EAAE,OAAe;QACnE,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,GA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/@modelcontextprotocol/sdk/dist/esm/spec.types.d.ts new file mode 100644 index 000000000..f94e3cf8f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/spec.types.d.ts @@ -0,0 +1,2299 @@ +/** + * This file is automatically generated from the Model Context Protocol specification. + * + * Source: https://github.com/modelcontextprotocol/modelcontextprotocol + * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts + * Last updated from commit: 35fa160caf287a9c48696e3ae452c0645c713669 + * + * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. + * To update this file, run: npm run fetch:spec-types + */ +/** + * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. + * + * @category JSON-RPC + */ +export type JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResponse; +/** @internal */ +export declare const LATEST_PROTOCOL_VERSION = "DRAFT-2026-v1"; +/** @internal */ +export declare const JSONRPC_VERSION = "2.0"; +/** + * A progress token, used to associate progress notifications with the original request. + * + * @category Common Types + */ +export type ProgressToken = string | number; +/** + * An opaque token used to represent a cursor for pagination. + * + * @category Common Types + */ +export type Cursor = string; +/** + * Common params for any task-augmented request. + * + * @internal + */ +export interface TaskAugmentedRequestParams extends RequestParams { + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task?: TaskMetadata; +} +/** + * Common params for any request. + * + * @internal + */ +export interface RequestParams { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken?: ProgressToken; + [key: string]: unknown; + }; +} +/** @internal */ +export interface Request { + method: string; + params?: { + [key: string]: any; + }; +} +/** @internal */ +export interface NotificationParams { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** @internal */ +export interface Notification { + method: string; + params?: { + [key: string]: any; + }; +} +/** + * @category Common Types + */ +export interface Result { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; + [key: string]: unknown; +} +/** + * @category Common Types + */ +export interface Error { + /** + * The error type that occurred. + */ + code: number; + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string; + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data?: unknown; +} +/** + * A uniquely identifying ID for a request in JSON-RPC. + * + * @category Common Types + */ +export type RequestId = string | number; +/** + * A request that expects a response. + * + * @category JSON-RPC + */ +export interface JSONRPCRequest extends Request { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; +} +/** + * A notification which does not expect a response. + * + * @category JSON-RPC + */ +export interface JSONRPCNotification extends Notification { + jsonrpc: typeof JSONRPC_VERSION; +} +/** + * A successful (non-error) response to a request. + * + * @category JSON-RPC + */ +export interface JSONRPCResultResponse { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + result: Result; +} +/** + * A response to a request that indicates an error occurred. + * + * @category JSON-RPC + */ +export interface JSONRPCErrorResponse { + jsonrpc: typeof JSONRPC_VERSION; + id?: RequestId; + error: Error; +} +/** + * A response to a request, containing either the result or error. + */ +export type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse; +export declare const PARSE_ERROR = -32700; +export declare const INVALID_REQUEST = -32600; +export declare const METHOD_NOT_FOUND = -32601; +export declare const INVALID_PARAMS = -32602; +export declare const INTERNAL_ERROR = -32603; +/** @internal */ +export declare const URL_ELICITATION_REQUIRED = -32042; +/** + * An error response that indicates that the server requires the client to provide additional information via an elicitation request. + * + * @internal + */ +export interface URLElicitationRequiredError extends Omit { + error: Error & { + code: typeof URL_ELICITATION_REQUIRED; + data: { + elicitations: ElicitRequestURLParams[]; + [key: string]: unknown; + }; + }; +} +/** + * A response that indicates success but carries no data. + * + * @category Common Types + */ +export type EmptyResult = Result; +/** + * Parameters for a `notifications/cancelled` notification. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotificationParams extends NotificationParams { + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + * This MUST be provided for cancelling non-task requests. + * This MUST NOT be used for cancelling tasks (use the `tasks/cancel` request instead). + */ + requestId?: RequestId; + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; +} +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + * + * For task cancellation, use the `tasks/cancel` request instead of this notification. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotification extends JSONRPCNotification { + method: "notifications/cancelled"; + params: CancelledNotificationParams; +} +/** + * Parameters for an `initialize` request. + * + * @category `initialize` + */ +export interface InitializeRequestParams extends RequestParams { + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string; + capabilities: ClientCapabilities; + clientInfo: Implementation; +} +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + * + * @category `initialize` + */ +export interface InitializeRequest extends JSONRPCRequest { + method: "initialize"; + params: InitializeRequestParams; +} +/** + * After receiving an initialize request from the client, the server sends this response. + * + * @category `initialize` + */ +export interface InitializeResult extends Result { + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string; + capabilities: ServerCapabilities; + serverInfo: Implementation; + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions?: string; +} +/** + * This notification is sent from the client to the server after initialization has finished. + * + * @category `notifications/initialized` + */ +export interface InitializedNotification extends JSONRPCNotification { + method: "notifications/initialized"; + params?: NotificationParams; +} +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + * + * @category `initialize` + */ +export interface ClientCapabilities { + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental?: { + [key: string]: object; + }; + /** + * Present if the client supports listing roots. + */ + roots?: { + /** + * Whether the client supports notifications for changes to the roots list. + */ + listChanged?: boolean; + }; + /** + * Present if the client supports sampling from an LLM. + */ + sampling?: { + /** + * Whether the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context?: object; + /** + * Whether the client supports tool use via tools and toolChoice parameters. + */ + tools?: object; + }; + /** + * Present if the client supports elicitation from the server. + */ + elicitation?: { + form?: object; + url?: object; + }; + /** + * Present if the client supports task-augmented requests. + */ + tasks?: { + /** + * Whether this client supports tasks/list. + */ + list?: object; + /** + * Whether this client supports tasks/cancel. + */ + cancel?: object; + /** + * Specifies which request types can be augmented with tasks. + */ + requests?: { + /** + * Task support for sampling-related requests. + */ + sampling?: { + /** + * Whether the client supports task-augmented sampling/createMessage requests. + */ + createMessage?: object; + }; + /** + * Task support for elicitation-related requests. + */ + elicitation?: { + /** + * Whether the client supports task-augmented elicitation/create requests. + */ + create?: object; + }; + }; + }; +} +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + * + * @category `initialize` + */ +export interface ServerCapabilities { + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental?: { + [key: string]: object; + }; + /** + * Present if the server supports sending log messages to the client. + */ + logging?: object; + /** + * Present if the server supports argument autocompletion suggestions. + */ + completions?: object; + /** + * Present if the server offers any prompt templates. + */ + prompts?: { + /** + * Whether this server supports notifications for changes to the prompt list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any resources to read. + */ + resources?: { + /** + * Whether this server supports subscribing to resource updates. + */ + subscribe?: boolean; + /** + * Whether this server supports notifications for changes to the resource list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any tools to call. + */ + tools?: { + /** + * Whether this server supports notifications for changes to the tool list. + */ + listChanged?: boolean; + }; + /** + * Present if the server supports task-augmented requests. + */ + tasks?: { + /** + * Whether this server supports tasks/list. + */ + list?: object; + /** + * Whether this server supports tasks/cancel. + */ + cancel?: object; + /** + * Specifies which request types can be augmented with tasks. + */ + requests?: { + /** + * Task support for tool-related requests. + */ + tools?: { + /** + * Whether the server supports task-augmented tools/call requests. + */ + call?: object; + }; + }; + }; +} +/** + * An optionally-sized icon that can be displayed in a user interface. + * + * @category Common Types + */ +export interface Icon { + /** + * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a + * `data:` URI with Base64-encoded image data. + * + * Consumers SHOULD takes steps to ensure URLs serving icons are from the + * same domain as the client/server or a trusted domain. + * + * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain + * executable JavaScript. + * + * @format uri + */ + src: string; + /** + * Optional MIME type override if the source MIME type is missing or generic. + * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. + */ + mimeType?: string; + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes?: string[]; + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme?: "light" | "dark"; +} +/** + * Base interface to add `icons` property. + * + * @internal + */ +export interface Icons { + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons?: Icon[]; +} +/** + * Base interface for metadata with name (identifier) and title (display name) properties. + * + * @internal + */ +export interface BaseMetadata { + /** + * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). + */ + name: string; + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title?: string; +} +/** + * Describes the MCP implementation. + * + * @category `initialize` + */ +export interface Implementation extends BaseMetadata, Icons { + version: string; + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description?: string; + /** + * An optional URL of the website for this implementation. + * + * @format uri + */ + websiteUrl?: string; +} +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + * + * @category `ping` + */ +export interface PingRequest extends JSONRPCRequest { + method: "ping"; + params?: RequestParams; +} +/** + * Parameters for a `notifications/progress` notification. + * + * @category `notifications/progress` + */ +export interface ProgressNotificationParams extends NotificationParams { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; +} +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category `notifications/progress` + */ +export interface ProgressNotification extends JSONRPCNotification { + method: "notifications/progress"; + params: ProgressNotificationParams; +} +/** + * Common parameters for paginated requests. + * + * @internal + */ +export interface PaginatedRequestParams extends RequestParams { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; +} +/** @internal */ +export interface PaginatedRequest extends JSONRPCRequest { + params?: PaginatedRequestParams; +} +/** @internal */ +export interface PaginatedResult extends Result { + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor?: Cursor; +} +/** + * Sent from the client to request a list of resources the server has. + * + * @category `resources/list` + */ +export interface ListResourcesRequest extends PaginatedRequest { + method: "resources/list"; +} +/** + * The server's response to a resources/list request from the client. + * + * @category `resources/list` + */ +export interface ListResourcesResult extends PaginatedResult { + resources: Resource[]; +} +/** + * Sent from the client to request a list of resource templates the server has. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesRequest extends PaginatedRequest { + method: "resources/templates/list"; +} +/** + * The server's response to a resources/templates/list request from the client. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesResult extends PaginatedResult { + resourceTemplates: ResourceTemplate[]; +} +/** + * Common parameters when working with resources. + * + * @internal + */ +export interface ResourceRequestParams extends RequestParams { + /** + * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; +} +/** + * Parameters for a `resources/read` request. + * + * @category `resources/read` + */ +export interface ReadResourceRequestParams extends ResourceRequestParams { +} +/** + * Sent from the client to the server, to read a specific resource URI. + * + * @category `resources/read` + */ +export interface ReadResourceRequest extends JSONRPCRequest { + method: "resources/read"; + params: ReadResourceRequestParams; +} +/** + * The server's response to a resources/read request from the client. + * + * @category `resources/read` + */ +export interface ReadResourceResult extends Result { + contents: (TextResourceContents | BlobResourceContents)[]; +} +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/resources/list_changed` + */ +export interface ResourceListChangedNotification extends JSONRPCNotification { + method: "notifications/resources/list_changed"; + params?: NotificationParams; +} +/** + * Parameters for a `resources/subscribe` request. + * + * @category `resources/subscribe` + */ +export interface SubscribeRequestParams extends ResourceRequestParams { +} +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + * + * @category `resources/subscribe` + */ +export interface SubscribeRequest extends JSONRPCRequest { + method: "resources/subscribe"; + params: SubscribeRequestParams; +} +/** + * Parameters for a `resources/unsubscribe` request. + * + * @category `resources/unsubscribe` + */ +export interface UnsubscribeRequestParams extends ResourceRequestParams { +} +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + * + * @category `resources/unsubscribe` + */ +export interface UnsubscribeRequest extends JSONRPCRequest { + method: "resources/unsubscribe"; + params: UnsubscribeRequestParams; +} +/** + * Parameters for a `notifications/resources/updated` notification. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotificationParams extends NotificationParams { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; +} +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotification extends JSONRPCNotification { + method: "notifications/resources/updated"; + params: ResourceUpdatedNotificationParams; +} +/** + * A known resource that the server is capable of reading. + * + * @category `resources/list` + */ +export interface Resource extends BaseMetadata, Icons { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size?: number; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * A template description for resources available on the server. + * + * @category `resources/templates/list` + */ +export interface ResourceTemplate extends BaseMetadata, Icons { + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * + * @format uri-template + */ + uriTemplate: string; + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType?: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The contents of a specific resource or sub-resource. + * + * @internal + */ +export interface ResourceContents { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * @category Content + */ +export interface TextResourceContents extends ResourceContents { + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string; +} +/** + * @category Content + */ +export interface BlobResourceContents extends ResourceContents { + /** + * A base64-encoded string representing the binary data of the item. + * + * @format byte + */ + blob: string; +} +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + * + * @category `prompts/list` + */ +export interface ListPromptsRequest extends PaginatedRequest { + method: "prompts/list"; +} +/** + * The server's response to a prompts/list request from the client. + * + * @category `prompts/list` + */ +export interface ListPromptsResult extends PaginatedResult { + prompts: Prompt[]; +} +/** + * Parameters for a `prompts/get` request. + * + * @category `prompts/get` + */ +export interface GetPromptRequestParams extends RequestParams { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { + [key: string]: string; + }; +} +/** + * Used by the client to get a prompt provided by the server. + * + * @category `prompts/get` + */ +export interface GetPromptRequest extends JSONRPCRequest { + method: "prompts/get"; + params: GetPromptRequestParams; +} +/** + * The server's response to a prompts/get request from the client. + * + * @category `prompts/get` + */ +export interface GetPromptResult extends Result { + /** + * An optional description for the prompt. + */ + description?: string; + messages: PromptMessage[]; +} +/** + * A prompt or prompt template that the server offers. + * + * @category `prompts/list` + */ +export interface Prompt extends BaseMetadata, Icons { + /** + * An optional description of what this prompt provides + */ + description?: string; + /** + * A list of arguments to use for templating the prompt. + */ + arguments?: PromptArgument[]; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * Describes an argument that a prompt can accept. + * + * @category `prompts/list` + */ +export interface PromptArgument extends BaseMetadata { + /** + * A human-readable description of the argument. + */ + description?: string; + /** + * Whether this argument must be provided. + */ + required?: boolean; +} +/** + * The sender or recipient of messages and data in a conversation. + * + * @category Common Types + */ +export type Role = "user" | "assistant"; +/** + * Describes a message returned as part of a prompt. + * + * This is similar to `SamplingMessage`, but also supports the embedding of + * resources from the MCP server. + * + * @category `prompts/get` + */ +export interface PromptMessage { + role: Role; + content: ContentBlock; +} +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + * + * @category Content + */ +export interface ResourceLink extends Resource { + type: "resource_link"; +} +/** + * The contents of a resource, embedded into a prompt or tool call result. + * + * It is up to the client how best to render embedded resources for the benefit + * of the LLM and/or the user. + * + * @category Content + */ +export interface EmbeddedResource { + type: "resource"; + resource: TextResourceContents | BlobResourceContents; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/prompts/list_changed` + */ +export interface PromptListChangedNotification extends JSONRPCNotification { + method: "notifications/prompts/list_changed"; + params?: NotificationParams; +} +/** + * Sent from the client to request a list of tools the server has. + * + * @category `tools/list` + */ +export interface ListToolsRequest extends PaginatedRequest { + method: "tools/list"; +} +/** + * The server's response to a tools/list request from the client. + * + * @category `tools/list` + */ +export interface ListToolsResult extends PaginatedResult { + tools: Tool[]; +} +/** + * The server's response to a tool call. + * + * @category `tools/call` + */ +export interface CallToolResult extends Result { + /** + * A list of content objects that represent the unstructured result of the tool call. + */ + content: ContentBlock[]; + /** + * An optional JSON object that represents the structured result of the tool call. + */ + structuredContent?: { + [key: string]: unknown; + }; + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError?: boolean; +} +/** + * Parameters for a `tools/call` request. + * + * @category `tools/call` + */ +export interface CallToolRequestParams extends TaskAugmentedRequestParams { + /** + * The name of the tool. + */ + name: string; + /** + * Arguments to use for the tool call. + */ + arguments?: { + [key: string]: unknown; + }; +} +/** + * Used by the client to invoke a tool provided by the server. + * + * @category `tools/call` + */ +export interface CallToolRequest extends JSONRPCRequest { + method: "tools/call"; + params: CallToolRequestParams; +} +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + * + * @category `notifications/tools/list_changed` + */ +export interface ToolListChangedNotification extends JSONRPCNotification { + method: "notifications/tools/list_changed"; + params?: NotificationParams; +} +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + * + * @category `tools/list` + */ +export interface ToolAnnotations { + /** + * A human-readable title for the tool. + */ + title?: string; + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint?: boolean; + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint?: boolean; + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint?: boolean; + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint?: boolean; +} +/** + * Execution-related properties for a tool. + * + * @category `tools/list` + */ +export interface ToolExecution { + /** + * Indicates whether this tool supports task-augmented execution. + * This allows clients to handle long-running operations through polling + * the task system. + * + * - "forbidden": Tool does not support task-augmented execution (default when absent) + * - "optional": Tool may support task-augmented execution + * - "required": Tool requires task-augmented execution + * + * Default: "forbidden" + */ + taskSupport?: "forbidden" | "optional" | "required"; +} +/** + * Definition for a tool the client can call. + * + * @category `tools/list` + */ +export interface Tool extends BaseMetadata, Icons { + /** + * A human-readable description of the tool. + * + * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. + */ + description?: string; + /** + * A JSON Schema object defining the expected parameters for the tool. + */ + inputSchema: { + $schema?: string; + type: "object"; + properties?: { + [key: string]: object; + }; + required?: string[]; + }; + /** + * Execution-related properties for this tool. + */ + execution?: ToolExecution; + /** + * An optional JSON Schema object defining the structure of the tool's output returned in + * the structuredContent field of a CallToolResult. + * + * Defaults to JSON Schema 2020-12 when no explicit $schema is provided. + * Currently restricted to type: "object" at the root level. + */ + outputSchema?: { + $schema?: string; + type: "object"; + properties?: { + [key: string]: object; + }; + required?: string[]; + }; + /** + * Optional additional tool information. + * + * Display name precedence order is: title, annotations.title, then name. + */ + annotations?: ToolAnnotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The status of a task. + * + * @category `tasks` + */ +export type TaskStatus = "working" | "input_required" | "completed" | "failed" | "cancelled"; +/** + * Metadata for augmenting a request with task execution. + * Include this in the `task` field of the request parameters. + * + * @category `tasks` + */ +export interface TaskMetadata { + /** + * Requested duration in milliseconds to retain task from creation. + */ + ttl?: number; +} +/** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @category `tasks` + */ +export interface RelatedTaskMetadata { + /** + * The task identifier this message is associated with. + */ + taskId: string; +} +/** + * Data associated with a task. + * + * @category `tasks` + */ +export interface Task { + /** + * The task identifier. + */ + taskId: string; + /** + * Current task state. + */ + status: TaskStatus; + /** + * Optional human-readable message describing the current task state. + * This can provide context for any status, including: + * - Reasons for "cancelled" status + * - Summaries for "completed" status + * - Diagnostic information for "failed" status (e.g., error details, what went wrong) + */ + statusMessage?: string; + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: string; + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: string; + /** + * Actual retention duration from creation in milliseconds, null for unlimited. + */ + ttl: number | null; + /** + * Suggested polling interval in milliseconds. + */ + pollInterval?: number; +} +/** + * A response to a task-augmented request. + * + * @category `tasks` + */ +export interface CreateTaskResult extends Result { + task: Task; +} +/** + * A request to retrieve the state of a task. + * + * @category `tasks/get` + */ +export interface GetTaskRequest extends JSONRPCRequest { + method: "tasks/get"; + params: { + /** + * The task identifier to query. + */ + taskId: string; + }; +} +/** + * The response to a tasks/get request. + * + * @category `tasks/get` + */ +export type GetTaskResult = Result & Task; +/** + * A request to retrieve the result of a completed task. + * + * @category `tasks/result` + */ +export interface GetTaskPayloadRequest extends JSONRPCRequest { + method: "tasks/result"; + params: { + /** + * The task identifier to retrieve results for. + */ + taskId: string; + }; +} +/** + * The response to a tasks/result request. + * The structure matches the result type of the original request. + * For example, a tools/call task would return the CallToolResult structure. + * + * @category `tasks/result` + */ +export interface GetTaskPayloadResult extends Result { + [key: string]: unknown; +} +/** + * A request to cancel a task. + * + * @category `tasks/cancel` + */ +export interface CancelTaskRequest extends JSONRPCRequest { + method: "tasks/cancel"; + params: { + /** + * The task identifier to cancel. + */ + taskId: string; + }; +} +/** + * The response to a tasks/cancel request. + * + * @category `tasks/cancel` + */ +export type CancelTaskResult = Result & Task; +/** + * A request to retrieve a list of tasks. + * + * @category `tasks/list` + */ +export interface ListTasksRequest extends PaginatedRequest { + method: "tasks/list"; +} +/** + * The response to a tasks/list request. + * + * @category `tasks/list` + */ +export interface ListTasksResult extends PaginatedResult { + tasks: Task[]; +} +/** + * Parameters for a `notifications/tasks/status` notification. + * + * @category `notifications/tasks/status` + */ +export type TaskStatusNotificationParams = NotificationParams & Task; +/** + * An optional notification from the receiver to the requestor, informing them that a task's status has changed. Receivers are not required to send these notifications. + * + * @category `notifications/tasks/status` + */ +export interface TaskStatusNotification extends JSONRPCNotification { + method: "notifications/tasks/status"; + params: TaskStatusNotificationParams; +} +/** + * Parameters for a `logging/setLevel` request. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequestParams extends RequestParams { + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/message. + */ + level: LoggingLevel; +} +/** + * A request from the client to the server, to enable or adjust logging. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequest extends JSONRPCRequest { + method: "logging/setLevel"; + params: SetLevelRequestParams; +} +/** + * Parameters for a `notifications/message` notification. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotificationParams extends NotificationParams { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; +} +/** + * JSONRPCNotification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotification extends JSONRPCNotification { + method: "notifications/message"; + params: LoggingMessageNotificationParams; +} +/** + * The severity of a log message. + * + * These map to syslog message severities, as specified in RFC-5424: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + * + * @category Common Types + */ +export type LoggingLevel = "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency"; +/** + * Parameters for a `sampling/createMessage` request. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequestParams extends TaskAugmentedRequestParams { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext?: "none" | "thisServer" | "allServers"; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: object; + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools?: Tool[]; + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice?: ToolChoice; +} +/** + * Controls tool selection behavior for sampling requests. + * + * @category `sampling/createMessage` + */ +export interface ToolChoice { + /** + * Controls the tool use ability of the model: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode?: "auto" | "required" | "none"; +} +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequest extends JSONRPCRequest { + method: "sampling/createMessage"; + params: CreateMessageRequestParams; +} +/** + * The client's response to a sampling/createMessage request from the server. + * The client should inform the user before returning the sampled message, to allow them + * to inspect the response (human in the loop) and decide whether to allow the server to see it. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageResult extends Result, SamplingMessage { + /** + * The name of the model that generated the message. + */ + model: string; + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason?: "endTurn" | "stopSequence" | "maxTokens" | "toolUse" | string; +} +/** + * Describes a message issued to or received from an LLM API. + * + * @category `sampling/createMessage` + */ +export interface SamplingMessage { + role: Role; + content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +export type SamplingMessageContentBlock = TextContent | ImageContent | AudioContent | ToolUseContent | ToolResultContent; +/** + * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed + * + * @category Common Types + */ +export interface Annotations { + /** + * Describes who the intended audience of this object or data is. + * + * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). + */ + audience?: Role[]; + /** + * Describes how important this data is for operating the server. + * + * A value of 1 means "most important," and indicates that the data is + * effectively required, while 0 means "least important," and indicates that + * the data is entirely optional. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + priority?: number; + /** + * The moment the resource was last modified, as an ISO 8601 formatted string. + * + * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). + * + * Examples: last activity timestamp in an open file, timestamp when the resource + * was attached, etc. + */ + lastModified?: string; +} +/** + * @category Content + */ +export type ContentBlock = TextContent | ImageContent | AudioContent | ResourceLink | EmbeddedResource; +/** + * Text provided to or from an LLM. + * + * @category Content + */ +export interface TextContent { + type: "text"; + /** + * The text content of the message. + */ + text: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * An image provided to or from an LLM. + * + * @category Content + */ +export interface ImageContent { + type: "image"; + /** + * The base64-encoded image data. + * + * @format byte + */ + data: string; + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * Audio provided to or from an LLM. + * + * @category Content + */ +export interface AudioContent { + type: "audio"; + /** + * The base64-encoded audio data. + * + * @format byte + */ + data: string; + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * A request from the assistant to call a tool. + * + * @category `sampling/createMessage` + */ +export interface ToolUseContent { + type: "tool_use"; + /** + * A unique identifier for this tool use. + * + * This ID is used to match tool results to their corresponding tool uses. + */ + id: string; + /** + * The name of the tool to call. + */ + name: string; + /** + * The arguments to pass to the tool, conforming to the tool's input schema. + */ + input: { + [key: string]: unknown; + }; + /** + * Optional metadata about the tool use. Clients SHOULD preserve this field when + * including tool uses in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The result of a tool use, provided by the user back to the assistant. + * + * @category `sampling/createMessage` + */ +export interface ToolResultContent { + type: "tool_result"; + /** + * The ID of the tool use this result corresponds to. + * + * This MUST match the ID from a previous ToolUseContent. + */ + toolUseId: string; + /** + * The unstructured result content of the tool use. + * + * This has the same format as CallToolResult.content and can include text, images, + * audio, resource links, and embedded resources. + */ + content: ContentBlock[]; + /** + * An optional structured result object. + * + * If the tool defined an outputSchema, this SHOULD conform to that schema. + */ + structuredContent?: { + [key: string]: unknown; + }; + /** + * Whether the tool use resulted in an error. + * + * If true, the content typically describes the error that occurred. + * Default: false + */ + isError?: boolean; + /** + * Optional metadata about the tool result. Clients SHOULD preserve this field when + * including tool results in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The server's preferences for model selection, requested of the client during sampling. + * + * Because LLMs can vary along multiple dimensions, choosing the "best" model is + * rarely straightforward. Different models excel in different areas—some are + * faster but less capable, others are more capable but more expensive, and so + * on. This interface allows servers to express their priorities across multiple + * dimensions to help clients make an appropriate selection for their use case. + * + * These preferences are always advisory. The client MAY ignore them. It is also + * up to the client to decide how to interpret these preferences and how to + * balance them against other considerations. + * + * @category `sampling/createMessage` + */ +export interface ModelPreferences { + /** + * Optional hints to use for model selection. + * + * If multiple hints are specified, the client MUST evaluate them in order + * (such that the first match is taken). + * + * The client SHOULD prioritize these hints over the numeric priorities, but + * MAY still use the priorities to select from ambiguous matches. + */ + hints?: ModelHint[]; + /** + * How much to prioritize cost when selecting a model. A value of 0 means cost + * is not important, while a value of 1 means cost is the most important + * factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + costPriority?: number; + /** + * How much to prioritize sampling speed (latency) when selecting a model. A + * value of 0 means speed is not important, while a value of 1 means speed is + * the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + speedPriority?: number; + /** + * How much to prioritize intelligence and capabilities when selecting a + * model. A value of 0 means intelligence is not important, while a value of 1 + * means intelligence is the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + intelligencePriority?: number; +} +/** + * Hints to use for model selection. + * + * Keys not declared here are currently left unspecified by the spec and are up + * to the client to interpret. + * + * @category `sampling/createMessage` + */ +export interface ModelHint { + /** + * A hint for a model name. + * + * The client SHOULD treat this as a substring of a model name; for example: + * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` + * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. + * - `claude` should match any Claude model + * + * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: + * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` + */ + name?: string; +} +/** + * Parameters for a `completion/complete` request. + * + * @category `completion/complete` + */ +export interface CompleteRequestParams extends RequestParams { + ref: PromptReference | ResourceTemplateReference; + /** + * The argument's information + */ + argument: { + /** + * The name of the argument + */ + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + /** + * Additional, optional context for completions + */ + context?: { + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments?: { + [key: string]: string; + }; + }; +} +/** + * A request from the client to the server, to ask for completion options. + * + * @category `completion/complete` + */ +export interface CompleteRequest extends JSONRPCRequest { + method: "completion/complete"; + params: CompleteRequestParams; +} +/** + * The server's response to a completion/complete request + * + * @category `completion/complete` + */ +export interface CompleteResult extends Result { + completion: { + /** + * An array of completion values. Must not exceed 100 items. + */ + values: string[]; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total?: number; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore?: boolean; + }; +} +/** + * A reference to a resource or resource template definition. + * + * @category `completion/complete` + */ +export interface ResourceTemplateReference { + type: "ref/resource"; + /** + * The URI or URI template of the resource. + * + * @format uri-template + */ + uri: string; +} +/** + * Identifies a prompt. + * + * @category `completion/complete` + */ +export interface PromptReference extends BaseMetadata { + type: "ref/prompt"; +} +/** + * Sent from the server to request a list of root URIs from the client. Roots allow + * servers to ask for specific directories or files to operate on. A common example + * for roots is providing a set of repositories or directories a server should operate + * on. + * + * This request is typically used when the server needs to understand the file system + * structure or access specific locations that the client has permission to read from. + * + * @category `roots/list` + */ +export interface ListRootsRequest extends JSONRPCRequest { + method: "roots/list"; + params?: RequestParams; +} +/** + * The client's response to a roots/list request from the server. + * This result contains an array of Root objects, each representing a root directory + * or file that the server can operate on. + * + * @category `roots/list` + */ +export interface ListRootsResult extends Result { + roots: Root[]; +} +/** + * Represents a root directory or file that the server can operate on. + * + * @category `roots/list` + */ +export interface Root { + /** + * The URI identifying the root. This *must* start with file:// for now. + * This restriction may be relaxed in future versions of the protocol to allow + * other URI schemes. + * + * @format uri + */ + uri: string; + /** + * An optional name for the root. This can be used to provide a human-readable + * identifier for the root, which may be useful for display purposes or for + * referencing the root in other parts of the application. + */ + name?: string; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * A notification from the client to the server, informing it that the list of roots has changed. + * This notification should be sent whenever the client adds, removes, or modifies any root. + * The server should then request an updated list of roots using the ListRootsRequest. + * + * @category `notifications/roots/list_changed` + */ +export interface RootsListChangedNotification extends JSONRPCNotification { + method: "notifications/roots/list_changed"; + params?: NotificationParams; +} +/** + * The parameters for a request to elicit non-sensitive information from the user via a form in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestFormParams extends TaskAugmentedRequestParams { + /** + * The elicitation mode. + */ + mode?: "form"; + /** + * The message to present to the user describing what information is being requested. + */ + message: string; + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: { + $schema?: string; + type: "object"; + properties: { + [key: string]: PrimitiveSchemaDefinition; + }; + required?: string[]; + }; +} +/** + * The parameters for a request to elicit information from the user via a URL in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestURLParams extends TaskAugmentedRequestParams { + /** + * The elicitation mode. + */ + mode: "url"; + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string; + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string; + /** + * The URL that the user should navigate to. + * + * @format uri + */ + url: string; +} +/** + * The parameters for a request to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export type ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLParams; +/** + * A request from the server to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequest extends JSONRPCRequest { + method: "elicitation/create"; + params: ElicitRequestParams; +} +/** + * Restricted schema definitions that only allow primitive types + * without nested objects or arrays. + * + * @category `elicitation/create` + */ +export type PrimitiveSchemaDefinition = StringSchema | NumberSchema | BooleanSchema | EnumSchema; +/** + * @category `elicitation/create` + */ +export interface StringSchema { + type: "string"; + title?: string; + description?: string; + minLength?: number; + maxLength?: number; + format?: "email" | "uri" | "date" | "date-time"; + default?: string; +} +/** + * @category `elicitation/create` + */ +export interface NumberSchema { + type: "number" | "integer"; + title?: string; + description?: string; + minimum?: number; + maximum?: number; + default?: number; +} +/** + * @category `elicitation/create` + */ +export interface BooleanSchema { + type: "boolean"; + title?: string; + description?: string; + default?: boolean; +} +/** + * Schema for single-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum values to choose from. + */ + enum: string[]; + /** + * Optional default value. + */ + default?: string; +} +/** + * Schema for single-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum options with values and display labels. + */ + oneOf: Array<{ + /** + * The enum value. + */ + const: string; + /** + * Display label for this option. + */ + title: string; + }>; + /** + * Optional default value. + */ + default?: string; +} +/** + * @category `elicitation/create` + */ +export type SingleSelectEnumSchema = UntitledSingleSelectEnumSchema | TitledSingleSelectEnumSchema; +/** + * Schema for multiple-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for the array items. + */ + items: { + type: "string"; + /** + * Array of enum values to choose from. + */ + enum: string[]; + }; + /** + * Optional default value. + */ + default?: string[]; +} +/** + * Schema for multiple-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for array items with enum options and display labels. + */ + items: { + /** + * Array of enum options with values and display labels. + */ + anyOf: Array<{ + /** + * The constant enum value. + */ + const: string; + /** + * Display title for this option. + */ + title: string; + }>; + }; + /** + * Optional default value. + */ + default?: string[]; +} +/** + * @category `elicitation/create` + */ +export type MultiSelectEnumSchema = UntitledMultiSelectEnumSchema | TitledMultiSelectEnumSchema; +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + * + * @category `elicitation/create` + */ +export interface LegacyTitledEnumSchema { + type: "string"; + title?: string; + description?: string; + enum: string[]; + /** + * (Legacy) Display names for enum values. + * Non-standard according to JSON schema 2020-12. + */ + enumNames?: string[]; + default?: string; +} +/** + * @category `elicitation/create` + */ +export type EnumSchema = SingleSelectEnumSchema | MultiSelectEnumSchema | LegacyTitledEnumSchema; +/** + * The client's response to an elicitation request. + * + * @category `elicitation/create` + */ +export interface ElicitResult extends Result { + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: "accept" | "decline" | "cancel"; + /** + * The submitted form data, only present when action is "accept" and mode was "form". + * Contains values matching the requested schema. + * Omitted for out-of-band mode responses. + */ + content?: { + [key: string]: string | number | boolean | string[]; + }; +} +/** + * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. + * + * @category `notifications/elicitation/complete` + */ +export interface ElicitationCompleteNotification extends JSONRPCNotification { + method: "notifications/elicitation/complete"; + params: { + /** + * The ID of the elicitation that completed. + */ + elicitationId: string; + }; +} +/** @internal */ +export type ClientRequest = PingRequest | InitializeRequest | CompleteRequest | SetLevelRequest | GetPromptRequest | ListPromptsRequest | ListResourcesRequest | ListResourceTemplatesRequest | ReadResourceRequest | SubscribeRequest | UnsubscribeRequest | CallToolRequest | ListToolsRequest | GetTaskRequest | GetTaskPayloadRequest | ListTasksRequest | CancelTaskRequest; +/** @internal */ +export type ClientNotification = CancelledNotification | ProgressNotification | InitializedNotification | RootsListChangedNotification | TaskStatusNotification; +/** @internal */ +export type ClientResult = EmptyResult | CreateMessageResult | ListRootsResult | ElicitResult | GetTaskResult | GetTaskPayloadResult | ListTasksResult | CancelTaskResult; +/** @internal */ +export type ServerRequest = PingRequest | CreateMessageRequest | ListRootsRequest | ElicitRequest | GetTaskRequest | GetTaskPayloadRequest | ListTasksRequest | CancelTaskRequest; +/** @internal */ +export type ServerNotification = CancelledNotification | ProgressNotification | LoggingMessageNotification | ResourceUpdatedNotification | ResourceListChangedNotification | ToolListChangedNotification | PromptListChangedNotification | ElicitationCompleteNotification | TaskStatusNotification; +/** @internal */ +export type ServerResult = EmptyResult | InitializeResult | CompleteResult | GetPromptResult | ListPromptsResult | ListResourceTemplatesResult | ListResourcesResult | ReadResourceResult | CallToolResult | ListToolsResult | GetTaskResult | GetTaskPayloadResult | ListTasksResult | CancelTaskResult; +//# sourceMappingURL=spec.types.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/spec.types.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/spec.types.d.ts.map new file mode 100644 index 000000000..7e4fb0e57 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/spec.types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"spec.types.d.ts","sourceRoot":"","sources":["../../src/spec.types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH;;;;GAIG;AACH,MAAM,MAAM,cAAc,GACtB,cAAc,GACd,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AAuB,GACvB,4BAA4B,GAC5B,sBAAsB,CAAC;AAE3B,gBAAgB;AAChB,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,mBAAmB,GACnB,eAAe,GACf,YAAY,GACZ,aAAa,GACb,oBAAoB,GACpB,eAAe,GACf,gBAAgB,CAAC;AAGrB,gBAAgB;AAChB,MAAM,MAAM,aAAa,GACrB,WAAW,GACX,oBAAoB,GACpB,gBAAgB,GAChB,aAAa,GACb,cAAc,GACd,qBAAqB,GACrB,gBAAgB,GAChB,iBAAiB,CAAC;AAEtB,gBAAgB;AAChB,MAAM,MAAM,kBAAkB,GAC1B,qBAAqB,GACrB,oBAAoB,GACpB,0BAA0B,GAC1B,2BAA2B,GAC3B,+BAA+B,GAC/B,2BAA2B,GAC3B,6BAA6B,GAC7B,+BAA+B,GAC/B,sBAAsB,CAAC;AAE3B,gBAAgB;AAChB,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,gBAAgB,GAChB,cAAc,GACd,eAAe,GACf,iBAAiB,GACjB,2BAA2B,GAC3B,mBAAmB,GACnB,kBAAkB,GAClB,cAAc,GACd,eAAe,GACf,aAAa,GACb,oBAAoB,GACpB,eAAe,GACf,gBAAgB,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/spec.types.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/spec.types.js new file mode 100644 index 000000000..7d0bd0552 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/spec.types.js @@ -0,0 +1,24 @@ +/** + * This file is automatically generated from the Model Context Protocol specification. + * + * Source: https://github.com/modelcontextprotocol/modelcontextprotocol + * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts + * Last updated from commit: 35fa160caf287a9c48696e3ae452c0645c713669 + * + * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. + * To update this file, run: npm run fetch:spec-types + */ /* JSON-RPC types */ +/** @internal */ +export const LATEST_PROTOCOL_VERSION = "DRAFT-2026-v1"; +/** @internal */ +export const JSONRPC_VERSION = "2.0"; +// Standard JSON-RPC error codes +export const PARSE_ERROR = -32700; +export const INVALID_REQUEST = -32600; +export const METHOD_NOT_FOUND = -32601; +export const INVALID_PARAMS = -32602; +export const INTERNAL_ERROR = -32603; +// Implementation-specific JSON-RPC error codes [-32000, -32099] +/** @internal */ +export const URL_ELICITATION_REQUIRED = -32042; +//# sourceMappingURL=spec.types.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/spec.types.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/spec.types.js.map new file mode 100644 index 000000000..02dadb912 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/spec.types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spec.types.js","sourceRoot":"","sources":["../../src/spec.types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG,CAAA,oBAAoB;AAYvB,gBAAgB;AAChB,MAAM,CAAC,MAAM,uBAAuB,GAAG,eAAe,CAAC;AACvD,gBAAgB;AAChB,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,CAAC;AA4JrC,gCAAgC;AAChC,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,KAAK,CAAC;AAClC,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,KAAK,CAAC;AACtC,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,KAAK,CAAC;AACvC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,KAAK,CAAC;AACrC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,KAAK,CAAC;AAErC,gEAAgE;AAChE,gBAAgB;AAChB,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/types.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/types.d.ts new file mode 100644 index 000000000..55f087ef8 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/types.d.ts @@ -0,0 +1,8133 @@ +import * as z from 'zod/v4'; +import { AuthInfo } from './server/auth/types.js'; +export declare const LATEST_PROTOCOL_VERSION = "2025-11-25"; +export declare const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; +export declare const SUPPORTED_PROTOCOL_VERSIONS: string[]; +export declare const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; +export declare const JSONRPC_VERSION = "2.0"; +/** + * Utility types + */ +type ExpandRecursively = T extends object ? (T extends infer O ? { + [K in keyof O]: ExpandRecursively; +} : never) : T; +/** + * A progress token, used to associate progress notifications with the original request. + */ +export declare const ProgressTokenSchema: z.ZodUnion; +/** + * An opaque token used to represent a cursor for pagination. + */ +export declare const CursorSchema: z.ZodString; +/** + * Task creation parameters, used to ask that the server create a task to represent a request. + */ +export declare const TaskCreationParamsSchema: z.ZodObject<{ + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: z.ZodOptional>; + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval: z.ZodOptional; +}, z.core.$loose>; +export declare const TaskMetadataSchema: z.ZodObject<{ + ttl: z.ZodOptional; +}, z.core.$strip>; +/** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + */ +export declare const RelatedTaskMetadataSchema: z.ZodObject<{ + taskId: z.ZodString; +}, z.core.$strip>; +declare const RequestMetaSchema: z.ZodObject<{ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; +}, z.core.$loose>; +/** + * Common params for any request. + */ +declare const BaseRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strip>; +/** + * Common params for any task-augmented request. + */ +export declare const TaskAugmentedRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * Checks if a value is a valid TaskAugmentedRequestParams. + * @param value - The value to check. + * + * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise. + */ +export declare const isTaskAugmentedRequestParams: (value: unknown) => value is TaskAugmentedRequestParams; +export declare const RequestSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$strip>; +declare const NotificationsParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strip>; +export declare const NotificationSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$strip>; +export declare const ResultSchema: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$loose>; +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +export declare const RequestIdSchema: z.ZodUnion; +/** + * A request that expects a response. + */ +export declare const JSONRPCRequestSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; +}, z.core.$strict>; +export declare const isJSONRPCRequest: (value: unknown) => value is JSONRPCRequest; +/** + * A notification which does not expect a response. + */ +export declare const JSONRPCNotificationSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; +}, z.core.$strict>; +export declare const isJSONRPCNotification: (value: unknown) => value is JSONRPCNotification; +/** + * A successful (non-error) response to a request. + */ +export declare const JSONRPCResultResponseSchema: z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; + result: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>; +}, z.core.$strict>; +/** + * Checks if a value is a valid JSONRPCResultResponse. + * @param value - The value to check. + * + * @returns True if the value is a valid JSONRPCResultResponse, false otherwise. + */ +export declare const isJSONRPCResultResponse: (value: unknown) => value is JSONRPCResultResponse; +/** + * @deprecated Use {@link isJSONRPCResultResponse} instead. + * + * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse}) + */ +export declare const isJSONRPCResponse: (value: unknown) => value is JSONRPCResultResponse; +/** + * Error codes defined by the JSON-RPC specification. + */ +export declare enum ErrorCode { + ConnectionClosed = -32000, + RequestTimeout = -32001, + ParseError = -32700, + InvalidRequest = -32600, + MethodNotFound = -32601, + InvalidParams = -32602, + InternalError = -32603, + UrlElicitationRequired = -32042 +} +/** + * A response to a request that indicates an error occurred. + */ +export declare const JSONRPCErrorResponseSchema: z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodOptional>; + error: z.ZodObject<{ + code: z.ZodNumber; + message: z.ZodString; + data: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strict>; +/** + * @deprecated Use {@link JSONRPCErrorResponseSchema} instead. + */ +export declare const JSONRPCErrorSchema: z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodOptional>; + error: z.ZodObject<{ + code: z.ZodNumber; + message: z.ZodString; + data: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strict>; +/** + * Checks if a value is a valid JSONRPCErrorResponse. + * @param value - The value to check. + * + * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise. + */ +export declare const isJSONRPCErrorResponse: (value: unknown) => value is JSONRPCErrorResponse; +/** + * @deprecated Use {@link isJSONRPCErrorResponse} instead. + */ +export declare const isJSONRPCError: (value: unknown) => value is JSONRPCErrorResponse; +export declare const JSONRPCMessageSchema: z.ZodUnion>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; +}, z.core.$strict>, z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; +}, z.core.$strict>, z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; + result: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>; +}, z.core.$strict>, z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodOptional>; + error: z.ZodObject<{ + code: z.ZodNumber; + message: z.ZodString; + data: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strict>]>; +export declare const JSONRPCResponseSchema: z.ZodUnion; + id: z.ZodUnion; + result: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>; +}, z.core.$strict>, z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodOptional>; + error: z.ZodObject<{ + code: z.ZodNumber; + message: z.ZodString; + data: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strict>]>; +/** + * A response that indicates success but carries no data. + */ +export declare const EmptyResultSchema: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strict>; +export declare const CancelledNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + requestId: z.ZodOptional>; + reason: z.ZodOptional; +}, z.core.$strip>; +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + */ +export declare const CancelledNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/cancelled">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + requestId: z.ZodOptional>; + reason: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Icon schema for use in tools, prompts, resources, and implementations. + */ +export declare const IconSchema: z.ZodObject<{ + src: z.ZodString; + mimeType: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; +}, z.core.$strip>; +/** + * Base schema to add `icons` property. + * + */ +export declare const IconsSchema: z.ZodObject<{ + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; +}, z.core.$strip>; +/** + * Base metadata interface for common properties across resources, tools, prompts, and implementations. + */ +export declare const BaseMetadataSchema: z.ZodObject<{ + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Describes the name and version of an MCP implementation. + */ +export declare const ImplementationSchema: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + description: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Task capabilities for clients, indicating which request types support task creation. + */ +export declare const ClientTasksCapabilitySchema: z.ZodObject<{ + /** + * Present if the client supports listing tasks. + */ + list: z.ZodOptional>; + /** + * Present if the client supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + /** + * Task support for elicitation requests. + */ + elicitation: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$loose>; +/** + * Task capabilities for servers, indicating which request types support task creation. + */ +export declare const ServerTasksCapabilitySchema: z.ZodObject<{ + /** + * Present if the server supports listing tasks. + */ + list: z.ZodOptional>; + /** + * Present if the server supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$loose>; +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ +export declare const ClientCapabilitiesSchema: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the client supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + /** + * Task support for elicitation requests. + */ + elicitation: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$strip>; +export declare const InitializeRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the client supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + /** + * Task support for elicitation requests. + */ + elicitation: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$strip>; + clientInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + description: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ +export declare const InitializeRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"initialize">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the client supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + /** + * Task support for elicitation requests. + */ + elicitation: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$strip>; + clientInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + description: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + }, z.core.$strip>; +}, z.core.$strip>; +export declare const isInitializeRequest: (value: unknown) => value is InitializeRequest; +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ +export declare const ServerCapabilitiesSchema: z.ZodObject<{ + experimental: z.ZodOptional>>; + logging: z.ZodOptional>; + completions: z.ZodOptional>; + prompts: z.ZodOptional; + }, z.core.$strip>>; + resources: z.ZodOptional; + listChanged: z.ZodOptional; + }, z.core.$strip>>; + tools: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the server supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$strip>; +/** + * After receiving an initialize request from the client, the server sends this response. + */ +export declare const InitializeResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + logging: z.ZodOptional>; + completions: z.ZodOptional>; + prompts: z.ZodOptional; + }, z.core.$strip>>; + resources: z.ZodOptional; + listChanged: z.ZodOptional; + }, z.core.$strip>>; + tools: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the server supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$strip>; + serverInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + description: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + instructions: z.ZodOptional; +}, z.core.$loose>; +/** + * This notification is sent from the client to the server after initialization has finished. + */ +export declare const InitializedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/initialized">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +export declare const isInitializedNotification: (value: unknown) => value is InitializedNotification; +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +export declare const PingRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"ping">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +export declare const ProgressSchema: z.ZodObject<{ + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; +}, z.core.$strip>; +export declare const ProgressNotificationParamsSchema: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strip>; +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ +export declare const ProgressNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/progress">; + params: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>; +}, z.core.$strip>; +export declare const PaginatedRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; +}, z.core.$strip>; +export declare const PaginatedRequestSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$strip>; +export declare const PaginatedResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; +}, z.core.$loose>; +/** + * The status of a task. + * */ +export declare const TaskStatusSchema: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; +}>; +/** + * A pollable state object associated with a request. + */ +export declare const TaskSchema: z.ZodObject<{ + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; +}, z.core.$strip>; +/** + * Result returned when a task is created, containing the task data wrapped in a task field. + */ +export declare const CreateTaskResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodObject<{ + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$loose>; +/** + * Parameters for task status notification. + */ +export declare const TaskStatusNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; +}, z.core.$strip>; +/** + * A notification sent when a task's status changes. + */ +export declare const TaskStatusNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/tasks/status">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * A request to get the state of a specific task. + */ +export declare const GetTaskRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"tasks/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * The response to a tasks/get request. + */ +export declare const GetTaskResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; +}, z.core.$strip>; +/** + * A request to get the result of a specific task. + */ +export declare const GetTaskPayloadRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"tasks/result">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * The response to a tasks/result request. + * The structure matches the result type of the original request. + * For example, a tools/call task would return the CallToolResult structure. + * + */ +export declare const GetTaskPayloadResultSchema: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$loose>; +/** + * A request to list tasks. + */ +export declare const ListTasksRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"tasks/list">; +}, z.core.$strip>; +/** + * The response to a tasks/list request. + */ +export declare const ListTasksResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + tasks: z.ZodArray; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * A request to cancel a specific task. + */ +export declare const CancelTaskRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"tasks/cancel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * The response to a tasks/cancel request. + */ +export declare const CancelTaskResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; +}, z.core.$strip>; +/** + * The contents of a specific resource or sub-resource. + */ +export declare const ResourceContentsSchema: z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>; +export declare const TextResourceContentsSchema: z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + text: z.ZodString; +}, z.core.$strip>; +export declare const BlobResourceContentsSchema: z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; +}, z.core.$strip>; +/** + * The sender or recipient of messages and data in a conversation. + */ +export declare const RoleSchema: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; +}>; +/** + * Optional annotations providing clients additional context about a resource. + */ +export declare const AnnotationsSchema: z.ZodObject<{ + audience: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; +}, z.core.$strip>; +/** + * A known resource that the server is capable of reading. + */ +export declare const ResourceSchema: z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * A template description for resources available on the server. + */ +export declare const ResourceTemplateSchema: z.ZodObject<{ + uriTemplate: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Sent from the client to request a list of resources the server has. + */ +export declare const ListResourcesRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"resources/list">; +}, z.core.$strip>; +/** + * The server's response to a resources/list request from the client. + */ +export declare const ListResourcesResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + resources: z.ZodArray; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * Sent from the client to request a list of resource templates the server has. + */ +export declare const ListResourceTemplatesRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"resources/templates/list">; +}, z.core.$strip>; +/** + * The server's response to a resources/templates/list request from the client. + */ +export declare const ListResourceTemplatesResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + resourceTemplates: z.ZodArray; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +export declare const ResourceRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$strip>; +/** + * Parameters for a `resources/read` request. + */ +export declare const ReadResourceRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$strip>; +/** + * Sent from the client to the server, to read a specific resource URI. + */ +export declare const ReadResourceRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"resources/read">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * The server's response to a resources/read request from the client. + */ +export declare const ReadResourceResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + contents: z.ZodArray; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>>; +}, z.core.$loose>; +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ +export declare const ResourceListChangedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/resources/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +export declare const SubscribeRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$strip>; +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + */ +export declare const SubscribeRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"resources/subscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +export declare const UnsubscribeRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$strip>; +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + */ +export declare const UnsubscribeRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"resources/unsubscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Parameters for a `notifications/resources/updated` notification. + */ +export declare const ResourceUpdatedNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$strip>; +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + */ +export declare const ResourceUpdatedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/resources/updated">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Describes an argument that a prompt can accept. + */ +export declare const PromptArgumentSchema: z.ZodObject<{ + name: z.ZodString; + description: z.ZodOptional; + required: z.ZodOptional; +}, z.core.$strip>; +/** + * A prompt or prompt template that the server offers. + */ +export declare const PromptSchema: z.ZodObject<{ + description: z.ZodOptional; + arguments: z.ZodOptional; + required: z.ZodOptional; + }, z.core.$strip>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ +export declare const ListPromptsRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"prompts/list">; +}, z.core.$strip>; +/** + * The server's response to a prompts/list request from the client. + */ +export declare const ListPromptsResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + prompts: z.ZodArray; + arguments: z.ZodOptional; + required: z.ZodOptional; + }, z.core.$strip>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * Parameters for a `prompts/get` request. + */ +export declare const GetPromptRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; +}, z.core.$strip>; +/** + * Used by the client to get a prompt provided by the server. + */ +export declare const GetPromptRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"prompts/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Text provided to or from an LLM. + */ +export declare const TextContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * An image provided to or from an LLM. + */ +export declare const ImageContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * An Audio provided to or from an LLM. + */ +export declare const AudioContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + */ +export declare const ToolUseContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * The contents of a resource, embedded into a prompt or tool call result. + */ +export declare const EmbeddedResourceSchema: z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + */ +export declare const ResourceLinkSchema: z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; +}, z.core.$strip>; +/** + * A content block that can be used in prompts and tool results. + */ +export declare const ContentBlockSchema: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Describes a message returned as part of a prompt. + */ +export declare const PromptMessageSchema: z.ZodObject<{ + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; +}, z.core.$strip>; +/** + * The server's response to a prompts/get request from the client. + */ +export declare const GetPromptResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + description: z.ZodOptional; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export declare const PromptListChangedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/prompts/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + */ +export declare const ToolAnnotationsSchema: z.ZodObject<{ + title: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; +}, z.core.$strip>; +/** + * Execution-related properties for a tool. + */ +export declare const ToolExecutionSchema: z.ZodObject<{ + taskSupport: z.ZodOptional>; +}, z.core.$strip>; +/** + * Definition for a tool the client can call. + */ +export declare const ToolSchema: z.ZodObject<{ + description: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + execution: z.ZodOptional>; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Sent from the client to request a list of tools the server has. + */ +export declare const ListToolsRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"tools/list">; +}, z.core.$strip>; +/** + * The server's response to a tools/list request from the client. + */ +export declare const ListToolsResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + tools: z.ZodArray; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + execution: z.ZodOptional>; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * The server's response to a tool call. + */ +export declare const CallToolResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; +}, z.core.$loose>; +/** + * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. + */ +export declare const CompatibilityCallToolResultSchema: z.ZodUnion<[z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + toolResult: z.ZodUnknown; +}, z.core.$loose>]>; +/** + * Parameters for a `tools/call` request. + */ +export declare const CallToolRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + name: z.ZodString; + arguments: z.ZodOptional>; +}, z.core.$strip>; +/** + * Used by the client to invoke a tool provided by the server. + */ +export declare const CallToolRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"tools/call">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export declare const ToolListChangedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/tools/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * Callback type for list changed notifications. + */ +export type ListChangedCallback = (error: Error | null, items: T[] | null) => void; +/** + * Base schema for list changed subscription options (without callback). + * Used internally for Zod validation of autoRefresh and debounceMs. + */ +export declare const ListChangedOptionsBaseSchema: z.ZodObject<{ + autoRefresh: z.ZodDefault; + debounceMs: z.ZodDefault; +}, z.core.$strip>; +/** + * Options for subscribing to list changed notifications. + * + * @typeParam T - The type of items in the list (Tool, Prompt, or Resource) + */ +export type ListChangedOptions = { + /** + * If true, the list will be refreshed automatically when a list changed notification is received. + * @default true + */ + autoRefresh?: boolean; + /** + * Debounce time in milliseconds. Set to 0 to disable. + * @default 300 + */ + debounceMs?: number; + /** + * Callback invoked when the list changes. + * + * If autoRefresh is true, items contains the updated list. + * If autoRefresh is false, items is null (caller should refresh manually). + */ + onChanged: ListChangedCallback; +}; +/** + * Configuration for list changed notification handlers. + * + * Use this to configure handlers for tools, prompts, and resources list changes + * when creating a client. + * + * Note: Handlers are only activated if the server advertises the corresponding + * `listChanged` capability (e.g., `tools.listChanged: true`). If the server + * doesn't advertise this capability, the handler will not be set up. + */ +export type ListChangedHandlers = { + /** + * Handler for tool list changes. + */ + tools?: ListChangedOptions; + /** + * Handler for prompt list changes. + */ + prompts?: ListChangedOptions; + /** + * Handler for resource list changes. + */ + resources?: ListChangedOptions; +}; +/** + * The severity of a log message. + */ +export declare const LoggingLevelSchema: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; +}>; +/** + * Parameters for a `logging/setLevel` request. + */ +export declare const SetLevelRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; +}, z.core.$strip>; +/** + * A request from the client to the server, to enable or adjust logging. + */ +export declare const SetLevelRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"logging/setLevel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Parameters for a `notifications/message` notification. + */ +export declare const LoggingMessageNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + logger: z.ZodOptional; + data: z.ZodUnknown; +}, z.core.$strip>; +/** + * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + */ +export declare const LoggingMessageNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/message">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + logger: z.ZodOptional; + data: z.ZodUnknown; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Hints to use for model selection. + */ +export declare const ModelHintSchema: z.ZodObject<{ + name: z.ZodOptional; +}, z.core.$strip>; +/** + * The server's preferences for model selection, requested of the client during sampling. + */ +export declare const ModelPreferencesSchema: z.ZodObject<{ + hints: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; +}, z.core.$strip>; +/** + * Controls tool usage behavior in sampling requests. + */ +export declare const ToolChoiceSchema: z.ZodObject<{ + mode: z.ZodOptional>; +}, z.core.$strip>; +/** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via ToolUseContent. + */ +export declare const ToolResultContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible CreateMessageResult when tools are not used. + */ +export declare const SamplingContentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + */ +export declare const SamplingMessageContentBlockSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Describes a message issued to or received from an LLM API. + */ +export declare const SamplingMessageSchema: z.ZodObject<{ + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>, z.ZodArray; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>]>; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * Parameters for a `sampling/createMessage` request. + */ +export declare const CreateMessageRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>, z.ZodArray; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>>; + modelPreferences: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; + }, z.core.$strip>>; + systemPrompt: z.ZodOptional; + includeContext: z.ZodOptional>; + temperature: z.ZodOptional; + maxTokens: z.ZodNumber; + stopSequences: z.ZodOptional>; + metadata: z.ZodOptional>; + tools: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + execution: z.ZodOptional>; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>>; + toolChoice: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + */ +export declare const CreateMessageRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"sampling/createMessage">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>, z.ZodArray; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>>; + modelPreferences: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; + }, z.core.$strip>>; + systemPrompt: z.ZodOptional; + includeContext: z.ZodOptional>; + temperature: z.ZodOptional; + maxTokens: z.ZodNumber; + stopSequences: z.ZodOptional>; + metadata: z.ZodOptional>; + tools: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + execution: z.ZodOptional>; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>>; + toolChoice: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * The client's response to a sampling/create_message request from the server. + * This is the backwards-compatible version that returns single content (no arrays). + * Used when the request does not include tools. + */ +export declare const CreateMessageResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + model: z.ZodString; + stopReason: z.ZodOptional, z.ZodString]>>; + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodDiscriminatedUnion<[z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; +}, z.core.$loose>; +/** + * The client's response to a sampling/create_message request when tools were provided. + * This version supports array content for tool use flows. + */ +export declare const CreateMessageResultWithToolsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + model: z.ZodString; + stopReason: z.ZodOptional, z.ZodString]>>; + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>, z.ZodArray; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>]>; +}, z.core.$loose>; +/** + * Primitive schema definition for boolean fields. + */ +export declare const BooleanSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Primitive schema definition for string fields. + */ +export declare const StringSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Primitive schema definition for number fields. + */ +export declare const NumberSchemaSchema: z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Schema for single-selection enumeration without display titles for options. + */ +export declare const UntitledSingleSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Schema for single-selection enumeration with display titles for each option. + */ +export declare const TitledSingleSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + */ +export declare const LegacyTitledEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>; +export declare const SingleSelectEnumSchemaSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>]>; +/** + * Schema for multiple-selection enumeration without display titles for options. + */ +export declare const UntitledMultiSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>; +/** + * Schema for multiple-selection enumeration with display titles for each option. + */ +export declare const TitledMultiSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>; +/** + * Combined schema for multiple-selection enumeration + */ +export declare const MultiSelectEnumSchemaSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Primitive schema definition for enum fields. + */ +export declare const EnumSchemaSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>]>]>; +/** + * Union of all primitive schema definitions. + */ +export declare const PrimitiveSchemaDefinitionSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>]>; +/** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ +export declare const ElicitRequestFormParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodOptional>; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * Parameters for an `elicitation/create` request for URL-based elicitation. + */ +export declare const ElicitRequestURLParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; +}, z.core.$strip>; +/** + * The parameters for a request to elicit additional information from the user via the client. + */ +export declare const ElicitRequestParamsSchema: z.ZodUnion>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodOptional>; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; +}, z.core.$strip>]>; +/** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ +export declare const ElicitRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"elicitation/create">; + params: z.ZodUnion>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodOptional>; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; + }, z.core.$strip>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; + }, z.core.$strip>]>; +}, z.core.$strip>; +/** + * Parameters for a `notifications/elicitation/complete` notification. + * + * @category notifications/elicitation/complete + */ +export declare const ElicitationCompleteNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + elicitationId: z.ZodString; +}, z.core.$strip>; +/** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ +export declare const ElicitationCompleteNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/elicitation/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + elicitationId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>; +/** + * The client's response to an elicitation/create request from the server. + */ +export declare const ElicitResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + action: z.ZodEnum<{ + cancel: "cancel"; + accept: "accept"; + decline: "decline"; + }>; + content: z.ZodPipe, z.ZodOptional]>>>>; +}, z.core.$loose>; +/** + * A reference to a resource or resource template definition. + */ +export declare const ResourceTemplateReferenceSchema: z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; +}, z.core.$strip>; +/** + * @deprecated Use ResourceTemplateReferenceSchema instead + */ +export declare const ResourceReferenceSchema: z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; +}, z.core.$strip>; +/** + * Identifies a prompt. + */ +export declare const PromptReferenceSchema: z.ZodObject<{ + type: z.ZodLiteral<"ref/prompt">; + name: z.ZodString; +}, z.core.$strip>; +/** + * Parameters for a `completion/complete` request. + */ +export declare const CompleteRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + ref: z.ZodUnion; + name: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; + }, z.core.$strip>]>; + argument: z.ZodObject<{ + name: z.ZodString; + value: z.ZodString; + }, z.core.$strip>; + context: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * A request from the client to the server, to ask for completion options. + */ +export declare const CompleteRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"completion/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + ref: z.ZodUnion; + name: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; + }, z.core.$strip>]>; + argument: z.ZodObject<{ + name: z.ZodString; + value: z.ZodString; + }, z.core.$strip>; + context: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$strip>; +}, z.core.$strip>; +export declare function assertCompleteRequestPrompt(request: CompleteRequest): asserts request is CompleteRequestPrompt; +export declare function assertCompleteRequestResourceTemplate(request: CompleteRequest): asserts request is CompleteRequestResourceTemplate; +/** + * The server's response to a completion/complete request + */ +export declare const CompleteResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + completion: z.ZodObject<{ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.ZodArray; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.ZodOptional; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$loose>; +/** + * Represents a root directory or file that the server can operate on. + */ +export declare const RootSchema: z.ZodObject<{ + uri: z.ZodString; + name: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * Sent from the server to request a list of root URIs from the client. + */ +export declare const ListRootsRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"roots/list">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * The client's response to a roots/list request from the server. + */ +export declare const ListRootsResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + roots: z.ZodArray; + _meta: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * A notification from the client to the server, informing it that the list of roots has changed. + */ +export declare const RootsListChangedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/roots/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>; +export declare const ClientRequestSchema: z.ZodUnion; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"initialize">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the client supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + /** + * Task support for elicitation requests. + */ + elicitation: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$strip>; + clientInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + description: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"completion/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + ref: z.ZodUnion; + name: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; + }, z.core.$strip>]>; + argument: z.ZodObject<{ + name: z.ZodString; + value: z.ZodString; + }, z.core.$strip>; + context: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"logging/setLevel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"prompts/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"prompts/list">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"resources/list">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"resources/templates/list">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"resources/read">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"resources/subscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"resources/unsubscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tools/call">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"tools/list">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tasks/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tasks/result">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"tasks/list">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tasks/cancel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>]>; +export declare const ClientNotificationSchema: z.ZodUnion; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + requestId: z.ZodOptional>; + reason: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/progress">; + params: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/initialized">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/roots/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/tasks/status">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>]>; +export declare const ClientResultSchema: z.ZodUnion>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strict>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + model: z.ZodString; + stopReason: z.ZodOptional, z.ZodString]>>; + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodDiscriminatedUnion<[z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + model: z.ZodString; + stopReason: z.ZodOptional, z.ZodString]>>; + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>, z.ZodArray; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>]>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + action: z.ZodEnum<{ + cancel: "cancel"; + accept: "accept"; + decline: "decline"; + }>; + content: z.ZodPipe, z.ZodOptional]>>>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + roots: z.ZodArray; + _meta: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + tasks: z.ZodArray; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodObject<{ + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$loose>]>; +export declare const ServerRequestSchema: z.ZodUnion; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"sampling/createMessage">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>, z.ZodArray; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodRecord; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>>; + modelPreferences: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; + }, z.core.$strip>>; + systemPrompt: z.ZodOptional; + includeContext: z.ZodOptional>; + temperature: z.ZodOptional; + maxTokens: z.ZodNumber; + stopSequences: z.ZodOptional>; + metadata: z.ZodOptional>; + tools: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + execution: z.ZodOptional>; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>>; + toolChoice: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"elicitation/create">; + params: z.ZodUnion>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodOptional>; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; + }, z.core.$strip>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodOptional; + }, z.core.$strip>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; + }, z.core.$strip>]>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"roots/list">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tasks/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tasks/result">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$strip>>; + method: z.ZodLiteral<"tasks/list">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tasks/cancel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>]>; +export declare const ServerNotificationSchema: z.ZodUnion; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + requestId: z.ZodOptional>; + reason: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/progress">; + params: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/message">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + logger: z.ZodOptional; + data: z.ZodUnknown; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/resources/updated">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/resources/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/tools/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/prompts/list_changed">; + params: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/tasks/status">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/elicitation/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + elicitationId: z.ZodString; + }, z.core.$strip>; +}, z.core.$strip>]>; +export declare const ServerResultSchema: z.ZodUnion>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strict>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + logging: z.ZodOptional>; + completions: z.ZodOptional>; + prompts: z.ZodOptional; + }, z.core.$strip>>; + resources: z.ZodOptional; + listChanged: z.ZodOptional; + }, z.core.$strip>>; + tools: z.ZodOptional; + }, z.core.$strip>>; + tasks: z.ZodOptional>; + /** + * Present if the server supports cancelling tasks. + */ + cancel: z.ZodOptional>; + /** + * Capabilities for task creation on specific request types. + */ + requests: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$loose>>; + }, z.core.$strip>; + serverInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + description: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + instructions: z.ZodOptional; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + completion: z.ZodObject<{ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.ZodArray; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.ZodOptional; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + description: z.ZodOptional; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + prompts: z.ZodArray; + arguments: z.ZodOptional; + required: z.ZodOptional; + }, z.core.$strip>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + resources: z.ZodArray; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + resourceTemplates: z.ZodArray; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + contents: z.ZodArray; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + content: z.ZodDefault; + text: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + annotations: z.ZodOptional>>; + priority: z.ZodOptional; + lastModified: z.ZodOptional; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + tools: z.ZodArray; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + execution: z.ZodOptional>; + }, z.core.$strip>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + theme: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + nextCursor: z.ZodOptional; + tasks: z.ZodArray; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + /** + * If specified, this request is related to the provided task. + */ + "io.modelcontextprotocol/related-task": z.ZodOptional>; + }, z.core.$loose>>; + task: z.ZodObject<{ + taskId: z.ZodString; + status: z.ZodEnum<{ + working: "working"; + input_required: "input_required"; + completed: "completed"; + failed: "failed"; + cancelled: "cancelled"; + }>; + ttl: z.ZodUnion; + createdAt: z.ZodString; + lastUpdatedAt: z.ZodString; + pollInterval: z.ZodOptional; + statusMessage: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$loose>]>; +export declare class McpError extends Error { + readonly code: number; + readonly data?: unknown; + constructor(code: number, message: string, data?: unknown); + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code: number, message: string, data?: unknown): McpError; +} +/** + * Specialized error type when a tool requires a URL mode elicitation. + * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. + */ +export declare class UrlElicitationRequiredError extends McpError { + constructor(elicitations: ElicitRequestURLParams[], message?: string); + get elicitations(): ElicitRequestURLParams[]; +} +type Primitive = string | number | boolean | bigint | null | undefined; +type Flatten = T extends Primitive ? T : T extends Array ? Array> : T extends Set ? Set> : T extends Map ? Map, Flatten> : T extends object ? { + [K in keyof T]: Flatten; +} : T; +type Infer = Flatten>; +/** + * Headers that are compatible with both Node.js and the browser. + */ +export type IsomorphicHeaders = Record; +/** + * Information about the incoming request. + */ +export interface RequestInfo { + /** + * The headers of the request. + */ + headers: IsomorphicHeaders; +} +/** + * Extra information about a message. + */ +export interface MessageExtraInfo { + /** + * The request information. + */ + requestInfo?: RequestInfo; + /** + * The authentication information. + */ + authInfo?: AuthInfo; + /** + * Callback to close the SSE stream for this request, triggering client reconnection. + * Only available when using StreamableHTTPServerTransport with eventStore configured. + */ + closeSSEStream?: () => void; + /** + * Callback to close the standalone GET SSE stream, triggering client reconnection. + * Only available when using StreamableHTTPServerTransport with eventStore configured. + */ + closeStandaloneSSEStream?: () => void; +} +export type ProgressToken = Infer; +export type Cursor = Infer; +export type Request = Infer; +export type TaskAugmentedRequestParams = Infer; +export type RequestMeta = Infer; +export type Notification = Infer; +export type Result = Infer; +export type RequestId = Infer; +export type JSONRPCRequest = Infer; +export type JSONRPCNotification = Infer; +export type JSONRPCResponse = Infer; +export type JSONRPCErrorResponse = Infer; +/** + * @deprecated Use {@link JSONRPCErrorResponse} instead. + * + * Please note that spec types have renamed {@link JSONRPCError} to {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCError}) and future versions will remove {@link JSONRPCError}. + */ +export type JSONRPCError = JSONRPCErrorResponse; +export type JSONRPCResultResponse = Infer; +export type JSONRPCMessage = Infer; +export type RequestParams = Infer; +export type NotificationParams = Infer; +export type EmptyResult = Infer; +export type CancelledNotificationParams = Infer; +export type CancelledNotification = Infer; +export type Icon = Infer; +export type Icons = Infer; +export type BaseMetadata = Infer; +export type Annotations = Infer; +export type Role = Infer; +export type Implementation = Infer; +export type ClientCapabilities = Infer; +export type InitializeRequestParams = Infer; +export type InitializeRequest = Infer; +export type ServerCapabilities = Infer; +export type InitializeResult = Infer; +export type InitializedNotification = Infer; +export type PingRequest = Infer; +export type Progress = Infer; +export type ProgressNotificationParams = Infer; +export type ProgressNotification = Infer; +export type Task = Infer; +export type TaskStatus = Infer; +export type TaskCreationParams = Infer; +export type TaskMetadata = Infer; +export type RelatedTaskMetadata = Infer; +export type CreateTaskResult = Infer; +export type TaskStatusNotificationParams = Infer; +export type TaskStatusNotification = Infer; +export type GetTaskRequest = Infer; +export type GetTaskResult = Infer; +export type GetTaskPayloadRequest = Infer; +export type ListTasksRequest = Infer; +export type ListTasksResult = Infer; +export type CancelTaskRequest = Infer; +export type CancelTaskResult = Infer; +export type GetTaskPayloadResult = Infer; +export type PaginatedRequestParams = Infer; +export type PaginatedRequest = Infer; +export type PaginatedResult = Infer; +export type ResourceContents = Infer; +export type TextResourceContents = Infer; +export type BlobResourceContents = Infer; +export type Resource = Infer; +export type ResourceTemplate = Infer; +export type ListResourcesRequest = Infer; +export type ListResourcesResult = Infer; +export type ListResourceTemplatesRequest = Infer; +export type ListResourceTemplatesResult = Infer; +export type ResourceRequestParams = Infer; +export type ReadResourceRequestParams = Infer; +export type ReadResourceRequest = Infer; +export type ReadResourceResult = Infer; +export type ResourceListChangedNotification = Infer; +export type SubscribeRequestParams = Infer; +export type SubscribeRequest = Infer; +export type UnsubscribeRequestParams = Infer; +export type UnsubscribeRequest = Infer; +export type ResourceUpdatedNotificationParams = Infer; +export type ResourceUpdatedNotification = Infer; +export type PromptArgument = Infer; +export type Prompt = Infer; +export type ListPromptsRequest = Infer; +export type ListPromptsResult = Infer; +export type GetPromptRequestParams = Infer; +export type GetPromptRequest = Infer; +export type TextContent = Infer; +export type ImageContent = Infer; +export type AudioContent = Infer; +export type ToolUseContent = Infer; +export type ToolResultContent = Infer; +export type EmbeddedResource = Infer; +export type ResourceLink = Infer; +export type ContentBlock = Infer; +export type PromptMessage = Infer; +export type GetPromptResult = Infer; +export type PromptListChangedNotification = Infer; +export type ToolAnnotations = Infer; +export type ToolExecution = Infer; +export type Tool = Infer; +export type ListToolsRequest = Infer; +export type ListToolsResult = Infer; +export type CallToolRequestParams = Infer; +export type CallToolResult = Infer; +export type CompatibilityCallToolResult = Infer; +export type CallToolRequest = Infer; +export type ToolListChangedNotification = Infer; +export type LoggingLevel = Infer; +export type SetLevelRequestParams = Infer; +export type SetLevelRequest = Infer; +export type LoggingMessageNotificationParams = Infer; +export type LoggingMessageNotification = Infer; +export type ToolChoice = Infer; +export type ModelHint = Infer; +export type ModelPreferences = Infer; +export type SamplingContent = Infer; +export type SamplingMessageContentBlock = Infer; +export type SamplingMessage = Infer; +export type CreateMessageRequestParams = Infer; +export type CreateMessageRequest = Infer; +export type CreateMessageResult = Infer; +export type CreateMessageResultWithTools = Infer; +/** + * CreateMessageRequestParams without tools - for backwards-compatible overload. + * Excludes tools/toolChoice to indicate they should not be provided. + */ +export type CreateMessageRequestParamsBase = Omit; +/** + * CreateMessageRequestParams with required tools - for tool-enabled overload. + */ +export interface CreateMessageRequestParamsWithTools extends CreateMessageRequestParams { + tools: Tool[]; +} +export type BooleanSchema = Infer; +export type StringSchema = Infer; +export type NumberSchema = Infer; +export type EnumSchema = Infer; +export type UntitledSingleSelectEnumSchema = Infer; +export type TitledSingleSelectEnumSchema = Infer; +export type LegacyTitledEnumSchema = Infer; +export type UntitledMultiSelectEnumSchema = Infer; +export type TitledMultiSelectEnumSchema = Infer; +export type SingleSelectEnumSchema = Infer; +export type MultiSelectEnumSchema = Infer; +export type PrimitiveSchemaDefinition = Infer; +export type ElicitRequestParams = Infer; +export type ElicitRequestFormParams = Infer; +export type ElicitRequestURLParams = Infer; +export type ElicitRequest = Infer; +export type ElicitationCompleteNotificationParams = Infer; +export type ElicitationCompleteNotification = Infer; +export type ElicitResult = Infer; +export type ResourceTemplateReference = Infer; +/** + * @deprecated Use ResourceTemplateReference instead + */ +export type ResourceReference = ResourceTemplateReference; +export type PromptReference = Infer; +export type CompleteRequestParams = Infer; +export type CompleteRequest = Infer; +export type CompleteRequestResourceTemplate = ExpandRecursively; +export type CompleteRequestPrompt = ExpandRecursively; +export type CompleteResult = Infer; +export type Root = Infer; +export type ListRootsRequest = Infer; +export type ListRootsResult = Infer; +export type RootsListChangedNotification = Infer; +export type ClientRequest = Infer; +export type ClientNotification = Infer; +export type ClientResult = Infer; +export type ServerRequest = Infer; +export type ServerNotification = Infer; +export type ServerResult = Infer; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/types.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/types.d.ts.map new file mode 100644 index 000000000..4745081a5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAElD,eAAO,MAAM,uBAAuB,eAAe,CAAC;AACpD,eAAO,MAAM,mCAAmC,eAAe,CAAC;AAChE,eAAO,MAAM,2BAA2B,UAAoF,CAAC;AAE7H,eAAO,MAAM,qBAAqB,yCAAyC,CAAC;AAG5E,eAAO,MAAM,eAAe,QAAQ,CAAC;AAErC;;GAEG;AACH,KAAK,iBAAiB,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;AAO7H;;GAEG;AACH,eAAO,MAAM,mBAAmB,iDAA0C,CAAC;AAE3E;;GAEG;AACH,eAAO,MAAM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G5D,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAC9D,MAAM,MAAM,kBAAkB,GAAG,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AACxE,MAAM,MAAM,YAAY,GAAG,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js new file mode 100644 index 000000000..8edb88eca --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js @@ -0,0 +1,2052 @@ +import * as z from 'zod/v4'; +export const LATEST_PROTOCOL_VERSION = '2025-11-25'; +export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; +export const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07']; +export const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task'; +/* JSON-RPC types */ +export const JSONRPC_VERSION = '2.0'; +/** + * Assert 'object' type schema. + * + * @internal + */ +const AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function')); +/** + * A progress token, used to associate progress notifications with the original request. + */ +export const ProgressTokenSchema = z.union([z.string(), z.number().int()]); +/** + * An opaque token used to represent a cursor for pagination. + */ +export const CursorSchema = z.string(); +/** + * Task creation parameters, used to ask that the server create a task to represent a request. + */ +export const TaskCreationParamsSchema = z.looseObject({ + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: z.union([z.number(), z.null()]).optional(), + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval: z.number().optional() +}); +export const TaskMetadataSchema = z.object({ + ttl: z.number().optional() +}); +/** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + */ +export const RelatedTaskMetadataSchema = z.object({ + taskId: z.string() +}); +const RequestMetaSchema = z.looseObject({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: ProgressTokenSchema.optional(), + /** + * If specified, this request is related to the provided task. + */ + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); +/** + * Common params for any request. + */ +const BaseRequestParamsSchema = z.object({ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta: RequestMetaSchema.optional() +}); +/** + * Common params for any task-augmented request. + */ +export const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task: TaskMetadataSchema.optional() +}); +/** + * Checks if a value is a valid TaskAugmentedRequestParams. + * @param value - The value to check. + * + * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise. + */ +export const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; +export const RequestSchema = z.object({ + method: z.string(), + params: BaseRequestParamsSchema.loose().optional() +}); +const NotificationsParamsSchema = z.object({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() +}); +export const NotificationSchema = z.object({ + method: z.string(), + params: NotificationsParamsSchema.loose().optional() +}); +export const ResultSchema = z.looseObject({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() +}); +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +export const RequestIdSchema = z.union([z.string(), z.number().int()]); +/** + * A request that expects a response. + */ +export const JSONRPCRequestSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape +}) + .strict(); +export const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +/** + * A notification which does not expect a response. + */ +export const JSONRPCNotificationSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + ...NotificationSchema.shape +}) + .strict(); +export const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +/** + * A successful (non-error) response to a request. + */ +export const JSONRPCResultResponseSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema +}) + .strict(); +/** + * Checks if a value is a valid JSONRPCResultResponse. + * @param value - The value to check. + * + * @returns True if the value is a valid JSONRPCResultResponse, false otherwise. + */ +export const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; +/** + * @deprecated Use {@link isJSONRPCResultResponse} instead. + * + * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse}) + */ +export const isJSONRPCResponse = isJSONRPCResultResponse; +/** + * Error codes defined by the JSON-RPC specification. + */ +export var ErrorCode; +(function (ErrorCode) { + // SDK error codes + ErrorCode[ErrorCode["ConnectionClosed"] = -32000] = "ConnectionClosed"; + ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout"; + // Standard JSON-RPC error codes + ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError"; + ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest"; + ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound"; + ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams"; + ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError"; + // MCP-specific error codes + ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; +})(ErrorCode || (ErrorCode = {})); +/** + * A response to a request that indicates an error occurred. + */ +export const JSONRPCErrorResponseSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: z.object({ + /** + * The error type that occurred. + */ + code: z.number().int(), + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: z.string(), + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data: z.unknown().optional() + }) +}) + .strict(); +/** + * @deprecated Use {@link JSONRPCErrorResponseSchema} instead. + */ +export const JSONRPCErrorSchema = JSONRPCErrorResponseSchema; +/** + * Checks if a value is a valid JSONRPCErrorResponse. + * @param value - The value to check. + * + * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise. + */ +export const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +/** + * @deprecated Use {@link isJSONRPCErrorResponse} instead. + */ +export const isJSONRPCError = isJSONRPCErrorResponse; +export const JSONRPCMessageSchema = z.union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +export const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +/* Empty result */ +/** + * A response that indicates success but carries no data. + */ +export const EmptyResultSchema = ResultSchema.strict(); +export const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestIdSchema.optional(), + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason: z.string().optional() +}); +/* Cancellation */ +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + */ +export const CancelledNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/cancelled'), + params: CancelledNotificationParamsSchema +}); +/* Base Metadata */ +/** + * Icon schema for use in tools, prompts, resources, and implementations. + */ +export const IconSchema = z.object({ + /** + * URL or data URI for the icon. + */ + src: z.string(), + /** + * Optional MIME type for the icon. + */ + mimeType: z.string().optional(), + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes: z.array(z.string()).optional(), + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme: z.enum(['light', 'dark']).optional() +}); +/** + * Base schema to add `icons` property. + * + */ +export const IconsSchema = z.object({ + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons: z.array(IconSchema).optional() +}); +/** + * Base metadata interface for common properties across resources, tools, prompts, and implementations. + */ +export const BaseMetadataSchema = z.object({ + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: z.string(), + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title: z.string().optional() +}); +/* Initialization */ +/** + * Describes the name and version of an MCP implementation. + */ +export const ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: z.string(), + /** + * An optional URL of the website for this implementation. + */ + websiteUrl: z.string().optional(), + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description: z.string().optional() +}); +const FormElicitationCapabilitySchema = z.intersection(z.object({ + applyDefaults: z.boolean().optional() +}), z.record(z.string(), z.unknown())); +const ElicitationCapabilitySchema = z.preprocess(value => { + if (value && typeof value === 'object' && !Array.isArray(value)) { + if (Object.keys(value).length === 0) { + return { form: {} }; + } + } + return value; +}, z.intersection(z.object({ + form: FormElicitationCapabilitySchema.optional(), + url: AssertObjectSchema.optional() +}), z.record(z.string(), z.unknown()).optional())); +/** + * Task capabilities for clients, indicating which request types support task creation. + */ +export const ClientTasksCapabilitySchema = z.looseObject({ + /** + * Present if the client supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the client supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: z + .looseObject({ + /** + * Task support for sampling requests. + */ + sampling: z + .looseObject({ + createMessage: AssertObjectSchema.optional() + }) + .optional(), + /** + * Task support for elicitation requests. + */ + elicitation: z + .looseObject({ + create: AssertObjectSchema.optional() + }) + .optional() + }) + .optional() +}); +/** + * Task capabilities for servers, indicating which request types support task creation. + */ +export const ServerTasksCapabilitySchema = z.looseObject({ + /** + * Present if the server supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the server supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: z + .looseObject({ + /** + * Task support for tool requests. + */ + tools: z + .looseObject({ + call: AssertObjectSchema.optional() + }) + .optional() + }) + .optional() +}); +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ +export const ClientCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the client supports sampling from an LLM. + */ + sampling: z + .object({ + /** + * Present if the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context: AssertObjectSchema.optional(), + /** + * Present if the client supports tool use via tools and toolChoice parameters. + */ + tools: AssertObjectSchema.optional() + }) + .optional(), + /** + * Present if the client supports eliciting user input. + */ + elicitation: ElicitationCapabilitySchema.optional(), + /** + * Present if the client supports listing roots. + */ + roots: z + .object({ + /** + * Whether the client supports issuing notifications for changes to the roots list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the client supports task creation. + */ + tasks: ClientTasksCapabilitySchema.optional() +}); +export const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: z.string(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ +export const InitializeRequestSchema = RequestSchema.extend({ + method: z.literal('initialize'), + params: InitializeRequestParamsSchema +}); +export const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ +export const ServerCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + */ + logging: AssertObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ + completions: AssertObjectSchema.optional(), + /** + * Present if the server offers any prompt templates. + */ + prompts: z + .object({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any resources to read. + */ + resources: z + .object({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: z.boolean().optional(), + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any tools to call. + */ + tools: z + .object({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server supports task creation. + */ + tasks: ServerTasksCapabilitySchema.optional() +}); +/** + * After receiving an initialize request from the client, the server sends this response. + */ +export const InitializeResultSchema = ResultSchema.extend({ + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: z.string(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: z.string().optional() +}); +/** + * This notification is sent from the client to the server after initialization has finished. + */ +export const InitializedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/initialized'), + params: NotificationsParamsSchema.optional() +}); +export const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +export const PingRequestSchema = RequestSchema.extend({ + method: z.literal('ping'), + params: BaseRequestParamsSchema.optional() +}); +/* Progress notifications */ +export const ProgressSchema = z.object({ + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: z.number(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: z.optional(z.number()), + /** + * An optional message describing the current progress. + */ + message: z.optional(z.string()) +}); +export const ProgressNotificationParamsSchema = z.object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressTokenSchema +}); +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ +export const ProgressNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/progress'), + params: ProgressNotificationParamsSchema +}); +export const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor: CursorSchema.optional() +}); +/* Pagination */ +export const PaginatedRequestSchema = RequestSchema.extend({ + params: PaginatedRequestParamsSchema.optional() +}); +export const PaginatedResultSchema = ResultSchema.extend({ + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor: CursorSchema.optional() +}); +/** + * The status of a task. + * */ +export const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']); +/* Tasks */ +/** + * A pollable state object associated with a request. + */ +export const TaskSchema = z.object({ + taskId: z.string(), + status: TaskStatusSchema, + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: z.union([z.number(), z.null()]), + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: z.string(), + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: z.string(), + pollInterval: z.optional(z.number()), + /** + * Optional diagnostic message for failed tasks or other status information. + */ + statusMessage: z.optional(z.string()) +}); +/** + * Result returned when a task is created, containing the task data wrapped in a task field. + */ +export const CreateTaskResultSchema = ResultSchema.extend({ + task: TaskSchema +}); +/** + * Parameters for task status notification. + */ +export const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +/** + * A notification sent when a task's status changes. + */ +export const TaskStatusNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/tasks/status'), + params: TaskStatusNotificationParamsSchema +}); +/** + * A request to get the state of a specific task. + */ +export const GetTaskRequestSchema = RequestSchema.extend({ + method: z.literal('tasks/get'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) +}); +/** + * The response to a tasks/get request. + */ +export const GetTaskResultSchema = ResultSchema.merge(TaskSchema); +/** + * A request to get the result of a specific task. + */ +export const GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: z.literal('tasks/result'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) +}); +/** + * The response to a tasks/result request. + * The structure matches the result type of the original request. + * For example, a tools/call task would return the CallToolResult structure. + * + */ +export const GetTaskPayloadResultSchema = ResultSchema.loose(); +/** + * A request to list tasks. + */ +export const ListTasksRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('tasks/list') +}); +/** + * The response to a tasks/list request. + */ +export const ListTasksResultSchema = PaginatedResultSchema.extend({ + tasks: z.array(TaskSchema) +}); +/** + * A request to cancel a specific task. + */ +export const CancelTaskRequestSchema = RequestSchema.extend({ + method: z.literal('tasks/cancel'), + params: BaseRequestParamsSchema.extend({ + taskId: z.string() + }) +}); +/** + * The response to a tasks/cancel request. + */ +export const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); +/* Resources */ +/** + * The contents of a specific resource or sub-resource. + */ +export const ResourceContentsSchema = z.object({ + /** + * The URI of this resource. + */ + uri: z.string(), + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +export const TextResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: z.string() +}); +/** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ +const Base64Schema = z.string().refine(val => { + try { + // atob throws a DOMException if the string contains characters + // that are not part of the Base64 character set. + atob(val); + return true; + } + catch { + return false; + } +}, { message: 'Invalid Base64 string' }); +export const BlobResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * A base64-encoded string representing the binary data of the item. + */ + blob: Base64Schema +}); +/** + * The sender or recipient of messages and data in a conversation. + */ +export const RoleSchema = z.enum(['user', 'assistant']); +/** + * Optional annotations providing clients additional context about a resource. + */ +export const AnnotationsSchema = z.object({ + /** + * Intended audience(s) for the resource. + */ + audience: z.array(RoleSchema).optional(), + /** + * Importance hint for the resource, from 0 (least) to 1 (most). + */ + priority: z.number().min(0).max(1).optional(), + /** + * ISO 8601 timestamp for the most recent modification. + */ + lastModified: z.iso.datetime({ offset: true }).optional() +}); +/** + * A known resource that the server is capable of reading. + */ +export const ResourceSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * The URI of this resource. + */ + uri: z.string(), + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * A template description for resources available on the server. + */ +export const ResourceTemplateSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: z.string(), + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType: z.optional(z.string()), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * Sent from the client to request a list of resources the server has. + */ +export const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('resources/list') +}); +/** + * The server's response to a resources/list request from the client. + */ +export const ListResourcesResultSchema = PaginatedResultSchema.extend({ + resources: z.array(ResourceSchema) +}); +/** + * Sent from the client to request a list of resource templates the server has. + */ +export const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('resources/templates/list') +}); +/** + * The server's response to a resources/templates/list request from the client. + */ +export const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ + resourceTemplates: z.array(ResourceTemplateSchema) +}); +export const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: z.string() +}); +/** + * Parameters for a `resources/read` request. + */ +export const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +/** + * Sent from the client to the server, to read a specific resource URI. + */ +export const ReadResourceRequestSchema = RequestSchema.extend({ + method: z.literal('resources/read'), + params: ReadResourceRequestParamsSchema +}); +/** + * The server's response to a resources/read request from the client. + */ +export const ReadResourceResultSchema = ResultSchema.extend({ + contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) +}); +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ +export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/resources/list_changed'), + params: NotificationsParamsSchema.optional() +}); +export const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + */ +export const SubscribeRequestSchema = RequestSchema.extend({ + method: z.literal('resources/subscribe'), + params: SubscribeRequestParamsSchema +}); +export const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + */ +export const UnsubscribeRequestSchema = RequestSchema.extend({ + method: z.literal('resources/unsubscribe'), + params: UnsubscribeRequestParamsSchema +}); +/** + * Parameters for a `notifications/resources/updated` notification. + */ +export const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + */ + uri: z.string() +}); +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + */ +export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/resources/updated'), + params: ResourceUpdatedNotificationParamsSchema +}); +/* Prompts */ +/** + * Describes an argument that a prompt can accept. + */ +export const PromptArgumentSchema = z.object({ + /** + * The name of the argument. + */ + name: z.string(), + /** + * A human-readable description of the argument. + */ + description: z.optional(z.string()), + /** + * Whether this argument must be provided. + */ + required: z.optional(z.boolean()) +}); +/** + * A prompt or prompt template that the server offers. + */ +export const PromptSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * An optional description of what this prompt provides + */ + description: z.optional(z.string()), + /** + * A list of arguments to use for templating the prompt. + */ + arguments: z.optional(z.array(PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ +export const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('prompts/list') +}); +/** + * The server's response to a prompts/list request from the client. + */ +export const ListPromptsResultSchema = PaginatedResultSchema.extend({ + prompts: z.array(PromptSchema) +}); +/** + * Parameters for a `prompts/get` request. + */ +export const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the prompt or prompt template. + */ + name: z.string(), + /** + * Arguments to use for templating the prompt. + */ + arguments: z.record(z.string(), z.string()).optional() +}); +/** + * Used by the client to get a prompt provided by the server. + */ +export const GetPromptRequestSchema = RequestSchema.extend({ + method: z.literal('prompts/get'), + params: GetPromptRequestParamsSchema +}); +/** + * Text provided to or from an LLM. + */ +export const TextContentSchema = z.object({ + type: z.literal('text'), + /** + * The text content of the message. + */ + text: z.string(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * An image provided to or from an LLM. + */ +export const ImageContentSchema = z.object({ + type: z.literal('image'), + /** + * The base64-encoded image data. + */ + data: Base64Schema, + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: z.string(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * An Audio provided to or from an LLM. + */ +export const AudioContentSchema = z.object({ + type: z.literal('audio'), + /** + * The base64-encoded audio data. + */ + data: Base64Schema, + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: z.string(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + */ +export const ToolUseContentSchema = z.object({ + type: z.literal('tool_use'), + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: z.string(), + /** + * Unique identifier for this tool call. + * Used to correlate with ToolResultContent in subsequent messages. + */ + id: z.string(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's inputSchema. + */ + input: z.record(z.string(), z.unknown()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * The contents of a resource, embedded into a prompt or tool call result. + */ +export const EmbeddedResourceSchema = z.object({ + type: z.literal('resource'), + resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + */ +export const ResourceLinkSchema = ResourceSchema.extend({ + type: z.literal('resource_link') +}); +/** + * A content block that can be used in prompts and tool results. + */ +export const ContentBlockSchema = z.union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema +]); +/** + * Describes a message returned as part of a prompt. + */ +export const PromptMessageSchema = z.object({ + role: RoleSchema, + content: ContentBlockSchema +}); +/** + * The server's response to a prompts/get request from the client. + */ +export const GetPromptResultSchema = ResultSchema.extend({ + /** + * An optional description for the prompt. + */ + description: z.string().optional(), + messages: z.array(PromptMessageSchema) +}); +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export const PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/prompts/list_changed'), + params: NotificationsParamsSchema.optional() +}); +/* Tools */ +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + */ +export const ToolAnnotationsSchema = z.object({ + /** + * A human-readable title for the tool. + */ + title: z.string().optional(), + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint: z.boolean().optional(), + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint: z.boolean().optional(), + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint: z.boolean().optional(), + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint: z.boolean().optional() +}); +/** + * Execution-related properties for a tool. + */ +export const ToolExecutionSchema = z.object({ + /** + * Indicates the tool's preference for task-augmented execution. + * - "required": Clients MUST invoke the tool as a task + * - "optional": Clients MAY invoke the tool as a task or normal request + * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task + * + * If not present, defaults to "forbidden". + */ + taskSupport: z.enum(['required', 'optional', 'forbidden']).optional() +}); +/** + * Definition for a tool the client can call. + */ +export const ToolSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A human-readable description of the tool. + */ + description: z.string().optional(), + /** + * A JSON Schema 2020-12 object defining the expected parameters for the tool. + * Must have type: 'object' at the root level per MCP spec. + */ + inputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), AssertObjectSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()), + /** + * An optional JSON Schema 2020-12 object defining the structure of the tool's output + * returned in the structuredContent field of a CallToolResult. + * Must have type: 'object' at the root level per MCP spec. + */ + outputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), AssertObjectSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()) + .optional(), + /** + * Optional additional tool information. + */ + annotations: ToolAnnotationsSchema.optional(), + /** + * Execution-related properties for this tool. + */ + execution: ToolExecutionSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Sent from the client to request a list of tools the server has. + */ +export const ListToolsRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('tools/list') +}); +/** + * The server's response to a tools/list request from the client. + */ +export const ListToolsResultSchema = PaginatedResultSchema.extend({ + tools: z.array(ToolSchema) +}); +/** + * The server's response to a tool call. + */ +export const CallToolResultSchema = ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the Tool does not define an outputSchema, this field MUST be present in the result. + * For backwards compatibility, this field is always present, but it may be empty. + */ + content: z.array(ContentBlockSchema).default([]), + /** + * An object containing structured tool output. + * + * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: z.record(z.string(), z.unknown()).optional(), + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError: z.boolean().optional() +}); +/** + * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. + */ +export const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ + toolResult: z.unknown() +})); +/** + * Parameters for a `tools/call` request. + */ +export const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The name of the tool to call. + */ + name: z.string(), + /** + * Arguments to pass to the tool. + */ + arguments: z.record(z.string(), z.unknown()).optional() +}); +/** + * Used by the client to invoke a tool provided by the server. + */ +export const CallToolRequestSchema = RequestSchema.extend({ + method: z.literal('tools/call'), + params: CallToolRequestParamsSchema +}); +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export const ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/tools/list_changed'), + params: NotificationsParamsSchema.optional() +}); +/** + * Base schema for list changed subscription options (without callback). + * Used internally for Zod validation of autoRefresh and debounceMs. + */ +export const ListChangedOptionsBaseSchema = z.object({ + /** + * If true, the list will be refreshed automatically when a list changed notification is received. + * The callback will be called with the updated list. + * + * If false, the callback will be called with null items, allowing manual refresh. + * + * @default true + */ + autoRefresh: z.boolean().default(true), + /** + * Debounce time in milliseconds for list changed notification processing. + * + * Multiple notifications received within this timeframe will only trigger one refresh. + * Set to 0 to disable debouncing. + * + * @default 300 + */ + debounceMs: z.number().int().nonnegative().default(300) +}); +/* Logging */ +/** + * The severity of a log message. + */ +export const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); +/** + * Parameters for a `logging/setLevel` request. + */ +export const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. + */ + level: LoggingLevelSchema +}); +/** + * A request from the client to the server, to enable or adjust logging. + */ +export const SetLevelRequestSchema = RequestSchema.extend({ + method: z.literal('logging/setLevel'), + params: SetLevelRequestParamsSchema +}); +/** + * Parameters for a `notifications/message` notification. + */ +export const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The severity of this log message. + */ + level: LoggingLevelSchema, + /** + * An optional name of the logger issuing this message. + */ + logger: z.string().optional(), + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: z.unknown() +}); +/** + * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + */ +export const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/message'), + params: LoggingMessageNotificationParamsSchema +}); +/* Sampling */ +/** + * Hints to use for model selection. + */ +export const ModelHintSchema = z.object({ + /** + * A hint for a model name. + */ + name: z.string().optional() +}); +/** + * The server's preferences for model selection, requested of the client during sampling. + */ +export const ModelPreferencesSchema = z.object({ + /** + * Optional hints to use for model selection. + */ + hints: z.array(ModelHintSchema).optional(), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: z.number().min(0).max(1).optional(), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: z.number().min(0).max(1).optional(), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: z.number().min(0).max(1).optional() +}); +/** + * Controls tool usage behavior in sampling requests. + */ +export const ToolChoiceSchema = z.object({ + /** + * Controls when tools are used: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode: z.enum(['auto', 'required', 'none']).optional() +}); +/** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via ToolUseContent. + */ +export const ToolResultContentSchema = z.object({ + type: z.literal('tool_result'), + toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), + content: z.array(ContentBlockSchema).default([]), + structuredContent: z.object({}).loose().optional(), + isError: z.boolean().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible CreateMessageResult when tools are not used. + */ +export const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]); +/** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + */ +export const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +/** + * Describes a message issued to or received from an LLM API. + */ +export const SamplingMessageSchema = z.object({ + role: RoleSchema, + content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Parameters for a `sampling/createMessage` request. + */ +export const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + messages: z.array(SamplingMessageSchema), + /** + * The server's preferences for which model to select. The client MAY modify or omit this request. + */ + modelPreferences: ModelPreferencesSchema.optional(), + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt: z.string().optional(), + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), + temperature: z.number().optional(), + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: z.number().int(), + stopSequences: z.array(z.string()).optional(), + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata: AssertObjectSchema.optional(), + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools: z.array(ToolSchema).optional(), + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice: ToolChoiceSchema.optional() +}); +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + */ +export const CreateMessageRequestSchema = RequestSchema.extend({ + method: z.literal('sampling/createMessage'), + params: CreateMessageRequestParamsSchema +}); +/** + * The client's response to a sampling/create_message request from the server. + * This is the backwards-compatible version that returns single content (no arrays). + * Used when the request does not include tools. + */ +export const CreateMessageResultSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: z.string(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())), + role: RoleSchema, + /** + * Response content. Single content block (text, image, or audio). + */ + content: SamplingContentSchema +}); +/** + * The client's response to a sampling/create_message request when tools were provided. + * This version supports array content for tool use flows. + */ +export const CreateMessageResultWithToolsSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: z.string(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())), + role: RoleSchema, + /** + * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". + */ + content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]) +}); +/* Elicitation */ +/** + * Primitive schema definition for boolean fields. + */ +export const BooleanSchemaSchema = z.object({ + type: z.literal('boolean'), + title: z.string().optional(), + description: z.string().optional(), + default: z.boolean().optional() +}); +/** + * Primitive schema definition for string fields. + */ +export const StringSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + minLength: z.number().optional(), + maxLength: z.number().optional(), + format: z.enum(['email', 'uri', 'date', 'date-time']).optional(), + default: z.string().optional() +}); +/** + * Primitive schema definition for number fields. + */ +export const NumberSchemaSchema = z.object({ + type: z.enum(['number', 'integer']), + title: z.string().optional(), + description: z.string().optional(), + minimum: z.number().optional(), + maximum: z.number().optional(), + default: z.number().optional() +}); +/** + * Schema for single-selection enumeration without display titles for options. + */ +export const UntitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + default: z.string().optional() +}); +/** + * Schema for single-selection enumeration with display titles for each option. + */ +export const TitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + oneOf: z.array(z.object({ + const: z.string(), + title: z.string() + })), + default: z.string().optional() +}); +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + */ +export const LegacyTitledEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + enumNames: z.array(z.string()).optional(), + default: z.string().optional() +}); +// Combined single selection enumeration +export const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); +/** + * Schema for multiple-selection enumeration without display titles for options. + */ +export const UntitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + type: z.literal('string'), + enum: z.array(z.string()) + }), + default: z.array(z.string()).optional() +}); +/** + * Schema for multiple-selection enumeration with display titles for each option. + */ +export const TitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + anyOf: z.array(z.object({ + const: z.string(), + title: z.string() + })) + }), + default: z.array(z.string()).optional() +}); +/** + * Combined schema for multiple-selection enumeration + */ +export const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); +/** + * Primitive schema definition for enum fields. + */ +export const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); +/** + * Union of all primitive schema definitions. + */ +export const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); +/** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ +export const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + * + * Optional for backward compatibility. Clients MUST treat missing mode as "form". + */ + mode: z.literal('form').optional(), + /** + * The message to present to the user describing what information is being requested. + */ + message: z.string(), + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: z.object({ + type: z.literal('object'), + properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), + required: z.array(z.string()).optional() + }) +}); +/** + * Parameters for an `elicitation/create` request for URL-based elicitation. + */ +export const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: z.literal('url'), + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: z.string(), + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: z.string(), + /** + * The URL that the user should navigate to. + */ + url: z.string().url() +}); +/** + * The parameters for a request to elicit additional information from the user via the client. + */ +export const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); +/** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ +export const ElicitRequestSchema = RequestSchema.extend({ + method: z.literal('elicitation/create'), + params: ElicitRequestParamsSchema +}); +/** + * Parameters for a `notifications/elicitation/complete` notification. + * + * @category notifications/elicitation/complete + */ +export const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the elicitation that completed. + */ + elicitationId: z.string() +}); +/** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ +export const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/elicitation/complete'), + params: ElicitationCompleteNotificationParamsSchema +}); +/** + * The client's response to an elicitation/create request from the server. + */ +export const ElicitResultSchema = ResultSchema.extend({ + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: z.enum(['accept', 'decline', 'cancel']), + /** + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. + * Per MCP spec, content is "typically omitted" for decline/cancel actions. + * We normalize null to undefined for leniency while maintaining type compatibility. + */ + content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional()) +}); +/* Autocomplete */ +/** + * A reference to a resource or resource template definition. + */ +export const ResourceTemplateReferenceSchema = z.object({ + type: z.literal('ref/resource'), + /** + * The URI or URI template of the resource. + */ + uri: z.string() +}); +/** + * @deprecated Use ResourceTemplateReferenceSchema instead + */ +export const ResourceReferenceSchema = ResourceTemplateReferenceSchema; +/** + * Identifies a prompt. + */ +export const PromptReferenceSchema = z.object({ + type: z.literal('ref/prompt'), + /** + * The name of the prompt or prompt template + */ + name: z.string() +}); +/** + * Parameters for a `completion/complete` request. + */ +export const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: z.object({ + /** + * The name of the argument + */ + name: z.string(), + /** + * The value of the argument to use for completion matching. + */ + value: z.string() + }), + context: z + .object({ + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: z.record(z.string(), z.string()).optional() + }) + .optional() +}); +/** + * A request from the client to the server, to ask for completion options. + */ +export const CompleteRequestSchema = RequestSchema.extend({ + method: z.literal('completion/complete'), + params: CompleteRequestParamsSchema +}); +export function assertCompleteRequestPrompt(request) { + if (request.params.ref.type !== 'ref/prompt') { + throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); + } + void request; +} +export function assertCompleteRequestResourceTemplate(request) { + if (request.params.ref.type !== 'ref/resource') { + throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); + } + void request; +} +/** + * The server's response to a completion/complete request + */ +export const CompleteResultSchema = ResultSchema.extend({ + completion: z.looseObject({ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.array(z.string()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.optional(z.number().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.optional(z.boolean()) + }) +}); +/* Roots */ +/** + * Represents a root directory or file that the server can operate on. + */ +export const RootSchema = z.object({ + /** + * The URI identifying the root. This *must* start with file:// for now. + */ + uri: z.string().startsWith('file://'), + /** + * An optional name for the root. + */ + name: z.string().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Sent from the server to request a list of root URIs from the client. + */ +export const ListRootsRequestSchema = RequestSchema.extend({ + method: z.literal('roots/list'), + params: BaseRequestParamsSchema.optional() +}); +/** + * The client's response to a roots/list request from the server. + */ +export const ListRootsResultSchema = ResultSchema.extend({ + roots: z.array(RootSchema) +}); +/** + * A notification from the client to the server, informing it that the list of roots has changed. + */ +export const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/roots/list_changed'), + params: NotificationsParamsSchema.optional() +}); +/* Client messages */ +export const ClientRequestSchema = z.union([ + PingRequestSchema, + InitializeRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema +]); +export const ClientNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema, + TaskStatusNotificationSchema +]); +export const ClientResultSchema = z.union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema +]); +/* Server messages */ +export const ServerRequestSchema = z.union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema +]); +export const ServerNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + TaskStatusNotificationSchema, + ElicitationCompleteNotificationSchema +]); +export const ServerResultSchema = z.union([ + EmptyResultSchema, + InitializeResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema +]); +export class McpError extends Error { + constructor(code, message, data) { + super(`MCP error ${code}: ${message}`); + this.code = code; + this.data = data; + this.name = 'McpError'; + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + // Check for specific error types + if (code === ErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) { + return new UrlElicitationRequiredError(errorData.elicitations, message); + } + } + // Default to generic McpError + return new McpError(code, message, data); + } +} +/** + * Specialized error type when a tool requires a URL mode elicitation. + * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. + */ +export class UrlElicitationRequiredError extends McpError { + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) { + super(ErrorCode.UrlElicitationRequired, message, { + elicitations: elicitations + }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +} +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js.map new file mode 100644 index 000000000..285ab0c32 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceR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SAAS,GAAG,IAAoC,CAAC;YACvD,IAAI,SAAS,CAAC,YAAY,EAAE,CAAC;gBACzB,OAAO,IAAI,2BAA2B,CAAC,SAAS,CAAC,YAAwC,EAAE,OAAO,CAAC,CAAC;YACxG,CAAC;QACL,CAAC;QAED,8BAA8B;QAC9B,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC7C,CAAC;CACJ;AAED;;;GAGG;AACH,MAAM,OAAO,2BAA4B,SAAQ,QAAQ;IACrD,YAAY,YAAsC,EAAE,UAAkB,kBAAkB,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,WAAW;QACjI,KAAK,CAAC,SAAS,CAAC,sBAAsB,EAAE,OAAO,EAAE;YAC7C,YAAY,EAAE,YAAY;SAC7B,CAAC,CAAC;IACP,CAAC;IAED,IAAI,YAAY;QACZ,OAAQ,IAAI,CAAC,IAAmD,EAAE,YAAY,IAAI,EAAE,CAAC;IACzF,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.d.ts new file mode 100644 index 000000000..952ee68df --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.d.ts @@ -0,0 +1,53 @@ +/** + * AJV-based JSON Schema validator provider + */ +import Ajv from 'ajv'; +import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from './types.js'; +/** + * @example + * ```typescript + * // Use with default AJV instance (recommended) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Use with custom AJV instance + * import { Ajv } from 'ajv'; + * const ajv = new Ajv({ strict: true, allErrors: true }); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ +export declare class AjvJsonSchemaValidator implements jsonSchemaValidator { + private _ajv; + /** + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ + constructor(ajv?: Ajv); + /** + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema: JsonSchemaType): JsonSchemaValidator; +} +//# sourceMappingURL=ajv-provider.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.d.ts.map new file mode 100644 index 000000000..6704c4d92 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ajv-provider.d.ts","sourceRoot":"","sources":["../../../src/validation/ajv-provider.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,GAAG,MAAM,KAAK,CAAC;AAEtB,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAA6B,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAgBtH;;;;;;;;;;;;GAYG;AACH,qBAAa,sBAAuB,YAAW,mBAAmB;IAC9D,OAAO,CAAC,IAAI,CAAM;IAElB;;;;;;;;;;;;;;;;;;;OAmBG;gBACS,GAAG,CAAC,EAAE,GAAG;IAIrB;;;;;;;;OAQG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC;CAyBlE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js new file mode 100644 index 000000000..a0ab06740 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js @@ -0,0 +1,87 @@ +/** + * AJV-based JSON Schema validator provider + */ +import Ajv from 'ajv'; +import _addFormats from 'ajv-formats'; +function createDefaultAjvInstance() { + const ajv = new Ajv({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + const addFormats = _addFormats; + addFormats(ajv); + return ajv; +} +/** + * @example + * ```typescript + * // Use with default AJV instance (recommended) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Use with custom AJV instance + * import { Ajv } from 'ajv'; + * const ajv = new Ajv({ strict: true, allErrors: true }); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ +export class AjvJsonSchemaValidator { + /** + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ + constructor(ajv) { + this._ajv = ajv ?? createDefaultAjvInstance(); + } + /** + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema) { + // Check if schema has $id and is already compiled/cached + const ajvValidator = '$id' in schema && typeof schema.$id === 'string' + ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema)) + : this._ajv.compile(schema); + return (input) => { + const valid = ajvValidator(input); + if (valid) { + return { + valid: true, + data: input, + errorMessage: undefined + }; + } + else { + return { + valid: false, + data: undefined, + errorMessage: this._ajv.errorsText(ajvValidator.errors) + }; + } + }; + } +} +//# sourceMappingURL=ajv-provider.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js.map new file mode 100644 index 000000000..7b0190597 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ajv-provider.js","sourceRoot":"","sources":["../../../src/validation/ajv-provider.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,WAAW,MAAM,aAAa,CAAC;AAGtC,SAAS,wBAAwB;IAC7B,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC;QAChB,MAAM,EAAE,KAAK;QACb,eAAe,EAAE,IAAI;QACrB,cAAc,EAAE,KAAK;QACrB,SAAS,EAAE,IAAI;KAClB,CAAC,CAAC;IAEH,MAAM,UAAU,GAAG,WAAoD,CAAC;IACxE,UAAU,CAAC,GAAG,CAAC,CAAC;IAEhB,OAAO,GAAG,CAAC;AACf,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,OAAO,sBAAsB;IAG/B;;;;;;;;;;;;;;;;;;;OAmBG;IACH,YAAY,GAAS;QACjB,IAAI,CAAC,IAAI,GAAG,GAAG,IAAI,wBAAwB,EAAE,CAAC;IAClD,CAAC;IAED;;;;;;;;OAQG;IACH,YAAY,CAAI,MAAsB;QAClC,yDAAyD;QACzD,MAAM,YAAY,GACd,KAAK,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,GAAG,KAAK,QAAQ;YAC7C,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAChE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAEpC,OAAO,CAAC,KAAc,EAAgC,EAAE;YACpD,MAAM,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;YAElC,IAAI,KAAK,EAAE,CAAC;gBACR,OAAO;oBACH,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,KAAU;oBAChB,YAAY,EAAE,SAAS;iBAC1B,CAAC;YACN,CAAC;iBAAM,CAAC;gBACJ,OAAO;oBACH,KAAK,EAAE,KAAK;oBACZ,IAAI,EAAE,SAAS;oBACf,YAAY,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC;iBAC1D,CAAC;YACN,CAAC;QACL,CAAC,CAAC;IACN,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/cfworker-provider.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/cfworker-provider.d.ts new file mode 100644 index 000000000..89c244a60 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/cfworker-provider.d.ts @@ -0,0 +1,51 @@ +/** + * Cloudflare Worker-compatible JSON Schema validator provider + * + * This provider uses @cfworker/json-schema for validation without code generation, + * making it compatible with edge runtimes like Cloudflare Workers that restrict + * eval and new Function. + */ +import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from './types.js'; +/** + * JSON Schema draft version supported by @cfworker/json-schema + */ +export type CfWorkerSchemaDraft = '4' | '7' | '2019-09' | '2020-12'; +/** + * + * @example + * ```typescript + * // Use with default configuration (2020-12, shortcircuit) + * const validator = new CfWorkerJsonSchemaValidator(); + * + * // Use with custom configuration + * const validator = new CfWorkerJsonSchemaValidator({ + * draft: '2020-12', + * shortcircuit: false // Report all errors + * }); + * ``` + */ +export declare class CfWorkerJsonSchemaValidator implements jsonSchemaValidator { + private shortcircuit; + private draft; + /** + * Create a validator + * + * @param options - Configuration options + * @param options.shortcircuit - If true, stop validation after first error (default: true) + * @param options.draft - JSON Schema draft version to use (default: '2020-12') + */ + constructor(options?: { + shortcircuit?: boolean; + draft?: CfWorkerSchemaDraft; + }); + /** + * Create a validator for the given JSON Schema + * + * Unlike AJV, this validator is not cached internally + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema: JsonSchemaType): JsonSchemaValidator; +} +//# sourceMappingURL=cfworker-provider.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/cfworker-provider.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/cfworker-provider.d.ts.map new file mode 100644 index 000000000..ce404d92f --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/cfworker-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cfworker-provider.d.ts","sourceRoot":"","sources":["../../../src/validation/cfworker-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAA6B,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtH;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,GAAG,GAAG,GAAG,GAAG,SAAS,GAAG,SAAS,CAAC;AAEpE;;;;;;;;;;;;;GAaG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IACnE,OAAO,CAAC,YAAY,CAAU;IAC9B,OAAO,CAAC,KAAK,CAAsB;IAEnC;;;;;;OAMG;gBACS,OAAO,CAAC,EAAE;QAAE,YAAY,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,mBAAmB,CAAA;KAAE;IAK7E;;;;;;;OAOG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC;CAsBlE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/cfworker-provider.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/cfworker-provider.js new file mode 100644 index 000000000..576491494 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/cfworker-provider.js @@ -0,0 +1,65 @@ +/** + * Cloudflare Worker-compatible JSON Schema validator provider + * + * This provider uses @cfworker/json-schema for validation without code generation, + * making it compatible with edge runtimes like Cloudflare Workers that restrict + * eval and new Function. + */ +import { Validator } from '@cfworker/json-schema'; +/** + * + * @example + * ```typescript + * // Use with default configuration (2020-12, shortcircuit) + * const validator = new CfWorkerJsonSchemaValidator(); + * + * // Use with custom configuration + * const validator = new CfWorkerJsonSchemaValidator({ + * draft: '2020-12', + * shortcircuit: false // Report all errors + * }); + * ``` + */ +export class CfWorkerJsonSchemaValidator { + /** + * Create a validator + * + * @param options - Configuration options + * @param options.shortcircuit - If true, stop validation after first error (default: true) + * @param options.draft - JSON Schema draft version to use (default: '2020-12') + */ + constructor(options) { + this.shortcircuit = options?.shortcircuit ?? true; + this.draft = options?.draft ?? '2020-12'; + } + /** + * Create a validator for the given JSON Schema + * + * Unlike AJV, this validator is not cached internally + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema) { + // Cast to the cfworker Schema type - our JsonSchemaType is structurally compatible + const validator = new Validator(schema, this.draft, this.shortcircuit); + return (input) => { + const result = validator.validate(input); + if (result.valid) { + return { + valid: true, + data: input, + errorMessage: undefined + }; + } + else { + return { + valid: false, + data: undefined, + errorMessage: result.errors.map(err => `${err.instanceLocation}: ${err.error}`).join('; ') + }; + } + }; + } +} +//# sourceMappingURL=cfworker-provider.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/cfworker-provider.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/cfworker-provider.js.map new file mode 100644 index 000000000..21c014ab7 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/cfworker-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cfworker-provider.js","sourceRoot":"","sources":["../../../src/validation/cfworker-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAQlD;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,2BAA2B;IAIpC;;;;;;OAMG;IACH,YAAY,OAAiE;QACzE,IAAI,CAAC,YAAY,GAAG,OAAO,EAAE,YAAY,IAAI,IAAI,CAAC;QAClD,IAAI,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,IAAI,SAAS,CAAC;IAC7C,CAAC;IAED;;;;;;;OAOG;IACH,YAAY,CAAI,MAAsB;QAClC,mFAAmF;QACnF,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,MAAoD,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QAErH,OAAO,CAAC,KAAc,EAAgC,EAAE;YACpD,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;YAEzC,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;gBACf,OAAO;oBACH,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,KAAU;oBAChB,YAAY,EAAE,SAAS;iBAC1B,CAAC;YACN,CAAC;iBAAM,CAAC;gBACJ,OAAO;oBACH,KAAK,EAAE,KAAK;oBACZ,IAAI,EAAE,SAAS;oBACf,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,gBAAgB,KAAK,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;iBAC7F,CAAC;YACN,CAAC;QACL,CAAC,CAAC;IACN,CAAC;CACJ"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/index.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/index.d.ts new file mode 100644 index 000000000..99e993967 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/index.d.ts @@ -0,0 +1,29 @@ +/** + * JSON Schema validation + * + * This module provides configurable JSON Schema validation for the MCP SDK. + * Choose a validator based on your runtime environment: + * + * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) + * Import from: @modelcontextprotocol/sdk/validation/ajv + * Requires peer dependencies: ajv, ajv-formats + * + * - CfWorkerJsonSchemaValidator: Best for edge runtimes + * Import from: @modelcontextprotocol/sdk/validation/cfworker + * Requires peer dependency: @cfworker/json-schema + * + * @example + * ```typescript + * // For Node.js with AJV + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // For Cloudflare Workers + * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; + * const validator = new CfWorkerJsonSchemaValidator(); + * ``` + * + * @module validation + */ +export type { JsonSchemaType, JsonSchemaValidator, JsonSchemaValidatorResult, jsonSchemaValidator } from './types.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/index.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/index.d.ts.map new file mode 100644 index 000000000..a8845b96e --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGH,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/index.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/index.js new file mode 100644 index 000000000..685b1fd45 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/index.js @@ -0,0 +1,29 @@ +/** + * JSON Schema validation + * + * This module provides configurable JSON Schema validation for the MCP SDK. + * Choose a validator based on your runtime environment: + * + * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) + * Import from: @modelcontextprotocol/sdk/validation/ajv + * Requires peer dependencies: ajv, ajv-formats + * + * - CfWorkerJsonSchemaValidator: Best for edge runtimes + * Import from: @modelcontextprotocol/sdk/validation/cfworker + * Requires peer dependency: @cfworker/json-schema + * + * @example + * ```typescript + * // For Node.js with AJV + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // For Cloudflare Workers + * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; + * const validator = new CfWorkerJsonSchemaValidator(); + * ``` + * + * @module validation + */ +export {}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/index.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/index.js.map new file mode 100644 index 000000000..ed2b9fc23 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/types.d.ts b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/types.d.ts new file mode 100644 index 000000000..9fa92226c --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/types.d.ts @@ -0,0 +1,65 @@ +import type { JSONSchema } from 'json-schema-typed'; +/** + * JSON Schema type definition (JSON Schema Draft 2020-12) + * + * This uses the object form of JSON Schema (excluding boolean schemas). + * While `true` and `false` are valid JSON Schemas, this SDK uses the + * object form for practical type safety. + * + * Re-exported from json-schema-typed for convenience. + * @see https://json-schema.org/draft/2020-12/json-schema-core.html + */ +export type JsonSchemaType = JSONSchema.Interface; +/** + * Result of a JSON Schema validation operation + */ +export type JsonSchemaValidatorResult = { + valid: true; + data: T; + errorMessage: undefined; +} | { + valid: false; + data: undefined; + errorMessage: string; +}; +/** + * A validator function that validates data against a JSON Schema + */ +export type JsonSchemaValidator = (input: unknown) => JsonSchemaValidatorResult; +/** + * Provider interface for creating validators from JSON Schemas + * + * This is the main extension point for custom validator implementations. + * Implementations should: + * - Support JSON Schema Draft 2020-12 (or be compatible with it) + * - Return validator functions that can be called multiple times + * - Handle schema compilation/caching internally + * - Provide clear error messages on validation failure + * + * @example + * ```typescript + * class MyValidatorProvider implements jsonSchemaValidator { + * getValidator(schema: JsonSchemaType): JsonSchemaValidator { + * // Compile/cache validator from schema + * return (input: unknown) => { + * // Validate input against schema + * if (valid) { + * return { valid: true, data: input as T, errorMessage: undefined }; + * } else { + * return { valid: false, data: undefined, errorMessage: 'Error details' }; + * } + * }; + * } + * } + * ``` + */ +export interface jsonSchemaValidator { + /** + * Create a validator for the given JSON Schema + * + * @param schema - Standard JSON Schema object + * @returns A validator function that can be called multiple times + */ + getValidator(schema: JsonSchemaType): JsonSchemaValidator; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/types.d.ts.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/types.d.ts.map new file mode 100644 index 000000000..52aa0ef42 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/validation/types.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD;;;;;;;;;GASG;AACH,MAAM,MAAM,cAAc,GAAG,UAAU,CAAC,SAAS,CAAC;AAElD;;GAEG;AACH,MAAM,MAAM,yBAAyB,CAAC,CAAC,IACjC;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,CAAC,CAAC;IAAC,YAAY,EAAE,SAAS,CAAA;CAAE,GACjD;IAAE,KAAK,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,SAAS,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC;AAE9D;;GAEG;AACH,MAAM,MAAM,mBAAmB,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,KAAK,yBAAyB,CAAC,CAAC,CAAC,CAAC;AAEtF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,WAAW,mBAAmB;IAChC;;;;;OAKG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAC;CACnE"} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/types.js b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/types.js new file mode 100644 index 000000000..718fd38ae --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/types.js.map b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/types.js.map new file mode 100644 index 000000000..51361cf6a --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/validation/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@modelcontextprotocol/sdk/package.json b/node_modules/@modelcontextprotocol/sdk/package.json new file mode 100644 index 000000000..8089d8227 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/package.json @@ -0,0 +1,145 @@ +{ + "name": "@modelcontextprotocol/sdk", + "version": "1.25.3", + "description": "Model Context Protocol implementation for TypeScript", + "license": "MIT", + "author": "Anthropic, PBC (https://anthropic.com)", + "homepage": "https://modelcontextprotocol.io", + "bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues", + "type": "module", + "repository": { + "type": "git", + "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git" + }, + "engines": { + "node": ">=18" + }, + "keywords": [ + "modelcontextprotocol", + "mcp" + ], + "exports": { + ".": { + "import": "./dist/esm/index.js", + "require": "./dist/cjs/index.js" + }, + "./client": { + "import": "./dist/esm/client/index.js", + "require": "./dist/cjs/client/index.js" + }, + "./server": { + "import": "./dist/esm/server/index.js", + "require": "./dist/cjs/server/index.js" + }, + "./validation": { + "import": "./dist/esm/validation/index.js", + "require": "./dist/cjs/validation/index.js" + }, + "./validation/ajv": { + "import": "./dist/esm/validation/ajv-provider.js", + "require": "./dist/cjs/validation/ajv-provider.js" + }, + "./validation/cfworker": { + "import": "./dist/esm/validation/cfworker-provider.js", + "require": "./dist/cjs/validation/cfworker-provider.js" + }, + "./experimental": { + "import": "./dist/esm/experimental/index.js", + "require": "./dist/cjs/experimental/index.js" + }, + "./experimental/tasks": { + "import": "./dist/esm/experimental/tasks/index.js", + "require": "./dist/cjs/experimental/tasks/index.js" + }, + "./*": { + "import": "./dist/esm/*", + "require": "./dist/cjs/*" + } + }, + "typesVersions": { + "*": { + "*": [ + "./dist/esm/*" + ] + } + }, + "files": [ + "dist" + ], + "scripts": { + "fetch:spec-types": "tsx scripts/fetch-spec-types.ts", + "typecheck": "tsgo --noEmit", + "build": "npm run build:esm && npm run build:cjs", + "build:esm": "mkdir -p dist/esm && echo '{\"type\": \"module\"}' > dist/esm/package.json && tsc -p tsconfig.prod.json", + "build:esm:w": "npm run build:esm -- -w", + "build:cjs": "mkdir -p dist/cjs && echo '{\"type\": \"commonjs\"}' > dist/cjs/package.json && tsc -p tsconfig.cjs.json", + "build:cjs:w": "npm run build:cjs -- -w", + "examples:simple-server:w": "tsx --watch src/examples/server/simpleStreamableHttp.ts --oauth", + "prepack": "npm run build:esm && npm run build:cjs", + "lint": "eslint src/ && prettier --check .", + "lint:fix": "eslint src/ --fix && prettier --write .", + "check": "npm run typecheck && npm run lint", + "test": "vitest run", + "test:watch": "vitest", + "start": "npm run server", + "server": "tsx watch --clear-screen=false scripts/cli.ts server", + "client": "tsx scripts/cli.ts client" + }, + "dependencies": { + "@hono/node-server": "^1.19.9", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.0.1", + "express-rate-limit": "^7.5.0", + "jose": "^6.1.1", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.0" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + }, + "devDependencies": { + "@cfworker/json-schema": "^4.1.1", + "@eslint/js": "^9.39.1", + "@types/content-type": "^1.1.8", + "@types/cors": "^2.8.17", + "@types/cross-spawn": "^6.0.6", + "@types/eventsource": "^1.1.15", + "@types/express": "^5.0.0", + "@types/express-serve-static-core": "^5.1.0", + "@types/node": "^22.12.0", + "@types/supertest": "^6.0.2", + "@types/ws": "^8.5.12", + "@typescript/native-preview": "^7.0.0-dev.20251103.1", + "eslint": "^9.8.0", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-n": "^17.23.1", + "prettier": "3.6.2", + "supertest": "^7.0.0", + "tsx": "^4.16.5", + "typescript": "^5.5.4", + "typescript-eslint": "^8.48.1", + "vitest": "^4.0.8", + "ws": "^8.18.0" + }, + "resolutions": { + "strip-ansi": "6.0.1" + } +} diff --git a/node_modules/accepts/HISTORY.md b/node_modules/accepts/HISTORY.md new file mode 100644 index 000000000..627a81d0c --- /dev/null +++ b/node_modules/accepts/HISTORY.md @@ -0,0 +1,250 @@ +2.0.0 / 2024-08-31 +================== + + * Drop node <18 support + * deps: mime-types@^3.0.0 + * deps: negotiator@^1.0.0 + +1.3.8 / 2022-02-02 +================== + + * deps: mime-types@~2.1.34 + - deps: mime-db@~1.51.0 + * deps: negotiator@0.6.3 + +1.3.7 / 2019-04-29 +================== + + * deps: negotiator@0.6.2 + - Fix sorting charset, encoding, and language with extra parameters + +1.3.6 / 2019-04-28 +================== + + * deps: mime-types@~2.1.24 + - deps: mime-db@~1.40.0 + +1.3.5 / 2018-02-28 +================== + + * deps: mime-types@~2.1.18 + - deps: mime-db@~1.33.0 + +1.3.4 / 2017-08-22 +================== + + * deps: mime-types@~2.1.16 + - deps: mime-db@~1.29.0 + +1.3.3 / 2016-05-02 +================== + + * deps: mime-types@~2.1.11 + - deps: mime-db@~1.23.0 + * deps: negotiator@0.6.1 + - perf: improve `Accept` parsing speed + - perf: improve `Accept-Charset` parsing speed + - perf: improve `Accept-Encoding` parsing speed + - perf: improve `Accept-Language` parsing speed + +1.3.2 / 2016-03-08 +================== + + * deps: mime-types@~2.1.10 + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + - deps: mime-db@~1.22.0 + +1.3.1 / 2016-01-19 +================== + + * deps: mime-types@~2.1.9 + - deps: mime-db@~1.21.0 + +1.3.0 / 2015-09-29 +================== + + * deps: mime-types@~2.1.7 + - deps: mime-db@~1.19.0 + * deps: negotiator@0.6.0 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Lazy-load modules from main entry point + - perf: delay type concatenation until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove closures getting spec properties + - perf: remove a closure from media type parsing + - perf: remove property delete from media type parsing + +1.2.13 / 2015-09-06 +=================== + + * deps: mime-types@~2.1.6 + - deps: mime-db@~1.18.0 + +1.2.12 / 2015-07-30 +=================== + + * deps: mime-types@~2.1.4 + - deps: mime-db@~1.16.0 + +1.2.11 / 2015-07-16 +=================== + + * deps: mime-types@~2.1.3 + - deps: mime-db@~1.15.0 + +1.2.10 / 2015-07-01 +=================== + + * deps: mime-types@~2.1.2 + - deps: mime-db@~1.14.0 + +1.2.9 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - perf: fix deopt during mapping + +1.2.8 / 2015-06-07 +================== + + * deps: mime-types@~2.1.0 + - deps: mime-db@~1.13.0 + * perf: avoid argument reassignment & argument slice + * perf: avoid negotiator recursive construction + * perf: enable strict mode + * perf: remove unnecessary bitwise operator + +1.2.7 / 2015-05-10 +================== + + * deps: negotiator@0.5.3 + - Fix media type parameter matching to be case-insensitive + +1.2.6 / 2015-05-07 +================== + + * deps: mime-types@~2.0.11 + - deps: mime-db@~1.9.1 + * deps: negotiator@0.5.2 + - Fix comparing media types with quoted values + - Fix splitting media types with quoted commas + +1.2.5 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - deps: mime-db@~1.8.0 + +1.2.4 / 2015-02-14 +================== + + * Support Node.js 0.6 + * deps: mime-types@~2.0.9 + - deps: mime-db@~1.7.0 + * deps: negotiator@0.5.1 + - Fix preference sorting to be stable for long acceptable lists + +1.2.3 / 2015-01-31 +================== + + * deps: mime-types@~2.0.8 + - deps: mime-db@~1.6.0 + +1.2.2 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - deps: mime-db@~1.5.0 + +1.2.1 / 2014-12-30 +================== + + * deps: mime-types@~2.0.5 + - deps: mime-db@~1.3.1 + +1.2.0 / 2014-12-19 +================== + + * deps: negotiator@0.5.0 + - Fix list return order when large accepted list + - Fix missing identity encoding when q=0 exists + - Remove dynamic building of Negotiator class + +1.1.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - deps: mime-db@~1.3.0 + +1.1.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - deps: mime-db@~1.2.0 + +1.1.2 / 2014-10-14 +================== + + * deps: negotiator@0.4.9 + - Fix error when media type has invalid parameter + +1.1.1 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - deps: mime-db@~1.1.0 + * deps: negotiator@0.4.8 + - Fix all negotiations to be case-insensitive + - Stable sort preferences of same quality according to client order + +1.1.0 / 2014-09-02 +================== + + * update `mime-types` + +1.0.7 / 2014-07-04 +================== + + * Fix wrong type returned from `type` when match after unknown extension + +1.0.6 / 2014-06-24 +================== + + * deps: negotiator@0.4.7 + +1.0.5 / 2014-06-20 +================== + + * fix crash when unknown extension given + +1.0.4 / 2014-06-19 +================== + + * use `mime-types` + +1.0.3 / 2014-06-11 +================== + + * deps: negotiator@0.4.6 + - Order by specificity when quality is the same + +1.0.2 / 2014-05-29 +================== + + * Fix interpretation when header not in request + * deps: pin negotiator@0.4.5 + +1.0.1 / 2014-01-18 +================== + + * Identity encoding isn't always acceptable + * deps: negotiator@~0.4.0 + +1.0.0 / 2013-12-27 +================== + + * Genesis diff --git a/node_modules/accepts/LICENSE b/node_modules/accepts/LICENSE new file mode 100644 index 000000000..06166077b --- /dev/null +++ b/node_modules/accepts/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +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/accepts/README.md b/node_modules/accepts/README.md new file mode 100644 index 000000000..f3f10c4a4 --- /dev/null +++ b/node_modules/accepts/README.md @@ -0,0 +1,140 @@ +# accepts + +[![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] + +Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). +Extracted from [koa](https://www.npmjs.com/package/koa) for general use. + +In addition to negotiator, it allows: + +- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` + as well as `('text/html', 'application/json')`. +- Allows type shorthands such as `json`. +- Returns `false` when no types match +- Treats non-existent headers as `*` + +## 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 accepts +``` + +## API + +```js +var accepts = require('accepts') +``` + +### accepts(req) + +Create a new `Accepts` object for the given `req`. + +#### .charset(charsets) + +Return the first accepted charset. If nothing in `charsets` is accepted, +then `false` is returned. + +#### .charsets() + +Return the charsets that the request accepts, in the order of the client's +preference (most preferred first). + +#### .encoding(encodings) + +Return the first accepted encoding. If nothing in `encodings` is accepted, +then `false` is returned. + +#### .encodings() + +Return the encodings that the request accepts, in the order of the client's +preference (most preferred first). + +#### .language(languages) + +Return the first accepted language. If nothing in `languages` is accepted, +then `false` is returned. + +#### .languages() + +Return the languages that the request accepts, in the order of the client's +preference (most preferred first). + +#### .type(types) + +Return the first accepted type (and it is returned as the same text as what +appears in the `types` array). If nothing in `types` is accepted, then `false` +is returned. + +The `types` array can contain full MIME types or file extensions. Any value +that is not a full MIME type is passed to `require('mime-types').lookup`. + +#### .types() + +Return the types that the request accepts, in the order of the client's +preference (most preferred first). + +## Examples + +### Simple type negotiation + +This simple example shows how to use `accepts` to return a different typed +respond body based on what the client wants to accept. The server lists it's +preferences in order and will get back the best match between the client and +server. + +```js +var accepts = require('accepts') +var http = require('http') + +function app (req, res) { + var accept = accepts(req) + + // the order of this list is significant; should be server preferred order + switch (accept.type(['json', 'html'])) { + case 'json': + res.setHeader('Content-Type', 'application/json') + res.write('{"hello":"world!"}') + break + case 'html': + res.setHeader('Content-Type', 'text/html') + res.write('hello, world!') + break + default: + // the fallback is text/plain, so no need to specify it above + res.setHeader('Content-Type', 'text/plain') + res.write('hello, world!') + break + } + + res.end() +} + +http.createServer(app).listen(3000) +``` + +You can test this out with the cURL program: +```sh +curl -I -H'Accept: text/html' http://localhost:3000/ +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master +[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml +[node-version-image]: https://badgen.net/npm/node/accepts +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/accepts +[npm-url]: https://npmjs.org/package/accepts +[npm-version-image]: https://badgen.net/npm/v/accepts diff --git a/node_modules/accepts/index.js b/node_modules/accepts/index.js new file mode 100644 index 000000000..4f2840c0b --- /dev/null +++ b/node_modules/accepts/index.js @@ -0,0 +1,238 @@ +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Negotiator = require('negotiator') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = Accepts + +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ + +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) + } + + this.headers = req.headers + this.negotiator = new Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] + } + } + + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } + + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } + + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] + + return first + ? types[mimes.indexOf(first)] + : false +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] + } + } + + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } + + return this.negotiator.encodings(encodings)[0] || false +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ + + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } + + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } + + return this.negotiator.charsets(charsets)[0] || false +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ + + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } + } + + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() + } + + return this.negotiator.languages(languages)[0] || false +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {Boolean} + * @private + */ + +function validMime (type) { + return typeof type === 'string' +} diff --git a/node_modules/accepts/package.json b/node_modules/accepts/package.json new file mode 100644 index 000000000..b35b262db --- /dev/null +++ b/node_modules/accepts/package.json @@ -0,0 +1,47 @@ +{ + "name": "accepts", + "description": "Higher-level content negotiation", + "version": "2.0.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/accepts", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "keywords": [ + "content", + "negotiation", + "accept", + "accepts" + ] +} diff --git a/node_modules/ajv-formats/LICENSE b/node_modules/ajv-formats/LICENSE new file mode 100644 index 000000000..a3f8ba027 --- /dev/null +++ b/node_modules/ajv-formats/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Evgeny Poberezkin + +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/ajv-formats/README.md b/node_modules/ajv-formats/README.md new file mode 100644 index 000000000..b4264cd6f --- /dev/null +++ b/node_modules/ajv-formats/README.md @@ -0,0 +1,125 @@ +# ajv-formats + +JSON Schema formats for Ajv + +[![Build Status](https://travis-ci.org/ajv-validator/ajv-formats.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv-formats) +[![npm](https://img.shields.io/npm/v/ajv-formats.svg)](https://www.npmjs.com/package/ajv-formats) +[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) +[![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) + +## Usage + +```javascript +// ESM/TypeScript import +import Ajv from "ajv" +import addFormats from "ajv-formats" +// Node.js require: +const Ajv = require("ajv") +const addFormats = require("ajv-formats") + +const ajv = new Ajv() +addFormats(ajv) +``` + +## Formats + +The package defines these formats: + +- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). +- _time_: time (time-zone is mandatory). +- _date-time_: date-time (time-zone is mandatory). +- _iso-time_: time with optional time-zone. +- _iso-date-time_: date-time with optional time-zone. +- _duration_: duration from [RFC3339](https://tools.ietf.org/html/rfc3339#appendix-A) +- _uri_: full URI. +- _uri-reference_: URI reference, including full and relative URIs. +- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) +- _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url). +- _email_: email address. +- _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). +- _ipv4_: IP address v4. +- _ipv6_: IP address v6. +- _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. +- _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). +- _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). +- _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). +- _byte_: base64 encoded data according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) +- _int32_: signed 32 bits integer according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) +- _int64_: signed 64 bits according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) +- _float_: float according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) +- _double_: double according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) +- _password_: password string according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) +- _binary_: binary string according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) + +See regular expressions used for format validation and the sources that were used in [formats.ts](https://github.com/ajv-validator/ajv-formats/blob/master/src/formats.ts). + +**Please note**: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. These formats are available in [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) plugin. + +## Keywords to compare values: `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` + +These keywords allow to define minimum/maximum constraints when the format keyword defines ordering (`compare` function in format definition). + +These keywords are added to ajv instance when ajv-formats is used without options or with option `keywords: true`. + +These keywords apply only to strings. If the data is not a string, the validation succeeds. + +The value of keywords `formatMaximum`/`formatMinimum` and `formatExclusiveMaximum`/`formatExclusiveMinimum` should be a string or [\$data reference](https://github.com/ajv-validator/ajv/blob/master/docs/validation.md#data-reference). This value is the maximum (minimum) allowed value for the data to be valid as determined by `format` keyword. If `format` keyword is not present schema compilation will throw exception. + +When these keyword are added, they also add comparison functions to formats `"date"`, `"time"` and `"date-time"`. User-defined formats also can have comparison functions. See [addFormat](https://github.com/ajv-validator/ajv/blob/master/docs/api.md#api-addformat) method. + +```javascript +require("ajv-formats")(ajv) + +const schema = { + type: "string", + format: "date", + formatMinimum: "2016-02-06", + formatExclusiveMaximum: "2016-12-27", +} + +const validDataList = ["2016-02-06", "2016-12-26"] + +const invalidDataList = ["2016-02-05", "2016-12-27", "abc"] +``` + +## Options + +Options can be passed via the second parameter. Options value can be + +1. The list of format names that will be added to ajv instance: + +```javascript +addFormats(ajv, ["date", "time"]) +``` + +**Please note**: when ajv encounters an undefined format it throws exception (unless ajv instance was configured with `strict: false` option). To allow specific undefined formats they have to be passed to ajv instance via `formats` option with `true` value: + +```javascript +const ajv = new Ajv((formats: {date: true, time: true})) // to ignore "date" and "time" formats in schemas. +``` + +2. Format validation mode (default is `"full"`) with optional list of format names and `keywords` option to add additional format comparison keywords: + +```javascript +addFormats(ajv, {mode: "fast"}) +``` + +or + +```javascript +addFormats(ajv, {mode: "fast", formats: ["date", "time"], keywords: true}) +``` + +In `"fast"` mode the following formats are simplified: `"date"`, `"time"`, `"date-time"`, `"iso-time"`, `"iso-date-time"`, `"uri"`, `"uri-reference"`, `"email"`. For example, `"date"`, `"time"` and `"date-time"` do not validate ranges in `"fast"` mode, only string structure, and other formats have simplified regular expressions. + +## Tests + +```bash +npm install +git submodule update --init +npm test +``` + +## License + +[MIT](https://github.com/ajv-validator/ajv-formats/blob/master/LICENSE) diff --git a/node_modules/ajv-formats/dist/formats.d.ts b/node_modules/ajv-formats/dist/formats.d.ts new file mode 100644 index 000000000..e63a9a9e7 --- /dev/null +++ b/node_modules/ajv-formats/dist/formats.d.ts @@ -0,0 +1,9 @@ +import type { Format } from "ajv"; +export type FormatMode = "fast" | "full"; +export type FormatName = "date" | "time" | "date-time" | "iso-time" | "iso-date-time" | "duration" | "uri" | "uri-reference" | "uri-template" | "url" | "email" | "hostname" | "ipv4" | "ipv6" | "regex" | "uuid" | "json-pointer" | "json-pointer-uri-fragment" | "relative-json-pointer" | "byte" | "int32" | "int64" | "float" | "double" | "password" | "binary"; +export type DefinedFormats = { + [key in FormatName]: Format; +}; +export declare const fullFormats: DefinedFormats; +export declare const fastFormats: DefinedFormats; +export declare const formatNames: FormatName[]; diff --git a/node_modules/ajv-formats/dist/formats.js b/node_modules/ajv-formats/dist/formats.js new file mode 100644 index 000000000..cf01ed845 --- /dev/null +++ b/node_modules/ajv-formats/dist/formats.js @@ -0,0 +1,208 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; +function fmtDef(validate, compare) { + return { validate, compare }; +} +exports.fullFormats = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: fmtDef(date, compareDate), + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + // duration: https://tools.ietf.org/html/rfc3339#appendix-A + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + // uri-template: https://tools.ietf.org/html/rfc6570 + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + // For the source: https://gist.github.com/dperini/729294 + // For test cases: https://mathiasbynens.be/demo/url-regex + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types + // byte: https://github.com/miguelmota/is-base64 + byte, + // signed 32 bit integer + int32: { type: "number", validate: validateInt32 }, + // signed 64 bit integer + int64: { type: "number", validate: validateInt64 }, + // C-type float + float: { type: "number", validate: validateNumber }, + // C-type double + double: { type: "number", validate: validateNumber }, + // hint to the UI to hide input strings + password: true, + // unchecked string payload + binary: true, +}; +exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, +}; +exports.formatNames = Object.keys(exports.fullFormats); +function isLeapYear(year) { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} +const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; +const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + const matches = DATE.exec(str); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return (month >= 1 && + month <= 12 && + day >= 1 && + day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month])); +} +function compareDate(d1, d2) { + if (!(d1 && d2)) + return undefined; + if (d1 > d2) + return 1; + if (d1 < d2) + return -1; + return 0; +} +const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; +function getTime(strictTimeZone) { + return function time(str) { + const matches = TIME.exec(str); + if (!matches) + return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) + return false; + if (hr <= 23 && min <= 59 && sec < 60) + return true; + // leap second + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; +} +function compareTime(s1, s2) { + if (!(s1 && s2)) + return undefined; + const t1 = new Date("2020-01-01T" + s1).valueOf(); + const t2 = new Date("2020-01-01T" + s2).valueOf(); + if (!(t1 && t2)) + return undefined; + return t1 - t2; +} +function compareIsoTime(t1, t2) { + if (!(t1 && t2)) + return undefined; + const a1 = TIME.exec(t1); + const a2 = TIME.exec(t2); + if (!(a1 && a2)) + return undefined; + t1 = a1[1] + a1[2] + a1[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t1 > t2) + return 1; + if (t1 < t2) + return -1; + return 0; +} +const DATE_TIME_SEPARATOR = /t|\s/i; +function getDateTime(strictTimeZone) { + const time = getTime(strictTimeZone); + return function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); + }; +} +function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return undefined; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) + return undefined; + return d1 - d2; +} +function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return undefined; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === undefined) + return undefined; + return res || compareTime(t1, t2); +} +const NOT_URI_FRAGMENT = /\/|:/; +const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} +const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; +function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); +} +const MIN_INT32 = -(2 ** 31); +const MAX_INT32 = 2 ** 31 - 1; +function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; +} +function validateInt64(value) { + // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64 + return Number.isInteger(value); +} +function validateNumber() { + return true; +} +const Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) + return false; + try { + new RegExp(str); + return true; + } + catch (e) { + return false; + } +} +//# sourceMappingURL=formats.js.map \ No newline at end of file diff --git a/node_modules/ajv-formats/dist/formats.js.map b/node_modules/ajv-formats/dist/formats.js.map new file mode 100644 index 000000000..a6be97f70 --- /dev/null +++ b/node_modules/ajv-formats/dist/formats.js.map @@ -0,0 +1 @@ +{"version":3,"file":"formats.js","sourceRoot":"","sources":["../src/formats.ts"],"names":[],"mappings":";;;AAqCA,SAAS,MAAM,CACb,QAA0C,EAC1C,OAA8B;IAE9B,OAAO,EAAC,QAAQ,EAAE,OAAO,EAAC,CAAA;AAC5B,CAAC;AAEY,QAAA,WAAW,GAAmB;IACzC,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,WAAW,CAAC;IAC/B,4DAA4D;IAC5D,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,WAAW,CAAC;IACxC,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,eAAe,CAAC;IACvD,UAAU,EAAE,MAAM,CAAC,OAAO,EAAE,EAAE,cAAc,CAAC;IAC7C,eAAe,EAAE,MAAM,CAAC,WAAW,EAAE,EAAE,kBAAkB,CAAC;IAC1D,2DAA2D;IAC3D,QAAQ,EAAE,wEAAwE;IAClF,GAAG;IACH,eAAe,EACb,woCAAwoC;IAC1oC,oDAAoD;IACpD,cAAc,EACZ,mLAAmL;IACrL,yDAAyD;IACzD,0DAA0D;IAC1D,GAAG,EAAE,odAAod;IACzd,KAAK,EACH,0IAA0I;IAC5I,QAAQ,EACN,uGAAuG;IACzG,mHAAmH;IACnH,IAAI,EAAE,mFAAmF;IACzF,IAAI,EAAE,k/BAAk/B;IACx/B,KAAK;IACL,2CAA2C;IAC3C,IAAI,EAAE,8DAA8D;I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a/node_modules/ajv-formats/dist/index.d.ts b/node_modules/ajv-formats/dist/index.d.ts new file mode 100644 index 000000000..045a0960a --- /dev/null +++ b/node_modules/ajv-formats/dist/index.d.ts @@ -0,0 +1,15 @@ +import { FormatMode, FormatName } from "./formats"; +import type { Plugin, Format } from "ajv"; +export { FormatMode, FormatName } from "./formats"; +export { LimitFormatError } from "./limit"; +export interface FormatOptions { + mode?: FormatMode; + formats?: FormatName[]; + keywords?: boolean; +} +export type FormatsPluginOptions = FormatName[] | FormatOptions; +export interface FormatsPlugin extends Plugin { + get: (format: FormatName, mode?: FormatMode) => Format; +} +declare const formatsPlugin: FormatsPlugin; +export default formatsPlugin; diff --git a/node_modules/ajv-formats/dist/index.js b/node_modules/ajv-formats/dist/index.js new file mode 100644 index 000000000..a3b71f91d --- /dev/null +++ b/node_modules/ajv-formats/dist/index.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const formats_1 = require("./formats"); +const limit_1 = require("./limit"); +const codegen_1 = require("ajv/dist/compile/codegen"); +const fullName = new codegen_1.Name("fullFormats"); +const fastName = new codegen_1.Name("fastFormats"); +const formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + const list = opts.formats || formats_1.formatNames; + addFormats(ajv, list, formats, exportName); + if (opts.keywords) + (0, limit_1.default)(ajv); + return ajv; +}; +formatsPlugin.get = (name, mode = "full") => { + const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; + const f = formats[name]; + if (!f) + throw new Error(`Unknown format "${name}"`); + return f; +}; +function addFormats(ajv, list, fs, exportName) { + var _a; + var _b; + (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = (0, codegen_1._) `require("ajv-formats/dist/formats").${exportName}`); + for (const f of list) + ajv.addFormat(f, fs[f]); +} +module.exports = exports = formatsPlugin; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = formatsPlugin; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv-formats/dist/index.js.map b/node_modules/ajv-formats/dist/index.js.map new file mode 100644 index 000000000..fead22d78 --- /dev/null +++ b/node_modules/ajv-formats/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAAA,uCAOkB;AAClB,mCAAiC;AAGjC,sDAAgD;AAgBhD,MAAM,QAAQ,GAAG,IAAI,cAAI,CAAC,aAAa,CAAC,CAAA;AACxC,MAAM,QAAQ,GAAG,IAAI,cAAI,CAAC,aAAa,CAAC,CAAA;AAExC,MAAM,aAAa,GAAkB,CACnC,GAAQ,EACR,OAA6B,EAAC,QAAQ,EAAE,IAAI,EAAC,EACxC,EAAE;IACP,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;QACvB,UAAU,CAAC,GAAG,EAAE,IAAI,EAAE,qBAAW,EAAE,QAAQ,CAAC,CAAA;QAC5C,OAAO,GAAG,CAAA;KACX;IACD,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GACzB,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,qBAAW,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,qBAAW,EAAE,QAAQ,CAAC,CAAA;IAC1E,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,IAAI,qBAAW,CAAA;IACxC,UAAU,CAAC,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,UAAU,CAAC,CAAA;IAC1C,IAAI,IAAI,CAAC,QAAQ;QAAE,IAAA,eAAW,EAAC,GAAG,CAAC,CAAA;IACnC,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA;AAED,aAAa,CAAC,GAAG,GAAG,CAAC,IAAgB,EAAE,OAAmB,MAAM,EAAU,EAAE;IAC1E,MAAM,OAAO,GAAG,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,qBAAW,CAAC,CAAC,CAAC,qBAAW,CAAA;IAC3D,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACvB,IAAI,CAAC,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,IAAI,GAAG,CAAC,CAAA;IACnD,OAAO,CAAC,CAAA;AACV,CAAC,CAAA;AAED,SAAS,UAAU,CAAC,GAAQ,EAAE,IAAkB,EAAE,EAAkB,EAAE,UAAgB;;;IACpF,YAAA,GAAG,CAAC,IAAI,CAAC,IAAI,EAAC,OAAO,uCAAP,OAAO,GAAK,IAAA,WAAC,EAAA,uCAAuC,UAAU,EAAE,EAAA;IAC9E,KAAK,MAAM,CAAC,IAAI,IAAI;QAAE,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;AAC/C,CAAC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,aAAa,CAAA;AACxC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,aAAa,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv-formats/dist/limit.d.ts b/node_modules/ajv-formats/dist/limit.d.ts new file mode 100644 index 000000000..139fe1e73 --- /dev/null +++ b/node_modules/ajv-formats/dist/limit.d.ts @@ -0,0 +1,10 @@ +import type { Plugin, CodeKeywordDefinition, ErrorObject } from "ajv"; +type Kwd = "formatMaximum" | "formatMinimum" | "formatExclusiveMaximum" | "formatExclusiveMinimum"; +type Comparison = "<=" | ">=" | "<" | ">"; +export type LimitFormatError = ErrorObject; +export declare const formatLimitDefinition: CodeKeywordDefinition; +declare const formatLimitPlugin: Plugin; +export default formatLimitPlugin; diff --git a/node_modules/ajv-formats/dist/limit.js b/node_modules/ajv-formats/dist/limit.js new file mode 100644 index 000000000..64979f839 --- /dev/null +++ b/node_modules/ajv-formats/dist/limit.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.formatLimitDefinition = void 0; +const ajv_1 = require("ajv"); +const codegen_1 = require("ajv/dist/compile/codegen"); +const ops = codegen_1.operators; +const KWDs = { + formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }, +}; +const error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str) `should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`, +}; +exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self } = it; + if (!opts.validateFormats) + return; + const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); + if (fCxt.$data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats, + }); + const fmt = gen.const("fmt", (0, codegen_1._) `${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._) `typeof ${fmt} != "object"`, (0, codegen_1._) `${fmt} instanceof RegExp`, (0, codegen_1._) `typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self.formats[format]; + if (!fmtDef || fmtDef === true) + return; + if (typeof fmtDef != "object" || + fmtDef instanceof RegExp || + typeof fmtDef.compare != "function") { + throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + } + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : undefined, + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._) `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"], +}; +const formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; +}; +exports.default = formatLimitPlugin; +//# sourceMappingURL=limit.js.map \ No newline at end of file diff --git a/node_modules/ajv-formats/dist/limit.js.map b/node_modules/ajv-formats/dist/limit.js.map new file mode 100644 index 000000000..f4a31b6bc --- /dev/null +++ b/node_modules/ajv-formats/dist/limit.js.map @@ -0,0 +1 @@ +{"version":3,"file":"limit.js","sourceRoot":"","sources":["../src/limit.ts"],"names":[],"mappings":";;;AAWA,6BAA8B;AAC9B,sDAA2E;AAM3E,MAAM,GAAG,GAAG,mBAAS,CAAA;AAErB,MAAM,IAAI,GAA4D;IACpE,aAAa,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACvD,aAAa,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACvD,sBAAsB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;IAC/D,sBAAsB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;CAChE,CAAA;AAID,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CAAC,I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,GAAG,CAAC,UAAU,CAAC,6BAAqB,CAAC,CAAA;IACrC,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA;AAED,kBAAe,iBAAiB,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv-formats/package.json b/node_modules/ajv-formats/package.json new file mode 100644 index 000000000..e673a8fc4 --- /dev/null +++ b/node_modules/ajv-formats/package.json @@ -0,0 +1,74 @@ +{ + "name": "ajv-formats", + "version": "3.0.1", + "description": "Format validation for Ajv v7+", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "src/", + "dist/" + ], + "scripts": { + "build": "tsc", + "prettier:write": "prettier --write \"./**/*.{md,json,yaml,js,ts}\"", + "prettier:check": "prettier --list-different \"./**/*.{md,json,yaml,js,ts}\"", + "eslint": "eslint --ext .ts ./src/**/*", + "test-spec": "jest", + "test-cov": "jest --coverage", + "test": "npm run prettier:check && npm run build && npm run eslint && npm run test-cov", + "ci-test": "npm run test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ajv-validator/ajv-formats.git" + }, + "keywords": [ + "Ajv", + "JSON-Schema", + "format", + "validation" + ], + "author": "Evgeny Poberezkin", + "license": "MIT", + "bugs": { + "url": "https://github.com/ajv-validator/ajv-formats/issues" + }, + "homepage": "https://github.com/ajv-validator/ajv-formats#readme", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + }, + "devDependencies": { + "@ajv-validator/config": "^0.3.0", + "@types/jest": "^26.0.5", + "@types/node": "^14.10.1", + "@typescript-eslint/eslint-plugin": "^3.7.0", + "@typescript-eslint/parser": "^3.7.0", + "ajv": "^8.0.0", + "eslint": "^7.5.0", + "eslint-config-prettier": "^6.11.0", + "husky": "^4.2.5", + "jest": "^26.1.0", + "json-schema-test": "^2.0.0", + "lint-staged": "^10.2.11", + "prettier": "^2.3.2", + "ts-jest": "^26.1.3", + "typescript": "^4.0.0" + }, + "prettier": "@ajv-validator/config/prettierrc.json", + "husky": { + "hooks": { + "pre-commit": "lint-staged && npm test" + } + }, + "lint-staged": { + "*.{md,json,yaml,js,ts}": "prettier --write" + } +} diff --git a/node_modules/ajv-formats/src/formats.ts b/node_modules/ajv-formats/src/formats.ts new file mode 100644 index 000000000..d3cde9bca --- /dev/null +++ b/node_modules/ajv-formats/src/formats.ts @@ -0,0 +1,269 @@ +import type {Format, FormatDefinition} from "ajv" +import type {FormatValidator, FormatCompare} from "ajv/dist/types" + +export type FormatMode = "fast" | "full" + +export type FormatName = + | "date" + | "time" + | "date-time" + | "iso-time" + | "iso-date-time" + | "duration" + | "uri" + | "uri-reference" + | "uri-template" + | "url" + | "email" + | "hostname" + | "ipv4" + | "ipv6" + | "regex" + | "uuid" + | "json-pointer" + | "json-pointer-uri-fragment" + | "relative-json-pointer" + | "byte" + | "int32" + | "int64" + | "float" + | "double" + | "password" + | "binary" + +export type DefinedFormats = { + [key in FormatName]: Format +} + +function fmtDef( + validate: RegExp | FormatValidator, + compare: FormatCompare +): FormatDefinition { + return {validate, compare} +} + +export const fullFormats: DefinedFormats = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: fmtDef(date, compareDate), + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + // duration: https://tools.ietf.org/html/rfc3339#appendix-A + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": + /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + // uri-template: https://tools.ietf.org/html/rfc6570 + "uri-template": + /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + // For the source: https://gist.github.com/dperini/729294 + // For test cases: https://mathiasbynens.be/demo/url-regex + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: + /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: + /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types + // byte: https://github.com/miguelmota/is-base64 + byte, + // signed 32 bit integer + int32: {type: "number", validate: validateInt32}, + // signed 64 bit integer + int64: {type: "number", validate: validateInt64}, + // C-type float + float: {type: "number", validate: validateNumber}, + // C-type double + double: {type: "number", validate: validateNumber}, + // hint to the UI to hide input strings + password: true, + // unchecked string payload + binary: true, +} + +export const fastFormats: DefinedFormats = { + ...fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef( + /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, + compareTime + ), + "date-time": fmtDef( + /^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, + compareDateTime + ), + "iso-time": fmtDef( + /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, + compareIsoTime + ), + "iso-date-time": fmtDef( + /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, + compareIsoDateTime + ), + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') + email: + /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, +} + +export const formatNames = Object.keys(fullFormats) as FormatName[] + +function isLeapYear(year: number): boolean { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) +} + +const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/ +const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + +function date(str: string): boolean { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + const matches: string[] | null = DATE.exec(str) + if (!matches) return false + const year: number = +matches[1] + const month: number = +matches[2] + const day: number = +matches[3] + return ( + month >= 1 && + month <= 12 && + day >= 1 && + day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]) + ) +} + +function compareDate(d1: string, d2: string): number | undefined { + if (!(d1 && d2)) return undefined + if (d1 > d2) return 1 + if (d1 < d2) return -1 + return 0 +} + +const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i + +function getTime(strictTimeZone?: boolean): (str: string) => boolean { + return function time(str: string): boolean { + const matches: string[] | null = TIME.exec(str) + if (!matches) return false + const hr: number = +matches[1] + const min: number = +matches[2] + const sec: number = +matches[3] + const tz: string | undefined = matches[4] + const tzSign: number = matches[5] === "-" ? -1 : 1 + const tzH: number = +(matches[6] || 0) + const tzM: number = +(matches[7] || 0) + if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) return false + if (hr <= 23 && min <= 59 && sec < 60) return true + // leap second + const utcMin = min - tzM * tzSign + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0) + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61 + } +} + +function compareTime(s1: string, s2: string): number | undefined { + if (!(s1 && s2)) return undefined + const t1 = new Date("2020-01-01T" + s1).valueOf() + const t2 = new Date("2020-01-01T" + s2).valueOf() + if (!(t1 && t2)) return undefined + return t1 - t2 +} + +function compareIsoTime(t1: string, t2: string): number | undefined { + if (!(t1 && t2)) return undefined + const a1 = TIME.exec(t1) + const a2 = TIME.exec(t2) + if (!(a1 && a2)) return undefined + t1 = a1[1] + a1[2] + a1[3] + t2 = a2[1] + a2[2] + a2[3] + if (t1 > t2) return 1 + if (t1 < t2) return -1 + return 0 +} + +const DATE_TIME_SEPARATOR = /t|\s/i +function getDateTime(strictTimeZone?: boolean): (str: string) => boolean { + const time = getTime(strictTimeZone) + + return function date_time(str: string): boolean { + // http://tools.ietf.org/html/rfc3339#section-5.6 + const dateTime: string[] = str.split(DATE_TIME_SEPARATOR) + return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]) + } +} + +function compareDateTime(dt1: string, dt2: string): number | undefined { + if (!(dt1 && dt2)) return undefined + const d1 = new Date(dt1).valueOf() + const d2 = new Date(dt2).valueOf() + if (!(d1 && d2)) return undefined + return d1 - d2 +} + +function compareIsoDateTime(dt1: string, dt2: string): number | undefined { + if (!(dt1 && dt2)) return undefined + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR) + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR) + const res = compareDate(d1, d2) + if (res === undefined) return undefined + return res || compareTime(t1, t2) +} + +const NOT_URI_FRAGMENT = /\/|:/ +const URI = + /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i + +function uri(str: string): boolean { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str) +} + +const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm + +function byte(str: string): boolean { + BYTE.lastIndex = 0 + return BYTE.test(str) +} + +const MIN_INT32 = -(2 ** 31) +const MAX_INT32 = 2 ** 31 - 1 + +function validateInt32(value: number): boolean { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32 +} + +function validateInt64(value: number): boolean { + // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64 + return Number.isInteger(value) +} + +function validateNumber(): boolean { + return true +} + +const Z_ANCHOR = /[^\\]\\Z/ +function regex(str: string): boolean { + if (Z_ANCHOR.test(str)) return false + try { + new RegExp(str) + return true + } catch (e) { + return false + } +} diff --git a/node_modules/ajv-formats/src/index.ts b/node_modules/ajv-formats/src/index.ts new file mode 100644 index 000000000..8fd944a09 --- /dev/null +++ b/node_modules/ajv-formats/src/index.ts @@ -0,0 +1,62 @@ +import { + DefinedFormats, + FormatMode, + FormatName, + formatNames, + fastFormats, + fullFormats, +} from "./formats" +import formatLimit from "./limit" +import type Ajv from "ajv" +import type {Plugin, Format} from "ajv" +import {_, Name} from "ajv/dist/compile/codegen" + +export {FormatMode, FormatName} from "./formats" +export {LimitFormatError} from "./limit" +export interface FormatOptions { + mode?: FormatMode + formats?: FormatName[] + keywords?: boolean +} + +export type FormatsPluginOptions = FormatName[] | FormatOptions + +export interface FormatsPlugin extends Plugin { + get: (format: FormatName, mode?: FormatMode) => Format +} + +const fullName = new Name("fullFormats") +const fastName = new Name("fastFormats") + +const formatsPlugin: FormatsPlugin = ( + ajv: Ajv, + opts: FormatsPluginOptions = {keywords: true} +): Ajv => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, fullFormats, fullName) + return ajv + } + const [formats, exportName] = + opts.mode === "fast" ? [fastFormats, fastName] : [fullFormats, fullName] + const list = opts.formats || formatNames + addFormats(ajv, list, formats, exportName) + if (opts.keywords) formatLimit(ajv) + return ajv +} + +formatsPlugin.get = (name: FormatName, mode: FormatMode = "full"): Format => { + const formats = mode === "fast" ? fastFormats : fullFormats + const f = formats[name] + if (!f) throw new Error(`Unknown format "${name}"`) + return f +} + +function addFormats(ajv: Ajv, list: FormatName[], fs: DefinedFormats, exportName: Name): void { + ajv.opts.code.formats ??= _`require("ajv-formats/dist/formats").${exportName}` + for (const f of list) ajv.addFormat(f, fs[f]) +} + +module.exports = exports = formatsPlugin +Object.defineProperty(exports, "__esModule", {value: true}) + +export default formatsPlugin diff --git a/node_modules/ajv-formats/src/limit.ts b/node_modules/ajv-formats/src/limit.ts new file mode 100644 index 000000000..bf6a57cb9 --- /dev/null +++ b/node_modules/ajv-formats/src/limit.ts @@ -0,0 +1,99 @@ +import type Ajv from "ajv" +import type { + Plugin, + CodeKeywordDefinition, + KeywordErrorDefinition, + Code, + Name, + ErrorObject, +} from "ajv" +import type {AddedFormat} from "ajv/dist/types" +import type {Rule} from "ajv/dist/compile/rules" +import {KeywordCxt} from "ajv" +import {_, str, or, getProperty, operators} from "ajv/dist/compile/codegen" + +type Kwd = "formatMaximum" | "formatMinimum" | "formatExclusiveMaximum" | "formatExclusiveMinimum" + +type Comparison = "<=" | ">=" | "<" | ">" + +const ops = operators + +const KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = { + formatMaximum: {okStr: "<=", ok: ops.LTE, fail: ops.GT}, + formatMinimum: {okStr: ">=", ok: ops.GTE, fail: ops.LT}, + formatExclusiveMaximum: {okStr: "<", ok: ops.LT, fail: ops.GTE}, + formatExclusiveMinimum: {okStr: ">", ok: ops.GT, fail: ops.LTE}, +} + +export type LimitFormatError = ErrorObject + +const error: KeywordErrorDefinition = { + message: ({keyword, schemaCode}) => str`should be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`, + params: ({keyword, schemaCode}) => + _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`, +} + +export const formatLimitDefinition: CodeKeywordDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const {gen, data, schemaCode, keyword, it} = cxt + const {opts, self} = it + if (!opts.validateFormats) return + + const fCxt = new KeywordCxt(it, (self.RULES.all.format as Rule).definition, "format") + if (fCxt.$data) validate$DataFormat() + else validateFormat() + + function validate$DataFormat(): void { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats, + }) + const fmt = gen.const("fmt", _`${fmts}[${fCxt.schemaCode}]`) + cxt.fail$data( + or( + _`typeof ${fmt} != "object"`, + _`${fmt} instanceof RegExp`, + _`typeof ${fmt}.compare != "function"`, + compareCode(fmt) + ) + ) + } + + function validateFormat(): void { + const format = fCxt.schema as string + const fmtDef: AddedFormat | undefined = self.formats[format] + if (!fmtDef || fmtDef === true) return + if ( + typeof fmtDef != "object" || + fmtDef instanceof RegExp || + typeof fmtDef.compare != "function" + ) { + throw new Error(`"${keyword}": format "${format}" does not define "compare" function`) + } + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? _`${opts.code.formats}${getProperty(format)}` : undefined, + }) + + cxt.fail$data(compareCode(fmt)) + } + + function compareCode(fmt: Name): Code { + return _`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword as Kwd].fail} 0` + } + }, + dependencies: ["format"], +} + +const formatLimitPlugin: Plugin = (ajv: Ajv): Ajv => { + ajv.addKeyword(formatLimitDefinition) + return ajv +} + +export default formatLimitPlugin diff --git a/node_modules/ajv/.runkit_example.js b/node_modules/ajv/.runkit_example.js new file mode 100644 index 000000000..0d578d5d5 --- /dev/null +++ b/node_modules/ajv/.runkit_example.js @@ -0,0 +1,23 @@ +const Ajv = require("ajv") +const ajv = new Ajv({allErrors: true}) + +const schema = { + type: "object", + properties: { + foo: {type: "string"}, + bar: {type: "number", maximum: 3}, + }, + required: ["foo", "bar"], + additionalProperties: false, +} + +const validate = ajv.compile(schema) + +test({foo: "abc", bar: 2}) +test({foo: 2, bar: 4}) + +function test(data) { + const valid = validate(data) + if (valid) console.log("Valid!") + else console.log("Invalid: " + ajv.errorsText(validate.errors)) +} diff --git a/node_modules/ajv/LICENSE b/node_modules/ajv/LICENSE new file mode 100644 index 000000000..139162ad2 --- /dev/null +++ b/node_modules/ajv/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015-2021 Evgeny Poberezkin + +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/ajv/README.md b/node_modules/ajv/README.md new file mode 100644 index 000000000..d8ee276ce --- /dev/null +++ b/node_modules/ajv/README.md @@ -0,0 +1,207 @@ +Ajv logo + +  + +# Ajv JSON schema validator + +The fastest JSON validator for Node.js and browser. + +Supports JSON Schema draft-04/06/07/2019-09/2020-12 ([draft-04 support](https://ajv.js.org/json-schema.html#draft-04) requires ajv-draft-04 package) and JSON Type Definition [RFC8927](https://datatracker.ietf.org/doc/rfc8927/). + +[![build](https://github.com/ajv-validator/ajv/actions/workflows/build.yml/badge.svg)](https://github.com/ajv-validator/ajv/actions?query=workflow%3Abuild) +[![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) +[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) +[![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) +[![SimpleX](https://img.shields.io/badge/chat-on%20SimpleX-70F0F9)](https://simplex.chat/contact#/?v=1-2&smp=smp%3A%2F%2Fu2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU%3D%40smp4.simplex.im%2F8KvvURM6J38Gdq9dCuPswMOkMny0xCOJ%23%2F%3Fv%3D1-2%26dh%3DMCowBQYDK2VuAyEAr8rPVRuMOXv6kwF2yUAap-eoVg-9ssOFCi1fIrxTUw0%253D%26srv%3Do5vmywmrnaxalvz6wi3zicyftgio6psuvyniis6gco6bp6ekl4cqj4id.onion&data=%7B%22type%22%3A%22group%22%2C%22groupLinkId%22%3A%224pwLRgWHU9tlroMWHz0uOg%3D%3D%22%7D) +[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) +[![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) + +## Ajv sponsors + +[Mozilla](https://www.mozilla.org)[](https://opencollective.com/ajv) + +[Microsoft](https://opensource.microsoft.com)[](https://opencollective.com/ajv)[](https://opencollective.com/ajv) + +[Retool](https://retool.com/?utm_source=sponsor&utm_campaign=ajv)[Tidelift](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=enterprise)[SimpleX](https://github.com/simplex-chat/simplex-chat)[](https://opencollective.com/ajv) + +## Contributing + +More than 100 people contributed to Ajv, and we would love to have you join the development. We welcome implementing new features that will benefit many users and ideas to improve our documentation. + +Please review [Contributing guidelines](./CONTRIBUTING.md) and [Code components](https://ajv.js.org/components.html). + +## Documentation + +All documentation is available on the [Ajv website](https://ajv.js.org). + +Some useful site links: + +- [Getting started](https://ajv.js.org/guide/getting-started.html) +- [JSON Schema vs JSON Type Definition](https://ajv.js.org/guide/schema-language.html) +- [API reference](https://ajv.js.org/api.html) +- [Strict mode](https://ajv.js.org/strict-mode.html) +- [Standalone validation code](https://ajv.js.org/standalone.html) +- [Security considerations](https://ajv.js.org/security.html) +- [Command line interface](https://ajv.js.org/packages/ajv-cli.html) +- [Frequently Asked Questions](https://ajv.js.org/faq.html) + +## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) + +Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! + +Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. + +Please sponsor Ajv via: + +- [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) +- [Ajv Open Collective](https://opencollective.com/ajv) + +Thank you. + +#### Open Collective sponsors + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Performance + +Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. + +Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: + +- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place +- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster +- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) +- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) + +Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): + +[![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=62,4,1&chs=600x416&chxl=-1:|ajv|@exodus/schemasafe|is-my-json-valid|djv|@cfworker/json-schema|jsonschema/=t:100,69.2,51.5,13.1,5.1,1.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) + +## Features + +- Ajv implements JSON Schema [draft-06/07/2019-09/2020-12](http://json-schema.org/) standards (draft-04 is supported in v6): + - all validation keywords (see [JSON Schema validation keywords](https://ajv.js.org/json-schema.html)) + - [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md) extensions: + - NEW: keyword [discriminator](https://ajv.js.org/json-schema.html#discriminator). + - keyword [nullable](https://ajv.js.org/json-schema.html#nullable). + - full support of remote references (remote schemas have to be added with `addSchema` or compiled to be available) + - support of recursive references between schemas + - correct string lengths for strings with unicode pairs + - JSON Schema [formats](https://ajv.js.org/guide/formats.html) (with [ajv-formats](https://github.com/ajv-validator/ajv-formats) plugin). + - [validates schemas against meta-schema](https://ajv.js.org/api.html#api-validateschema) +- NEW: supports [JSON Type Definition](https://datatracker.ietf.org/doc/rfc8927/): + - all keywords (see [JSON Type Definition schema forms](https://ajv.js.org/json-type-definition.html)) + - meta-schema for JTD schemas + - "union" keyword and user-defined keywords (can be used inside "metadata" member of the schema) +- supports [browsers](https://ajv.js.org/guide/environments.html#browsers) and Node.js 10.x - current +- [asynchronous loading](https://ajv.js.org/guide/managing-schemas.html#asynchronous-schema-loading) of referenced schemas during compilation +- "All errors" validation mode with [option allErrors](https://ajv.js.org/options.html#allerrors) +- [error messages with parameters](https://ajv.js.org/api.html#validation-errors) describing error reasons to allow error message generation +- i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package +- [removing-additional-properties](https://ajv.js.org/guide/modifying-data.html#removing-additional-properties) +- [assigning defaults](https://ajv.js.org/guide/modifying-data.html#assigning-defaults) to missing properties and items +- [coercing data](https://ajv.js.org/guide/modifying-data.html#coercing-data-types) to the types specified in `type` keywords +- [user-defined keywords](https://ajv.js.org/guide/user-keywords.html) +- additional extension keywords with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package +- [\$data reference](https://ajv.js.org/guide/combining-schemas.html#data-reference) to use values from the validated data as values for the schema keywords +- [asynchronous validation](https://ajv.js.org/guide/async-validation.html) of user-defined formats and keywords + +## Install + +To install version 8: + +``` +npm install ajv +``` + +## Getting started + +Try it in the Node.js REPL: https://runkit.com/npm/ajv + +In JavaScript: + +```javascript +// or ESM/TypeScript import +import Ajv from "ajv" +// Node.js require: +const Ajv = require("ajv") + +const ajv = new Ajv() // options can be passed, e.g. {allErrors: true} + +const schema = { + type: "object", + properties: { + foo: {type: "integer"}, + bar: {type: "string"}, + }, + required: ["foo"], + additionalProperties: false, +} + +const data = { + foo: 1, + bar: "abc", +} + +const validate = ajv.compile(schema) +const valid = validate(data) +if (!valid) console.log(validate.errors) +``` + +Learn how to use Ajv and see more examples in the [Guide: getting started](https://ajv.js.org/guide/getting-started.html) + +## Changes history + +See [https://github.com/ajv-validator/ajv/releases](https://github.com/ajv-validator/ajv/releases) + +**Please note**: [Changes in version 8.0.0](https://github.com/ajv-validator/ajv/releases/tag/v8.0.0) + +[Version 7.0.0](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0) + +[Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). + +## Code of conduct + +Please review and follow the [Code of conduct](./CODE_OF_CONDUCT.md). + +Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team. + +## Security contact + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. + +## Open-source software support + +Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. + +## License + +[MIT](./LICENSE) diff --git a/node_modules/ajv/dist/2019.d.ts b/node_modules/ajv/dist/2019.d.ts new file mode 100644 index 000000000..e835e2b27 --- /dev/null +++ b/node_modules/ajv/dist/2019.d.ts @@ -0,0 +1,19 @@ +import type { AnySchemaObject } from "./types"; +import AjvCore, { Options } from "./core"; +export declare class Ajv2019 extends AjvCore { + constructor(opts?: Options); + _addVocabularies(): void; + _addDefaultMetaSchema(): void; + defaultMeta(): string | AnySchemaObject | undefined; +} +export default Ajv2019; +export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, ErrorObject, ErrorNoParams, } from "./types"; +export { Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions } from "./core"; +export { SchemaCxt, SchemaObjCxt } from "./compile"; +export { KeywordCxt } from "./compile/validate"; +export { DefinedError } from "./vocabularies/errors"; +export { JSONType } from "./compile/rules"; +export { JSONSchemaType } from "./types/json-schema"; +export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen"; +export { default as ValidationError } from "./runtime/validation_error"; +export { default as MissingRefError } from "./compile/ref_error"; diff --git a/node_modules/ajv/dist/2019.js b/node_modules/ajv/dist/2019.js new file mode 100644 index 000000000..bad415cc2 --- /dev/null +++ b/node_modules/ajv/dist/2019.js @@ -0,0 +1,61 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; +const core_1 = require("./core"); +const draft7_1 = require("./vocabularies/draft7"); +const dynamic_1 = require("./vocabularies/dynamic"); +const next_1 = require("./vocabularies/next"); +const unevaluated_1 = require("./vocabularies/unevaluated"); +const discriminator_1 = require("./vocabularies/discriminator"); +const json_schema_2019_09_1 = require("./refs/json-schema-2019-09"); +const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; +class Ajv2019 extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true, + }); + } + _addVocabularies() { + super._addVocabularies(); + this.addVocabulary(dynamic_1.default); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + this.addVocabulary(next_1.default); + this.addVocabulary(unevaluated_1.default); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) + return; + json_schema_2019_09_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); + } +} +exports.Ajv2019 = Ajv2019; +module.exports = exports = Ajv2019; +module.exports.Ajv2019 = Ajv2019; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = Ajv2019; +var validate_1 = require("./compile/validate"); +Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); +var codegen_1 = require("./compile/codegen"); +Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } }); +Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } }); +Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); +Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); +Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); +Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); +var validation_error_1 = require("./runtime/validation_error"); +Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } }); +var ref_error_1 = require("./compile/ref_error"); +Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } }); +//# sourceMappingURL=2019.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/2019.js.map b/node_modules/ajv/dist/2019.js.map new file mode 100644 index 000000000..7e55d9577 --- /dev/null +++ b/node_modules/ajv/dist/2019.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2019.js","sourceRoot":"","sources":["../lib/2019.ts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CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAA;IACzF,CAAC;CACF;AA/BD,0BA+BC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,OAAO,CAAA;AAClC,MAAM,CAAC,OAAO,CAAC,OAAO,GAAG,OAAO,CAAA;AAChC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,OAAO,CAAA;AAyBtB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAIlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AACnD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"} \ No newline at end of file diff --git a/node_modules/ajv/dist/2020.d.ts b/node_modules/ajv/dist/2020.d.ts new file mode 100644 index 000000000..2e56c8fcf --- /dev/null +++ b/node_modules/ajv/dist/2020.d.ts @@ -0,0 +1,19 @@ +import type { AnySchemaObject } from "./types"; +import AjvCore, { Options } from "./core"; +export declare class Ajv2020 extends AjvCore { + constructor(opts?: Options); + _addVocabularies(): void; + _addDefaultMetaSchema(): void; + defaultMeta(): string | AnySchemaObject | undefined; +} +export default Ajv2020; +export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, ErrorObject, ErrorNoParams, } from "./types"; +export { Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions } from "./core"; +export { SchemaCxt, SchemaObjCxt } from "./compile"; +export { KeywordCxt } from "./compile/validate"; +export { DefinedError } from "./vocabularies/errors"; +export { JSONType } from "./compile/rules"; +export { JSONSchemaType } from "./types/json-schema"; +export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen"; +export { default as ValidationError } from "./runtime/validation_error"; +export { default as MissingRefError } from "./compile/ref_error"; diff --git a/node_modules/ajv/dist/2020.js b/node_modules/ajv/dist/2020.js new file mode 100644 index 000000000..b3fe71cb8 --- /dev/null +++ b/node_modules/ajv/dist/2020.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; +const core_1 = require("./core"); +const draft2020_1 = require("./vocabularies/draft2020"); +const discriminator_1 = require("./vocabularies/discriminator"); +const json_schema_2020_12_1 = require("./refs/json-schema-2020-12"); +const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; +class Ajv2020 extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true, + }); + } + _addVocabularies() { + super._addVocabularies(); + draft2020_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) + return; + json_schema_2020_12_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); + } +} +exports.Ajv2020 = Ajv2020; +module.exports = exports = Ajv2020; +module.exports.Ajv2020 = Ajv2020; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = Ajv2020; +var validate_1 = require("./compile/validate"); +Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); +var codegen_1 = require("./compile/codegen"); +Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } }); +Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } }); +Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); +Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); +Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); +Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); +var validation_error_1 = require("./runtime/validation_error"); +Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } }); +var ref_error_1 = require("./compile/ref_error"); +Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } }); +//# sourceMappingURL=2020.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/2020.js.map b/node_modules/ajv/dist/2020.js.map new file mode 100644 index 000000000..2f4fda81e --- /dev/null +++ b/node_modules/ajv/dist/2020.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2020.js","sourceRoot":"","sources":["../lib/2020.ts"],"names":[],"mappings":";;;AACA,iCAAuC;AAEvC,wDAA4D;AAC5D,gEAAwD;AACxD,oEAA0D;AAE1D,MAAM,cAAc,GAAG,8CAA8C,CAAA;AAErE,MAAa,OAAQ,SAAQ,cAAO;IAClC,YAAY,OAAgB,EAAE;QAC5B,KAAK,CAAC;YACJ,GAAG,IAAI;YACP,UAAU,EAAE,IAAI;YAChB,IAAI,EAAE,IAAI;YACV,WAAW,EAAE,IAAI;SAClB,CAAC,CAAA;IACJ,CAAC;IAED,gBAAgB;QACd,KAAK,CAAC,gBAAgB,EAAE,CAAA;QACxB,mBAAqB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAA;QAC3D,IAAI,IAAI,CAAC,IAAI,CAAC,aAAa;YAAE,IAAI,CAAC,UAAU,CAAC,uBAAa,CAAC,CAAA;IAC7D,CAAC;IAED,qBAAqB;QACnB,KAAK,CAAC,qBAAqB,EAAE,CAAA;QAC7B,MAAM,EAAC,KAAK,EAAE,IAAI,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;QAC/B,IAAI,CAAC,IAAI;YAAE,OAAM;QACjB,6BAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACnC,IAAI,CAAC,IAAI,CAAC,+BAA+B,CAAC,GAAG,cAAc,CAAA;IAC7D,CAAC;IAED,WAAW;QACT,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW;YAC3B,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAA;IACzF,CAAC;CACF;AA5BD,0BA4BC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,OAAO,CAAA;AAClC,MAAM,CAAC,OAAO,CAAC,OAAO,GAAG,OAAO,CAAA;AAChC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,OAAO,CAAA;AAyBtB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAIlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AACnD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"} \ No newline at end of file diff --git a/node_modules/ajv/dist/ajv.d.ts b/node_modules/ajv/dist/ajv.d.ts new file mode 100644 index 000000000..fce3b03b8 --- /dev/null +++ b/node_modules/ajv/dist/ajv.d.ts @@ -0,0 +1,18 @@ +import type { AnySchemaObject } from "./types"; +import AjvCore from "./core"; +export declare class Ajv extends AjvCore { + _addVocabularies(): void; + _addDefaultMetaSchema(): void; + defaultMeta(): string | AnySchemaObject | undefined; +} +export default Ajv; +export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, SchemaValidateFunction, ErrorObject, ErrorNoParams, } from "./types"; +export { Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions } from "./core"; +export { SchemaCxt, SchemaObjCxt } from "./compile"; +export { KeywordCxt } from "./compile/validate"; +export { DefinedError } from "./vocabularies/errors"; +export { JSONType } from "./compile/rules"; +export { JSONSchemaType } from "./types/json-schema"; +export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen"; +export { default as ValidationError } from "./runtime/validation_error"; +export { default as MissingRefError } from "./compile/ref_error"; diff --git a/node_modules/ajv/dist/ajv.js b/node_modules/ajv/dist/ajv.js new file mode 100644 index 000000000..8eecf1bea --- /dev/null +++ b/node_modules/ajv/dist/ajv.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; +const core_1 = require("./core"); +const draft7_1 = require("./vocabularies/draft7"); +const discriminator_1 = require("./vocabularies/discriminator"); +const draft7MetaSchema = require("./refs/json-schema-draft-07.json"); +const META_SUPPORT_DATA = ["/properties"]; +const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; +class Ajv extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + const metaSchema = this.opts.$data + ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) + : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); + } +} +exports.Ajv = Ajv; +module.exports = exports = Ajv; +module.exports.Ajv = Ajv; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = Ajv; +var validate_1 = require("./compile/validate"); +Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); +var codegen_1 = require("./compile/codegen"); +Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } }); +Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } }); +Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); +Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); +Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); +Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); +var validation_error_1 = require("./runtime/validation_error"); +Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } }); +var ref_error_1 = require("./compile/ref_error"); +Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } }); +//# sourceMappingURL=ajv.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/ajv.js.map b/node_modules/ajv/dist/ajv.js.map new file mode 100644 index 000000000..42c3edf1a --- /dev/null +++ b/node_modules/ajv/dist/ajv.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ajv.js","sourceRoot":"","sources":["../lib/ajv.ts"],"names":[],"mappings":";;;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cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,GAAG,CAAA;AA0BlB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAIlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AACnD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/codegen/code.d.ts b/node_modules/ajv/dist/compile/codegen/code.d.ts new file mode 100644 index 000000000..a0220ad76 --- /dev/null +++ b/node_modules/ajv/dist/compile/codegen/code.d.ts @@ -0,0 +1,40 @@ +export declare abstract class _CodeOrName { + abstract readonly str: string; + abstract readonly names: UsedNames; + abstract toString(): string; + abstract emptyStr(): boolean; +} +export declare const IDENTIFIER: RegExp; +export declare class Name extends _CodeOrName { + readonly str: string; + constructor(s: string); + toString(): string; + emptyStr(): boolean; + get names(): UsedNames; +} +export declare class _Code extends _CodeOrName { + readonly _items: readonly CodeItem[]; + private _str?; + private _names?; + constructor(code: string | readonly CodeItem[]); + toString(): string; + emptyStr(): boolean; + get str(): string; + get names(): UsedNames; +} +export type CodeItem = Name | string | number | boolean | null; +export type UsedNames = Record; +export type Code = _Code | Name; +export type SafeExpr = Code | number | boolean | null; +export declare const nil: _Code; +type CodeArg = SafeExpr | string | undefined; +export declare function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code; +export declare function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code; +export declare function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void; +export declare function strConcat(c1: Code, c2: Code): Code; +export declare function stringify(x: unknown): Code; +export declare function safeStringify(x: unknown): string; +export declare function getProperty(key: Code | string | number): Code; +export declare function getEsmExportName(key: Code | string | number): Code; +export declare function regexpCode(rx: RegExp): Code; +export {}; diff --git a/node_modules/ajv/dist/compile/codegen/code.js b/node_modules/ajv/dist/compile/codegen/code.js new file mode 100644 index 000000000..f9ea5259a --- /dev/null +++ b/node_modules/ajv/dist/compile/codegen/code.js @@ -0,0 +1,156 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; +// eslint-disable-next-line @typescript-eslint/no-extraneous-class +class _CodeOrName { +} +exports._CodeOrName = _CodeOrName; +exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; +class Name extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) + throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } +} +exports.Name = Name; +class _Code extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) + return false; + const item = this._items[0]; + return item === "" || item === '""'; + } + get str() { + var _a; + return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, ""))); + } + get names() { + var _a; + return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => { + if (c instanceof Name) + names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}))); + } +} +exports._Code = _Code; +exports.nil = new _Code(""); +function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); +} +exports._ = _; +const plus = new _Code("+"); +function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); +} +exports.str = str; +function addCodeArg(code, arg) { + if (arg instanceof _Code) + code.push(...arg._items); + else if (arg instanceof Name) + code.push(arg); + else + code.push(interpolate(arg)); +} +exports.addCodeArg = addCodeArg; +function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== undefined) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } +} +function mergeExprItems(a, b) { + if (b === '""') + return a; + if (a === '""') + return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== '"') + return; + if (typeof b != "string") + return `${a.slice(0, -1)}${b}"`; + if (b[0] === '"') + return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) + return `"${a}${b.slice(1)}`; + return; +} +function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`; +} +exports.strConcat = strConcat; +// TODO do not allow arrays here +function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null + ? x + : safeStringify(Array.isArray(x) ? x.join(",") : x); +} +function stringify(x) { + return new _Code(safeStringify(x)); +} +exports.stringify = stringify; +function safeStringify(x) { + return JSON.stringify(x) + .replace(/\u2028/g, "\\u2028") + .replace(/\u2029/g, "\\u2029"); +} +exports.safeStringify = safeStringify; +function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`; +} +exports.getProperty = getProperty; +//Does best effort to format the name properly +function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) { + return new _Code(`${key}`); + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); +} +exports.getEsmExportName = getEsmExportName; +function regexpCode(rx) { + return new _Code(rx.toString()); +} +exports.regexpCode = regexpCode; +//# sourceMappingURL=code.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/codegen/code.js.map b/node_modules/ajv/dist/compile/codegen/code.js.map new file mode 100644 index 000000000..2fe66c15e --- /dev/null +++ b/node_modules/ajv/dist/compile/codegen/code.js.map @@ -0,0 +1 @@ +{"version":3,"file":"code.js","sourceRoot":"","sources":["../../../lib/compile/codegen/code.ts"],"names":[],"mappings":";;;AAAA,kEAAkE;AAClE,MAAsB,WAAW;CAKhC;AALD,kCAKC;AAEY,QAAA,UAAU,GAAG,uBAAuB,CAAA;AAEjD,MAAa,IAAK,SAAQ,WAAW;IAEnC,YAAY,CAAS;QACnB,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,kBAAU,CAAC,IAAI,CAAC,CAAC,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;QACpF,IAAI,CAAC,GAAG,GAAG,CAAC,CAAA;IACd,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,GAAG,CAAA;IACjB,CAAC;IAED,QAAQ;QACN,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IAAI,KAAK;QACP,OAAO,EAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,EAAC,CAAA;IACxB,CAAC;CACF;AAnBD,oBAmBC;AAED,MAAa,KAAM,SAAQ,WAAW;IAKpC,YAAY,IAAkC;QAC5C,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,MAAM,GAAG,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACxD,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,GAAG,CAAA;IACjB,CAAC;IAED,QAAQ;QACN,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO,KAAK,CAAA;QACxC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC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AAC,GAAG,GAAG,EAAE,CAAC,CAAA;IAC5B,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,iCAAiC,GAAG,iCAAiC,CAAC,CAAA;AACxF,CAAC;AALD,4CAKC;AAED,SAAgB,UAAU,CAAC,EAAU;IACnC,OAAO,IAAI,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAA;AACjC,CAAC;AAFD,gCAEC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/codegen/index.d.ts b/node_modules/ajv/dist/compile/codegen/index.d.ts new file mode 100644 index 000000000..d586a4b49 --- /dev/null +++ b/node_modules/ajv/dist/compile/codegen/index.d.ts @@ -0,0 +1,79 @@ +import type { ScopeValueSets, NameValue, ValueScope, ValueScopeName } from "./scope"; +import { _Code, Code, Name } from "./code"; +import { Scope } from "./scope"; +export { _, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code } from "./code"; +export { Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds } from "./scope"; +export type SafeExpr = Code | number | boolean | null; +export type Block = Code | (() => void); +export declare const operators: { + GT: _Code; + GTE: _Code; + LT: _Code; + LTE: _Code; + EQ: _Code; + NEQ: _Code; + NOT: _Code; + OR: _Code; + AND: _Code; + ADD: _Code; +}; +export interface CodeGenOptions { + es5?: boolean; + lines?: boolean; + ownProperties?: boolean; +} +export declare class CodeGen { + readonly _scope: Scope; + readonly _extScope: ValueScope; + readonly _values: ScopeValueSets; + private readonly _nodes; + private readonly _blockStarts; + private readonly _constants; + private readonly opts; + constructor(extScope: ValueScope, opts?: CodeGenOptions); + toString(): string; + name(prefix: string): Name; + scopeName(prefix: string): ValueScopeName; + scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name; + getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined; + scopeRefs(scopeName: Name): Code; + scopeCode(): Code; + private _def; + const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name; + let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name; + var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name; + assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen; + add(lhs: Code, rhs: SafeExpr): CodeGen; + code(c: Block | SafeExpr): CodeGen; + object(...keyValues: [Name | string, SafeExpr | string][]): _Code; + if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen; + elseIf(condition: Code | boolean): CodeGen; + else(): CodeGen; + endIf(): CodeGen; + private _for; + for(iteration: Code, forBody?: Block): CodeGen; + forRange(nameOrPrefix: Name | string, from: SafeExpr, to: SafeExpr, forBody: (index: Name) => void, varKind?: Code): CodeGen; + forOf(nameOrPrefix: Name | string, iterable: Code, forBody: (item: Name) => void, varKind?: Code): CodeGen; + forIn(nameOrPrefix: Name | string, obj: Code, forBody: (item: Name) => void, varKind?: Code): CodeGen; + endFor(): CodeGen; + label(label: Name): CodeGen; + break(label?: Code): CodeGen; + return(value: Block | SafeExpr): CodeGen; + try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen; + throw(error: Code): CodeGen; + block(body?: Block, nodeCount?: number): CodeGen; + endBlock(nodeCount?: number): CodeGen; + func(name: Name, args?: Code, async?: boolean, funcBody?: Block): CodeGen; + endFunc(): CodeGen; + optimize(n?: number): void; + private _leafNode; + private _blockNode; + private _endBlockNode; + private _elseNode; + private get _root(); + private get _currNode(); + private set _currNode(value); +} +export declare function not(x: T): T; +export declare function and(...args: Code[]): Code; +export declare function or(...args: Code[]): Code; diff --git a/node_modules/ajv/dist/compile/codegen/index.js b/node_modules/ajv/dist/compile/codegen/index.js new file mode 100644 index 000000000..a6c805af1 --- /dev/null +++ b/node_modules/ajv/dist/compile/codegen/index.js @@ -0,0 +1,697 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; +const code_1 = require("./code"); +const scope_1 = require("./scope"); +var code_2 = require("./code"); +Object.defineProperty(exports, "_", { enumerable: true, get: function () { return code_2._; } }); +Object.defineProperty(exports, "str", { enumerable: true, get: function () { return code_2.str; } }); +Object.defineProperty(exports, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } }); +Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return code_2.nil; } }); +Object.defineProperty(exports, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } }); +Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return code_2.stringify; } }); +Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } }); +Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return code_2.Name; } }); +var scope_2 = require("./scope"); +Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } }); +Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } }); +Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } }); +Object.defineProperty(exports, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } }); +exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+"), +}; +class Node { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } +} +class Def extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) + return; + if (this.rhs) + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } +} +class Assign extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) + return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; + return addExprNames(names, this.rhs); + } +} +class AssignOp extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } +} +class Label extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } +} +class Break extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + const label = this.label ? ` ${this.label}` : ""; + return `break${label};` + _n; + } +} +class Throw extends Node { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } +} +class AnyCode extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : undefined; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } +} +class ParentNode extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) + nodes.splice(i, 1, ...n); + else if (n) + nodes[i] = n; + else + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : undefined; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + // iterating backwards improves 1-pass optimization + const n = nodes[i]; + if (n.optimizeNames(names, constants)) + continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : undefined; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } +} +class BlockNode extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } +} +class Root extends ParentNode { +} +class Else extends BlockNode { +} +Else.kind = "else"; +class If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) + code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) + return this.nodes; // else is ignored here + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) + return e instanceof If ? e : e.nodes; + if (this.nodes.length) + return this; + return new If(not(cond), e instanceof If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) + return undefined; + return this; + } + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) + return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) + addNames(names, this.else.names); + return names; + } +} +If.kind = "if"; +class For extends BlockNode { +} +For.kind = "for"; +class ForLoop extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } +} +class ForRange extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + const names = addExprNames(super.names, this.from); + return addExprNames(names, this.to); + } +} +class ForIter extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } +} +class Func extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + const _async = this.async ? "async " : ""; + return `${_async}function ${this.name}(${this.args})` + super.render(opts); + } +} +Func.kind = "func"; +class Return extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } +} +Return.kind = "return"; +class Try extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) + code += this.catch.render(opts); + if (this.finally) + code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) + addNames(names, this.catch.names); + if (this.finally) + addNames(names, this.finally.names); + return names; + } +} +class Catch extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } +} +Catch.kind = "catch"; +class Finally extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } +} +Finally.kind = "finally"; +class CodeGen { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + // returns unique name in the internal scope + name(prefix) { + return this._scope.name(prefix); + } + // reserves unique name in the external scope + scopeName(prefix) { + return this._extScope.name(prefix); + } + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()); + vs.add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== undefined && constant) + this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + // `var` declaration with optional assignment + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + // assignment code + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + // `+=` code + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + // appends passed SafeExpr to code or executes Block + code(c) { + if (typeof c == "function") + c(); + else if (c !== code_1.nil) + this._leafNode(new AnyCode(c)); + return this; + } + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) + code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf(); + } + else if (thenBody) { + this.code(thenBody).endIf(); + } + else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body'); + } + return this; + } + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition) { + return this._elseNode(new If(condition)); + } + // `else` clause - only valid after `if` or `else if` clauses + else() { + return this._elseNode(new Else()); + } + // end `if` statement (needed if gen.if was used only with condition) + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) + this.code(forBody).endFor(); + return this; + } + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + // `for` statement for a range of values + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => { + this.var(name, (0, code_1._) `${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody); + } + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + // end `for` loop + endFor() { + return this._endBlockNode(For); + } + // `label` statement + label(label) { + return this._leafNode(new Label(label)); + } + // `break` statement + break(label) { + return this._leafNode(new Break(label)); + } + // `return` statement + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) + throw new Error('CodeGen: "return" should have one node'); + return this._endBlockNode(Return); + } + // `try` statement + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) + throw new Error('CodeGen: "try" without "catch" and "finally"'); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + // `throw` statement + throw(error) { + return this._leafNode(new Throw(error)); + } + // start self-balancing block + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) + this.code(body).endBlock(nodeCount); + return this; + } + // end the current self-balancing block + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === undefined) + throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + } + this._nodes.length = len; + return this; + } + // `function` heading (or definition if funcBody is passed) + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) + this.code(funcBody).endFunc(); + return this; + } + // end function definition + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || (N2 && n instanceof N2)) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) { + throw new Error('CodeGen: "else" without "if"'); + } + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } +} +exports.CodeGen = CodeGen; +function addNames(names, from) { + for (const n in from) + names[n] = (names[n] || 0) + (from[n] || 0); + return names; +} +function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; +} +function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) + return replaceName(expr); + if (!canOptimize(expr)) + return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) + c = replaceName(c); + if (c instanceof code_1._Code) + items.push(...c._items); + else + items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === undefined || names[n.str] !== 1) + return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return (e instanceof code_1._Code && + e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined)); + } +} +function subtractNames(names, from) { + for (const n in from) + names[n] = (names[n] || 0) - (from[n] || 0); +} +function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`; +} +exports.not = not; +const andCode = mappend(exports.operators.AND); +// boolean AND (&&) expression with the passed arguments +function and(...args) { + return args.reduce(andCode); +} +exports.and = and; +const orCode = mappend(exports.operators.OR); +// boolean OR (||) expression with the passed arguments +function or(...args) { + return args.reduce(orCode); +} +exports.or = or; +function mappend(op) { + return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`); +} +function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/codegen/index.js.map b/node_modules/ajv/dist/compile/codegen/index.js.map new file mode 100644 index 000000000..baef9cff5 --- /dev/null +++ b/node_modules/ajv/dist/compile/codegen/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/compile/codegen/index.ts"],"names":[],"mappings":";;;AACA,iCAA8F;AAC9F,mCAAuC;AAEvC,+BAA6F;AAArF,yFAAA,CAAC,OAAA;AAAE,2FAAA,GAAG,OAAA;AAAE,iGAAA,SAAS,OAAA;AAAE,2FAAA,GAAG,OAAA;AAAE,mGAAA,WAAW,OAAA;AAAE,iGAAA,SAAS,OAAA;AAAE,kGAAA,UAAU,OAAA;AAAE,4FAAA,IAAI,OAAA;AACxE,iCAA+F;AAAvF,8FAAA,KAAK,OAAA;AAAc,mGAAA,UAAU,OAAA;AAAE,uGAAA,cAAc,OAAA;AAAkB,iGAAA,QAAQ,OAAA;AAQlE,QAAA,SAAS,GAAG;IACvB,EAAE,EAAE,IAAI,YAAK,CAAC,GAAG,CAAC;IAClB,GAAG,EAAE,IAAI,YAAK,CAAC,IAAI,CAAC;IACpB,EAAE,EAAE,IAAI,YAAK,CAAC,GAAG,CAAC;IAClB,GAAG,EAAE,IAAI,YAAK,CAAC,IAAI,CAAC;IACpB,EAAE,EAAE,IAAI,YAAK,CAAC,KAAK,CAAC;IACpB,GAAG,EAAE,IAAI,YAAK,CAAC,KAAK,CAAC;IACrB,GAAG,EAAE,IAAI,YAAK,CAAC,GAAG,CAAC;IACnB,EAAE,EAAE,IAAI,YAAK,CAAC,IAAI,CAAC;IAC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,CAAC;AAED,SAAS,GAAG,CAAC,CAAO;IAClB,OAAO,CAAC,YAAY,WAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAA,QAAC,EAAA,IAAI,CAAC,GAAG,CAAA;AAC1C,CAAC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/codegen/scope.d.ts b/node_modules/ajv/dist/compile/codegen/scope.d.ts new file mode 100644 index 000000000..3d9530538 --- /dev/null +++ b/node_modules/ajv/dist/compile/codegen/scope.d.ts @@ -0,0 +1,79 @@ +import { Code, Name } from "./code"; +interface NameGroup { + prefix: string; + index: number; +} +export interface NameValue { + ref: ValueReference; + key?: unknown; + code?: Code; +} +export type ValueReference = unknown; +interface ScopeOptions { + prefixes?: Set; + parent?: Scope; +} +interface ValueScopeOptions extends ScopeOptions { + scope: ScopeStore; + es5?: boolean; + lines?: boolean; +} +export type ScopeStore = Record; +type ScopeValues = { + [Prefix in string]?: Map; +}; +export type ScopeValueSets = { + [Prefix in string]?: Set; +}; +export declare enum UsedValueState { + Started = 0, + Completed = 1 +} +export type UsedScopeValues = { + [Prefix in string]?: Map; +}; +export declare const varKinds: { + const: Name; + let: Name; + var: Name; +}; +export declare class Scope { + protected readonly _names: { + [Prefix in string]?: NameGroup; + }; + protected readonly _prefixes?: Set; + protected readonly _parent?: Scope; + constructor({ prefixes, parent }?: ScopeOptions); + toName(nameOrPrefix: Name | string): Name; + name(prefix: string): Name; + protected _newName(prefix: string): string; + private _nameGroup; +} +interface ScopePath { + property: string; + itemIndex: number; +} +export declare class ValueScopeName extends Name { + readonly prefix: string; + value?: NameValue; + scopePath?: Code; + constructor(prefix: string, nameStr: string); + setValue(value: NameValue, { property, itemIndex }: ScopePath): void; +} +interface VSOptions extends ValueScopeOptions { + _n: Code; +} +export declare class ValueScope extends Scope { + protected readonly _values: ScopeValues; + protected readonly _scope: ScopeStore; + readonly opts: VSOptions; + constructor(opts: ValueScopeOptions); + get(): ScopeStore; + name(prefix: string): ValueScopeName; + value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName; + getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined; + scopeRefs(scopeName: Name, values?: ScopeValues | ScopeValueSets): Code; + scopeCode(values?: ScopeValues | ScopeValueSets, usedValues?: UsedScopeValues, getCode?: (n: ValueScopeName) => Code | undefined): Code; + private _reduceValues; +} +export {}; diff --git a/node_modules/ajv/dist/compile/codegen/scope.js b/node_modules/ajv/dist/compile/codegen/scope.js new file mode 100644 index 000000000..4bc7794e3 --- /dev/null +++ b/node_modules/ajv/dist/compile/codegen/scope.js @@ -0,0 +1,143 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; +const code_1 = require("./code"); +class ValueError extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } +} +var UsedValueState; +(function (UsedValueState) { + UsedValueState[UsedValueState["Started"] = 0] = "Started"; + UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; +})(UsedValueState || (exports.UsedValueState = UsedValueState = {})); +exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var"), +}; +class Scope { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + } + return (this._names[prefix] = { prefix, index: 0 }); + } +} +exports.Scope = Scope; +class ValueScopeName extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`; + } +} +exports.ValueScopeName = ValueScopeName; +const line = (0, code_1._) `\n`; +class ValueScope extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === undefined) + throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) + return _name; + } + else { + vs = this._values[prefix] = new Map(); + } + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { property: prefix, itemIndex }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) + return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === undefined) + throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._) `${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === undefined) + throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) + continue; + const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map()); + vs.forEach((name) => { + if (nameSet.has(name)) + return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`; + } + else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) { + code = (0, code_1._) `${code}${c}${this.opts._n}`; + } + else { + throw new ValueError(name); + } + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } +} +exports.ValueScope = ValueScope; +//# sourceMappingURL=scope.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/codegen/scope.js.map b/node_modules/ajv/dist/compile/codegen/scope.js.map new file mode 100644 index 000000000..911769f87 --- /dev/null +++ b/node_modules/ajv/dist/compile/codegen/scope.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scope.js","sourceRoot":"","sources":["../../../lib/compile/codegen/scope.ts"],"names":[],"mappings":";;;AAAA,iCAAyC;AAezC,MAAM,UAAW,SAAQ,KAAK;IAE5B,YAAY,IAAoB;QAC9B,KAAK,CAAC,uBAAuB,IAAI,cAAc,CAAC,CAAA;QAChD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAA;IACzB,CAAC;CACF;AAuBD,IAAY,cAGX;AAHD,WAAY,cAAc;IACxB,yDAAO,CAAA;IACP,6DAAS,CAAA;AACX,CAAC,EAHW,cAAc,8BAAd,cAAc,QAGzB;AAMY,QAAA,QAAQ,GAAG;IACtB,KAAK,EAAE,IAAI,WAAI,CAAC,OAAO,CAAC;IACxB,GAAG,EAAE,IAAI,WAAI,CAAC,KAAK,CAAC;IACpB,GAAG,EAAE,IAAI,WAAI,CAAC,KAAK,CAAC;CACrB,CAAA;AAED,MAAa,KAAK;IAKhB,YAAY,EAAC,QAAQ,EAAE,MAAM,KAAkB,EAAE;QAJ9B,WAAM,GAAqC,EAAE,CAAA;QAK9D,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;QACzB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAA;IACvB,CAAC;IAED,MAAM,CAAC,YAA2B;QAChC,OAAO,YAA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AA,GAAG,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAA;gBACtC,CAAC;qBAAM,CAAC;oBACN,MAAM,IAAI,UAAU,CAAC,IAAI,CAAC,CAAA;gBAC5B,CAAC;gBACD,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,SAAS,CAAC,CAAA;YAC7C,CAAC,CAAC,CAAA;QACJ,CAAC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAjGD,gCAiGC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/errors.d.ts b/node_modules/ajv/dist/compile/errors.d.ts new file mode 100644 index 000000000..74eef7e21 --- /dev/null +++ b/node_modules/ajv/dist/compile/errors.d.ts @@ -0,0 +1,13 @@ +import type { KeywordErrorCxt, KeywordErrorDefinition } from "../types"; +import { CodeGen, Code, Name } from "./codegen"; +export declare const keywordError: KeywordErrorDefinition; +export declare const keyword$DataError: KeywordErrorDefinition; +export interface ErrorPaths { + instancePath?: Code; + schemaPath?: string; + parentSchema?: boolean; +} +export declare function reportError(cxt: KeywordErrorCxt, error?: KeywordErrorDefinition, errorPaths?: ErrorPaths, overrideAllErrors?: boolean): void; +export declare function reportExtraError(cxt: KeywordErrorCxt, error?: KeywordErrorDefinition, errorPaths?: ErrorPaths): void; +export declare function resetErrorsCount(gen: CodeGen, errsCount: Name): void; +export declare function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }: KeywordErrorCxt): void; diff --git a/node_modules/ajv/dist/compile/errors.js b/node_modules/ajv/dist/compile/errors.js new file mode 100644 index 000000000..24d721d80 --- /dev/null +++ b/node_modules/ajv/dist/compile/errors.js @@ -0,0 +1,123 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; +const codegen_1 = require("./codegen"); +const util_1 = require("./util"); +const names_1 = require("./names"); +exports.keywordError = { + message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`, +}; +exports.keyword$DataError = { + message: ({ keyword, schemaType }) => schemaType + ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)` + : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`, +}; +function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) { + addError(gen, errObj); + } + else { + returnErrors(it, (0, codegen_1._) `[${errObj}]`); + } +} +exports.reportError = reportError; +function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + addError(gen, errObj); + if (!(compositeRule || allErrors)) { + returnErrors(it, names_1.default.vErrors); + } +} +exports.reportExtraError = reportExtraError; +function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); +} +exports.resetErrorsCount = resetErrorsCount; +function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) { + /* istanbul ignore if */ + if (errsCount === undefined) + throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._) `${err}.schema`, schemaValue); + gen.assign((0, codegen_1._) `${err}.data`, data); + } + }); +} +exports.extendErrors = extendErrors; +function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._) `${names_1.default.errors}++`); +} +function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) { + gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`); + } + else { + gen.assign((0, codegen_1._) `${validateName}.errors`, errs); + gen.return(false); + } +} +const E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema"), +}; +function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) + return (0, codegen_1._) `{}`; + return errorObject(cxt, error, errorPaths); +} +function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths), + ]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); +} +function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath + ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` + : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; +} +function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`; + if (schemaPath) { + schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + } + return [E.schemaPath, schPath]; +} +function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]); + if (opts.messages) { + keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + } + if (opts.verbose) { + keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + } + if (propertyName) + keyValues.push([E.propertyName, propertyName]); +} +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/errors.js.map b/node_modules/ajv/dist/compile/errors.js.map new file mode 100644 index 000000000..ea08e4e31 --- /dev/null +++ b/node_modules/ajv/dist/compile/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../lib/compile/errors.ts"],"names":[],"mappings":";;;AAEA,uCAAgE;AAEhE,iCAAyC;AACzC,mCAAuB;AAEV,QAAA,YAAY,GAA2B;IAClD,OAAO,EAAE,CAAC,EAAC,OAAO,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,cAAc,OAAO,sBAAsB;CACvE,CAAA;AAEY,QAAA,iBAAiB,GAA2B;IACvD,OAAO,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CACjC,UAAU;QACR,CAAC,CAAC,IAAA,aAAG,EAAA,IAAI,OAAO,qBAAqB,UAAU,UAAU;QACzD,CAAC,CAAC,IAAA,aAAG,EAAA,IAAI,OAAO,8BAA8B;CACnD,CAAA;AAQD,SAAgB,WAAW,CACzB,GAAoB,EACpB,QAAgC,oBAAY,EAC5C,UAAuB,EACvB,iBAA2B;IAE3B,MAAM,EAAC,EAAE,EAAC,GAAG,GAAG,CAAA;IAChB,MAAM,EAAC,GAAG,EAAE,aAAa,EAAE,SAAS,EAAC,GAAG,E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AAE,WAAW,CAAC,EACvB,CAAC,CAAC,CAAC,YAAY,EAAE,IAAA,WAAC,EAAA,GAAG,YAAY,GAAG,UAAU,EAAE,CAAC,EACjD,CAAC,eAAC,CAAC,IAAI,EAAE,IAAI,CAAC,CACf,CAAA;IACH,CAAC;IACD,IAAI,YAAY;QAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC,CAAA;AAClE,CAAC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/index.d.ts b/node_modules/ajv/dist/compile/index.d.ts new file mode 100644 index 000000000..2809353d7 --- /dev/null +++ b/node_modules/ajv/dist/compile/index.d.ts @@ -0,0 +1,80 @@ +import type { AnySchema, AnySchemaObject, AnyValidateFunction, EvaluatedProperties, EvaluatedItems } from "../types"; +import type Ajv from "../core"; +import type { InstanceOptions } from "../core"; +import { CodeGen, Name, Code, ValueScopeName } from "./codegen"; +import { LocalRefs } from "./resolve"; +import { JSONType } from "./rules"; +export type SchemaRefs = { + [Ref in string]?: SchemaEnv | AnySchema; +}; +export interface SchemaCxt { + readonly gen: CodeGen; + readonly allErrors?: boolean; + readonly data: Name; + readonly parentData: Name; + readonly parentDataProperty: Code | number; + readonly dataNames: Name[]; + readonly dataPathArr: (Code | number)[]; + readonly dataLevel: number; + dataTypes: JSONType[]; + definedProperties: Set; + readonly topSchemaRef: Code; + readonly validateName: Name; + evaluated?: Name; + readonly ValidationError?: Name; + readonly schema: AnySchema; + readonly schemaEnv: SchemaEnv; + readonly rootId: string; + baseId: string; + readonly schemaPath: Code; + readonly errSchemaPath: string; + readonly errorPath: Code; + readonly propertyName?: Name; + readonly compositeRule?: boolean; + props?: EvaluatedProperties | Name; + items?: EvaluatedItems | Name; + jtdDiscriminator?: string; + jtdMetadata?: boolean; + readonly createErrors?: boolean; + readonly opts: InstanceOptions; + readonly self: Ajv; +} +export interface SchemaObjCxt extends SchemaCxt { + readonly schema: AnySchemaObject; +} +interface SchemaEnvArgs { + readonly schema: AnySchema; + readonly schemaId?: "$id" | "id"; + readonly root?: SchemaEnv; + readonly baseId?: string; + readonly schemaPath?: string; + readonly localRefs?: LocalRefs; + readonly meta?: boolean; +} +export declare class SchemaEnv implements SchemaEnvArgs { + readonly schema: AnySchema; + readonly schemaId?: "$id" | "id"; + readonly root: SchemaEnv; + baseId: string; + schemaPath?: string; + localRefs?: LocalRefs; + readonly meta?: boolean; + readonly $async?: boolean; + readonly refs: SchemaRefs; + readonly dynamicAnchors: { + [Ref in string]?: true; + }; + validate?: AnyValidateFunction; + validateName?: ValueScopeName; + serialize?: (data: unknown) => string; + serializeName?: ValueScopeName; + parse?: (data: string) => unknown; + parseName?: ValueScopeName; + constructor(env: SchemaEnvArgs); +} +export declare function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv; +export declare function resolveRef(this: Ajv, root: SchemaEnv, baseId: string, ref: string): AnySchema | SchemaEnv | undefined; +export declare function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void; +export declare function resolveSchema(this: Ajv, root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it +ref: string): SchemaEnv | undefined; +export {}; diff --git a/node_modules/ajv/dist/compile/index.js b/node_modules/ajv/dist/compile/index.js new file mode 100644 index 000000000..9e42a5588 --- /dev/null +++ b/node_modules/ajv/dist/compile/index.js @@ -0,0 +1,242 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; +const codegen_1 = require("./codegen"); +const validation_error_1 = require("../runtime/validation_error"); +const names_1 = require("./names"); +const resolve_1 = require("./resolve"); +const util_1 = require("./util"); +const validate_1 = require("./validate"); +class SchemaEnv { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") + schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } +} +exports.SchemaEnv = SchemaEnv; +// let codeSize = 0 +// let nodeCount = 0 +// Compiles schema in SchemaEnv +function compileSchema(sch) { + // TODO refactor - remove compilations + const _sch = getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + let _ValidationError; + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`, + }); + } + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true + ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } + : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._) `""`, + opts: this.opts, + self: this, + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + // gen.optimize(1) + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) + if (this.opts.code.process) + sourceCode = this.opts.code.process(sourceCode, sch); + // console.log("\n\n\n *** \n", sourceCode) + const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); + const validate = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) + validate.$async = true; + if (this.opts.code.source === true) { + validate.source = { validateName, validateCode, scopeValues: gen._values }; + } + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? undefined : props, + items: items instanceof codegen_1.Name ? undefined : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name, + }; + if (validate.source) + validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } + catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) + this.logger.error("Error compiling schema, function code:", sourceCode); + // console.log("\n\n\n *** \n", sourceCode, this.opts) + throw e; + } + finally { + this._compilations.delete(sch); + } +} +exports.compileSchema = compileSchema; +function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) + return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === undefined) { + const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv + const { schemaId } = this.opts; + if (schema) + _sch = new SchemaEnv({ schema, schemaId, root, baseId }); + } + if (_sch === undefined) + return; + return (root.refs[ref] = inlineOrCompile.call(this, _sch)); +} +exports.resolveRef = resolveRef; +function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) + return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); +} +// Index of schema compilation in the currently compiled list +function getCompilingSchema(schEnv) { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) + return sch; + } +} +exports.getCompilingSchema = getCompilingSchema; +function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; +} +// resolve and compile the references ($ref) +// TODO returns AnySchemaObject (if the schema can be inlined) or validation function +function resolve(root, // information about the root schema for the current schema +ref // reference to resolve +) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") + ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); +} +// Resolve schema, its root and baseId +function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it +ref // reference to resolve +) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined); + // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p, root); + } + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") + return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") + return; + if (!schOrRef.validate) + compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ schema, schemaId, root, baseId }); + } + return getJsonPointer.call(this, p, schOrRef); +} +exports.resolveSchema = resolveSchema; +const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions", +]); +function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") + return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") + return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === undefined) + return; + schema = partSchema; + // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def? + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + // even though resolution failed we need to return SchemaEnv to throw exception + // so that compileAsync loads missing schema. + const { schemaId } = this.opts; + env = env || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env.schema !== env.root.schema) + return env; + return undefined; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/index.js.map b/node_modules/ajv/dist/compile/index.js.map new file mode 100644 index 000000000..22dcc0bb6 --- /dev/null +++ b/node_modules/ajv/dist/compile/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/compile/index.ts"],"names":[],"mappings":";;;AAUA,uCAAgF;AAChF,kEAAyD;AACzD,mCAAuB;AACvB,uCAAkG;AAClG,iCAA6D;AAC7D,yCAA+C;AA0D/C,MAAa,SAAS;IAkBpB,YAAY,GAAkB;;QATrB,SAAI,GAAe,EAAE,CAAA;QACrB,mBAAc,GAA6B,EAAE,CAAA;QASpD,IAAI,MAAmC,CAAA;QACvC,IAAI,OAAO,GAAG,CAAC,MAAM,IAAI,QAAQ;YAAE,MAAM,GAAG,GAAG,CAAC,MAAM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;QAC3D,CAAC;IACH,CAAC;IACD,IAAI,GAA0B,CAAA;IAC9B,IAAI,OAAO,MAAM,IAAI,SAAS,IAAI,MAAM,CAAC,IAAI,IAAI,CAAC,IAAA,2BAAoB,EAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3F,MAAM,IAAI,GAAG,IAAA,oBAAU,EAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,CAAA;QACnE,GAAG,GAAG,aAAa,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;IAC5C,CAAC;IACD,+EAA+E;IAC/E,6CAA6C;IAC7C,MAAM,EAAC,QAAQ,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;IAC5B,GAAG,GAAG,GAAG,IAAI,IAAI,SAAS,CAAC,EAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAC,CAAC,CAAA;IAC5D,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,CAAC,IAAI,CAAC,MAAM;QAAE,OAAO,GAAG,CAAA;IAC9C,OAAO,SAAS,CAAA;AAClB,CAAC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/jtd/parse.d.ts b/node_modules/ajv/dist/compile/jtd/parse.d.ts new file mode 100644 index 000000000..618c64aea --- /dev/null +++ b/node_modules/ajv/dist/compile/jtd/parse.d.ts @@ -0,0 +1,4 @@ +import type Ajv from "../../core"; +import { SchemaObjectMap } from "./types"; +import { SchemaEnv } from ".."; +export default function compileParser(this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap): SchemaEnv; diff --git a/node_modules/ajv/dist/compile/jtd/parse.js b/node_modules/ajv/dist/compile/jtd/parse.js new file mode 100644 index 000000000..8fc94fd0e --- /dev/null +++ b/node_modules/ajv/dist/compile/jtd/parse.js @@ -0,0 +1,350 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const types_1 = require("./types"); +const __1 = require(".."); +const codegen_1 = require("../codegen"); +const ref_error_1 = require("../ref_error"); +const names_1 = require("../names"); +const code_1 = require("../../vocabularies/code"); +const ref_1 = require("../../vocabularies/jtd/ref"); +const type_1 = require("../../vocabularies/jtd/type"); +const parseJson_1 = require("../../runtime/parseJson"); +const util_1 = require("../util"); +const timestamp_1 = require("../../runtime/timestamp"); +const genParse = { + elements: parseElements, + values: parseValues, + discriminator: parseDiscriminator, + properties: parseProperties, + optionalProperties: parseProperties, + enum: parseEnum, + type: parseType, + ref: parseRef, +}; +function compileParser(sch, definitions) { + const _sch = __1.getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + const parseName = gen.scopeName("parse"); + const cxt = { + self: this, + gen, + schema: sch.schema, + schemaEnv: sch, + definitions, + data: names_1.default.data, + parseName, + char: gen.name("c"), + }; + let sourceCode; + try { + this._compilations.add(sch); + sch.parseName = parseName; + parserFunction(cxt); + gen.optimize(this.opts.code.optimize); + const parseFuncCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${parseFuncCode}`; + const makeParse = new Function(`${names_1.default.scope}`, sourceCode); + const parse = makeParse(this.scope.get()); + this.scope.value(parseName, { ref: parse }); + sch.parse = parse; + } + catch (e) { + if (sourceCode) + this.logger.error("Error compiling parser, function code:", sourceCode); + delete sch.parse; + delete sch.parseName; + throw e; + } + finally { + this._compilations.delete(sch); + } + return sch; +} +exports.default = compileParser; +const undef = (0, codegen_1._) `undefined`; +function parserFunction(cxt) { + const { gen, parseName, char } = cxt; + gen.func(parseName, (0, codegen_1._) `${names_1.default.json}, ${names_1.default.jsonPos}, ${names_1.default.jsonPart}`, false, () => { + gen.let(names_1.default.data); + gen.let(char); + gen.assign((0, codegen_1._) `${parseName}.message`, undef); + gen.assign((0, codegen_1._) `${parseName}.position`, undef); + gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${names_1.default.jsonPos} || 0`); + gen.const(names_1.default.jsonLen, (0, codegen_1._) `${names_1.default.json}.length`); + parseCode(cxt); + skipWhitespace(cxt); + gen.if(names_1.default.jsonPart, () => { + gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos); + gen.return(names_1.default.data); + }); + gen.if((0, codegen_1._) `${names_1.default.jsonPos} === ${names_1.default.jsonLen}`, () => gen.return(names_1.default.data)); + jsonSyntaxError(cxt); + }); +} +function parseCode(cxt) { + let form; + for (const key of types_1.jtdForms) { + if (key in cxt.schema) { + form = key; + break; + } + } + if (form) + parseNullable(cxt, genParse[form]); + else + parseEmpty(cxt); +} +const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError)); +function parseNullable(cxt, parseForm) { + const { gen, schema, data } = cxt; + if (!schema.nullable) + return parseForm(cxt); + tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null)); +} +function parseElements(cxt) { + const { gen, schema, data } = cxt; + parseToken(cxt, "["); + const ix = gen.let("i", 0); + gen.assign(data, (0, codegen_1._) `[]`); + parseItems(cxt, "]", () => { + const el = gen.let("el"); + parseCode({ ...cxt, schema: schema.elements, data: el }); + gen.assign((0, codegen_1._) `${data}[${ix}++]`, el); + }); +} +function parseValues(cxt) { + const { gen, schema, data } = cxt; + parseToken(cxt, "{"); + gen.assign(data, (0, codegen_1._) `{}`); + parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values)); +} +function parseItems(cxt, endToken, block) { + tryParseItems(cxt, endToken, block); + parseToken(cxt, endToken); +} +function tryParseItems(cxt, endToken, block) { + const { gen } = cxt; + gen.for((0, codegen_1._) `;${names_1.default.jsonPos}<${names_1.default.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => { + block(); + tryParseToken(cxt, ",", () => gen.break(), hasItem); + }); + function hasItem() { + tryParseToken(cxt, endToken, () => { }, jsonSyntaxError); + } +} +function parseKeyValue(cxt, schema) { + const { gen } = cxt; + const key = gen.let("key"); + parseString({ ...cxt, data: key }); + parseToken(cxt, ":"); + parsePropertyValue(cxt, key, schema); +} +function parseDiscriminator(cxt) { + const { gen, data, schema } = cxt; + const { discriminator, mapping } = schema; + parseToken(cxt, "{"); + gen.assign(data, (0, codegen_1._) `{}`); + const startPos = gen.const("pos", names_1.default.jsonPos); + const value = gen.let("value"); + const tag = gen.let("tag"); + tryParseItems(cxt, "}", () => { + const key = gen.let("key"); + parseString({ ...cxt, data: key }); + parseToken(cxt, ":"); + gen.if((0, codegen_1._) `${key} === ${discriminator}`, () => { + parseString({ ...cxt, data: tag }); + gen.assign((0, codegen_1._) `${data}[${key}]`, tag); + gen.break(); + }, () => parseEmpty({ ...cxt, data: value }) // can be discarded/skipped + ); + }); + gen.assign(names_1.default.jsonPos, startPos); + gen.if((0, codegen_1._) `${tag} === undefined`); + parsingError(cxt, (0, codegen_1.str) `discriminator tag not found`); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); + parseSchemaProperties({ ...cxt, schema: mapping[tagValue] }, discriminator); + } + gen.else(); + parsingError(cxt, (0, codegen_1.str) `discriminator value not in schema`); + gen.endIf(); +} +function parseProperties(cxt) { + const { gen, data } = cxt; + parseToken(cxt, "{"); + gen.assign(data, (0, codegen_1._) `{}`); + parseSchemaProperties(cxt); +} +function parseSchemaProperties(cxt, discriminator) { + const { gen, schema, data } = cxt; + const { properties, optionalProperties, additionalProperties } = schema; + parseItems(cxt, "}", () => { + const key = gen.let("key"); + parseString({ ...cxt, data: key }); + parseToken(cxt, ":"); + gen.if(false); + parseDefinedProperty(cxt, key, properties); + parseDefinedProperty(cxt, key, optionalProperties); + if (discriminator) { + gen.elseIf((0, codegen_1._) `${key} === ${discriminator}`); + const tag = gen.let("tag"); + parseString({ ...cxt, data: tag }); // can be discarded, it is already assigned + } + gen.else(); + if (additionalProperties) { + parseEmpty({ ...cxt, data: (0, codegen_1._) `${data}[${key}]` }); + } + else { + parsingError(cxt, (0, codegen_1.str) `property ${key} not allowed`); + } + gen.endIf(); + }); + if (properties) { + const hasProp = (0, code_1.hasPropFunc)(gen); + const allProps = (0, codegen_1.and)(...Object.keys(properties).map((p) => (0, codegen_1._) `${hasProp}.call(${data}, ${p})`)); + gen.if((0, codegen_1.not)(allProps), () => parsingError(cxt, (0, codegen_1.str) `missing required properties`)); + } +} +function parseDefinedProperty(cxt, key, schemas = {}) { + const { gen } = cxt; + for (const prop in schemas) { + gen.elseIf((0, codegen_1._) `${key} === ${prop}`); + parsePropertyValue(cxt, key, schemas[prop]); + } +} +function parsePropertyValue(cxt, key, schema) { + parseCode({ ...cxt, schema, data: (0, codegen_1._) `${cxt.data}[${key}]` }); +} +function parseType(cxt) { + const { gen, schema, data, self } = cxt; + switch (schema.type) { + case "boolean": + parseBoolean(cxt); + break; + case "string": + parseString(cxt); + break; + case "timestamp": { + parseString(cxt); + const vts = (0, util_1.useFunc)(gen, timestamp_1.default); + const { allowDate, parseDate } = self.opts; + const notValid = allowDate ? (0, codegen_1._) `!${vts}(${data}, true)` : (0, codegen_1._) `!${vts}(${data})`; + const fail = parseDate + ? (0, codegen_1.or)(notValid, (0, codegen_1._) `(${data} = new Date(${data}), false)`, (0, codegen_1._) `isNaN(${data}.valueOf())`) + : notValid; + gen.if(fail, () => parsingError(cxt, (0, codegen_1.str) `invalid timestamp`)); + break; + } + case "float32": + case "float64": + parseNumber(cxt); + break; + default: { + const t = schema.type; + if (!self.opts.int32range && (t === "int32" || t === "uint32")) { + parseNumber(cxt, 16); // 2 ** 53 - max safe integer + if (t === "uint32") { + gen.if((0, codegen_1._) `${data} < 0`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`)); + } + } + else { + const [min, max, maxDigits] = type_1.intRange[t]; + parseNumber(cxt, maxDigits); + gen.if((0, codegen_1._) `${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`)); + } + } + } +} +function parseString(cxt) { + parseToken(cxt, '"'); + parseWith(cxt, parseJson_1.parseJsonString); +} +function parseEnum(cxt) { + const { gen, data, schema } = cxt; + const enumSch = schema.enum; + parseToken(cxt, '"'); + // TODO loopEnum + gen.if(false); + for (const value of enumSch) { + const valueStr = JSON.stringify(value).slice(1); // remove starting quote + gen.elseIf((0, codegen_1._) `${jsonSlice(valueStr.length)} === ${valueStr}`); + gen.assign(data, (0, codegen_1.str) `${value}`); + gen.add(names_1.default.jsonPos, valueStr.length); + } + gen.else(); + jsonSyntaxError(cxt); + gen.endIf(); +} +function parseNumber(cxt, maxDigits) { + const { gen } = cxt; + skipWhitespace(cxt); + gen.if((0, codegen_1._) `"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJson_1.parseJsonNumber, maxDigits)); +} +function parseBooleanToken(bool, fail) { + return (cxt) => { + const { gen, data } = cxt; + tryParseToken(cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool)); + }; +} +function parseRef(cxt) { + const { gen, self, definitions, schema, schemaEnv } = cxt; + const { ref } = schema; + const refSchema = definitions[ref]; + if (!refSchema) + throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`); + if (!(0, ref_1.hasRef)(refSchema)) + return parseCode({ ...cxt, schema: refSchema }); + const { root } = schemaEnv; + const sch = compileParser.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions); + partialParse(cxt, getParser(gen, sch), true); +} +function getParser(gen, sch) { + return sch.parse + ? gen.scopeValue("parse", { ref: sch.parse }) + : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.parse`; +} +function parseEmpty(cxt) { + parseWith(cxt, parseJson_1.parseJson); +} +function parseWith(cxt, parseFunc, args) { + partialParse(cxt, (0, util_1.useFunc)(cxt.gen, parseFunc), args); +} +function partialParse(cxt, parseFunc, args) { + const { gen, data } = cxt; + gen.assign(data, (0, codegen_1._) `${parseFunc}(${names_1.default.json}, ${names_1.default.jsonPos}${args ? (0, codegen_1._) `, ${args}` : codegen_1.nil})`); + gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${parseFunc}.position`); + gen.if((0, codegen_1._) `${data} === undefined`, () => parsingError(cxt, (0, codegen_1._) `${parseFunc}.message`)); +} +function parseToken(cxt, tok) { + tryParseToken(cxt, tok, jsonSyntaxError); +} +function tryParseToken(cxt, tok, fail, success) { + const { gen } = cxt; + const n = tok.length; + skipWhitespace(cxt); + gen.if((0, codegen_1._) `${jsonSlice(n)} === ${tok}`, () => { + gen.add(names_1.default.jsonPos, n); + success === null || success === void 0 ? void 0 : success(cxt); + }, () => fail(cxt)); +} +function skipWhitespace({ gen, char: c }) { + gen.code((0, codegen_1._) `while((${c}=${names_1.default.json}[${names_1.default.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${names_1.default.jsonPos}++;`); +} +function jsonSlice(len) { + return len === 1 + ? (0, codegen_1._) `${names_1.default.json}[${names_1.default.jsonPos}]` + : (0, codegen_1._) `${names_1.default.json}.slice(${names_1.default.jsonPos}, ${names_1.default.jsonPos}+${len})`; +} +function jsonSyntaxError(cxt) { + parsingError(cxt, (0, codegen_1._) `"unexpected token " + ${names_1.default.json}[${names_1.default.jsonPos}]`); +} +function parsingError({ gen, parseName }, msg) { + gen.assign((0, codegen_1._) `${parseName}.message`, msg); + gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos); + gen.return(undef); +} +//# sourceMappingURL=parse.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/jtd/parse.js.map b/node_modules/ajv/dist/compile/jtd/parse.js.map new file mode 100644 index 000000000..87bd922ae --- /dev/null +++ b/node_modules/ajv/dist/compile/jtd/parse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parse.js","sourceRoot":"","sources":["../../../lib/compile/jtd/parse.ts"],"names":[],"mappings":";;AAEA,mCAA0D;AAC1D,0BAAgD;AAChD,wCAAmF;AACnF,4CAA0C;AAC1C,oCAAwB;AACxB,kDAAmD;AACnD,oDAAiD;AACj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/jtd/serialize.d.ts new file mode 100644 index 000000000..b0413d716 --- /dev/null +++ b/node_modules/ajv/dist/compile/jtd/serialize.d.ts @@ -0,0 +1,4 @@ +import type Ajv from "../../core"; +import { SchemaObjectMap } from "./types"; +import { SchemaEnv } from ".."; +export default function compileSerializer(this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap): SchemaEnv; diff --git a/node_modules/ajv/dist/compile/jtd/serialize.js b/node_modules/ajv/dist/compile/jtd/serialize.js new file mode 100644 index 000000000..341c50078 --- /dev/null +++ b/node_modules/ajv/dist/compile/jtd/serialize.js @@ -0,0 +1,229 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const types_1 = require("./types"); +const __1 = require(".."); +const codegen_1 = require("../codegen"); +const ref_error_1 = require("../ref_error"); +const names_1 = require("../names"); +const code_1 = require("../../vocabularies/code"); +const ref_1 = require("../../vocabularies/jtd/ref"); +const util_1 = require("../util"); +const quote_1 = require("../../runtime/quote"); +const genSerialize = { + elements: serializeElements, + values: serializeValues, + discriminator: serializeDiscriminator, + properties: serializeProperties, + optionalProperties: serializeProperties, + enum: serializeString, + type: serializeType, + ref: serializeRef, +}; +function compileSerializer(sch, definitions) { + const _sch = __1.getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + const serializeName = gen.scopeName("serialize"); + const cxt = { + self: this, + gen, + schema: sch.schema, + schemaEnv: sch, + definitions, + data: names_1.default.data, + }; + let sourceCode; + try { + this._compilations.add(sch); + sch.serializeName = serializeName; + gen.func(serializeName, names_1.default.data, false, () => { + gen.let(names_1.default.json, (0, codegen_1.str) ``); + serializeCode(cxt); + gen.return(names_1.default.json); + }); + gen.optimize(this.opts.code.optimize); + const serializeFuncCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${serializeFuncCode}`; + const makeSerialize = new Function(`${names_1.default.scope}`, sourceCode); + const serialize = makeSerialize(this.scope.get()); + this.scope.value(serializeName, { ref: serialize }); + sch.serialize = serialize; + } + catch (e) { + if (sourceCode) + this.logger.error("Error compiling serializer, function code:", sourceCode); + delete sch.serialize; + delete sch.serializeName; + throw e; + } + finally { + this._compilations.delete(sch); + } + return sch; +} +exports.default = compileSerializer; +function serializeCode(cxt) { + let form; + for (const key of types_1.jtdForms) { + if (key in cxt.schema) { + form = key; + break; + } + } + serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty); +} +function serializeNullable(cxt, serializeForm) { + const { gen, schema, data } = cxt; + if (!schema.nullable) + return serializeForm(cxt); + gen.if((0, codegen_1._) `${data} === undefined || ${data} === null`, () => gen.add(names_1.default.json, (0, codegen_1._) `"null"`), () => serializeForm(cxt)); +} +function serializeElements(cxt) { + const { gen, schema, data } = cxt; + gen.add(names_1.default.json, (0, codegen_1.str) `[`); + const first = gen.let("first", true); + gen.forOf("el", data, (el) => { + addComma(cxt, first); + serializeCode({ ...cxt, schema: schema.elements, data: el }); + }); + gen.add(names_1.default.json, (0, codegen_1.str) `]`); +} +function serializeValues(cxt) { + const { gen, schema, data } = cxt; + gen.add(names_1.default.json, (0, codegen_1.str) `{`); + const first = gen.let("first", true); + gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first)); + gen.add(names_1.default.json, (0, codegen_1.str) `}`); +} +function serializeKeyValue(cxt, key, schema, first) { + const { gen, data } = cxt; + addComma(cxt, first); + serializeString({ ...cxt, data: key }); + gen.add(names_1.default.json, (0, codegen_1.str) `:`); + const value = gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`); + serializeCode({ ...cxt, schema, data: value }); +} +function serializeDiscriminator(cxt) { + const { gen, schema, data } = cxt; + const { discriminator } = schema; + gen.add(names_1.default.json, (0, codegen_1.str) `{${JSON.stringify(discriminator)}:`); + const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(discriminator)}`); + serializeString({ ...cxt, data: tag }); + gen.if(false); + for (const tagValue in schema.mapping) { + gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); + const sch = schema.mapping[tagValue]; + serializeSchemaProperties({ ...cxt, schema: sch }, discriminator); + } + gen.endIf(); + gen.add(names_1.default.json, (0, codegen_1.str) `}`); +} +function serializeProperties(cxt) { + const { gen } = cxt; + gen.add(names_1.default.json, (0, codegen_1.str) `{`); + serializeSchemaProperties(cxt); + gen.add(names_1.default.json, (0, codegen_1.str) `}`); +} +function serializeSchemaProperties(cxt, discriminator) { + const { gen, schema, data } = cxt; + const { properties, optionalProperties } = schema; + const props = keys(properties); + const optProps = keys(optionalProperties); + const allProps = allProperties(props.concat(optProps)); + let first = !discriminator; + let firstProp; + for (const key of props) { + if (first) + first = false; + else + gen.add(names_1.default.json, (0, codegen_1.str) `,`); + serializeProperty(key, properties[key], keyValue(key)); + } + if (first) + firstProp = gen.let("first", true); + for (const key of optProps) { + const value = keyValue(key); + gen.if((0, codegen_1.and)((0, codegen_1._) `${value} !== undefined`, (0, code_1.isOwnProperty)(gen, data, key)), () => { + addComma(cxt, firstProp); + serializeProperty(key, optionalProperties[key], value); + }); + } + if (schema.additionalProperties) { + gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp))); + } + function keys(ps) { + return ps ? Object.keys(ps) : []; + } + function allProperties(ps) { + if (discriminator) + ps.push(discriminator); + if (new Set(ps).size !== ps.length) { + throw new Error("JTD: properties/optionalProperties/disciminator overlap"); + } + return ps; + } + function keyValue(key) { + return gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`); + } + function serializeProperty(key, propSchema, value) { + gen.add(names_1.default.json, (0, codegen_1.str) `${JSON.stringify(key)}:`); + serializeCode({ ...cxt, schema: propSchema, data: value }); + } + function isAdditional(key, ps) { + return ps.length ? (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`)) : true; + } +} +function serializeType(cxt) { + const { gen, schema, data } = cxt; + switch (schema.type) { + case "boolean": + gen.add(names_1.default.json, (0, codegen_1._) `${data} ? "true" : "false"`); + break; + case "string": + serializeString(cxt); + break; + case "timestamp": + gen.if((0, codegen_1._) `${data} instanceof Date`, () => gen.add(names_1.default.json, (0, codegen_1._) `'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt)); + break; + default: + serializeNumber(cxt); + } +} +function serializeString({ gen, data }) { + gen.add(names_1.default.json, (0, codegen_1._) `${(0, util_1.useFunc)(gen, quote_1.default)}(${data})`); +} +function serializeNumber({ gen, data }) { + gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`); +} +function serializeRef(cxt) { + const { gen, self, data, definitions, schema, schemaEnv } = cxt; + const { ref } = schema; + const refSchema = definitions[ref]; + if (!refSchema) + throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`); + if (!(0, ref_1.hasRef)(refSchema)) + return serializeCode({ ...cxt, schema: refSchema }); + const { root } = schemaEnv; + const sch = compileSerializer.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions); + gen.add(names_1.default.json, (0, codegen_1._) `${getSerialize(gen, sch)}(${data})`); +} +function getSerialize(gen, sch) { + return sch.serialize + ? gen.scopeValue("serialize", { ref: sch.serialize }) + : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.serialize`; +} +function serializeEmpty({ gen, data }) { + gen.add(names_1.default.json, (0, codegen_1._) `JSON.stringify(${data})`); +} +function addComma({ gen }, first) { + if (first) { + gen.if(first, () => gen.assign(first, false), () => gen.add(names_1.default.json, (0, codegen_1.str) `,`)); + } + else { + gen.add(names_1.default.json, (0, codegen_1.str) `,`); + } +} +//# sourceMappingURL=serialize.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/jtd/serialize.js.map b/node_modules/ajv/dist/compile/jtd/serialize.js.map new file mode 100644 index 000000000..15c82c714 --- /dev/null +++ b/node_modules/ajv/dist/compile/jtd/serialize.js.map @@ -0,0 +1 @@ +{"version":3,"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,IAAA,WAAC,EAAA,GAAG,YAAY,CAAC,GAAG,EAAE,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,CAAA;AACxD,CAAC;AAED,SAAS,YAAY,CAAC,GAAY,EAAE,GAAc;IAChD,OAAO,GAAG,CAAC,SAAS;QAClB,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,EAAC,GAAG,EAAE,GAAG,CAAC,SAAS,EAAC,CAAC;QACnD,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,CAAC,UAAU,CAAC,SAAS,EAAE,EAAC,GAAG,EAAE,GAAG,EAAC,CAAC,YAAY,CAAA;AAC3D,CAAC;AAED,SAAS,cAAc,CAAC,EAAC,GAAG,EAAE,IAAI,EAAe;IAC/C,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,kBAAkB,IAAI,GAAG,CAAC,CAAA;AAC7C,CAAC;AAED,SAAS,QAAQ,CAAC,EAAC,GAAG,EAAe,EAAE,KAAY;IACjD,IAAI,KAAK,EAAE,CAAC;QACV,GAAG,CAAC,EAAE,CACJ,KAAK,EACL,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EAC9B,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAC9B,CAAA;IACH,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;IACzB,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/jtd/types.d.ts b/node_modules/ajv/dist/compile/jtd/types.d.ts new file mode 100644 index 000000000..678986f1b --- /dev/null +++ b/node_modules/ajv/dist/compile/jtd/types.d.ts @@ -0,0 +1,6 @@ +import type { SchemaObject } from "../../types"; +export type SchemaObjectMap = { + [Ref in string]?: SchemaObject; +}; +export declare const jtdForms: readonly ["elements", "values", "discriminator", "properties", "optionalProperties", "enum", "type", "ref"]; +export type JTDForm = (typeof jtdForms)[number]; diff --git a/node_modules/ajv/dist/compile/jtd/types.js b/node_modules/ajv/dist/compile/jtd/types.js new file mode 100644 index 000000000..b9c60a90f --- /dev/null +++ b/node_modules/ajv/dist/compile/jtd/types.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.jtdForms = void 0; +exports.jtdForms = [ + "elements", + "values", + "discriminator", + "properties", + "optionalProperties", + "enum", + "type", + "ref", +]; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/jtd/types.js.map b/node_modules/ajv/dist/compile/jtd/types.js.map new file mode 100644 index 000000000..53439e002 --- /dev/null +++ b/node_modules/ajv/dist/compile/jtd/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/compile/jtd/types.ts"],"names":[],"mappings":";;;AAIa,QAAA,QAAQ,GAAG;IACtB,UAAU;IACV,QAAQ;IACR,eAAe;IACf,YAAY;IACZ,oBAAoB;IACpB,MAAM;IACN,MAAM;IACN,KAAK;CACG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/names.d.ts b/node_modules/ajv/dist/compile/names.d.ts new file mode 100644 index 000000000..5740e82c6 --- /dev/null +++ b/node_modules/ajv/dist/compile/names.d.ts @@ -0,0 +1,20 @@ +import { Name } from "./codegen"; +declare const names: { + data: Name; + valCxt: Name; + instancePath: Name; + parentData: Name; + parentDataProperty: Name; + rootData: Name; + dynamicAnchors: Name; + vErrors: Name; + errors: Name; + this: Name; + self: Name; + scope: Name; + json: Name; + jsonPos: Name; + jsonLen: Name; + jsonPart: Name; +}; +export default names; diff --git a/node_modules/ajv/dist/compile/names.js b/node_modules/ajv/dist/compile/names.js new file mode 100644 index 000000000..3bce5aaa9 --- /dev/null +++ b/node_modules/ajv/dist/compile/names.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("./codegen"); +const names = { + // validation function arguments + data: new codegen_1.Name("data"), // data passed to validation function + // args passed from referencing schema + valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef + // function scoped variables + vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors + errors: new codegen_1.Name("errors"), // counter of validation errors + this: new codegen_1.Name("this"), + // "globals" + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart"), +}; +exports.default = names; +//# sourceMappingURL=names.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/names.js.map b/node_modules/ajv/dist/compile/names.js.map new file mode 100644 index 000000000..971fcbf70 --- /dev/null +++ b/node_modules/ajv/dist/compile/names.js.map @@ -0,0 +1 @@ +{"version":3,"file":"names.js","sourceRoot":"","sources":["../../lib/compile/names.ts"],"names":[],"mappings":";;AAAA,uCAA8B;AAE9B,MAAM,KAAK,GAAG;IACZ,gCAAgC;IAChC,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC,EAAE,qCAAqC;IAC7D,sCAAsC;IACtC,MAAM,EAAE,IAAI,cAAI,CAAC,QAAQ,CAAC,EAAE,+FAA+F;IAC3H,YAAY,EAAE,IAAI,cAAI,CAAC,cAAc,CAAC;IACtC,UAAU,EAAE,IAAI,cAAI,CAAC,YAAY,CAAC;IAClC,kBAAkB,EAAE,IAAI,cAAI,CAAC,oBAAoB,CAAC;IAClD,QAAQ,EAAE,IAAI,cAAI,CAAC,UAAU,CAAC,EAAE,2EAA2E;IAC3G,cAAc,EAAE,IAAI,cAAI,CAAC,gBAAgB,CAAC,EAAE,8CAA8C;IAC1F,4BAA4B;IAC5B,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC,EAAE,qCAAqC;IACnE,MAAM,EAAE,IAAI,cAAI,CAAC,QAAQ,CAAC,EAAE,+BAA+B;IAC3D,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,YAAY;IACZ,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,KAAK,EAAE,IAAI,cAAI,CAAC,OAAO,CAAC;IACxB,wDAAwD;IACxD,IAAI,EAAE,IAAI,cAAI,CAAC,MAAM,CAAC;IACtB,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC;IAC5B,OAAO,EAAE,IAAI,cAAI,CAAC,SAAS,CAAC;IAC5B,QAAQ,EAAE,IAAI,cAAI,CAAC,UAAU,CAAC;CAC/B,CAAA;AAED,kBAAe,KAAK,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/ref_error.d.ts b/node_modules/ajv/dist/compile/ref_error.d.ts new file mode 100644 index 000000000..43374439e --- /dev/null +++ b/node_modules/ajv/dist/compile/ref_error.d.ts @@ -0,0 +1,6 @@ +import type { UriResolver } from "../types"; +export default class MissingRefError extends Error { + readonly missingRef: string; + readonly missingSchema: string; + constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string); +} diff --git a/node_modules/ajv/dist/compile/ref_error.js b/node_modules/ajv/dist/compile/ref_error.js new file mode 100644 index 000000000..3916dec8a --- /dev/null +++ b/node_modules/ajv/dist/compile/ref_error.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const resolve_1 = require("./resolve"); +class MissingRefError extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } +} +exports.default = MissingRefError; +//# sourceMappingURL=ref_error.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/ref_error.js.map b/node_modules/ajv/dist/compile/ref_error.js.map new file mode 100644 index 000000000..d13f5f2dd --- /dev/null +++ b/node_modules/ajv/dist/compile/ref_error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ref_error.js","sourceRoot":"","sources":["../../lib/compile/ref_error.ts"],"names":[],"mappings":";;AAAA,uCAA8D;AAG9D,MAAqB,eAAgB,SAAQ,KAAK;IAIhD,YAAY,QAAqB,EAAE,MAAc,EAAE,GAAW,EAAE,GAAY;QAC1E,KAAK,CAAC,GAAG,IAAI,2BAA2B,GAAG,YAAY,MAAM,EAAE,CAAC,CAAA;QAChE,IAAI,CAAC,UAAU,GAAG,IAAA,oBAAU,EAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,CAAA;QACnD,IAAI,CAAC,aAAa,GAAG,IAAA,qBAAW,EAAC,IAAA,qBAAW,EAAC,QAAQ,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,CAAA;IAC1E,CAAC;CACF;AATD,kCASC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/resolve.d.ts b/node_modules/ajv/dist/compile/resolve.d.ts new file mode 100644 index 000000000..3c20fffcb --- /dev/null +++ b/node_modules/ajv/dist/compile/resolve.d.ts @@ -0,0 +1,12 @@ +import type { AnySchema, AnySchemaObject, UriResolver } from "../types"; +import type Ajv from "../ajv"; +import type { URIComponent } from "fast-uri"; +export type LocalRefs = { + [Ref in string]?: AnySchemaObject; +}; +export declare function inlineRef(schema: AnySchema, limit?: boolean | number): boolean; +export declare function getFullPath(resolver: UriResolver, id?: string, normalize?: boolean): string; +export declare function _getFullPath(resolver: UriResolver, p: URIComponent): string; +export declare function normalizeId(id: string | undefined): string; +export declare function resolveUrl(resolver: UriResolver, baseId: string, id: string): string; +export declare function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs; diff --git a/node_modules/ajv/dist/compile/resolve.js b/node_modules/ajv/dist/compile/resolve.js new file mode 100644 index 000000000..f12f968dc --- /dev/null +++ b/node_modules/ajv/dist/compile/resolve.js @@ -0,0 +1,155 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; +const util_1 = require("./util"); +const equal = require("fast-deep-equal"); +const traverse = require("json-schema-traverse"); +// TODO refactor to use keyword definitions +const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const", +]); +function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") + return true; + if (limit === true) + return !hasRef(schema); + if (!limit) + return false; + return countKeys(schema) <= limit; +} +exports.inlineRef = inlineRef; +const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor", +]); +function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) + return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) + return true; + if (typeof sch == "object" && hasRef(sch)) + return true; + } + return false; +} +function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") + return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) + continue; + if (typeof schema[key] == "object") { + (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch))); + } + if (count === Infinity) + return Infinity; + } + return count; +} +function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) + id = normalizeId(id); + const p = resolver.parse(id); + return _getFullPath(resolver, p); +} +exports.getFullPath = getFullPath; +function _getFullPath(resolver, p) { + const serialized = resolver.serialize(p); + return serialized.split("#")[0] + "#"; +} +exports._getFullPath = _getFullPath; +const TRAILING_SLASH_HASH = /#\/?$/; +function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; +} +exports.normalizeId = normalizeId; +function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); +} +exports.resolveUrl = resolveUrl; +const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; +function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") + return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === undefined) + return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") + innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + // eslint-disable-next-line @typescript-eslint/unbound-method + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) + throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") + schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref); + } + else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } + else { + this.refs[ref] = fullPath; + } + } + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) + throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== undefined && !equal(sch1, sch2)) + throw ambiguos(ref); + } + function ambiguos(ref) { + return new Error(`reference "${ref}" resolves to more than one schema`); + } +} +exports.getSchemaRefs = getSchemaRefs; +//# sourceMappingURL=resolve.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/resolve.js.map b/node_modules/ajv/dist/compile/resolve.js.map new file mode 100644 index 000000000..f57919454 --- /dev/null +++ b/node_modules/ajv/dist/compile/resolve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../lib/compile/resolve.ts"],"names":[],"mappings":";;;AAGA,iCAA+B;AAC/B,yCAAwC;AACxC,iDAAgD;AAKhD,2CAA2C;AAC3C,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC;IAC7B,MAAM;IACN,QAAQ;IACR,SAAS;IACT,WAAW;IACX,WAAW;IACX,eAAe;IACf,eAAe;IACf,UAAU;IACV,UAAU;IACV,SAAS;IACT,SAAS;IACT,aAAa;IACb,YAAY;IACZ,UAAU;IACV,MAAM;IACN,OAAO;CACR,CAAC,CAAA;AAEF,SAAgB,SAAS,CAAC,MAAiB,EAAE,QAA0B,IAAI;IACzE,IAAI,OAAO,MAAM,IAAI,SAAS;QAAE,OAAO,IAAI,CAAA;IAC3C,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;IAC1C,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAA;IACxB,OAAO,SAAS,CAAC,MAAM,CAAC,IAAI,KAAK,CAAA;AACnC,CAAC;AALD,8BAKC;AAED,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC;IAC3B,MAAM;IACN,eAAe;IACf,kBAAkB;IAClB,aAAa;IACb,gBAAgB;CACjB,CAAC,CAAA;AAEF,SAAS,MAAM,CAAC,MAAuB;IACrC,KAAK,MAAM,GAAG,IAAI,MAAM,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CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;YAC7C,CAAC;iBAAM,IAAI,GAAG,KAAK,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACzC,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;oBACnB,gBAAgB,CAAC,GAAG,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAA;oBAC1C,SAAS,CAAC,GAAG,CAAC,GAAG,GAAG,CAAA;gBACtB,CAAC;qBAAM,CAAC;oBACN,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAA;gBAC3B,CAAC;YACH,CAAC;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;QAED,SAAS,SAAS,CAAY,MAAe;YAC3C,IAAI,OAAO,MAAM,IAAI,QAAQ,EAAE,CAAC;gBAC9B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,MAAM,GAAG,CAAC,CAAA;gBACvE,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,MAAM,EAAE,CAAC,CAAA;YACjC,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAA;IAEF,OAAO,SAAS,CAAA;IAEhB,SAAS,gBAAgB,CAAC,IAAe,EAAE,IAA2B,EAAE,GAAW;QACjF,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;YAAE,MAAM,QAAQ,CAAC,GAAG,CAAC,CAAA;IACnE,CAAC;IAED,SAAS,QAAQ,CAAC,GAAW;QAC3B,OAAO,IAAI,KAAK,CAAC,cAAc,GAAG,oCAAoC,CAAC,CAAA;IACzE,CAAC;AACH,CAAC;AAxDD,sCAwDC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/rules.d.ts b/node_modules/ajv/dist/compile/rules.d.ts new file mode 100644 index 000000000..51ec46ab3 --- /dev/null +++ b/node_modules/ajv/dist/compile/rules.d.ts @@ -0,0 +1,28 @@ +import type { AddedKeywordDefinition } from "../types"; +declare const _jsonTypes: readonly ["string", "number", "integer", "boolean", "null", "object", "array"]; +export type JSONType = (typeof _jsonTypes)[number]; +export declare function isJSONType(x: unknown): x is JSONType; +type ValidationTypes = { + [K in JSONType]: boolean | RuleGroup | undefined; +}; +export interface ValidationRules { + rules: RuleGroup[]; + post: RuleGroup; + all: { + [Key in string]?: boolean | Rule; + }; + keywords: { + [Key in string]?: boolean; + }; + types: ValidationTypes; +} +export interface RuleGroup { + type?: JSONType; + rules: Rule[]; +} +export interface Rule { + keyword: string; + definition: AddedKeywordDefinition; +} +export declare function getRules(): ValidationRules; +export {}; diff --git a/node_modules/ajv/dist/compile/rules.js b/node_modules/ajv/dist/compile/rules.js new file mode 100644 index 000000000..82a591ff4 --- /dev/null +++ b/node_modules/ajv/dist/compile/rules.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRules = exports.isJSONType = void 0; +const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; +const jsonTypes = new Set(_jsonTypes); +function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); +} +exports.isJSONType = isJSONType; +function getRules() { + const groups = { + number: { type: "number", rules: [] }, + string: { type: "string", rules: [] }, + array: { type: "array", rules: [] }, + object: { type: "object", rules: [] }, + }; + return { + types: { ...groups, integer: true, boolean: true, null: true }, + rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], + post: { rules: [] }, + all: {}, + keywords: {}, + }; +} +exports.getRules = getRules; +//# sourceMappingURL=rules.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/rules.js.map b/node_modules/ajv/dist/compile/rules.js.map new file mode 100644 index 000000000..084c70f82 --- /dev/null +++ b/node_modules/ajv/dist/compile/rules.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rules.js","sourceRoot":"","sources":["../../lib/compile/rules.ts"],"names":[],"mappings":";;;AAEA,MAAM,UAAU,GAAG,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAU,CAAA;AAIjG,MAAM,SAAS,GAAgB,IAAI,GAAG,CAAC,UAAU,CAAC,CAAA;AAElD,SAAgB,UAAU,CAAC,CAAU;IACnC,OAAO,OAAO,CAAC,IAAI,QAAQ,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC;AAFD,gCAEC;AAyBD,SAAgB,QAAQ;IACtB,MAAM,MAAM,GAAgE;QAC1E,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;QACnC,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;QACnC,KAAK,EAAE,EAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAC;QACjC,MAAM,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAC;KACpC,CAAA;IACD,OAAO;QACL,KAAK,EAAE,EAAC,GAAG,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAC;QAC5D,KAAK,EAAE,CAAC,EAAC,KAAK,EAAE,EAAE,EAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QAC/E,IAAI,EAAE,EAAC,KAAK,EAAE,EAAE,EAAC;QACjB,GAAG,EAAE,EAAE;QACP,QAAQ,EAAE,EAAE;KACb,CAAA;AACH,CAAC;AAdD,4BAcC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/util.d.ts b/node_modules/ajv/dist/compile/util.d.ts new file mode 100644 index 000000000..1ec282aee --- /dev/null +++ b/node_modules/ajv/dist/compile/util.d.ts @@ -0,0 +1,40 @@ +import type { AnySchema, EvaluatedProperties, EvaluatedItems } from "../types"; +import type { SchemaCxt, SchemaObjCxt } from "."; +import { Code, Name, CodeGen } from "./codegen"; +import type { Rule, ValidationRules } from "./rules"; +export declare function toHash(arr: T[]): { + [K in T]?: true; +}; +export declare function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void; +export declare function checkUnknownRules(it: SchemaCxt, schema?: AnySchema): void; +export declare function schemaHasRules(schema: AnySchema, rules: { + [Key in string]?: boolean | Rule; +}): boolean; +export declare function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean; +export declare function schemaRefOrVal({ topSchemaRef, schemaPath }: SchemaObjCxt, schema: unknown, keyword: string, $data?: string | false): Code | number | boolean; +export declare function unescapeFragment(str: string): string; +export declare function escapeFragment(str: string | number): string; +export declare function escapeJsonPointer(str: string | number): string; +export declare function unescapeJsonPointer(str: string): string; +export declare function eachItem(xs: T | T[], f: (x: T) => void): void; +type SomeEvaluated = EvaluatedProperties | EvaluatedItems; +type MergeEvaluatedFunc = (gen: CodeGen, from: Name | T, to: Name | Exclude | undefined, toName?: typeof Name) => Name | T; +interface MergeEvaluated { + props: MergeEvaluatedFunc; + items: MergeEvaluatedFunc; +} +export declare const mergeEvaluated: MergeEvaluated; +export declare function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name; +export declare function setEvaluated(gen: CodeGen, props: Name, ps: { + [K in string]?: true; +}): void; +export declare function useFunc(gen: CodeGen, f: { + code: string; +}): Name; +export declare enum Type { + Num = 0, + Str = 1 +} +export declare function getErrorPath(dataProp: Name | string | number, dataPropType?: Type, jsPropertySyntax?: boolean): Code | string; +export declare function checkStrictMode(it: SchemaCxt, msg: string, mode?: boolean | "log"): void; +export {}; diff --git a/node_modules/ajv/dist/compile/util.js b/node_modules/ajv/dist/compile/util.js new file mode 100644 index 000000000..73c87c854 --- /dev/null +++ b/node_modules/ajv/dist/compile/util.js @@ -0,0 +1,178 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; +const codegen_1 = require("./codegen"); +const code_1 = require("./codegen/code"); +// TODO refactor to use Set +function toHash(arr) { + const hash = {}; + for (const item of arr) + hash[item] = true; + return hash; +} +exports.toHash = toHash; +function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") + return schema; + if (Object.keys(schema).length === 0) + return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); +} +exports.alwaysValidSchema = alwaysValidSchema; +function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) + return; + if (typeof schema === "boolean") + return; + const rules = self.RULES.keywords; + for (const key in schema) { + if (!rules[key]) + checkStrictMode(it, `unknown keyword: "${key}"`); + } +} +exports.checkUnknownRules = checkUnknownRules; +function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (rules[key]) + return true; + return false; +} +exports.schemaHasRules = schemaHasRules; +function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (key !== "$ref" && RULES.all[key]) + return true; + return false; +} +exports.schemaHasRulesButRef = schemaHasRulesButRef; +function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") + return schema; + if (typeof schema == "string") + return (0, codegen_1._) `${schema}`; + } + return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; +} +exports.schemaRefOrVal = schemaRefOrVal; +function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); +} +exports.unescapeFragment = unescapeFragment; +function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); +} +exports.escapeFragment = escapeFragment; +function escapeJsonPointer(str) { + if (typeof str == "number") + return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); +} +exports.escapeJsonPointer = escapeJsonPointer; +function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); +} +exports.unescapeJsonPointer = unescapeJsonPointer; +function eachItem(xs, f) { + if (Array.isArray(xs)) { + for (const x of xs) + f(x); + } + else { + f(xs); + } +} +exports.eachItem = eachItem; +function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) { + return (gen, from, to, toName) => { + const res = to === undefined + ? from + : to instanceof codegen_1.Name + ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) + : from instanceof codegen_1.Name + ? (mergeToName(gen, to, from), from) + : mergeValues(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; +} +exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => { + if (from === true) { + gen.assign(to, true); + } + else { + gen.assign(to, (0, codegen_1._) `${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => (from === true ? true : { ...from, ...to }), + resultToName: evaluatedPropsToName, + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => (from === true ? true : Math.max(from, to)), + resultToName: (gen, items) => gen.var("items", items), + }), +}; +function evaluatedPropsToName(gen, ps) { + if (ps === true) + return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._) `{}`); + if (ps !== undefined) + setEvaluated(gen, props, ps); + return props; +} +exports.evaluatedPropsToName = evaluatedPropsToName; +function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true)); +} +exports.setEvaluated = setEvaluated; +const snippets = {}; +function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)), + }); +} +exports.useFunc = useFunc; +var Type; +(function (Type) { + Type[Type["Num"] = 0] = "Num"; + Type[Type["Str"] = 1] = "Str"; +})(Type || (exports.Type = Type = {})); +function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + // let path + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax + ? isNumber + ? (0, codegen_1._) `"[" + ${dataProp} + "]"` + : (0, codegen_1._) `"['" + ${dataProp} + "']"` + : isNumber + ? (0, codegen_1._) `"/" + ${dataProp}` + : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); +} +exports.getErrorPath = getErrorPath; +function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) + return; + msg = `strict mode: ${msg}`; + if (mode === true) + throw new Error(msg); + it.self.logger.warn(msg); +} +exports.checkStrictMode = checkStrictMode; +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/util.js.map b/node_modules/ajv/dist/compile/util.js.map new file mode 100644 index 000000000..ee0100890 --- /dev/null +++ b/node_modules/ajv/dist/compile/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../../lib/compile/util.ts"],"names":[],"mappings":";;;AAEA,uCAA6D;AAC7D,yCAAoC;AAGpC,2BAA2B;AAC3B,SAAgB,MAAM,CAA4B,GAAQ;IACxD,MAAM,IAAI,GAAsB,EAAE,CAAA;IAClC,KAAK,MAAM,IAAI,IAAI,GAAG;QAAE,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAA;IACzC,OAAO,IAAI,CAAA;AACb,CAAC;AAJD,wBAIC;AAED,SAAgB,iBAAiB,CAAC,EAAa,EAAE,MAAiB;IAChE,IAAI,OAAO,MAAM,IAAI,SAAS;QAAE,OAAO,MAAM,CAAA;IAC7C,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAA;IACjD,iBAAiB,CAAC,EAAE,EAAE,MAAM,CAAC,CAAA;IAC7B,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;AACnD,CAAC;AALD,8CAKC;AAED,SAAgB,iBAAiB,CAAC,EAAa,EAAE,SAAoB,EAAE,CAAC,MAAM;IAC5E,MAAM,EAAC,IAAI,EAAE,IAAI,EAAC,GAAG,EAAE,CAAA;IACvB,IAAI,CAAC,IAAI,CAAC,YAAY;QAAE,OAAM;IAC9B,IAAI,OAAO,MAAM,KAAK,SAAS;QAAE,OAAM;IACvC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAA;IACjC,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;QACzB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;YAAE,eAAe,CAAC,EAAE,EAAE,qBAAqB,GAAG,GAAG,CAAC,CAAA;IACnE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,IAAI,QAGf;AAED,SAAgB,YAAY,CAC1B,QAAgC,EAChC,YAAmB,EACnB,gBAA0B;IAE1B,WAAW;IACX,IAAI,QAAQ,YAAY,cAAI,EAAE,CAAC;QAC7B,MAAM,QAAQ,GAAG,YAAY,KAAK,IAAI,CAAC,GAAG,CAAA;QAC1C,OAAO,gBAAgB;YACrB,CAAC,CAAC,QAAQ;gBACR,CAAC,CAAC,IAAA,WAAC,EAAA,SAAS,QAAQ,QAAQ;gBAC5B,CAAC,CAAC,IAAA,WAAC,EAAA,UAAU,QAAQ,SAAS;YAChC,CAAC,CAAC,QAAQ;gBACV,CAAC,CAAC,IAAA,WAAC,EAAA,SAAS,QAAQ,EAAE;gBACtB,CAAC,CAAC,IAAA,WAAC,EAAA,SAAS,QAAQ,4CAA4C,CAAA,CAAC,sCAAsC;IAC3G,CAAC;IACD,OAAO,gBAAgB,CAAC,CAAC,CAAC,IAAA,qBAAW,EAAC,QAAQ,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAA;AAChG,CAAC;AAjBD,oCAiBC;AAED,SAAgB,eAAe,CAC7B,EAAa,EACb,GAAW,EACX,OAAwB,EAAE,CAAC,IAAI,CAAC,YAAY;IAE5C,IAAI,CAAC,IAAI;QAAE,OAAM;IACjB,GAAG,GAAG,gBAAgB,GAAG,EAAE,CAAA;IAC3B,IAAI,IAAI,KAAK,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAA;IACvC,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AAC1B,CAAC;AATD,0CASC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/applicability.d.ts b/node_modules/ajv/dist/compile/validate/applicability.d.ts new file mode 100644 index 000000000..165d375dc --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/applicability.d.ts @@ -0,0 +1,6 @@ +import type { AnySchemaObject } from "../../types"; +import type { SchemaObjCxt } from ".."; +import type { JSONType, RuleGroup, Rule } from "../rules"; +export declare function schemaHasRulesForType({ schema, self }: SchemaObjCxt, type: JSONType): boolean | undefined; +export declare function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean; +export declare function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined; diff --git a/node_modules/ajv/dist/compile/validate/applicability.js b/node_modules/ajv/dist/compile/validate/applicability.js new file mode 100644 index 000000000..6187dbbee --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/applicability.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; +function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); +} +exports.schemaHasRulesForType = schemaHasRulesForType; +function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); +} +exports.shouldUseGroup = shouldUseGroup; +function shouldUseRule(schema, rule) { + var _a; + return (schema[rule.keyword] !== undefined || + ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined))); +} +exports.shouldUseRule = shouldUseRule; +//# sourceMappingURL=applicability.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/applicability.js.map b/node_modules/ajv/dist/compile/validate/applicability.js.map new file mode 100644 index 000000000..450cfe75a --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/applicability.js.map @@ -0,0 +1 @@ +{"version":3,"file":"applicability.js","sourceRoot":"","sources":["../../../lib/compile/validate/applicability.ts"],"names":[],"mappings":";;;AAIA,SAAgB,qBAAqB,CACnC,EAAC,MAAM,EAAE,IAAI,EAAe,EAC5B,IAAc;IAEd,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IACpC,OAAO,KAAK,IAAI,KAAK,KAAK,IAAI,IAAI,cAAc,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;AACjE,CAAC;AAND,sDAMC;AAED,SAAgB,cAAc,CAAC,MAAuB,EAAE,KAAgB;IACtE,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAA;AAChE,CAAC;AAFD,wCAEC;AAED,SAAgB,aAAa,CAAC,MAAuB,EAAE,IAAU;;IAC/D,OAAO,CACL,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,SAAS;SAClC,MAAA,IAAI,CAAC,UAAU,CAAC,UAAU,0CAAE,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC,CAAA,CACrE,CAAA;AACH,CAAC;AALD,sCAKC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/boolSchema.d.ts b/node_modules/ajv/dist/compile/validate/boolSchema.d.ts new file mode 100644 index 000000000..0ce795201 --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/boolSchema.d.ts @@ -0,0 +1,4 @@ +import type { SchemaCxt } from ".."; +import { Name } from "../codegen"; +export declare function topBoolOrEmptySchema(it: SchemaCxt): void; +export declare function boolOrEmptySchema(it: SchemaCxt, valid: Name): void; diff --git a/node_modules/ajv/dist/compile/validate/boolSchema.js b/node_modules/ajv/dist/compile/validate/boolSchema.js new file mode 100644 index 000000000..8eeb7b5ee --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/boolSchema.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; +const errors_1 = require("../errors"); +const codegen_1 = require("../codegen"); +const names_1 = require("../names"); +const boolError = { + message: "boolean schema is false", +}; +function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) { + falseSchemaError(it, false); + } + else if (typeof schema == "object" && schema.$async === true) { + gen.return(names_1.default.data); + } + else { + gen.assign((0, codegen_1._) `${validateName}.errors`, null); + gen.return(true); + } +} +exports.topBoolOrEmptySchema = topBoolOrEmptySchema; +function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); // TODO var + falseSchemaError(it); + } + else { + gen.var(valid, true); // TODO var + } +} +exports.boolOrEmptySchema = boolOrEmptySchema; +function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + // TODO maybe some other interface should be used for non-keyword validation errors... + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it, + }; + (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors); +} +//# sourceMappingURL=boolSchema.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/boolSchema.js.map b/node_modules/ajv/dist/compile/validate/boolSchema.js.map new file mode 100644 index 000000000..b7444a20f --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/boolSchema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"boolSchema.js","sourceRoot":"","sources":["../../../lib/compile/validate/boolSchema.ts"],"names":[],"mappings":";;;AAEA,sCAAqC;AACrC,wCAAkC;AAClC,oCAAwB;AAExB,MAAM,SAAS,GAA2B;IACxC,OAAO,EAAE,yBAAyB;CACnC,CAAA;AAED,SAAgB,oBAAoB,CAAC,EAAa;IAChD,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,YAAY,EAAC,GAAG,EAAE,CAAA;IACtC,IAAI,MAAM,KAAK,KAAK,EAAE,CAAC;QACrB,gBAAgB,CAAC,EAAE,EAAE,KAAK,CAAC,CAAA;IAC7B,CAAC;SAAM,IAAI,OAAO,MAAM,IAAI,QAAQ,IAAI,MAAM,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QAC/D,GAAG,CAAC,MAAM,CAAC,eAAC,CAAC,IAAI,CAAC,CAAA;IACpB,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,YAAY,SAAS,EAAE,IAAI,CAAC,CAAA;QAC3C,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IAClB,CAAC;AACH,CAAC;AAVD,oDAUC;AAED,SAAgB,iBAAiB,CAAC,EAAa,EAAE,KAAW;IAC1D,MAAM,EAAC,GAAG,EAAE,MAAM,EAAC,GAAG,EAAE,CAAA;IACxB,IAAI,MAAM,KAAK,KAAK,EAAE,CAAC;QACrB,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA,CAAC,WAAW;QACjC,gBAAgB,CAAC,EAAE,CAAC,CAAA;IACtB,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA,CAAC,WAAW;IAClC,CAAC;AACH,CAAC;AARD,8CAQC;AAED,SAAS,gBAAgB,CAAC,EAAa,EAAE,iBAA2B;IAClE,MAAM,EAAC,GAAG,EAAE,IAAI,EAAC,GAAG,EAAE,CAAA;IACtB,sFAAsF;IACtF,MAAM,GAAG,GAAoB;QAC3B,GAAG;QACH,OAAO,EAAE,cAAc;QACvB,IAAI;QACJ,MAAM,EAAE,KAAK;QACb,UAAU,EAAE,KAAK;QACjB,WAAW,EAAE,KAAK;QAClB,MAAM,EAAE,EAAE;QACV,EAAE;KACH,CAAA;IACD,IAAA,oBAAW,EAAC,GAAG,EAAE,SAAS,EAAE,SAAS,EAAE,iBAAiB,CAAC,CAAA;AAC3D,CAAC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/dataType.d.ts b/node_modules/ajv/dist/compile/validate/dataType.d.ts new file mode 100644 index 000000000..91a6194ae --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/dataType.d.ts @@ -0,0 +1,17 @@ +import type { ErrorObject, AnySchemaObject } from "../../types"; +import type { SchemaObjCxt } from ".."; +import { JSONType } from "../rules"; +import { Code, Name } from "../codegen"; +export declare enum DataType { + Correct = 0, + Wrong = 1 +} +export declare function getSchemaTypes(schema: AnySchemaObject): JSONType[]; +export declare function getJSONTypes(ts: unknown | unknown[]): JSONType[]; +export declare function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean; +export declare function checkDataType(dataType: JSONType, data: Name, strictNums?: boolean | "log", correct?: DataType): Code; +export declare function checkDataTypes(dataTypes: JSONType[], data: Name, strictNums?: boolean | "log", correct?: DataType): Code; +export type TypeError = ErrorObject<"type", { + type: string; +}>; +export declare function reportTypeError(it: SchemaObjCxt): void; diff --git a/node_modules/ajv/dist/compile/validate/dataType.js b/node_modules/ajv/dist/compile/validate/dataType.js new file mode 100644 index 000000000..6d03e0dc0 --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/dataType.js @@ -0,0 +1,203 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; +const rules_1 = require("../rules"); +const applicability_1 = require("./applicability"); +const errors_1 = require("../errors"); +const codegen_1 = require("../codegen"); +const util_1 = require("../util"); +var DataType; +(function (DataType) { + DataType[DataType["Correct"] = 0] = "Correct"; + DataType[DataType["Wrong"] = 1] = "Wrong"; +})(DataType || (exports.DataType = DataType = {})); +function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + const hasNull = types.includes("null"); + if (hasNull) { + if (schema.nullable === false) + throw new Error("type: null contradicts nullable: false"); + } + else { + if (!types.length && schema.nullable !== undefined) { + throw new Error('"nullable" cannot be used without "type"'); + } + if (schema.nullable === true) + types.push("null"); + } + return types; +} +exports.getSchemaTypes = getSchemaTypes; +// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents +function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) + return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); +} +exports.getJSONTypes = getJSONTypes; +function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && + !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) + coerceData(it, types, coerceTo); + else + reportTypeError(it); + }); + } + return checkTypes; +} +exports.coerceAndCheckDataType = coerceAndCheckDataType; +const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]); +function coerceToTypes(types, coerceTypes) { + return coerceTypes + ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array")) + : []; +} +function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._) `undefined`); + if (opts.coerceTypes === "array") { + gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen + .assign(data, (0, codegen_1._) `${data}[0]`) + .assign(dataType, (0, codegen_1._) `typeof ${data}`) + .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + } + gen.if((0, codegen_1._) `${coerced} !== undefined`); + for (const t of coerceTo) { + if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) { + coerceSpecificType(t); + } + } + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._) `${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen + .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`) + .assign(coerced, (0, codegen_1._) `"" + ${data}`) + .elseIf((0, codegen_1._) `${data} === null`) + .assign(coerced, (0, codegen_1._) `""`); + return; + case "number": + gen + .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`) + .assign(coerced, (0, codegen_1._) `+${data}`); + return; + case "integer": + gen + .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`) + .assign(coerced, (0, codegen_1._) `+${data}`); + return; + case "boolean": + gen + .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`) + .assign(coerced, false) + .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`) + .assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": + gen + .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`) + .assign(coerced, (0, codegen_1._) `[${data}]`); + } + } +} +function assignParentData({ gen, parentData, parentDataProperty }, expr) { + // TODO use gen.property + gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr)); +} +function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": + return (0, codegen_1._) `${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._) `Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: + return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil); + } +} +exports.checkDataType = checkDataType; +function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct); + } + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._) `typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } + else { + cond = codegen_1.nil; + } + if (types.number) + delete types.integer; + for (const t in types) + cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; +} +exports.checkDataTypes = checkDataTypes; +const typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`, +}; +function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); +} +exports.reportTypeError = reportTypeError; +function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it, + }; +} +//# sourceMappingURL=dataType.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/dataType.js.map b/node_modules/ajv/dist/compile/validate/dataType.js.map new file mode 100644 index 000000000..c8fb1c6e8 --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/dataType.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dataType.js","sourceRoot":"","sources":["../../../lib/compile/validate/dataType.ts"],"names":[],"mappings":";;;AAOA,oCAA6C;AAC7C,mDAAqD;AACrD,sCAAqC;AACrC,wCAAkE;AAClE,kCAA8C;AAE9C,IAAY,QAGX;AAHD,WAAY,QAAQ;IAClB,6CAAO,CAAA;IACP,yCAAK,CAAA;AACP,CAAC,EAHW,QAAQ,wBAAR,Q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qBAAc,EAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,CAAA;IACrD,OAAO;QACL,GAAG;QACH,OAAO,EAAE,MAAM;QACf,IAAI;QACJ,MAAM,EAAE,MAAM,CAAC,IAAI;QACnB,UAAU;QACV,WAAW,EAAE,UAAU;QACvB,YAAY,EAAE,MAAM;QACpB,MAAM,EAAE,EAAE;QACV,EAAE;KACH,CAAA;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/defaults.d.ts b/node_modules/ajv/dist/compile/validate/defaults.d.ts new file mode 100644 index 000000000..02ba453b2 --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/defaults.d.ts @@ -0,0 +1,2 @@ +import type { SchemaObjCxt } from ".."; +export declare function assignDefaults(it: SchemaObjCxt, ty?: string): void; diff --git a/node_modules/ajv/dist/compile/validate/defaults.js b/node_modules/ajv/dist/compile/validate/defaults.js new file mode 100644 index 000000000..cd9c42d9a --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/defaults.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assignDefaults = void 0; +const codegen_1 = require("../codegen"); +const util_1 = require("../util"); +function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default); + } + } + else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } +} +exports.assignDefaults = assignDefaults; +function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === undefined) + return; + const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._) `${childData} === undefined`; + if (opts.useDefaults === "empty") { + condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`; + } + // `${childData} === undefined` + + // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "") + gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); +} +//# sourceMappingURL=defaults.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/defaults.js.map b/node_modules/ajv/dist/compile/validate/defaults.js.map new file mode 100644 index 000000000..88d3672e9 --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/defaults.js.map @@ -0,0 +1 @@ +{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../../../lib/compile/validate/defaults.ts"],"names":[],"mappings":";;;AACA,wCAAoD;AACpD,kCAAuC;AAEvC,SAAgB,cAAc,CAAC,EAAgB,EAAE,EAAW;IAC1D,MAAM,EAAC,UAAU,EAAE,KAAK,EAAC,GAAG,EAAE,CAAC,MAAM,CAAA;IACrC,IAAI,EAAE,KAAK,QAAQ,IAAI,UAAU,EAAE,CAAC;QAClC,KAAK,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;YAC7B,aAAa,CAAC,EAAE,EAAE,GAAG,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAA;QACjD,CAAC;IACH,CAAC;SAAM,IAAI,EAAE,KAAK,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAClD,KAAK,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,CAAS,EAAE,EAAE,CAAC,aAAa,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAA;IACtE,CAAC;AACH,CAAC;AATD,wCASC;AAED,SAAS,aAAa,CAAC,EAAgB,EAAE,IAAqB,EAAE,YAAqB;IACnF,MAAM,EAAC,GAAG,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,EAAC,GAAG,EAAE,CAAA;IAC3C,IAAI,YAAY,KAAK,SAAS;QAAE,OAAM;IACtC,MAAM,SAAS,GAAG,IAAA,WAAC,EAAA,GAAG,IAAI,GAAG,IAAA,qBAAW,EAAC,IAAI,CAAC,EAAE,CAAA;IAChD,IAAI,aAAa,EAAE,CAAC;QAClB,IAAA,sBAAe,EAAC,EAAE,EAAE,2BAA2B,SAAS,EAAE,CAAC,CAAA;QAC3D,OAAM;IACR,CAAC;IAED,IAAI,SAAS,GAAG,IAAA,WAAC,EAAA,GAAG,SAAS,gBAAgB,CAAA;IAC7C,IAAI,IAAI,CAAC,WAAW,KAAK,OAAO,EAAE,CAAC;QACjC,SAAS,GAAG,IAAA,WAAC,EAAA,GAAG,SAAS,OAAO,SAAS,gBAAgB,SAAS,SAAS,CAAA;IAC7E,CAAC;IACD,iCAAiC;IACjC,2FAA2F;IAC3F,GAAG,CAAC,EAAE,CAAC,SAAS,EAAE,IAAA,WAAC,EAAA,GAAG,SAAS,MAAM,IAAA,mBAAS,EAAC,YAAY,CAAC,EAAE,CAAC,CAAA;AACjE,CAAC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/index.d.ts b/node_modules/ajv/dist/compile/validate/index.d.ts new file mode 100644 index 000000000..6c533ed72 --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/index.d.ts @@ -0,0 +1,42 @@ +import type { AddedKeywordDefinition, AnySchemaObject, KeywordErrorCxt, KeywordCxtParams } from "../../types"; +import type { SchemaCxt, SchemaObjCxt } from ".."; +import { SubschemaArgs } from "./subschema"; +import { Code, Name, CodeGen } from "../codegen"; +import type { JSONType } from "../rules"; +import { ErrorPaths } from "../errors"; +export declare function validateFunctionCode(it: SchemaCxt): void; +export declare class KeywordCxt implements KeywordErrorCxt { + readonly gen: CodeGen; + readonly allErrors?: boolean; + readonly keyword: string; + readonly data: Name; + readonly $data?: string | false; + schema: any; + readonly schemaValue: Code | number | boolean; + readonly schemaCode: Code | number | boolean; + readonly schemaType: JSONType[]; + readonly parentSchema: AnySchemaObject; + readonly errsCount?: Name; + params: KeywordCxtParams; + readonly it: SchemaObjCxt; + readonly def: AddedKeywordDefinition; + constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string); + result(condition: Code, successAction?: () => void, failAction?: () => void): void; + failResult(condition: Code, successAction?: () => void, failAction?: () => void): void; + pass(condition: Code, failAction?: () => void): void; + fail(condition?: Code): void; + fail$data(condition: Code): void; + error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void; + private _error; + $dataError(): void; + reset(): void; + ok(cond: Code | boolean): void; + setParams(obj: KeywordCxtParams, assign?: true): void; + block$data(valid: Name, codeBlock: () => void, $dataValid?: Code): void; + check$data(valid?: Name, $dataValid?: Code): void; + invalid$data(): Code; + subschema(appl: SubschemaArgs, valid: Name): SchemaCxt; + mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void; + mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void; +} +export declare function getData($data: string, { dataLevel, dataNames, dataPathArr }: SchemaCxt): Code | number; diff --git a/node_modules/ajv/dist/compile/validate/index.js b/node_modules/ajv/dist/compile/validate/index.js new file mode 100644 index 000000000..0d683322a --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/index.js @@ -0,0 +1,520 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; +const boolSchema_1 = require("./boolSchema"); +const dataType_1 = require("./dataType"); +const applicability_1 = require("./applicability"); +const dataType_2 = require("./dataType"); +const defaults_1 = require("./defaults"); +const keyword_1 = require("./keyword"); +const subschema_1 = require("./subschema"); +const codegen_1 = require("../codegen"); +const names_1 = require("../names"); +const resolve_1 = require("../resolve"); +const util_1 = require("../util"); +const errors_1 = require("../errors"); +// schema compilation - generates validation function, subschemaCode (below) is used for subschemas +function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); +} +exports.validateFunctionCode = validateFunctionCode; +function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) { + gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + } + else { + gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } +} +function destructureValCxt(opts) { + return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; +} +function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._) `""`); + gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`); + }); +} +function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) + commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) + resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + return; +} +function resetEvaluated(it) { + // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`); + gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`)); + gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`)); +} +function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil; +} +// schema compilation - this function is used recursively to generate code for sub-schemas +function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); +} +function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (self.RULES.all[key]) + return true; + return false; +} +function isSchemaObj(it) { + return typeof it.schema != "boolean"; +} +function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) + commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + // TODO var + gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); +} +function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); +} +function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) + return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); + schemaKeywords(it, types, !checkedTypes, errsCount); +} +function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { + self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } +} +function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) { + (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } +} +function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) + it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); +} +function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) + throw new Error("async schema in sync schema"); +} +function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) { + gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`); + } + else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } +} +function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) { + // TODO assign unevaluated + gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`)); + } + else { + gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) + assignEvaluated(it); + gen.return((0, codegen_1._) `${names_1.default.errors} === 0`); + } +} +function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) + gen.assign((0, codegen_1._) `${evaluated}.props`, props); + if (items instanceof codegen_1.Name) + gen.assign((0, codegen_1._) `${evaluated}.items`, items); +} +function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast + return; + } + if (!opts.jtd) + checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) + groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) + return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } + else { + iterateKeywords(it, group); + } + // TODO make it "ok" call? + if (!allErrors) + gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`); + } +} +function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults }, } = it; + if (useDefaults) + (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) { + if ((0, applicability_1.shouldUseRule)(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type); + } + } + }); +} +function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) + return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) + checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); +} +function checkContextTypes(it, types) { + if (!types.length) + return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) { + strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + } + }); + narrowSchemaTypes(it, types); +} +function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } +} +function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } +} +function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer")); +} +function includesType(ts, t) { + return ts.includes(t) || (t === "integer" && ts.includes("number")); +} +function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) { + if (includesType(withTypes, t)) + ts.push(t); + else if (withTypes.includes("integer") && t === "number") + ts.push("integer"); + } + it.dataTypes = ts; +} +function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); +} +class KeywordCxt { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + } + else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + } + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) + failAction(); + else + this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) + this.gen.endIf(); + } + else { + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), undefined, failAction); + } + fail(condition) { + if (condition === undefined) { + this.error(); + if (!this.allErrors) + this.gen.if(false); // this branch will be removed by gen.optimize + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + fail$data(condition) { + if (!this.$data) + return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + ; + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === undefined) + throw new Error('add "trackErrors" to keyword definition'); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) + this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) + Object.assign(this.params, obj); + else + this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) + return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) + gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) + gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof codegen_1.Name)) + throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone + return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) + return; + if (it.props !== true && schemaCxt.props !== undefined) { + it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + } + if (it.items !== true && schemaCxt.items !== undefined) { + it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } +} +exports.KeywordCxt = KeywordCxt; +function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) { + def.code(cxt, ruleType); + } + else if (cxt.$data && def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } + else if ("macro" in def) { + (0, keyword_1.macroKeywordCode)(cxt, def); + } + else if (def.compile || def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } +} +const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; +const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; +function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") + return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) + throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } + else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) + throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) + throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) + throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) + return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) { + if (segment) { + data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._) `${expr} && ${data}`; + } + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } +} +exports.getData = getData; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/index.js.map b/node_modules/ajv/dist/compile/validate/index.js.map new file mode 100644 index 000000000..cdf5854ea --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/compile/validate/index.ts"],"names":[],"mappings":";;;AASA,6CAAoE;AACpE,yCAAiE;AACjE,mDAA6D;AAC7D,yCAAmF;AACnF,yCAAyC;AACzC,uCAAkG;AAClG,2CAAiG;AACjG,wCAAwF;AACxF,oCAAwB;AACxB,wCAAqC;AACrC,kCAOgB;AAEhB,sCAMkB;AAElB,mGAAmG;AACnG,SAAgB,oBAAoB,CAAC,E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EAAA,GAAG,IAAI,GAAG,IAAA,qBAAW,EAAC,IAAA,0BAAmB,EAAC,OAAO,CAAC,CAAC,EAAE,CAAA;YAC7D,IAAI,GAAG,IAAA,WAAC,EAAA,GAAG,IAAI,OAAO,IAAI,EAAE,CAAA;QAC9B,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;IAEX,SAAS,QAAQ,CAAC,WAAmB,EAAE,EAAU;QAC/C,OAAO,iBAAiB,WAAW,IAAI,EAAE,gCAAgC,SAAS,EAAE,CAAA;IACtF,CAAC;AACH,CAAC;AAtCD,0BAsCC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/keyword.d.ts b/node_modules/ajv/dist/compile/validate/keyword.d.ts new file mode 100644 index 000000000..d15cee878 --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/keyword.d.ts @@ -0,0 +1,8 @@ +import type { KeywordCxt } from "."; +import type { AddedKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition } from "../../types"; +import type { SchemaObjCxt } from ".."; +import type { JSONType } from "../rules"; +export declare function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void; +export declare function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void; +export declare function validSchemaType(schema: unknown, schemaType: JSONType[], allowUndefined?: boolean): boolean; +export declare function validateKeywordUsage({ schema, opts, self, errSchemaPath }: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string): void; diff --git a/node_modules/ajv/dist/compile/validate/keyword.js b/node_modules/ajv/dist/compile/validate/keyword.js new file mode 100644 index 000000000..1109d3a45 --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/keyword.js @@ -0,0 +1,124 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; +const codegen_1 = require("../codegen"); +const names_1 = require("../names"); +const code_1 = require("../../vocabularies/code"); +const errors_1 = require("../errors"); +function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) + it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true, + }, valid); + cxt.pass(valid, () => cxt.error(true)); +} +exports.macroKeywordCode = macroKeywordCode; +function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => cxt.error()); + } + else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._) `${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !(("compile" in def && !$data) || def.schema === false); + gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a; + gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors); + } +} +exports.funcKeywordCode = funcKeywordCode; +function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`)); +} +function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => { + gen + .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`) + .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); +} +function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) + throw new Error("async keyword in sync schema"); +} +function useKeyword(gen, keyword, result) { + if (result === undefined) + throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); +} +function validSchemaType(schema, schemaType, allowUndefined = false) { + // TODO add tests + return (!schemaType.length || + schemaType.some((st) => st === "array" + ? Array.isArray(schema) + : st === "object" + ? schema && typeof schema == "object" && !Array.isArray(schema) + : typeof schema == st || (allowUndefined && typeof schema == "undefined"))); +} +exports.validSchemaType = validSchemaType; +function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error"); + } + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + } + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]); + if (!valid) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + + self.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") + self.logger.error(msg); + else + throw new Error(msg); + } + } +} +exports.validateKeywordUsage = validateKeywordUsage; +//# sourceMappingURL=keyword.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/keyword.js.map b/node_modules/ajv/dist/compile/validate/keyword.js.map new file mode 100644 index 000000000..ad1d1b99a --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/keyword.js.map @@ -0,0 +1 @@ +{"version":3,"file":"keyword.js","sourceRoot":"","sources":["../../../lib/compile/validate/keyword.ts"],"names":[],"mappings":";;;AAUA,wCAAsE;AACtE,oCAAwB;AAExB,kDAAwD;AACxD,sCAAsC;AAItC,SAAgB,gBAAgB,CAAC,GAAe,EAAE,GAA2B;IAC3E,MAAM,EAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IACpD,MAAM,WAAW,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,CAAC,CAAA;IACrE,MAAM,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE,OAAO,EAAE,WAAW,CAAC,CAAA;IACvD,IAAI,EAAE,CAAC,IAAI,CAAC,cAAc,KAAK,KAAK;QAAE,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,IAAI,CAAC,CAAA;IAE/E,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/B,GAAG,CAAC,SAAS,CACX;QACE,MAAM,EAAE,WAAW;QACnB,UAAU,EAAE,aAAG;QACf,aAAa,EAAE,GAAG,EAAE,CAAC,aAAa,IAAI,OAAO,EAAE;QAC/C,YAAY,EAAE,SAAS;QACvB,aAAa,EAAE,IAAI;KACpB,EACD,KAAK,CACN,CAAA;IACD,GAAG,CAAC,IAAI,CAAC,KA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/dist/compile/validate/subschema.d.ts b/node_modules/ajv/dist/compile/validate/subschema.d.ts new file mode 100644 index 000000000..b92785f2d --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/subschema.d.ts @@ -0,0 +1,47 @@ +import type { AnySchema } from "../../types"; +import type { SchemaObjCxt } from ".."; +import { Code, Name } from "../codegen"; +import { Type } from "../util"; +import type { JSONType } from "../rules"; +export interface SubschemaContext { + schema: AnySchema; + schemaPath: Code; + errSchemaPath: string; + topSchemaRef?: Code; + errorPath?: Code; + dataLevel?: number; + dataTypes?: JSONType[]; + data?: Name; + parentData?: Name; + parentDataProperty?: Code | number; + dataNames?: Name[]; + dataPathArr?: (Code | number)[]; + propertyName?: Name; + jtdDiscriminator?: string; + jtdMetadata?: boolean; + compositeRule?: true; + createErrors?: boolean; + allErrors?: boolean; +} +export type SubschemaArgs = Partial<{ + keyword: string; + schemaProp: string | number; + schema: AnySchema; + schemaPath: Code; + errSchemaPath: string; + topSchemaRef: Code; + data: Name | Code; + dataProp: Code | string | number; + dataTypes: JSONType[]; + definedProperties: Set; + propertyName: Name; + dataPropType: Type; + jtdDiscriminator: string; + jtdMetadata: boolean; + compositeRule: true; + createErrors: boolean; + allErrors: boolean; +}>; +export declare function getSubschema(it: SchemaObjCxt, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }: SubschemaArgs): SubschemaContext; +export declare function extendSubschemaData(subschema: SubschemaContext, it: SchemaObjCxt, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }: SubschemaArgs): void; +export declare function extendSubschemaMode(subschema: SubschemaContext, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }: SubschemaArgs): void; diff --git a/node_modules/ajv/dist/compile/validate/subschema.js b/node_modules/ajv/dist/compile/validate/subschema.js new file mode 100644 index 000000000..9de282869 --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/subschema.js @@ -0,0 +1,81 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; +const codegen_1 = require("../codegen"); +const util_1 = require("../util"); +function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== undefined && schema !== undefined) { + throw new Error('both "keyword" and "schema" passed, only one allowed'); + } + if (keyword !== undefined) { + const sch = it.schema[keyword]; + return schemaProp === undefined + ? { + schema: sch, + schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + } + : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`, + }; + } + if (schema !== undefined) { + if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath, + }; + } + throw new Error('either "keyword" or "schema" must be passed'); +} +exports.getSubschema = getSubschema; +function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== undefined && dataProp !== undefined) { + throw new Error('both "data" and "dataProp" passed, only one allowed'); + } + const { gen } = it; + if (dataProp !== undefined) { + const { errorPath, dataPathArr, opts } = it; + const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); + dataContextProps(nextData); + subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== undefined) { + const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once? + dataContextProps(nextData); + if (propertyName !== undefined) + subschema.propertyName = propertyName; + // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr + } + if (dataTypes) + subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } +} +exports.extendSubschemaData = extendSubschemaData; +function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== undefined) + subschema.compositeRule = compositeRule; + if (createErrors !== undefined) + subschema.createErrors = createErrors; + if (allErrors !== undefined) + subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; // not inherited + subschema.jtdMetadata = jtdMetadata; // not inherited +} +exports.extendSubschemaMode = extendSubschemaMode; +//# sourceMappingURL=subschema.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/compile/validate/subschema.js.map b/node_modules/ajv/dist/compile/validate/subschema.js.map new file mode 100644 index 000000000..e4f903fbb --- /dev/null +++ b/node_modules/ajv/dist/compile/validate/subschema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subschema.js","sourceRoot":"","sources":["../../../lib/compile/validate/subschema.ts"],"names":[],"mappings":";;;AAEA,wCAA0D;AAC1D,kCAA0D;AA6C1D,SAAgB,YAAY,CAC1B,EAAgB,EAChB,EAAC,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,aAAa,EAAE,YAAY,EAAgB;IAErF,IAAI,OAAO,KAAK,SAAS,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QAClD,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAA;IACzE,CAAC;IAED,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,MAAM,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;QAC9B,OAAO,UAAU,KAAK,SAAS;YAC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BAAiB,GAAG,IAAI,GAAG,EAAU,CAAA;QACxC,SAAS,CAAC,UAAU,GAAG,EAAE,CAAC,IAAI,CAAA;QAC9B,SAAS,CAAC,SAAS,GAAG,CAAC,GAAG,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;IACpD,CAAC;AACH,CAAC;AArCD,kDAqCC;AAED,SAAgB,mBAAmB,CACjC,SAA2B,EAC3B,EAAC,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,YAAY,EAAE,SAAS,EAAgB;IAEtF,IAAI,aAAa,KAAK,SAAS;QAAE,SAAS,CAAC,aAAa,GAAG,aAAa,CAAA;IACxE,IAAI,YAAY,KAAK,SAAS;QAAE,SAAS,CAAC,YAAY,GAAG,YAAY,CAAA;IACrE,IAAI,SAAS,KAAK,SAAS;QAAE,SAAS,CAAC,SAAS,GAAG,SAAS,CAAA;IAC5D,SAAS,CAAC,gBAAgB,GAAG,gBAAgB,CAAA,CAAC,gBAAgB;IAC9D,SAAS,CAAC,WAAW,GAAG,WAAW,CAAA,CAAC,gBAAgB;AACtD,CAAC;AATD,kDASC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/core.d.ts b/node_modules/ajv/dist/core.d.ts new file mode 100644 index 000000000..4591ed9ec --- /dev/null +++ b/node_modules/ajv/dist/core.d.ts @@ -0,0 +1,173 @@ +export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, AnyValidateFunction, ErrorObject, ErrorNoParams, } from "./types"; +export { SchemaCxt, SchemaObjCxt } from "./compile"; +export interface Plugin { + (ajv: Ajv, options?: Opts): Ajv; + [prop: string]: any; +} +export { KeywordCxt } from "./compile/validate"; +export { DefinedError } from "./vocabularies/errors"; +export { JSONType } from "./compile/rules"; +export { JSONSchemaType } from "./types/json-schema"; +export { JTDSchemaType, SomeJTDSchemaType, JTDDataType } from "./types/jtd-schema"; +export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen"; +import type { Schema, AnySchema, AnySchemaObject, SchemaObject, AsyncSchema, Vocabulary, KeywordDefinition, AddedKeywordDefinition, AnyValidateFunction, ValidateFunction, AsyncValidateFunction, ErrorObject, Format, AddedFormat, RegExpEngine, UriResolver } from "./types"; +import type { JSONSchemaType } from "./types/json-schema"; +import type { JTDSchemaType, SomeJTDSchemaType, JTDDataType } from "./types/jtd-schema"; +import ValidationError from "./runtime/validation_error"; +import MissingRefError from "./compile/ref_error"; +import { ValidationRules } from "./compile/rules"; +import { SchemaEnv } from "./compile"; +import { Code, ValueScope } from "./compile/codegen"; +export type Options = CurrentOptions & DeprecatedOptions; +export interface CurrentOptions { + strict?: boolean | "log"; + strictSchema?: boolean | "log"; + strictNumbers?: boolean | "log"; + strictTypes?: boolean | "log"; + strictTuples?: boolean | "log"; + strictRequired?: boolean | "log"; + allowMatchingProperties?: boolean; + allowUnionTypes?: boolean; + validateFormats?: boolean; + $data?: boolean; + allErrors?: boolean; + verbose?: boolean; + discriminator?: boolean; + unicodeRegExp?: boolean; + timestamp?: "string" | "date"; + parseDate?: boolean; + allowDate?: boolean; + $comment?: true | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown); + formats?: { + [Name in string]?: Format; + }; + keywords?: Vocabulary; + schemas?: AnySchema[] | { + [Key in string]?: AnySchema; + }; + logger?: Logger | false; + loadSchema?: (uri: string) => Promise; + removeAdditional?: boolean | "all" | "failing"; + useDefaults?: boolean | "empty"; + coerceTypes?: boolean | "array"; + next?: boolean; + unevaluated?: boolean; + dynamicRef?: boolean; + schemaId?: "id" | "$id"; + jtd?: boolean; + meta?: SchemaObject | boolean; + defaultMeta?: string | AnySchemaObject; + validateSchema?: boolean | "log"; + addUsedSchema?: boolean; + inlineRefs?: boolean | number; + passContext?: boolean; + loopRequired?: number; + loopEnum?: number; + ownProperties?: boolean; + multipleOfPrecision?: number; + int32range?: boolean; + messages?: boolean; + code?: CodeOptions; + uriResolver?: UriResolver; +} +export interface CodeOptions { + es5?: boolean; + esm?: boolean; + lines?: boolean; + optimize?: boolean | number; + formats?: Code; + source?: boolean; + process?: (code: string, schema?: SchemaEnv) => string; + regExp?: RegExpEngine; +} +interface InstanceCodeOptions extends CodeOptions { + regExp: RegExpEngine; + optimize: number; +} +interface DeprecatedOptions { + /** @deprecated */ + ignoreKeywordsWithRef?: boolean; + /** @deprecated */ + jsPropertySyntax?: boolean; + /** @deprecated */ + unicode?: boolean; +} +type RequiredInstanceOptions = { + [K in "strictSchema" | "strictNumbers" | "strictTypes" | "strictTuples" | "strictRequired" | "inlineRefs" | "loopRequired" | "loopEnum" | "meta" | "messages" | "schemaId" | "addUsedSchema" | "validateSchema" | "validateFormats" | "int32range" | "unicodeRegExp" | "uriResolver"]: NonNullable; +} & { + code: InstanceCodeOptions; +}; +export type InstanceOptions = Options & RequiredInstanceOptions; +export interface Logger { + log(...args: unknown[]): unknown; + warn(...args: unknown[]): unknown; + error(...args: unknown[]): unknown; +} +export default class Ajv { + opts: InstanceOptions; + errors?: ErrorObject[] | null; + logger: Logger; + readonly scope: ValueScope; + readonly schemas: { + [Key in string]?: SchemaEnv; + }; + readonly refs: { + [Ref in string]?: SchemaEnv | string; + }; + readonly formats: { + [Name in string]?: AddedFormat; + }; + readonly RULES: ValidationRules; + readonly _compilations: Set; + private readonly _loading; + private readonly _cache; + private readonly _metaOpts; + static ValidationError: typeof ValidationError; + static MissingRefError: typeof MissingRefError; + constructor(opts?: Options); + _addVocabularies(): void; + _addDefaultMetaSchema(): void; + defaultMeta(): string | AnySchemaObject | undefined; + validate(schema: Schema | string, data: unknown): boolean; + validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise; + validate(schema: Schema | JSONSchemaType | string, data: unknown): data is T; + validate(schema: JTDSchemaType, data: unknown): data is T; + validate(schema: T, data: unknown): data is JTDDataType; + validate(schema: AsyncSchema, data: unknown | T): Promise; + validate(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise; + compile(schema: Schema | JSONSchemaType, _meta?: boolean): ValidateFunction; + compile(schema: JTDSchemaType, _meta?: boolean): ValidateFunction; + compile(schema: T, _meta?: boolean): ValidateFunction>; + compile(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction; + compile(schema: AnySchema, _meta?: boolean): AnyValidateFunction; + compileAsync(schema: SchemaObject | JSONSchemaType, _meta?: boolean): Promise>; + compileAsync(schema: JTDSchemaType, _meta?: boolean): Promise>; + compileAsync(schema: AsyncSchema, meta?: boolean): Promise>; + compileAsync(schema: AnySchemaObject, meta?: boolean): Promise>; + addSchema(schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored + key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + _validateSchema?: boolean | "log"): Ajv; + addMetaSchema(schema: AnySchemaObject, key?: string, // schema key + _validateSchema?: boolean | "log"): Ajv; + validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise; + getSchema(keyRef: string): AnyValidateFunction | undefined; + removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv; + addVocabulary(definitions: Vocabulary): Ajv; + addKeyword(kwdOrDef: string | KeywordDefinition, def?: KeywordDefinition): Ajv; + getKeyword(keyword: string): AddedKeywordDefinition | boolean; + removeKeyword(keyword: string): Ajv; + addFormat(name: string, format: Format): Ajv; + errorsText(errors?: ErrorObject[] | null | undefined, // optional array of validation errors + { separator, dataVar }?: ErrorsTextOptions): string; + $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject; + private _removeAllSchemas; + _addSchema(schema: AnySchema, meta?: boolean, baseId?: string, validateSchema?: boolean | "log", addSchema?: boolean): SchemaEnv; + private _checkUnique; + private _compileSchemaEnv; + private _compileMetaSchema; +} +export interface ErrorsTextOptions { + separator?: string; + dataVar?: string; +} diff --git a/node_modules/ajv/dist/core.js b/node_modules/ajv/dist/core.js new file mode 100644 index 000000000..7e30c83af --- /dev/null +++ b/node_modules/ajv/dist/core.js @@ -0,0 +1,618 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; +var validate_1 = require("./compile/validate"); +Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); +var codegen_1 = require("./compile/codegen"); +Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } }); +Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } }); +Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); +Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); +Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); +Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); +const validation_error_1 = require("./runtime/validation_error"); +const ref_error_1 = require("./compile/ref_error"); +const rules_1 = require("./compile/rules"); +const compile_1 = require("./compile"); +const codegen_2 = require("./compile/codegen"); +const resolve_1 = require("./compile/resolve"); +const dataType_1 = require("./compile/validate/dataType"); +const util_1 = require("./compile/util"); +const $dataRefSchema = require("./refs/data.json"); +const uri_1 = require("./runtime/uri"); +const defaultRegExp = (str, flags) => new RegExp(str, flags); +defaultRegExp.code = "new RegExp"; +const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; +const EXT_SCOPE_NAMES = new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error", +]); +const removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now.", +}; +const deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.', +}; +const MAX_EXPRESSION = 200; +// eslint-disable-next-line complexity +function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver: uriResolver, + }; +} +class Ajv { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = new Set(); + this._loading = {}; + this._cache = new Map(); + opts = this.opts = { ...opts, ...requiredOptions(opts) }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) + addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) + addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") + this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) + this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined); + } + validate(schemaKeyRef, // key, ref or schema object + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents + data // to be validated + ) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) + throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } + else { + v = this.compile(schemaKeyRef); + } + const valid = v(data); + if (!("$async" in v)) + this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return (sch.validate || this._compileSchemaEnv(sch)); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function"); + } + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, { $ref }, true); + } + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } + catch (e) { + if (!(e instanceof ref_error_1.default)) + throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) + await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) + this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) + return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } + finally { + delete this._loading[ref]; + } + } + } + // Adds schema to the instance + addSchema(schema, // If array is passed, `key` will be ignored + key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead. + ) { + if (Array.isArray(schema)) { + for (const sch of schema) + this.addSchema(sch, undefined, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== undefined && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`); + } + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema(schema, key, // schema key + _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema + ) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + // Validate schema against its meta-schema + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") + return true; + let $schema; + $schema = schema.$schema; + if ($schema !== undefined && typeof $schema != "string") { + throw new Error("$schema must be a string"); + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") + this.logger.error(message); + else + throw new Error(message); + } + return valid; + } + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") + keyRef = sch; + if (sch === undefined) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) + return; + this.refs[keyRef] = sch; + } + return (sch.validate || this._compileSchemaEnv(sch)); + } + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") + this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: + throw new Error("ajv.removeSchema: invalid parameter"); + } + } + // add "vocabulary" - a collection of keywords + addVocabulary(definitions) { + for (const def of definitions) + this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def // deprecated + ) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } + else if (typeof kwdOrDef == "object" && def === undefined) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array"); + } + } + else { + throw new Error("invalid addKeywords parameters"); + } + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType), + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 + ? (k) => addRule.call(this, k, definition) + : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + // Remove keyword + removeKeyword(keyword) { + // TODO return type should be Ajv + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) + group.rules.splice(i, 1); + } + return this; + } + // Add format + addFormat(name, format) { + if (typeof format == "string") + format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, // optional array of validation errors + { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar` + ) { + if (!errors || errors.length === 0) + return "No errors"; + return errors + .map((e) => `${dataVar}${e.instancePath} ${e.message}`) + .reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); // first segment is an empty string + let keywords = metaSchema; + for (const seg of segments) + keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") + continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) + keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef]; + } + else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") { + id = schema[schemaId]; + } + else { + if (this.opts.jtd) + throw new Error("schema must be object"); + else if (typeof schema != "boolean") + throw new Error("schema must be object or boolean"); + } + let sch = this._cache.get(schema); + if (sch !== undefined) + return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + // TODO atm it is allowed to overwrite schemas without id (instead of not adding them) + if (baseId) + this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) + this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`); + } + } + _compileSchemaEnv(sch) { + if (sch.meta) + this._compileMetaSchema(sch); + else + compile_1.compileSchema.call(this, sch); + /* istanbul ignore if */ + if (!sch.validate) + throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } + finally { + this.opts = currentOpts; + } + } +} +Ajv.ValidationError = validation_error_1.default; +Ajv.MissingRefError = ref_error_1.default; +exports.default = Ajv; +function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) + this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } +} +function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line + return this.schemas[keyRef] || this.refs[keyRef]; +} +function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) + return; + if (Array.isArray(optsSchemas)) + this.addSchema(optsSchemas); + else + for (const key in optsSchemas) + this.addSchema(optsSchemas[key], key); +} +function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) + this.addFormat(name, format); + } +} +function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) + def.keyword = keyword; + this.addKeyword(def); + } +} +function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) + delete metaOpts[opt]; + return metaOpts; +} +const noLogs = { log() { }, warn() { }, error() { } }; +function getLogger(logger) { + if (logger === false) + return noLogs; + if (logger === undefined) + return console; + if (logger.log && logger.warn && logger.error) + return logger; + throw new Error("logger must implement log, warn and error methods"); +} +const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; +function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) + throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) + throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) + return; + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function'); + } +} +function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) + throw new Error('keyword with "post" flag cannot have "type"'); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) + return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType), + }, + }; + if (definition.before) + addBeforeRule.call(this, ruleGroup, rule, definition.before); + else + ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd)); +} +function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) { + ruleGroup.rules.splice(i, 0, rule); + } + else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } +} +function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === undefined) + return; + if (def.$data && this.opts.$data) + metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); +} +const $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", +}; +function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; +} +//# sourceMappingURL=core.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/core.js.map b/node_modules/ajv/dist/core.js.map new file mode 100644 index 000000000..3760c3e46 --- /dev/null +++ b/node_modules/ajv/dist/core.js.map @@ -0,0 +1 @@ +{"version":3,"file":"core.js","sourceRoot":"","sources":["../lib/core.ts"],"names":[],"mappings":";;;AA4BA,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAKlB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AAsBnD,iEAAwD;AACxD,mDAAiD;AACjD,2CAAoF;AACpF,uCAAiE;AACjE,+CAAkD;AAClD,+CAA4D;AAC5D,0DAAwD;AACxD,yCAAuC;AACvC,mDAAkD;AAElD,uCAA8C;AAE9C,MAAM,aAAa,GAAiB,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;AAC1E,aAAa,CAAC,IAAI,GAAG,YAAY,CAAA;AAEjC,MAAM,mBAAmB,GAAsB,CAAC,kBAAkB,EAAE,aAAa,EAAE,aAAa,CAAC,CAAA;AACjG,MAAM,eAAe,GAAG,IAAI,GAAG,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AE,IAAI,CAAC,CAAA;AACrD,CAAC;AAED,MAAM,QAAQ,GAAG;IACf,IAAI,EAAE,gFAAgF;CACvF,CAAA;AAED,SAAS,YAAY,CAAC,MAAiB;IACrC,OAAO,EAAC,KAAK,EAAE,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAC,CAAA;AACpC,CAAC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/jtd.d.ts b/node_modules/ajv/dist/jtd.d.ts new file mode 100644 index 000000000..a079ba4b1 --- /dev/null +++ b/node_modules/ajv/dist/jtd.d.ts @@ -0,0 +1,47 @@ +import type { AnySchemaObject, SchemaObject, JTDParser } from "./types"; +import type { JTDSchemaType, SomeJTDSchemaType, JTDDataType } from "./types/jtd-schema"; +import AjvCore, { CurrentOptions } from "./core"; +type JTDOptions = CurrentOptions & { + strict?: never; + allowMatchingProperties?: never; + allowUnionTypes?: never; + validateFormats?: never; + $data?: never; + verbose?: boolean; + $comment?: never; + formats?: never; + loadSchema?: never; + useDefaults?: never; + coerceTypes?: never; + next?: never; + unevaluated?: never; + dynamicRef?: never; + meta?: boolean; + defaultMeta?: never; + inlineRefs?: boolean; + loopRequired?: never; + multipleOfPrecision?: never; +}; +export declare class Ajv extends AjvCore { + constructor(opts?: JTDOptions); + _addVocabularies(): void; + _addDefaultMetaSchema(): void; + defaultMeta(): string | AnySchemaObject | undefined; + compileSerializer(schema: SchemaObject): (data: T) => string; + compileSerializer(schema: JTDSchemaType): (data: T) => string; + compileParser(schema: SchemaObject): JTDParser; + compileParser(schema: JTDSchemaType): JTDParser; + private _compileSerializer; + private _compileParser; +} +export default Ajv; +export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, ErrorObject, ErrorNoParams, JTDParser, } from "./types"; +export { Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions } from "./core"; +export { SchemaCxt, SchemaObjCxt } from "./compile"; +export { KeywordCxt } from "./compile/validate"; +export { JTDErrorObject } from "./vocabularies/jtd"; +export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen"; +export { JTDSchemaType, SomeJTDSchemaType, JTDDataType }; +export { JTDOptions }; +export { default as ValidationError } from "./runtime/validation_error"; +export { default as MissingRefError } from "./compile/ref_error"; diff --git a/node_modules/ajv/dist/jtd.js b/node_modules/ajv/dist/jtd.js new file mode 100644 index 000000000..1a3baaf2e --- /dev/null +++ b/node_modules/ajv/dist/jtd.js @@ -0,0 +1,72 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; +const core_1 = require("./core"); +const jtd_1 = require("./vocabularies/jtd"); +const jtd_schema_1 = require("./refs/jtd-schema"); +const serialize_1 = require("./compile/jtd/serialize"); +const parse_1 = require("./compile/jtd/parse"); +const META_SCHEMA_ID = "JTD-meta-schema"; +class Ajv extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + jtd: true, + }); + } + _addVocabularies() { + super._addVocabularies(); + this.addVocabulary(jtd_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + this.addMetaSchema(jtd_schema_1.default, META_SCHEMA_ID, false); + } + defaultMeta() { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); + } + compileSerializer(schema) { + const sch = this._addSchema(schema); + return sch.serialize || this._compileSerializer(sch); + } + compileParser(schema) { + const sch = this._addSchema(schema); + return (sch.parse || this._compileParser(sch)); + } + _compileSerializer(sch) { + serialize_1.default.call(this, sch, sch.schema.definitions || {}); + /* istanbul ignore if */ + if (!sch.serialize) + throw new Error("ajv implementation error"); + return sch.serialize; + } + _compileParser(sch) { + parse_1.default.call(this, sch, sch.schema.definitions || {}); + /* istanbul ignore if */ + if (!sch.parse) + throw new Error("ajv implementation error"); + return sch.parse; + } +} +exports.Ajv = Ajv; +module.exports = exports = Ajv; +module.exports.Ajv = Ajv; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = Ajv; +var validate_1 = require("./compile/validate"); +Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); +var codegen_1 = require("./compile/codegen"); +Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } }); +Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } }); +Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); +Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); +Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); +Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); +var validation_error_1 = require("./runtime/validation_error"); +Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } }); +var ref_error_1 = require("./compile/ref_error"); +Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } }); +//# sourceMappingURL=jtd.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/jtd.js.map b/node_modules/ajv/dist/jtd.js.map new file mode 100644 index 000000000..6bf9f3b1b --- /dev/null +++ b/node_modules/ajv/dist/jtd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jtd.js","sourceRoot":"","sources":["../lib/jtd.ts"],"names":[],"mappings":";;;AAEA,iCAA8C;AAC9C,4CAA8C;AAC9C,kDAA6C;AAC7C,uDAAuD;AACvD,+CAA+C;AAG/C,MAAM,cAAc,GAAG,iBAAiB,CAAA;AA4BxC,MAAa,GAAI,SAAQ,cAAO;IAC9B,YAAY,OAAmB,EAAE;QAC/B,KAAK,CAAC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O,GAAG,CAAC,SAAS,CAAA;IACtB,CAAC;IAEO,cAAc,CAAC,GAAc;QACnC,eAAa,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAG,GAAG,CAAC,MAA0B,CAAC,WAAW,IAAI,EAAE,CAAC,CAAA;QAChF,wBAAwB;QACxB,IAAI,CAAC,GAAG,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QAC3D,OAAO,GAAG,CAAC,KAAK,CAAA;IAClB,CAAC;CACF;AAvDD,kBAuDC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,GAAG,CAAA;AAC9B,MAAM,CAAC,OAAO,CAAC,GAAG,GAAG,GAAG,CAAA;AACxB,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,GAAG,CAAA;AA0BlB,+CAA6C;AAArC,sGAAA,UAAU,OAAA;AAElB,6CAA6F;AAArF,4FAAA,CAAC,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,oGAAA,SAAS,OAAA;AAAE,8FAAA,GAAG,OAAA;AAAE,+FAAA,IAAI,OAAA;AAAQ,kGAAA,OAAO,OAAA;AAInD,+DAAqE;AAA7D,mHAAA,OAAO,OAAmB;AAClC,iDAA8D;AAAtD,4GAAA,OAAO,OAAmB"} \ No newline at end of file diff --git a/node_modules/ajv/dist/refs/data.json b/node_modules/ajv/dist/refs/data.json new file mode 100644 index 000000000..9ffc9f5ce --- /dev/null +++ b/node_modules/ajv/dist/refs/data.json @@ -0,0 +1,13 @@ +{ + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", + "type": "object", + "required": ["$data"], + "properties": { + "$data": { + "type": "string", + "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}] + } + }, + "additionalProperties": false +} diff --git a/node_modules/ajv/dist/refs/json-schema-2019-09/index.d.ts b/node_modules/ajv/dist/refs/json-schema-2019-09/index.d.ts new file mode 100644 index 000000000..cf008331f --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2019-09/index.d.ts @@ -0,0 +1,2 @@ +import type Ajv from "../../core"; +export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv; diff --git a/node_modules/ajv/dist/refs/json-schema-2019-09/index.js b/node_modules/ajv/dist/refs/json-schema-2019-09/index.js new file mode 100644 index 000000000..e86496282 --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2019-09/index.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const metaSchema = require("./schema.json"); +const applicator = require("./meta/applicator.json"); +const content = require("./meta/content.json"); +const core = require("./meta/core.json"); +const format = require("./meta/format.json"); +const metadata = require("./meta/meta-data.json"); +const validation = require("./meta/validation.json"); +const META_SUPPORT_DATA = ["/properties"]; +function addMetaSchema2019($data) { + ; + [ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } +} +exports.default = addMetaSchema2019; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/refs/json-schema-2019-09/index.js.map b/node_modules/ajv/dist/refs/json-schema-2019-09/index.js.map new file mode 100644 index 000000000..9b8a36d61 --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2019-09/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/refs/json-schema-2019-09/index.ts"],"names":[],"mappings":";;AAEA,4CAA2C;AAC3C,qDAAoD;AACpD,+CAA8C;AAC9C,yCAAwC;AACxC,6CAA4C;AAC5C,kDAAiD;AACjD,qDAAoD;AAEpD,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,SAAwB,iBAAiB,CAAY,KAAe;IAClE,CAAC;IAAA;QACC,UAAU;QACV,UAAU;QACV,OAAO;QACP,IAAI;QACJ,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;QACvB,QAAQ;QACR,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC;KAC5B,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAA;IAC7D,OAAO,IAAI,CAAA;IAEX,SAAS,SAAS,CAAC,GAAQ,EAAE,GAAoB;QAC/C,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;IAClE,CAAC;AACH,CAAC;AAfD,oCAeC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json b/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json new file mode 100644 index 000000000..c5e91cf2a --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json @@ -0,0 +1,53 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/applicator": true + }, + "$recursiveAnchor": true, + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "additionalItems": {"$recursiveRef": "#"}, + "unevaluatedItems": {"$recursiveRef": "#"}, + "items": { + "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}] + }, + "contains": {"$recursiveRef": "#"}, + "additionalProperties": {"$recursiveRef": "#"}, + "unevaluatedProperties": {"$recursiveRef": "#"}, + "properties": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { + "$recursiveRef": "#" + } + }, + "propertyNames": {"$recursiveRef": "#"}, + "if": {"$recursiveRef": "#"}, + "then": {"$recursiveRef": "#"}, + "else": {"$recursiveRef": "#"}, + "allOf": {"$ref": "#/$defs/schemaArray"}, + "anyOf": {"$ref": "#/$defs/schemaArray"}, + "oneOf": {"$ref": "#/$defs/schemaArray"}, + "not": {"$recursiveRef": "#"} + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$recursiveRef": "#"} + } + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json b/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json new file mode 100644 index 000000000..b8f637343 --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentMediaType": {"type": "string"}, + "contentEncoding": {"type": "string"}, + "contentSchema": {"$recursiveRef": "#"} + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json b/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json new file mode 100644 index 000000000..f71adbff0 --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json @@ -0,0 +1,57 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true + }, + "$recursiveAnchor": true, + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$anchor": { + "type": "string", + "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveRef": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveAnchor": { + "type": "boolean", + "default": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + } + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json b/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json new file mode 100644 index 000000000..03ccfce26 --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/format", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/format": true + }, + "$recursiveAnchor": true, + + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "format": {"type": "string"} + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json b/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json new file mode 100644 index 000000000..0e194326f --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/meta-data": true + }, + "$recursiveAnchor": true, + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json b/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json new file mode 100644 index 000000000..7027a1279 --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/validation": true + }, + "$recursiveAnchor": true, + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, + "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, + "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, + "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/$defs/stringArray"}, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "type": { + "anyOf": [ + {"$ref": "#/$defs/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/$defs/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json b/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json new file mode 100644 index 000000000..54eb7157a --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json @@ -0,0 +1,39 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", + "type": "object", + "additionalProperties": { + "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}] + } + } + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2020-12/index.d.ts b/node_modules/ajv/dist/refs/json-schema-2020-12/index.d.ts new file mode 100644 index 000000000..c232ab05c --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2020-12/index.d.ts @@ -0,0 +1,2 @@ +import type Ajv from "../../core"; +export default function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv; diff --git a/node_modules/ajv/dist/refs/json-schema-2020-12/index.js b/node_modules/ajv/dist/refs/json-schema-2020-12/index.js new file mode 100644 index 000000000..d92567564 --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2020-12/index.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const metaSchema = require("./schema.json"); +const applicator = require("./meta/applicator.json"); +const unevaluated = require("./meta/unevaluated.json"); +const content = require("./meta/content.json"); +const core = require("./meta/core.json"); +const format = require("./meta/format-annotation.json"); +const metadata = require("./meta/meta-data.json"); +const validation = require("./meta/validation.json"); +const META_SUPPORT_DATA = ["/properties"]; +function addMetaSchema2020($data) { + ; + [ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } +} +exports.default = addMetaSchema2020; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/refs/json-schema-2020-12/index.js.map b/node_modules/ajv/dist/refs/json-schema-2020-12/index.js.map new file mode 100644 index 000000000..eb90027dd --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2020-12/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/refs/json-schema-2020-12/index.ts"],"names":[],"mappings":";;AAEA,4CAA2C;AAC3C,qDAAoD;AACpD,uDAAsD;AACtD,+CAA8C;AAC9C,yCAAwC;AACxC,wDAAuD;AACvD,kDAAiD;AACjD,qDAAoD;AAEpD,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,SAAwB,iBAAiB,CAAY,KAAe;IAClE,CAAC;IAAA;QACC,UAAU;QACV,UAAU;QACV,WAAW;QACX,OAAO;QACP,IAAI;QACJ,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;QACvB,QAAQ;QACR,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC;KAC5B,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAA;IAC7D,OAAO,IAAI,CAAA;IAEX,SAAS,SAAS,CAAC,GAAQ,EAAE,GAAoB;QAC/C,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;IAClE,CAAC;AACH,CAAC;AAhBD,oCAgBC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json new file mode 100644 index 000000000..674c913da --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json @@ -0,0 +1,48 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/applicator": true + }, + "$dynamicAnchor": "meta", + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "prefixItems": {"$ref": "#/$defs/schemaArray"}, + "items": {"$dynamicRef": "#meta"}, + "contains": {"$dynamicRef": "#meta"}, + "additionalProperties": {"$dynamicRef": "#meta"}, + "properties": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "default": {} + }, + "propertyNames": {"$dynamicRef": "#meta"}, + "if": {"$dynamicRef": "#meta"}, + "then": {"$dynamicRef": "#meta"}, + "else": {"$dynamicRef": "#meta"}, + "allOf": {"$ref": "#/$defs/schemaArray"}, + "anyOf": {"$ref": "#/$defs/schemaArray"}, + "oneOf": {"$ref": "#/$defs/schemaArray"}, + "not": {"$dynamicRef": "#meta"} + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$dynamicRef": "#meta"} + } + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json new file mode 100644 index 000000000..2ae23ddb5 --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentEncoding": {"type": "string"}, + "contentMediaType": {"type": "string"}, + "contentSchema": {"$dynamicRef": "#meta"} + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json new file mode 100644 index 000000000..4c8e5cb61 --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true + }, + "$dynamicAnchor": "meta", + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "$ref": "#/$defs/uriReferenceString", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": {"$ref": "#/$defs/uriString"}, + "$ref": {"$ref": "#/$defs/uriReferenceString"}, + "$anchor": {"$ref": "#/$defs/anchorString"}, + "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"}, + "$dynamicAnchor": {"$ref": "#/$defs/anchorString"}, + "$vocabulary": { + "type": "object", + "propertyNames": {"$ref": "#/$defs/uriString"}, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"} + } + }, + "$defs": { + "anchorString": { + "type": "string", + "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "uriReferenceString": { + "type": "string", + "format": "uri-reference" + } + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json new file mode 100644 index 000000000..83c26e35f --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true + }, + "$dynamicAnchor": "meta", + + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { + "format": {"type": "string"} + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json new file mode 100644 index 000000000..11946fb50 --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/meta-data": true + }, + "$dynamicAnchor": "meta", + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json new file mode 100644 index 000000000..5e4b203b2 --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true + }, + "$dynamicAnchor": "meta", + + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": {"$dynamicRef": "#meta"}, + "unevaluatedProperties": {"$dynamicRef": "#meta"} + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json new file mode 100644 index 000000000..e0ae13d9d --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/validation": true + }, + "$dynamicAnchor": "meta", + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "type": { + "anyOf": [ + {"$ref": "#/$defs/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/$defs/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, + "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, + "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, + "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/$defs/stringArray"}, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json b/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json new file mode 100644 index 000000000..1c68270fd --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json @@ -0,0 +1,55 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/unevaluated"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format-annotation"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", + "properties": { + "definitions": { + "$comment": "\"definitions\" has been replaced by \"$defs\".", + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "deprecated": true, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", + "type": "object", + "additionalProperties": { + "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}] + }, + "deprecated": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } +} diff --git a/node_modules/ajv/dist/refs/json-schema-draft-06.json b/node_modules/ajv/dist/refs/json-schema-draft-06.json new file mode 100644 index 000000000..5410064ba --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-draft-06.json @@ -0,0 +1,137 @@ +{ + "$schema": "http://json-schema.org/draft-06/schema#", + "$id": "http://json-schema.org/draft-06/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "examples": { + "type": "array", + "items": {} + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, + "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": {"$ref": "#"}, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], + "default": {} + }, + "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, + "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": {"$ref": "#"}, + "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, + "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/definitions/stringArray"}, + "additionalProperties": {"$ref": "#"}, + "definitions": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] + } + }, + "propertyNames": {"$ref": "#"}, + "const": {}, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + {"$ref": "#/definitions/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/definitions/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": {"type": "string"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"} + }, + "default": {} +} diff --git a/node_modules/ajv/dist/refs/json-schema-draft-07.json b/node_modules/ajv/dist/refs/json-schema-draft-07.json new file mode 100644 index 000000000..6a7485104 --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-draft-07.json @@ -0,0 +1,151 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, + "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": {"$ref": "#"}, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], + "default": true + }, + "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, + "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": {"$ref": "#"}, + "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, + "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/definitions/stringArray"}, + "additionalProperties": {"$ref": "#"}, + "definitions": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] + } + }, + "propertyNames": {"$ref": "#"}, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + {"$ref": "#/definitions/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/definitions/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": {"type": "string"}, + "contentMediaType": {"type": "string"}, + "contentEncoding": {"type": "string"}, + "if": {"$ref": "#"}, + "then": {"$ref": "#"}, + "else": {"$ref": "#"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"} + }, + "default": true +} diff --git a/node_modules/ajv/dist/refs/json-schema-secure.json b/node_modules/ajv/dist/refs/json-schema-secure.json new file mode 100644 index 000000000..3968abd5d --- /dev/null +++ b/node_modules/ajv/dist/refs/json-schema-secure.json @@ -0,0 +1,88 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#", + "title": "Meta-schema for the security assessment of JSON Schemas", + "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + } + }, + "dependencies": { + "patternProperties": { + "description": "prevent slow validation of large property names", + "required": ["propertyNames"], + "properties": { + "propertyNames": { + "required": ["maxLength"] + } + } + }, + "uniqueItems": { + "description": "prevent slow validation of large non-scalar arrays", + "if": { + "properties": { + "uniqueItems": {"const": true}, + "items": { + "properties": { + "type": { + "anyOf": [ + { + "enum": ["object", "array"] + }, + { + "type": "array", + "contains": {"enum": ["object", "array"]} + } + ] + } + } + } + } + }, + "then": { + "required": ["maxItems"] + } + }, + "pattern": { + "description": "prevent slow pattern matching of large strings", + "required": ["maxLength"] + }, + "format": { + "description": "prevent slow format validation of large strings", + "required": ["maxLength"] + } + }, + "properties": { + "additionalItems": {"$ref": "#"}, + "additionalProperties": {"$ref": "#"}, + "dependencies": { + "additionalProperties": { + "anyOf": [{"type": "array"}, {"$ref": "#"}] + } + }, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}] + }, + "definitions": { + "additionalProperties": {"$ref": "#"} + }, + "patternProperties": { + "additionalProperties": {"$ref": "#"} + }, + "properties": { + "additionalProperties": {"$ref": "#"} + }, + "if": {"$ref": "#"}, + "then": {"$ref": "#"}, + "else": {"$ref": "#"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"}, + "contains": {"$ref": "#"}, + "propertyNames": {"$ref": "#"} + } +} diff --git a/node_modules/ajv/dist/refs/jtd-schema.d.ts b/node_modules/ajv/dist/refs/jtd-schema.d.ts new file mode 100644 index 000000000..932797a38 --- /dev/null +++ b/node_modules/ajv/dist/refs/jtd-schema.d.ts @@ -0,0 +1,3 @@ +import { SchemaObject } from "../types"; +declare const jtdMetaSchema: SchemaObject; +export default jtdMetaSchema; diff --git a/node_modules/ajv/dist/refs/jtd-schema.js b/node_modules/ajv/dist/refs/jtd-schema.js new file mode 100644 index 000000000..1ee940afb --- /dev/null +++ b/node_modules/ajv/dist/refs/jtd-schema.js @@ -0,0 +1,118 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const shared = (root) => { + const sch = { + nullable: { type: "boolean" }, + metadata: { + optionalProperties: { + union: { elements: { ref: "schema" } }, + }, + additionalProperties: true, + }, + }; + if (root) + sch.definitions = { values: { ref: "schema" } }; + return sch; +}; +const emptyForm = (root) => ({ + optionalProperties: shared(root), +}); +const refForm = (root) => ({ + properties: { + ref: { type: "string" }, + }, + optionalProperties: shared(root), +}); +const typeForm = (root) => ({ + properties: { + type: { + enum: [ + "boolean", + "timestamp", + "string", + "float32", + "float64", + "int8", + "uint8", + "int16", + "uint16", + "int32", + "uint32", + ], + }, + }, + optionalProperties: shared(root), +}); +const enumForm = (root) => ({ + properties: { + enum: { elements: { type: "string" } }, + }, + optionalProperties: shared(root), +}); +const elementsForm = (root) => ({ + properties: { + elements: { ref: "schema" }, + }, + optionalProperties: shared(root), +}); +const propertiesForm = (root) => ({ + properties: { + properties: { values: { ref: "schema" } }, + }, + optionalProperties: { + optionalProperties: { values: { ref: "schema" } }, + additionalProperties: { type: "boolean" }, + ...shared(root), + }, +}); +const optionalPropertiesForm = (root) => ({ + properties: { + optionalProperties: { values: { ref: "schema" } }, + }, + optionalProperties: { + additionalProperties: { type: "boolean" }, + ...shared(root), + }, +}); +const discriminatorForm = (root) => ({ + properties: { + discriminator: { type: "string" }, + mapping: { + values: { + metadata: { + union: [propertiesForm(false), optionalPropertiesForm(false)], + }, + }, + }, + }, + optionalProperties: shared(root), +}); +const valuesForm = (root) => ({ + properties: { + values: { ref: "schema" }, + }, + optionalProperties: shared(root), +}); +const schema = (root) => ({ + metadata: { + union: [ + emptyForm, + refForm, + typeForm, + enumForm, + elementsForm, + propertiesForm, + optionalPropertiesForm, + discriminatorForm, + valuesForm, + ].map((s) => s(root)), + }, +}); +const jtdMetaSchema = { + definitions: { + schema: schema(false), + }, + ...schema(true), +}; +exports.default = jtdMetaSchema; +//# sourceMappingURL=jtd-schema.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/refs/jtd-schema.js.map b/node_modules/ajv/dist/refs/jtd-schema.js.map new file mode 100644 index 000000000..d46755b21 --- /dev/null +++ b/node_modules/ajv/dist/refs/jtd-schema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jtd-schema.js","sourceRoot":"","sources":["../../lib/refs/jtd-schema.ts"],"names":[],"mappings":";;AAIA,MAAM,MAAM,GAAe,CAAC,IAAI,EAAE,EAAE;IAClC,MAAM,GAAG,GAAiB;QACxB,QAAQ,EAAE,EAAC,IAAI,EAAE,SAAS,EAAC;QAC3B,QAAQ,EAAE;YACR,kBAAkB,EAAE;gBAClB,KAAK,EAAE,EAAC,QAAQ,EAAE,EAAC,GAAG,EAAE,QAAQ,EAAC,EAAC;aACnC;YACD,oBAAoB,EAAE,IAAI;SAC3B;KACF,CAAA;IACD,IAAI,IAAI;QAAE,GAAG,CAAC,WAAW,GAAG,EAAC,MAAM,EAAE,EAAC,GAAG,EAAE,QAAQ,EAAC,EAAC,CAAA;IACrD,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA;AAED,MAAM,SAAS,GAAe,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACvC,kBAAkB,EAAE,MAAM,CAAC,IAAI,CAAC;CACjC,CAAC,CAAA;AAEF,MAAM,OAAO,GAAe,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACrC,UAAU,EAAE;QACV,GA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AAG,MAAM,CAAC,IAAI,CAAC;CAChB,CAAA;AAED,kBAAe,aAAa,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/equal.d.ts b/node_modules/ajv/dist/runtime/equal.d.ts new file mode 100644 index 000000000..777cae20e --- /dev/null +++ b/node_modules/ajv/dist/runtime/equal.d.ts @@ -0,0 +1,6 @@ +import * as equal from "fast-deep-equal"; +type Equal = typeof equal & { + code: string; +}; +declare const _default: Equal; +export default _default; diff --git a/node_modules/ajv/dist/runtime/equal.js b/node_modules/ajv/dist/runtime/equal.js new file mode 100644 index 000000000..774bba05a --- /dev/null +++ b/node_modules/ajv/dist/runtime/equal.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +// https://github.com/ajv-validator/ajv/issues/889 +const equal = require("fast-deep-equal"); +equal.code = 'require("ajv/dist/runtime/equal").default'; +exports.default = equal; +//# sourceMappingURL=equal.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/equal.js.map b/node_modules/ajv/dist/runtime/equal.js.map new file mode 100644 index 000000000..0e17901c3 --- /dev/null +++ b/node_modules/ajv/dist/runtime/equal.js.map @@ -0,0 +1 @@ +{"version":3,"file":"equal.js","sourceRoot":"","sources":["../../lib/runtime/equal.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAClD,yCAAwC;AAGtC,KAAe,CAAC,IAAI,GAAG,2CAA2C,CAAA;AAEpE,kBAAe,KAAc,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/parseJson.d.ts b/node_modules/ajv/dist/runtime/parseJson.d.ts new file mode 100644 index 000000000..85f1d5670 --- /dev/null +++ b/node_modules/ajv/dist/runtime/parseJson.d.ts @@ -0,0 +1,18 @@ +export declare function parseJson(s: string, pos: number): unknown; +export declare namespace parseJson { + var message: string | undefined; + var position: number; + var code: string; +} +export declare function parseJsonNumber(s: string, pos: number, maxDigits?: number): number | undefined; +export declare namespace parseJsonNumber { + var message: string | undefined; + var position: number; + var code: string; +} +export declare function parseJsonString(s: string, pos: number): string | undefined; +export declare namespace parseJsonString { + var message: string | undefined; + var position: number; + var code: string; +} diff --git a/node_modules/ajv/dist/runtime/parseJson.js b/node_modules/ajv/dist/runtime/parseJson.js new file mode 100644 index 000000000..eaa283818 --- /dev/null +++ b/node_modules/ajv/dist/runtime/parseJson.js @@ -0,0 +1,185 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseJsonString = exports.parseJsonNumber = exports.parseJson = void 0; +const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/; +function parseJson(s, pos) { + let endPos; + parseJson.message = undefined; + let matches; + if (pos) + s = s.slice(pos); + try { + parseJson.position = pos + s.length; + return JSON.parse(s); + } + catch (e) { + matches = rxParseJson.exec(e.message); + if (!matches) { + parseJson.message = "unexpected end"; + return undefined; + } + endPos = +matches[1]; + const c = s[endPos]; + s = s.slice(0, endPos); + parseJson.position = pos + endPos; + try { + return JSON.parse(s); + } + catch (e1) { + parseJson.message = `unexpected token ${c}`; + return undefined; + } + } +} +exports.parseJson = parseJson; +parseJson.message = undefined; +parseJson.position = 0; +parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson'; +function parseJsonNumber(s, pos, maxDigits) { + let numStr = ""; + let c; + parseJsonNumber.message = undefined; + if (s[pos] === "-") { + numStr += "-"; + pos++; + } + if (s[pos] === "0") { + numStr += "0"; + pos++; + } + else { + if (!parseDigits(maxDigits)) { + errorMessage(); + return undefined; + } + } + if (maxDigits) { + parseJsonNumber.position = pos; + return +numStr; + } + if (s[pos] === ".") { + numStr += "."; + pos++; + if (!parseDigits()) { + errorMessage(); + return undefined; + } + } + if (((c = s[pos]), c === "e" || c === "E")) { + numStr += "e"; + pos++; + if (((c = s[pos]), c === "+" || c === "-")) { + numStr += c; + pos++; + } + if (!parseDigits()) { + errorMessage(); + return undefined; + } + } + parseJsonNumber.position = pos; + return +numStr; + function parseDigits(maxLen) { + let digit = false; + while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) { + digit = true; + numStr += c; + pos++; + } + return digit; + } + function errorMessage() { + parseJsonNumber.position = pos; + parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end"; + } +} +exports.parseJsonNumber = parseJsonNumber; +parseJsonNumber.message = undefined; +parseJsonNumber.position = 0; +parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber'; +const escapedChars = { + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t", + '"': '"', + "/": "/", + "\\": "\\", +}; +const CODE_A = "a".charCodeAt(0); +const CODE_0 = "0".charCodeAt(0); +function parseJsonString(s, pos) { + let str = ""; + let c; + parseJsonString.message = undefined; + // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition + while (true) { + c = s[pos++]; + if (c === '"') + break; + if (c === "\\") { + c = s[pos]; + if (c in escapedChars) { + str += escapedChars[c]; + pos++; + } + else if (c === "u") { + pos++; + let count = 4; + let code = 0; + while (count--) { + code <<= 4; + c = s[pos]; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (c === undefined) { + errorMessage("unexpected end"); + return undefined; + } + c = c.toLowerCase(); + if (c >= "a" && c <= "f") { + code += c.charCodeAt(0) - CODE_A + 10; + } + else if (c >= "0" && c <= "9") { + code += c.charCodeAt(0) - CODE_0; + } + else { + errorMessage(`unexpected token ${c}`); + return undefined; + } + pos++; + } + str += String.fromCharCode(code); + } + else { + errorMessage(`unexpected token ${c}`); + return undefined; + } + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + } + else if (c === undefined) { + errorMessage("unexpected end"); + return undefined; + } + else { + if (c.charCodeAt(0) >= 0x20) { + str += c; + } + else { + errorMessage(`unexpected token ${c}`); + return undefined; + } + } + } + parseJsonString.position = pos; + return str; + function errorMessage(msg) { + parseJsonString.position = pos; + parseJsonString.message = msg; + } +} +exports.parseJsonString = parseJsonString; +parseJsonString.message = undefined; +parseJsonString.position = 0; +parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString'; +//# sourceMappingURL=parseJson.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/parseJson.js.map b/node_modules/ajv/dist/runtime/parseJson.js.map new file mode 100644 index 000000000..7c125f87e --- /dev/null +++ b/node_modules/ajv/dist/runtime/parseJson.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parseJson.js","sourceRoot":"","sources":["../../lib/runtime/parseJson.ts"],"names":[],"mappings":";;;AAAA,MAAM,WAAW,GAAG,+CAA+C,CAAA;AAEnE,SAAgB,SAAS,CAAC,CAAS,EAAE,GAAW;IAC9C,IAAI,MAA0B,CAAA;IAC9B,SAAS,CAAC,OAAO,GAAG,SAAS,CAAA;IAC7B,IAAI,OAA+B,CAAA;IACnC,IAAI,GAAG;QAAE,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACzB,IAAI,CAAC;QACH,SAAS,CAAC,QAAQ,GAAG,GAAG,GAAG,CAAC,CAAC,MAAM,CAAA;QACnC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IACtB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,GAAG,WAAW,CAAC,IAAI,CAAE,CAAW,CAAC,OAAO,CAAC,CAAA;QAChD,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,SAAS,CAAC,OAAO,GAAG,gBAAgB,CAAA;YACpC,OAAO,SAAS,CAAA;QAClB,CAAC;QACD,MAAM,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;QACpB,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAA;QACnB,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAA;QACtB,SAAS,CAAC,QAAQ,GAAG,GAAG,GAAG,MAAM,CAAA;QACjC,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC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SAAS,YAAY,CAAC,GAAW;QAC/B,eAAe,CAAC,QAAQ,GAAG,GAAG,CAAA;QAC9B,eAAe,CAAC,OAAO,GAAG,GAAG,CAAA;IAC/B,CAAC;AACH,CAAC;AA7DD,0CA6DC;AAED,eAAe,CAAC,OAAO,GAAG,SAA+B,CAAA;AACzD,eAAe,CAAC,QAAQ,GAAG,CAAW,CAAA;AACtC,eAAe,CAAC,IAAI,GAAG,uDAAuD,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/quote.d.ts b/node_modules/ajv/dist/runtime/quote.d.ts new file mode 100644 index 000000000..0579dd3c6 --- /dev/null +++ b/node_modules/ajv/dist/runtime/quote.d.ts @@ -0,0 +1,5 @@ +declare function quote(s: string): string; +declare namespace quote { + var code: string; +} +export default quote; diff --git a/node_modules/ajv/dist/runtime/quote.js b/node_modules/ajv/dist/runtime/quote.js new file mode 100644 index 000000000..ebf78f70d --- /dev/null +++ b/node_modules/ajv/dist/runtime/quote.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const rxEscapable = +// eslint-disable-next-line no-control-regex, no-misleading-character-class +/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; +const escaped = { + "\b": "\\b", + "\t": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + '"': '\\"', + "\\": "\\\\", +}; +function quote(s) { + rxEscapable.lastIndex = 0; + return ('"' + + (rxEscapable.test(s) + ? s.replace(rxEscapable, (a) => { + const c = escaped[a]; + return typeof c === "string" + ? c + : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); + }) + : s) + + '"'); +} +exports.default = quote; +quote.code = 'require("ajv/dist/runtime/quote").default'; +//# sourceMappingURL=quote.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/quote.js.map b/node_modules/ajv/dist/runtime/quote.js.map new file mode 100644 index 000000000..4d226252d --- /dev/null +++ b/node_modules/ajv/dist/runtime/quote.js.map @@ -0,0 +1 @@ +{"version":3,"file":"quote.js","sourceRoot":"","sources":["../../lib/runtime/quote.ts"],"names":[],"mappings":";;AAAA,MAAM,WAAW;AACf,2EAA2E;AAC3E,iIAAiI,CAAA;AAEnI,MAAM,OAAO,GAA6B;IACxC,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,GAAG,EAAE,KAAK;IACV,IAAI,EAAE,MAAM;CACb,CAAA;AAED,SAAwB,KAAK,CAAC,CAAS;IACrC,WAAW,CAAC,SAAS,GAAG,CAAC,CAAA;IACzB,OAAO,CACL,GAAG;QACH,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC,EAAE,EAAE;gBAC3B,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;gBACpB,OAAO,OAAO,CAAC,KAAK,QAAQ;oBAC1B,CAAC,CAAC,CAAC;oBACH,CAAC,CAAC,KAAK,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;YAC/D,CAAC,CAAC;YACJ,CAAC,CAAC,CAAC,CAAC;QACN,GAAG,CACJ,CAAA;AACH,CAAC;AAdD,wBAcC;AAED,KAAK,CAAC,IAAI,GAAG,2CAA2C,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/re2.d.ts b/node_modules/ajv/dist/runtime/re2.d.ts new file mode 100644 index 000000000..c34a98f2f --- /dev/null +++ b/node_modules/ajv/dist/runtime/re2.d.ts @@ -0,0 +1,6 @@ +import * as re2 from "re2"; +type Re2 = typeof re2 & { + code: string; +}; +declare const _default: Re2; +export default _default; diff --git a/node_modules/ajv/dist/runtime/re2.js b/node_modules/ajv/dist/runtime/re2.js new file mode 100644 index 000000000..4b1ee2537 --- /dev/null +++ b/node_modules/ajv/dist/runtime/re2.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const re2 = require("re2"); +re2.code = 'require("ajv/dist/runtime/re2").default'; +exports.default = re2; +//# sourceMappingURL=re2.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/re2.js.map b/node_modules/ajv/dist/runtime/re2.js.map new file mode 100644 index 000000000..bb938a2c4 --- /dev/null +++ b/node_modules/ajv/dist/runtime/re2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"re2.js","sourceRoot":"","sources":["../../lib/runtime/re2.ts"],"names":[],"mappings":";;AAAA,2BAA0B;AAGxB,GAAW,CAAC,IAAI,GAAG,yCAAyC,CAAA;AAE9D,kBAAe,GAAU,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/timestamp.d.ts b/node_modules/ajv/dist/runtime/timestamp.d.ts new file mode 100644 index 000000000..cd4832688 --- /dev/null +++ b/node_modules/ajv/dist/runtime/timestamp.d.ts @@ -0,0 +1,5 @@ +declare function validTimestamp(str: string, allowDate: boolean): boolean; +declare namespace validTimestamp { + var code: string; +} +export default validTimestamp; diff --git a/node_modules/ajv/dist/runtime/timestamp.js b/node_modules/ajv/dist/runtime/timestamp.js new file mode 100644 index 000000000..5e0f06564 --- /dev/null +++ b/node_modules/ajv/dist/runtime/timestamp.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const DT_SEPARATOR = /t|\s/i; +const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; +const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i; +const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +function validTimestamp(str, allowDate) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + const dt = str.split(DT_SEPARATOR); + return ((dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) || + (allowDate && dt.length === 1 && validDate(dt[0]))); +} +exports.default = validTimestamp; +function validDate(str) { + const matches = DATE.exec(str); + if (!matches) + return false; + const y = +matches[1]; + const m = +matches[2]; + const d = +matches[3]; + return (m >= 1 && + m <= 12 && + d >= 1 && + (d <= DAYS[m] || + // leap year: https://tools.ietf.org/html/rfc3339#appendix-C + (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0)))); +} +function validTime(str) { + const matches = TIME.exec(str); + if (!matches) + return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tzH = +(matches[4] || 0); + const tzM = +(matches[5] || 0); + return ((hr <= 23 && min <= 59 && sec <= 59) || + // leap second + (hr - tzH === 23 && min - tzM === 59 && sec === 60)); +} +validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default'; +//# sourceMappingURL=timestamp.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/timestamp.js.map b/node_modules/ajv/dist/runtime/timestamp.js.map new file mode 100644 index 000000000..6b0eee039 --- /dev/null +++ b/node_modules/ajv/dist/runtime/timestamp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"timestamp.js","sourceRoot":"","sources":["../../lib/runtime/timestamp.ts"],"names":[],"mappings":";;AAAA,MAAM,YAAY,GAAG,OAAO,CAAA;AAC5B,MAAM,IAAI,GAAG,4BAA4B,CAAA;AACzC,MAAM,IAAI,GAAG,gEAAgE,CAAA;AAC7E,MAAM,IAAI,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAA;AAEhE,SAAwB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,CAAC,OAAO;QAAE,OAAO,KAAK,CAAA;IAC1B,MAAM,EAAE,GAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC9B,MAAM,GAAG,GAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC/B,MAAM,GAAG,GAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC/B,MAAM,GAAG,GAAW,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;IACtC,MAAM,GAAG,GAAW,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;IACtC,OAAO,CACL,CAAC,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,CAAC;QACpC,cAAc;QACd,CAAC,EAAE,GAAG,GAAG,KAAK,EAAE,IAAI,GAAG,GAAG,GAAG,KAAK,EAAE,IAAI,GAAG,KAAK,EAAE,CAAC,CACpD,CAAA;AACH,CAAC;AAED,cAAc,CAAC,IAAI,GAAG,+CAA+C,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/ucs2length.d.ts b/node_modules/ajv/dist/runtime/ucs2length.d.ts new file mode 100644 index 000000000..ecbee69c5 --- /dev/null +++ b/node_modules/ajv/dist/runtime/ucs2length.d.ts @@ -0,0 +1,5 @@ +declare function ucs2length(str: string): number; +declare namespace ucs2length { + var code: string; +} +export default ucs2length; diff --git a/node_modules/ajv/dist/runtime/ucs2length.js b/node_modules/ajv/dist/runtime/ucs2length.js new file mode 100644 index 000000000..92ea0c08a --- /dev/null +++ b/node_modules/ajv/dist/runtime/ucs2length.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode +function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 0xd800 && value <= 0xdbff && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xfc00) === 0xdc00) + pos++; // low surrogate + } + } + return length; +} +exports.default = ucs2length; +ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; +//# sourceMappingURL=ucs2length.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/ucs2length.js.map b/node_modules/ajv/dist/runtime/ucs2length.js.map new file mode 100644 index 000000000..a5ceb6b10 --- /dev/null +++ b/node_modules/ajv/dist/runtime/ucs2length.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ucs2length.js","sourceRoot":"","sources":["../../lib/runtime/ucs2length.ts"],"names":[],"mappings":";;AAAA,qDAAqD;AACrD,iEAAiE;AACjE,SAAwB,UAAU,CAAC,GAAW;IAC5C,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAA;IACtB,IAAI,MAAM,GAAG,CAAC,CAAA;IACd,IAAI,GAAG,GAAG,CAAC,CAAA;IACX,IAAI,KAAa,CAAA;IACjB,OAAO,GAAG,GAAG,GAAG,EAAE,CAAC;QACjB,MAAM,EAAE,CAAA;QACR,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,CAAA;QAC7B,IAAI,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,MAAM,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC;YACpD,gDAAgD;YAChD,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;YAC3B,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,MAAM;gBAAE,GAAG,EAAE,CAAA,CAAC,gBAAgB;QACzD,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAfD,6BAeC;AAED,UAAU,CAAC,IAAI,GAAG,gDAAgD,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/uri.d.ts b/node_modules/ajv/dist/runtime/uri.d.ts new file mode 100644 index 000000000..8e9e079f9 --- /dev/null +++ b/node_modules/ajv/dist/runtime/uri.d.ts @@ -0,0 +1,6 @@ +import * as uri from "fast-uri"; +type URI = typeof uri & { + code: string; +}; +declare const _default: URI; +export default _default; diff --git a/node_modules/ajv/dist/runtime/uri.js b/node_modules/ajv/dist/runtime/uri.js new file mode 100644 index 000000000..bbd2f0524 --- /dev/null +++ b/node_modules/ajv/dist/runtime/uri.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const uri = require("fast-uri"); +uri.code = 'require("ajv/dist/runtime/uri").default'; +exports.default = uri; +//# sourceMappingURL=uri.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/uri.js.map b/node_modules/ajv/dist/runtime/uri.js.map new file mode 100644 index 000000000..3f80a4c30 --- /dev/null +++ b/node_modules/ajv/dist/runtime/uri.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uri.js","sourceRoot":"","sources":["../../lib/runtime/uri.ts"],"names":[],"mappings":";;AAAA,gCAA+B;AAG7B,GAAW,CAAC,IAAI,GAAG,yCAAyC,CAAA;AAE9D,kBAAe,GAAU,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/validation_error.d.ts b/node_modules/ajv/dist/runtime/validation_error.d.ts new file mode 100644 index 000000000..b0ee9698f --- /dev/null +++ b/node_modules/ajv/dist/runtime/validation_error.d.ts @@ -0,0 +1,7 @@ +import type { ErrorObject } from "../types"; +export default class ValidationError extends Error { + readonly errors: Partial[]; + readonly ajv: true; + readonly validation: true; + constructor(errors: Partial[]); +} diff --git a/node_modules/ajv/dist/runtime/validation_error.js b/node_modules/ajv/dist/runtime/validation_error.js new file mode 100644 index 000000000..353502c08 --- /dev/null +++ b/node_modules/ajv/dist/runtime/validation_error.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +class ValidationError extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } +} +exports.default = ValidationError; +//# sourceMappingURL=validation_error.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/runtime/validation_error.js.map b/node_modules/ajv/dist/runtime/validation_error.js.map new file mode 100644 index 000000000..70206fbc1 --- /dev/null +++ b/node_modules/ajv/dist/runtime/validation_error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"validation_error.js","sourceRoot":"","sources":["../../lib/runtime/validation_error.ts"],"names":[],"mappings":";;AAEA,MAAqB,eAAgB,SAAQ,KAAK;IAKhD,YAAY,MAA8B;QACxC,KAAK,CAAC,mBAAmB,CAAC,CAAA;QAC1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;IACnC,CAAC;CACF;AAVD,kCAUC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/standalone/index.d.ts b/node_modules/ajv/dist/standalone/index.d.ts new file mode 100644 index 000000000..a9141c3d2 --- /dev/null +++ b/node_modules/ajv/dist/standalone/index.d.ts @@ -0,0 +1,6 @@ +import type AjvCore from "../core"; +import type { AnyValidateFunction } from "../types"; +declare function standaloneCode(ajv: AjvCore, refsOrFunc?: { + [K in string]?: string; +} | AnyValidateFunction): string; +export default standaloneCode; diff --git a/node_modules/ajv/dist/standalone/index.js b/node_modules/ajv/dist/standalone/index.js new file mode 100644 index 000000000..b44bb5db5 --- /dev/null +++ b/node_modules/ajv/dist/standalone/index.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const scope_1 = require("../compile/codegen/scope"); +const code_1 = require("../compile/codegen/code"); +function standaloneCode(ajv, refsOrFunc) { + if (!ajv.opts.code.source) { + throw new Error("moduleCode: ajv instance must have code.source option"); + } + const { _n } = ajv.scope.opts; + return typeof refsOrFunc == "function" + ? funcExportCode(refsOrFunc.source) + : refsOrFunc !== undefined + ? multiExportsCode(refsOrFunc, getValidate) + : multiExportsCode(ajv.schemas, (sch) => sch.meta ? undefined : ajv.compile(sch.schema)); + function getValidate(id) { + const v = ajv.getSchema(id); + if (!v) + throw new Error(`moduleCode: no schema with id ${id}`); + return v; + } + function funcExportCode(source) { + const usedValues = {}; + const n = source === null || source === void 0 ? void 0 : source.validateName; + const vCode = validateCode(usedValues, source); + if (ajv.opts.code.esm) { + // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value + return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`; + } + return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`; + } + function multiExportsCode(schemas, getValidateFunc) { + var _a; + const usedValues = {}; + let code = (0, code_1._) `"use strict";`; + for (const name in schemas) { + const v = getValidateFunc(schemas[name]); + if (v) { + const vCode = validateCode(usedValues, v.source); + const exportSyntax = ajv.opts.code.esm + ? (0, code_1._) `export const ${(0, code_1.getEsmExportName)(name)}` + : (0, code_1._) `exports${(0, code_1.getProperty)(name)}`; + code = (0, code_1._) `${code}${_n}${exportSyntax} = ${(_a = v.source) === null || _a === void 0 ? void 0 : _a.validateName};${_n}${vCode}`; + } + } + return `${code}`; + } + function validateCode(usedValues, s) { + if (!s) + throw new Error('moduleCode: function does not have "source" property'); + if (usedState(s.validateName) === scope_1.UsedValueState.Completed) + return code_1.nil; + setUsedState(s.validateName, scope_1.UsedValueState.Started); + const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode); + const code = new code_1._Code(`${scopeCode}${_n}${s.validateCode}`); + return s.evaluated ? (0, code_1._) `${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code; + function refValidateCode(n) { + var _a; + const vRef = (_a = n.value) === null || _a === void 0 ? void 0 : _a.ref; + if (n.prefix === "validate" && typeof vRef == "function") { + const v = vRef; + return validateCode(usedValues, v.source); + } + else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { + const { validate, validateName } = vRef; + if (!validateName) + throw new Error("ajv internal error"); + const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const; + const wrapper = (0, code_1._) `${def} ${n} = {validate: ${validateName}};`; + if (usedState(validateName) === scope_1.UsedValueState.Started) + return wrapper; + const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source); + return (0, code_1._) `${wrapper}${_n}${vCode}`; + } + return undefined; + } + function usedState(name) { + var _a; + return (_a = usedValues[name.prefix]) === null || _a === void 0 ? void 0 : _a.get(name); + } + function setUsedState(name, state) { + const { prefix } = name; + const names = (usedValues[prefix] = usedValues[prefix] || new Map()); + names.set(name, state); + } + } +} +module.exports = exports = standaloneCode; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = standaloneCode; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/standalone/index.js.map b/node_modules/ajv/dist/standalone/index.js.map new file mode 100644 index 000000000..8551fe910 --- /dev/null +++ b/node_modules/ajv/dist/standalone/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/standalone/index.ts"],"names":[],"mappings":";;AAGA,oDAAkG;AAClG,kDAA0F;AAE1F,SAAS,cAAc,CACrB,GAAY,EACZ,UAA2D;IAE3D,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAA;IAC1E,CAAC;IACD,MAAM,EAAC,EAAE,EAAC,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAA;IAC3B,OAAO,OAAO,UAAU,IAAI,UAAU;QACpC,CAAC,CAAC,cAAc,CAAC,UAAU,CAAC,MAAM,CAAC;QACnC,CAAC,CAAC,UAAU,KAAK,SAAS;YAC1B,CAAC,CAAC,gBAAgB,CAAS,UAAU,EAAE,WAAW,CAAC;YACnD,CAAC,CAAC,gBAAgB,CAAY,GAAG,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAC/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C,IAAoB,EAAE,KAAqB;YAC/D,MAAM,EAAC,MAAM,EAAC,GAAG,IAAI,CAAA;YACrB,MAAM,KAAK,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC,MAAM,CAAC,IAAI,IAAI,GAAG,EAAE,CAAC,CAAA;YACpE,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACxB,CAAC;IACH,CAAC;AACH,CAAC;AAED,MAAM,CAAC,OAAO,GAAG,OAAO,GAAG,cAAc,CAAA;AACzC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,KAAK,EAAE,IAAI,EAAC,CAAC,CAAA;AAE3D,kBAAe,cAAc,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/standalone/instance.d.ts b/node_modules/ajv/dist/standalone/instance.d.ts new file mode 100644 index 000000000..156ac3226 --- /dev/null +++ b/node_modules/ajv/dist/standalone/instance.d.ts @@ -0,0 +1,12 @@ +import Ajv, { AnySchema, AnyValidateFunction, ErrorObject } from "../core"; +export default class AjvPack { + readonly ajv: Ajv; + errors?: ErrorObject[] | null; + constructor(ajv: Ajv); + validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise; + compile(schema: AnySchema, meta?: boolean): AnyValidateFunction; + getSchema(keyRef: string): AnyValidateFunction | undefined; + private getStandalone; + addSchema(...args: Parameters): AjvPack; + addKeyword(...args: Parameters): AjvPack; +} diff --git a/node_modules/ajv/dist/standalone/instance.js b/node_modules/ajv/dist/standalone/instance.js new file mode 100644 index 000000000..35e5c9925 --- /dev/null +++ b/node_modules/ajv/dist/standalone/instance.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const core_1 = require("../core"); +const _1 = require("."); +const requireFromString = require("require-from-string"); +class AjvPack { + constructor(ajv) { + this.ajv = ajv; + } + validate(schemaKeyRef, data) { + return core_1.default.prototype.validate.call(this, schemaKeyRef, data); + } + compile(schema, meta) { + return this.getStandalone(this.ajv.compile(schema, meta)); + } + getSchema(keyRef) { + const v = this.ajv.getSchema(keyRef); + if (!v) + return undefined; + return this.getStandalone(v); + } + getStandalone(v) { + return requireFromString((0, _1.default)(this.ajv, v)); + } + addSchema(...args) { + this.ajv.addSchema.call(this.ajv, ...args); + return this; + } + addKeyword(...args) { + this.ajv.addKeyword.call(this.ajv, ...args); + return this; + } +} +exports.default = AjvPack; +//# sourceMappingURL=instance.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/standalone/instance.js.map b/node_modules/ajv/dist/standalone/instance.js.map new file mode 100644 index 000000000..6ac33b114 --- /dev/null +++ b/node_modules/ajv/dist/standalone/instance.js.map @@ -0,0 +1 @@ +{"version":3,"file":"instance.js","sourceRoot":"","sources":["../../lib/standalone/instance.ts"],"names":[],"mappings":";;AAAA,kCAAwE;AACxE,wBAA8B;AAC9B,yDAAwD;AAExD,MAAqB,OAAO;IAE1B,YAAqB,GAAQ;QAAR,QAAG,GAAH,GAAG,CAAK;IAAG,CAAC;IAEjC,QAAQ,CAAC,YAAgC,EAAE,IAAa;QACtD,OAAO,cAAG,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,CAAC,CAAA;IAC9D,CAAC;IAED,OAAO,CAAc,MAAiB,EAAE,IAAc;QACpD,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAI,MAAM,EAAE,IAAI,CAAC,CAAC,CAAA;IAC9D,CAAC;IAED,SAAS,CAAc,MAAc;QACnC,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,SAAS,CAAI,MAAM,CAAC,CAAA;QACvC,IAAI,CAAC,CAAC;YAAE,OAAO,SAAS,CAAA;QACxB,OAAO,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAA;IAC9B,CAAC;IAEO,aAAa,CAAc,CAAyB;QAC1D,OAAO,iBAAiB,CAAC,IAAA,UAAc,EAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAA2B,CAAA;IACjF,CAAC;IAED,SAAS,CAAC,GAAG,IAAgD;QAC3D,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;QAC1C,OAAO,IAAI,CAAA;IACb,CAAC;IAED,UAAU,CAAC,GAAG,IAAiD;QAC7D,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;QAC3C,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AA/BD,0BA+BC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/types/index.d.ts b/node_modules/ajv/dist/types/index.d.ts new file mode 100644 index 000000000..49903cd32 --- /dev/null +++ b/node_modules/ajv/dist/types/index.d.ts @@ -0,0 +1,183 @@ +import { URIComponent } from "fast-uri"; +import type { CodeGen, Code, Name, ScopeValueSets, ValueScopeName } from "../compile/codegen"; +import type { SchemaEnv, SchemaCxt, SchemaObjCxt } from "../compile"; +import type { JSONType } from "../compile/rules"; +import type { KeywordCxt } from "../compile/validate"; +import type Ajv from "../core"; +interface _SchemaObject { + id?: string; + $id?: string; + $schema?: string; + [x: string]: any; +} +export interface SchemaObject extends _SchemaObject { + id?: string; + $id?: string; + $schema?: string; + $async?: false; + [x: string]: any; +} +export interface AsyncSchema extends _SchemaObject { + $async: true; +} +export type AnySchemaObject = SchemaObject | AsyncSchema; +export type Schema = SchemaObject | boolean; +export type AnySchema = Schema | AsyncSchema; +export type SchemaMap = { + [Key in string]?: AnySchema; +}; +export interface SourceCode { + validateName: ValueScopeName; + validateCode: string; + scopeValues: ScopeValueSets; + evaluated?: Code; +} +export interface DataValidationCxt { + instancePath: string; + parentData: { + [K in T]: any; + }; + parentDataProperty: T; + rootData: Record | any[]; + dynamicAnchors: { + [Ref in string]?: ValidateFunction; + }; +} +export interface ValidateFunction { + (this: Ajv | any, data: any, dataCxt?: DataValidationCxt): data is T; + errors?: null | ErrorObject[]; + evaluated?: Evaluated; + schema: AnySchema; + schemaEnv: SchemaEnv; + source?: SourceCode; +} +export interface JTDParser { + (json: string): T | undefined; + message?: string; + position?: number; +} +export type EvaluatedProperties = { + [K in string]?: true; +} | true; +export type EvaluatedItems = number | true; +export interface Evaluated { + props?: EvaluatedProperties; + items?: EvaluatedItems; + dynamicProps: boolean; + dynamicItems: boolean; +} +export interface AsyncValidateFunction extends ValidateFunction { + (...args: Parameters>): Promise; + $async: true; +} +export type AnyValidateFunction = ValidateFunction | AsyncValidateFunction; +export interface ErrorObject, S = unknown> { + keyword: K; + instancePath: string; + schemaPath: string; + params: P; + propertyName?: string; + message?: string; + schema?: S; + parentSchema?: AnySchemaObject; + data?: unknown; +} +export type ErrorNoParams = ErrorObject, S>; +interface _KeywordDef { + keyword: string | string[]; + type?: JSONType | JSONType[]; + schemaType?: JSONType | JSONType[]; + allowUndefined?: boolean; + $data?: boolean; + implements?: string[]; + before?: string; + post?: boolean; + metaSchema?: AnySchemaObject; + validateSchema?: AnyValidateFunction; + dependencies?: string[]; + error?: KeywordErrorDefinition; + $dataError?: KeywordErrorDefinition; +} +export interface CodeKeywordDefinition extends _KeywordDef { + code: (cxt: KeywordCxt, ruleType?: string) => void; + trackErrors?: boolean; +} +export type MacroKeywordFunc = (schema: any, parentSchema: AnySchemaObject, it: SchemaCxt) => AnySchema; +export type CompileKeywordFunc = (schema: any, parentSchema: AnySchemaObject, it: SchemaObjCxt) => DataValidateFunction; +export interface DataValidateFunction { + (...args: Parameters): boolean | Promise; + errors?: Partial[]; +} +export interface SchemaValidateFunction { + (schema: any, data: any, parentSchema?: AnySchemaObject, dataCxt?: DataValidationCxt): boolean | Promise; + errors?: Partial[]; +} +export interface FuncKeywordDefinition extends _KeywordDef { + validate?: SchemaValidateFunction | DataValidateFunction; + compile?: CompileKeywordFunc; + schema?: boolean; + modifying?: boolean; + async?: boolean; + valid?: boolean; + errors?: boolean | "full"; +} +export interface MacroKeywordDefinition extends FuncKeywordDefinition { + macro: MacroKeywordFunc; +} +export type KeywordDefinition = CodeKeywordDefinition | FuncKeywordDefinition | MacroKeywordDefinition; +export type AddedKeywordDefinition = KeywordDefinition & { + type: JSONType[]; + schemaType: JSONType[]; +}; +export interface KeywordErrorDefinition { + message: string | Code | ((cxt: KeywordErrorCxt) => string | Code); + params?: Code | ((cxt: KeywordErrorCxt) => Code); +} +export type Vocabulary = (KeywordDefinition | string)[]; +export interface KeywordErrorCxt { + gen: CodeGen; + keyword: string; + data: Name; + $data?: string | false; + schema: any; + parentSchema?: AnySchemaObject; + schemaCode: Code | number | boolean; + schemaValue: Code | number | boolean; + schemaType?: JSONType[]; + errsCount?: Name; + params: KeywordCxtParams; + it: SchemaCxt; +} +export type KeywordCxtParams = { + [P in string]?: Code | string | number; +}; +export type FormatValidator = (data: T) => boolean; +export type FormatCompare = (data1: T, data2: T) => number | undefined; +export type AsyncFormatValidator = (data: T) => Promise; +export interface FormatDefinition { + type?: T extends string ? "string" | undefined : "number"; + validate: FormatValidator | (T extends string ? string | RegExp : never); + async?: false | undefined; + compare?: FormatCompare; +} +export interface AsyncFormatDefinition { + type?: T extends string ? "string" | undefined : "number"; + validate: AsyncFormatValidator; + async: true; + compare?: FormatCompare; +} +export type AddedFormat = true | RegExp | FormatValidator | FormatDefinition | FormatDefinition | AsyncFormatDefinition | AsyncFormatDefinition; +export type Format = AddedFormat | string; +export interface RegExpEngine { + (pattern: string, u: string): RegExpLike; + code: string; +} +export interface RegExpLike { + test: (s: string) => boolean; +} +export interface UriResolver { + parse(uri: string): URIComponent; + resolve(base: string, path: string): string; + serialize(component: URIComponent): string; +} +export {}; diff --git a/node_modules/ajv/dist/types/index.js b/node_modules/ajv/dist/types/index.js new file mode 100644 index 000000000..aa219d8f2 --- /dev/null +++ b/node_modules/ajv/dist/types/index.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/types/index.js.map b/node_modules/ajv/dist/types/index.js.map new file mode 100644 index 000000000..1f80f85ec --- /dev/null +++ b/node_modules/ajv/dist/types/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/types/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/ajv/dist/types/json-schema.d.ts b/node_modules/ajv/dist/types/json-schema.d.ts new file mode 100644 index 000000000..a391fef72 --- /dev/null +++ b/node_modules/ajv/dist/types/json-schema.d.ts @@ -0,0 +1,125 @@ +type StrictNullChecksWrapper = undefined extends null ? `strictNullChecks must be true in tsconfig to use ${Name}` : Type; +type UnionToIntersection = (U extends any ? (_: U) => void : never) extends (_: infer I) => void ? I : never; +export type SomeJSONSchema = UncheckedJSONSchemaType; +type UncheckedPartialSchema = Partial>; +export type PartialSchema = StrictNullChecksWrapper<"PartialSchema", UncheckedPartialSchema>; +type JSONType = IsPartial extends true ? T | undefined : T; +interface NumberKeywords { + minimum?: number; + maximum?: number; + exclusiveMinimum?: number; + exclusiveMaximum?: number; + multipleOf?: number; + format?: string; +} +interface StringKeywords { + minLength?: number; + maxLength?: number; + pattern?: string; + format?: string; +} +type UncheckedJSONSchemaType = (// these two unions allow arbitrary unions of types +{ + anyOf: readonly UncheckedJSONSchemaType[]; +} | { + oneOf: readonly UncheckedJSONSchemaType[]; +} | ({ + type: readonly (T extends number ? JSONType<"number" | "integer", IsPartial> : T extends string ? JSONType<"string", IsPartial> : T extends boolean ? JSONType<"boolean", IsPartial> : never)[]; +} & UnionToIntersection) | ((T extends number ? { + type: JSONType<"number" | "integer", IsPartial>; +} & NumberKeywords : T extends string ? { + type: JSONType<"string", IsPartial>; +} & StringKeywords : T extends boolean ? { + type: JSONType<"boolean", IsPartial>; +} : T extends readonly [any, ...any[]] ? { + type: JSONType<"array", IsPartial>; + items: { + readonly [K in keyof T]-?: UncheckedJSONSchemaType & Nullable; + } & { + length: T["length"]; + }; + minItems: T["length"]; +} & ({ + maxItems: T["length"]; +} | { + additionalItems: false; +}) : T extends readonly any[] ? { + type: JSONType<"array", IsPartial>; + items: UncheckedJSONSchemaType; + contains?: UncheckedPartialSchema; + minItems?: number; + maxItems?: number; + minContains?: number; + maxContains?: number; + uniqueItems?: true; + additionalItems?: never; +} : T extends Record ? { + type: JSONType<"object", IsPartial>; + additionalProperties?: boolean | UncheckedJSONSchemaType; + unevaluatedProperties?: boolean | UncheckedJSONSchemaType; + properties?: IsPartial extends true ? Partial> : UncheckedPropertiesSchema; + patternProperties?: Record>; + propertyNames?: Omit, "type"> & { + type?: "string"; + }; + dependencies?: { + [K in keyof T]?: readonly (keyof T)[] | UncheckedPartialSchema; + }; + dependentRequired?: { + [K in keyof T]?: readonly (keyof T)[]; + }; + dependentSchemas?: { + [K in keyof T]?: UncheckedPartialSchema; + }; + minProperties?: number; + maxProperties?: number; +} & (IsPartial extends true ? { + required: readonly (keyof T)[]; +} : [UncheckedRequiredMembers] extends [never] ? { + required?: readonly UncheckedRequiredMembers[]; +} : { + required: readonly UncheckedRequiredMembers[]; +}) : T extends null ? { + type: JSONType<"null", IsPartial>; + nullable: true; +} : never) & { + allOf?: readonly UncheckedPartialSchema[]; + anyOf?: readonly UncheckedPartialSchema[]; + oneOf?: readonly UncheckedPartialSchema[]; + if?: UncheckedPartialSchema; + then?: UncheckedPartialSchema; + else?: UncheckedPartialSchema; + not?: UncheckedPartialSchema; +})) & { + [keyword: string]: any; + $id?: string; + $ref?: string; + $defs?: Record>; + definitions?: Record>; +}; +export type JSONSchemaType = StrictNullChecksWrapper<"JSONSchemaType", UncheckedJSONSchemaType>; +type Known = { + [key: string]: Known; +} | [Known, ...Known[]] | Known[] | number | string | boolean | null; +type UncheckedPropertiesSchema = { + [K in keyof T]-?: (UncheckedJSONSchemaType & Nullable) | { + $ref: string; + }; +}; +export type PropertiesSchema = StrictNullChecksWrapper<"PropertiesSchema", UncheckedPropertiesSchema>; +type UncheckedRequiredMembers = { + [K in keyof T]-?: undefined extends T[K] ? never : K; +}[keyof T]; +export type RequiredMembers = StrictNullChecksWrapper<"RequiredMembers", UncheckedRequiredMembers>; +type Nullable = undefined extends T ? { + nullable: true; + const?: null; + enum?: readonly (T | null)[]; + default?: T | null; +} : { + nullable?: false; + const?: T; + enum?: readonly T[]; + default?: T; +}; +export {}; diff --git a/node_modules/ajv/dist/types/json-schema.js b/node_modules/ajv/dist/types/json-schema.js new file mode 100644 index 000000000..2d8f98dc5 --- /dev/null +++ b/node_modules/ajv/dist/types/json-schema.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=json-schema.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/types/json-schema.js.map b/node_modules/ajv/dist/types/json-schema.js.map new file mode 100644 index 000000000..ae6b4d0fe --- /dev/null +++ b/node_modules/ajv/dist/types/json-schema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"json-schema.js","sourceRoot":"","sources":["../../lib/types/json-schema.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/ajv/dist/types/jtd-schema.d.ts b/node_modules/ajv/dist/types/jtd-schema.d.ts new file mode 100644 index 000000000..80ad3129a --- /dev/null +++ b/node_modules/ajv/dist/types/jtd-schema.d.ts @@ -0,0 +1,174 @@ +/** numeric strings */ +type NumberType = "float32" | "float64" | "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32"; +/** string strings */ +type StringType = "string" | "timestamp"; +/** Generic JTD Schema without inference of the represented type */ +export type SomeJTDSchemaType = (// ref +{ + ref: string; +} | { + type: NumberType | StringType | "boolean"; +} | { + enum: string[]; +} | { + elements: SomeJTDSchemaType; +} | { + values: SomeJTDSchemaType; +} | { + properties: Record; + optionalProperties?: Record; + additionalProperties?: boolean; +} | { + properties?: Record; + optionalProperties: Record; + additionalProperties?: boolean; +} | { + discriminator: string; + mapping: Record; +} | {}) & { + nullable?: boolean; + metadata?: Record; + definitions?: Record; +}; +/** required keys of an object, not undefined */ +type RequiredKeys = { + [K in keyof T]-?: undefined extends T[K] ? never : K; +}[keyof T]; +/** optional or undifined-able keys of an object */ +type OptionalKeys = { + [K in keyof T]-?: undefined extends T[K] ? K : never; +}[keyof T]; +/** type is true if T is a union type */ +type IsUnion_ = false extends (T extends unknown ? ([U] extends [T] ? false : true) : never) ? false : true; +type IsUnion = IsUnion_; +/** type is true if T is identically E */ +type TypeEquality = [T] extends [E] ? ([E] extends [T] ? true : false) : false; +/** type is true if T or null is identically E or null*/ +type NullTypeEquality = TypeEquality; +/** gets only the string literals of a type or null if a type isn't a string literal */ +type EnumString = [T] extends [never] ? null : T extends string ? string extends T ? null : T : null; +/** true if type is a union of string literals */ +type IsEnum = null extends EnumString ? false : true; +/** true only if all types are array types (not tuples) */ +type IsElements = false extends IsUnion ? [T] extends [readonly unknown[]] ? undefined extends T[0.5] ? false : true : false : false; +/** true if the the type is a values type */ +type IsValues = false extends IsUnion ? TypeEquality : false; +/** true if type is a properties type and Union is false, or type is a discriminator type and Union is true */ +type IsRecord = Union extends IsUnion ? null extends EnumString ? false : true : false; +/** true if type represents an empty record */ +type IsEmptyRecord = [T] extends [Record] ? [T] extends [never] ? false : true : false; +/** actual schema */ +export type JTDSchemaType = Record> = (// refs - where null wasn't specified, must match exactly +(null extends EnumString ? never : ({ + [K in keyof D]: [T] extends [D[K]] ? { + ref: K; + } : never; +}[keyof D] & { + nullable?: false; +}) | (null extends T ? { + [K in keyof D]: [Exclude] extends [Exclude] ? { + ref: K; + } : never; +}[keyof D] & { + nullable: true; +} : never)) | (unknown extends T ? { + nullable?: boolean; +} : never) | ((true extends NullTypeEquality ? { + type: NumberType; +} : true extends NullTypeEquality ? { + type: "boolean"; +} : true extends NullTypeEquality ? { + type: StringType; +} : true extends NullTypeEquality ? { + type: "timestamp"; +} : true extends IsEnum> ? { + enum: EnumString>[]; +} : true extends IsElements> ? T extends readonly (infer E)[] ? { + elements: JTDSchemaType; +} : never : true extends IsEmptyRecord> ? { + properties: Record; + optionalProperties?: Record; +} | { + optionalProperties: Record; +} : true extends IsValues> ? T extends Record ? { + values: JTDSchemaType; +} : never : true extends IsRecord, false> ? ([RequiredKeys>] extends [never] ? { + properties?: Record; +} : { + properties: { + [K in RequiredKeys]: JTDSchemaType; + }; +}) & ([OptionalKeys>] extends [never] ? { + optionalProperties?: Record; +} : { + optionalProperties: { + [K in OptionalKeys]: JTDSchemaType, D>; + }; +}) & { + additionalProperties?: boolean; +} : true extends IsRecord, true> ? { + [K in keyof Exclude]-?: Exclude[K] extends string ? { + discriminator: K; + mapping: { + [M in Exclude[K]]: JTDSchemaType ? T : never, K>, D>; + }; + } : never; +}[keyof Exclude] : never) & (null extends T ? { + nullable: true; +} : { + nullable?: false; +}))) & { + metadata?: Record; + definitions?: { + [K in keyof D]: JTDSchemaType; + }; +}; +type JTDDataDef> = // ref +(S extends { + ref: string; +} ? D extends { + [K in S["ref"]]: infer V; +} ? JTDDataDef : never : S extends { + type: NumberType; +} ? number : S extends { + type: "boolean"; +} ? boolean : S extends { + type: "string"; +} ? string : S extends { + type: "timestamp"; +} ? string | Date : S extends { + enum: readonly (infer E)[]; +} ? string extends E ? never : [E] extends [string] ? E : never : S extends { + elements: infer E; +} ? JTDDataDef[] : S extends { + properties: Record; + optionalProperties?: Record; + additionalProperties?: boolean; +} ? { + -readonly [K in keyof S["properties"]]-?: JTDDataDef; +} & { + -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef; +} & ([S["additionalProperties"]] extends [true] ? Record : unknown) : S extends { + properties?: Record; + optionalProperties: Record; + additionalProperties?: boolean; +} ? { + -readonly [K in keyof S["properties"]]-?: JTDDataDef; +} & { + -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef; +} & ([S["additionalProperties"]] extends [true] ? Record : unknown) : S extends { + values: infer V; +} ? Record> : S extends { + discriminator: infer M; + mapping: Record; +} ? [M] extends [string] ? { + [K in keyof S["mapping"]]: JTDDataDef & { + [KM in M]: K; + }; +}[keyof S["mapping"]] : never : unknown) | (S extends { + nullable: true; +} ? null : never); +export type JTDDataType = S extends { + definitions: Record; +} ? JTDDataDef : JTDDataDef>; +export {}; diff --git a/node_modules/ajv/dist/types/jtd-schema.js b/node_modules/ajv/dist/types/jtd-schema.js new file mode 100644 index 000000000..11338aa8a --- /dev/null +++ b/node_modules/ajv/dist/types/jtd-schema.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=jtd-schema.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/types/jtd-schema.js.map b/node_modules/ajv/dist/types/jtd-schema.js.map new file mode 100644 index 000000000..add89bd77 --- /dev/null +++ b/node_modules/ajv/dist/types/jtd-schema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jtd-schema.js","sourceRoot":"","sources":["../../lib/types/jtd-schema.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/additionalItems.d.ts b/node_modules/ajv/dist/vocabularies/applicator/additionalItems.d.ts new file mode 100644 index 000000000..607515646 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/additionalItems.d.ts @@ -0,0 +1,8 @@ +import type { CodeKeywordDefinition, ErrorObject, AnySchema } from "../../types"; +import type { KeywordCxt } from "../../compile/validate"; +export type AdditionalItemsError = ErrorObject<"additionalItems", { + limit: number; +}, AnySchema>; +declare const def: CodeKeywordDefinition; +export declare function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js b/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js new file mode 100644 index 000000000..608d51eb6 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateAdditionalItems = void 0; +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const error = { + message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`, +}; +const def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); + return; + } + validateAdditionalItems(cxt, items); + }, +}; +function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._) `${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._) `${len} <= ${items.length}`); + } + else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } +} +exports.validateAdditionalItems = validateAdditionalItems; +exports.default = def; +//# sourceMappingURL=additionalItems.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js.map b/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js.map new file mode 100644 index 000000000..0091d3142 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js.map @@ -0,0 +1 @@ +{"version":3,"file":"additionalItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/additionalItems.ts"],"names":[],"mappings":";;;AAOA,mDAAuD;AACvD,6CAA2E;AAI3E,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE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,EAAE,CAAC,CAAA;IACxC,CAAC;SAAM,IAAI,OAAO,MAAM,IAAI,QAAQ,IAAI,CAAC,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC;QACvE,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,GAAG,OAAO,KAAK,CAAC,MAAM,EAAE,CAAC,CAAA,CAAC,WAAW;QACxE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAA;QAC9C,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;IAED,SAAS,aAAa,CAAC,KAAW;QAChC,GAAG,CAAC,QAAQ,CAAC,GAAG,EAAE,KAAK,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE;YACzC,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,QAAQ,EAAE,CAAC,EAAE,YAAY,EAAE,WAAI,CAAC,GAAG,EAAC,EAAE,KAAK,CAAC,CAAA;YACpE,IAAI,CAAC,EAAE,CAAC,SAAS;gBAAE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;QAC1D,CAAC,CAAC,CAAA;IACJ,CAAC;AACH,CAAC;AAnBD,0DAmBC;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.d.ts b/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.d.ts new file mode 100644 index 000000000..74698c7a2 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.d.ts @@ -0,0 +1,6 @@ +import type { CodeKeywordDefinition, AddedKeywordDefinition, ErrorObject, AnySchema } from "../../types"; +export type AdditionalPropertiesError = ErrorObject<"additionalProperties", { + additionalProperty: string; +}, AnySchema>; +declare const def: CodeKeywordDefinition & AddedKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js b/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js new file mode 100644 index 000000000..1d3374bb7 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js @@ -0,0 +1,106 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const code_1 = require("../code"); +const codegen_1 = require("../../compile/codegen"); +const names_1 = require("../../compile/names"); +const util_1 = require("../../compile/util"); +const error = { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`, +}; +const def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) + return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) + additionalPropertyCode(key); + else + gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + // TODO maybe an option instead of hard-coded 8? + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } + else if (props.length) { + definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`)); + } + else { + definedProp = codegen_1.nil; + } + if (patProps.length) { + definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + } + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._) `delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } + else { + applyAdditionalSchema(key, valid); + if (!allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str, + }; + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false, + }); + } + cxt.subschema(subschema, valid); + } + }, +}; +exports.default = def; +//# sourceMappingURL=additionalProperties.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js.map b/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js.map new file mode 100644 index 000000000..649ddae51 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"additionalProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/additionalProperties.ts"],"names":[],"mappings":";;AAOA,kCAAsE;AACtE,mDAAiE;AACjE,+CAAmC;AAEnC,6CAA0E;AAQ1E,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,qCAAqC;IAC9C,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,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sBAAsB;gBAC/B,QAAQ,EAAE,GAAG;gBACb,YAAY,EAAE,WAAI,CAAC,GAAG;aACvB,CAAA;YACD,IAAI,MAAM,KAAK,KAAK,EAAE,CAAC;gBACrB,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE;oBACvB,aAAa,EAAE,IAAI;oBACnB,YAAY,EAAE,KAAK;oBACnB,SAAS,EAAE,KAAK;iBACjB,CAAC,CAAA;YACJ,CAAC;YACD,GAAG,CAAC,SAAS,CAAC,SAAS,EAAE,KAAK,CAAC,CAAA;QACjC,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/allOf.d.ts b/node_modules/ajv/dist/vocabularies/applicator/allOf.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/allOf.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/allOf.js b/node_modules/ajv/dist/vocabularies/applicator/allOf.js new file mode 100644 index 000000000..1b1ae7376 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/allOf.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("../../compile/util"); +const def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + }, +}; +exports.default = def; +//# sourceMappingURL=allOf.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/allOf.js.map b/node_modules/ajv/dist/vocabularies/applicator/allOf.js.map new file mode 100644 index 000000000..d119d0eae --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/allOf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"allOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/allOf.ts"],"names":[],"mappings":";;AAEA,6CAAoD;AAEpD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC7B,wBAAwB;QACxB,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QACvE,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,MAAM,CAAC,OAAO,CAAC,CAAC,GAAc,EAAE,CAAS,EAAE,EAAE;YAC3C,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,GAAG,CAAC;gBAAE,OAAM;YACtC,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC,EAAC,EAAE,KAAK,CAAC,CAAA;YACtE,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;YACb,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAA;QAC5B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/anyOf.d.ts b/node_modules/ajv/dist/vocabularies/applicator/anyOf.d.ts new file mode 100644 index 000000000..61bca56e0 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/anyOf.d.ts @@ -0,0 +1,4 @@ +import type { CodeKeywordDefinition, ErrorNoParams, AnySchema } from "../../types"; +export type AnyOfError = ErrorNoParams<"anyOf", AnySchema[]>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/anyOf.js b/node_modules/ajv/dist/vocabularies/applicator/anyOf.js new file mode 100644 index 000000000..66cfce2cc --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/anyOf.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const code_1 = require("../code"); +const def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in anyOf" }, +}; +exports.default = def; +//# sourceMappingURL=anyOf.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/anyOf.js.map b/node_modules/ajv/dist/vocabularies/applicator/anyOf.js.map new file mode 100644 index 000000000..537ffcbeb --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/anyOf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"anyOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/anyOf.ts"],"names":[],"mappings":";;AACA,kCAAqC;AAIrC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,WAAW,EAAE,IAAI;IACjB,IAAI,EAAE,oBAAa;IACnB,KAAK,EAAE,EAAC,OAAO,EAAE,8BAA8B,EAAC;CACjD,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/contains.d.ts b/node_modules/ajv/dist/vocabularies/applicator/contains.d.ts new file mode 100644 index 000000000..5493e844f --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/contains.d.ts @@ -0,0 +1,7 @@ +import type { CodeKeywordDefinition, ErrorObject, AnySchema } from "../../types"; +export type ContainsError = ErrorObject<"contains", { + minContains: number; + maxContains?: number; +}, AnySchema>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/contains.js b/node_modules/ajv/dist/vocabularies/applicator/contains.js new file mode 100644 index 000000000..6c5473f5d --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/contains.js @@ -0,0 +1,95 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const error = { + message: ({ params: { min, max } }) => max === undefined + ? (0, codegen_1.str) `must contain at least ${min} valid item(s)` + : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`, +}; +const def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === undefined ? 1 : minContains; + max = maxContains; + } + else { + min = 1; + } + const len = gen.const("len", (0, codegen_1._) `${data}.length`); + cxt.setParams({ min, max }); + if (max === undefined && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== undefined && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._) `${len} >= ${min}`; + if (max !== undefined) + cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === undefined && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())); + } + else if (min === 0) { + gen.let(valid, true); + if (max !== undefined) + gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount); + } + else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true, + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._) `${count}++`); + if (max === undefined) { + gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break()); + } + else { + gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) + gen.assign(valid, true); + else + gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + }, +}; +exports.default = def; +//# sourceMappingURL=contains.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/contains.js.map b/node_modules/ajv/dist/vocabularies/applicator/contains.js.map new file mode 100644 index 000000000..415792846 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/contains.js.map @@ -0,0 +1 @@ +{"version":3,"file":"contains.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/contains.ts"],"names":[],"mappings":";;AAOA,mDAAkD;AAClD,6CAA2E;AAQ3E,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAE,GAAG,EAAC,EAAC,EAAE,EAAE,CAChC,GAAG,KAAK,SAAS;QACf,CAAC,CAAC,IAAA,aAAG,EAAA,yBAAyB,GAAG,gBAAgB;QACjD,CAAC,CAAC,IAAA,aAAG,EAAA,yBAAyB,GAAG,qBAAqB,GAAG,gBAAgB;IAC7E,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAE,GAAG,EAAC,EAAC,EAAE,EAAE,CAC/B,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,iBAAiB,GAAG,GAAG,CAAC,CAAC,CAAC,I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AAC,EAAA,GAAG,KAAK,OAAO,GAAG,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAA;YACnE,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/dependencies.d.ts b/node_modules/ajv/dist/vocabularies/applicator/dependencies.d.ts new file mode 100644 index 000000000..05900e0c5 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/dependencies.d.ts @@ -0,0 +1,21 @@ +import type { CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition, SchemaMap, AnySchema } from "../../types"; +import type { KeywordCxt } from "../../compile/validate"; +export type PropertyDependencies = { + [K in string]?: string[]; +}; +export interface DependenciesErrorParams { + property: string; + missingProperty: string; + depsCount: number; + deps: string; +} +export type DependenciesError = ErrorObject<"dependencies", DependenciesErrorParams, { + [K in string]?: string[] | AnySchema; +}>; +export declare const error: KeywordErrorDefinition; +declare const def: CodeKeywordDefinition; +export declare function validatePropertyDeps(cxt: KeywordCxt, propertyDeps?: { + [K in string]?: string[]; +}): void; +export declare function validateSchemaDeps(cxt: KeywordCxt, schemaDeps?: SchemaMap): void; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/dependencies.js b/node_modules/ajv/dist/vocabularies/applicator/dependencies.js new file mode 100644 index 000000000..e81f86d1d --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/dependencies.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const code_1 = require("../code"); +exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}`, // TODO change to reference +}; +const def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + }, +}; +function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") + continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; +} +function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) + return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) + continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", "), + }); + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + (0, code_1.checkReportMissingProp)(cxt, depProp); + } + }); + } + else { + gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } +} +exports.validatePropertyDeps = validatePropertyDeps; +function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) + continue; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { + const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, () => gen.var(valid, true) // TODO var + ); + cxt.ok(valid); + } +} +exports.validateSchemaDeps = validateSchemaDeps; +exports.default = def; +//# sourceMappingURL=dependencies.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/dependencies.js.map b/node_modules/ajv/dist/vocabularies/applicator/dependencies.js.map new file mode 100644 index 000000000..50d7ca348 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/dependencies.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dependencies.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/dependencies.ts"],"names":[],"mappings":";;;AAQA,mDAA4C;AAC5C,6CAAoD;AACpD,kCAAmG;AAmBtF,QAAA,KAAK,GAA2B;IAC3C,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAC,EAAC,EAAE,EAAE;QACjD,MAAM,YAAY,GAAG,SAAS,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,YAAY,CAAA;QAChE,OAAO,IAAA,aAAG,EAAA,aAAa,YAAY,IAAI,IAAI,kBAAkB,QAAQ,aAAa,CAAA;IACpF,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,eAAe,EAAC,EAAC,EAAE,EAAE,CACjE,IAAA,WAAC,EAAA,cAAc,QAAQ;uBACJ,eAAe;iBACrB,SAAS;YACd,IAAI,GAAG,EAAE,2BAA2B;CAC/C,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,cAAc;IACvB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAL,aAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,CAAC,QAAQ,EAAE,OAAO,CAAC,GAAG,iBAAiB,CAAC,GAAG,CAAC,CAAA;QAClD,oBAAoB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;QACnC,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;I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D,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,WAAW;SACvC,CAAA;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;AACH,CAAC;AAfD,gDAeC;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.d.ts b/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js b/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js new file mode 100644 index 000000000..66ef2e843 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const dependencies_1 = require("./dependencies"); +const def = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt), +}; +exports.default = def; +//# sourceMappingURL=dependentSchemas.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js.map b/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js.map new file mode 100644 index 000000000..17712e6fb --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dependentSchemas.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/dependentSchemas.ts"],"names":[],"mappings":";;AACA,iDAAiD;AAEjD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,kBAAkB;IAC3B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,iCAAkB,EAAC,GAAG,CAAC;CACvC,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/if.d.ts b/node_modules/ajv/dist/vocabularies/applicator/if.d.ts new file mode 100644 index 000000000..8f602e33f --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/if.d.ts @@ -0,0 +1,6 @@ +import type { CodeKeywordDefinition, ErrorObject, AnySchema } from "../../types"; +export type IfKeywordError = ErrorObject<"if", { + failingKeyword: string; +}, AnySchema>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/if.js b/node_modules/ajv/dist/vocabularies/applicator/if.js new file mode 100644 index 000000000..2c42a3e9c --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/if.js @@ -0,0 +1,66 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const error = { + message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`, +}; +const def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === undefined && parentSchema.else === undefined) { + (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); + } + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) + return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } + else if (hasThen) { + gen.if(schValid, validateClause("then")); + } + else { + gen.if((0, codegen_1.not)(schValid), validateClause("else")); + } + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false, + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) + gen.assign(ifClause, (0, codegen_1._) `${keyword}`); + else + cxt.setParams({ ifClause: keyword }); + }; + } + }, +}; +function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema); +} +exports.default = def; +//# sourceMappingURL=if.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/if.js.map b/node_modules/ajv/dist/vocabularies/applicator/if.js.map new file mode 100644 index 000000000..54efb1dcc --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/if.js.map @@ -0,0 +1 @@ +{"version":3,"file":"if.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/if.ts"],"names":[],"mappings":";;AAQA,mDAAuD;AACvD,6CAAqE;AAIrE,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,eAAe,MAAM,CAAC,QAAQ,UAAU;IAClE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,oBAAoB,MAAM,CAAC,QAAQ,GAAG;CAC9D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,IAAI;IACb,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,WAAW,EAAE,IAAI;IACjB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,IAAI,YAAY,CAAC,IAAI,KAAK,SAAS,IAAI,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AAC,SAAS,CAC1B;gBACE,OAAO,EAAE,IAAI;gBACb,aAAa,EAAE,IAAI;gBACnB,YAAY,EAAE,KAAK;gBACnB,SAAS,EAAE,KAAK;aACjB,EACD,QAAQ,CACT,CAAA;YACD,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAA;QAC5B,CAAC;QAED,SAAS,cAAc,CAAC,OAAe,EAAE,QAAe;YACtD,OAAO,GAAG,EAAE;gBACV,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAC,EAAE,QAAQ,CAAC,CAAA;gBACjD,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;gBAC3B,GAAG,CAAC,mBAAmB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;gBACtC,IAAI,QAAQ;oBAAE,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAA,WAAC,EAAA,GAAG,OAAO,EAAE,CAAC,CAAA;;oBAC5C,GAAG,CAAC,SAAS,CAAC,EAAC,QAAQ,EAAE,OAAO,EAAC,CAAC,CAAA;YACzC,CAAC,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,SAAS,SAAS,CAAC,EAAgB,EAAE,OAAe;IAClD,MAAM,MAAM,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;IACjC,OAAO,MAAM,KAAK,SAAS,IAAI,CAAC,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,CAAA;AAC/D,CAAC;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/index.d.ts b/node_modules/ajv/dist/vocabularies/applicator/index.d.ts new file mode 100644 index 000000000..b9cc5f5c8 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/index.d.ts @@ -0,0 +1,13 @@ +import type { ErrorNoParams, Vocabulary } from "../../types"; +import { AdditionalItemsError } from "./additionalItems"; +import { ItemsError } from "./items2020"; +import { ContainsError } from "./contains"; +import { DependenciesError } from "./dependencies"; +import { PropertyNamesError } from "./propertyNames"; +import { AdditionalPropertiesError } from "./additionalProperties"; +import { NotKeywordError } from "./not"; +import { AnyOfError } from "./anyOf"; +import { OneOfError } from "./oneOf"; +import { IfKeywordError } from "./if"; +export default function getApplicator(draft2020?: boolean): Vocabulary; +export type ApplicatorKeywordError = ErrorNoParams<"false schema"> | AdditionalItemsError | ItemsError | ContainsError | AdditionalPropertiesError | DependenciesError | IfKeywordError | AnyOfError | OneOfError | NotKeywordError | PropertyNamesError; diff --git a/node_modules/ajv/dist/vocabularies/applicator/index.js b/node_modules/ajv/dist/vocabularies/applicator/index.js new file mode 100644 index 000000000..cf592f279 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/index.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const additionalItems_1 = require("./additionalItems"); +const prefixItems_1 = require("./prefixItems"); +const items_1 = require("./items"); +const items2020_1 = require("./items2020"); +const contains_1 = require("./contains"); +const dependencies_1 = require("./dependencies"); +const propertyNames_1 = require("./propertyNames"); +const additionalProperties_1 = require("./additionalProperties"); +const properties_1 = require("./properties"); +const patternProperties_1 = require("./patternProperties"); +const not_1 = require("./not"); +const anyOf_1 = require("./anyOf"); +const oneOf_1 = require("./oneOf"); +const allOf_1 = require("./allOf"); +const if_1 = require("./if"); +const thenElse_1 = require("./thenElse"); +function getApplicator(draft2020 = false) { + const applicator = [ + // any + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + // object + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default, + ]; + // array + if (draft2020) + applicator.push(prefixItems_1.default, items2020_1.default); + else + applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; +} +exports.default = getApplicator; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/index.js.map b/node_modules/ajv/dist/vocabularies/applicator/index.js.map new file mode 100644 index 000000000..ebcb8534d --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/index.ts"],"names":[],"mappings":";;AACA,uDAAuE;AACvE,+CAAuC;AACvC,mCAA2B;AAC3B,2CAAiD;AACjD,yCAAkD;AAClD,iDAA8D;AAC9D,mDAAiE;AACjE,iEAAsF;AACtF,6CAAqC;AACrC,2DAAmD;AACnD,+BAAiD;AACjD,mCAAyC;AACzC,mCAAyC;AACzC,mCAA2B;AAC3B,6BAA8C;AAC9C,yCAAiC;AAEjC,SAAwB,aAAa,CAAC,SAAS,GAAG,KAAK;IACrD,MAAM,UAAU,GAAG;QACjB,MAAM;QACN,aAAU;QACV,eAAK;QACL,eAAK;QACL,eAAK;QACL,YAAS;QACT,kBAAQ;QACR,SAAS;QACT,uBAAa;QACb,8BAAoB;QACpB,sBAAY;QACZ,oBAAU;QACV,2BAAiB;KAClB,CAAA;IACD,QAAQ;IACR,IAAI,SAAS;QAAE,UAAU,CAAC,IAAI,CAAC,qBAAW,EAAE,mBAAS,CAAC,CAAA;;QACjD,UAAU,CAAC,IAAI,CAAC,yBAAe,EAAE,eAAK,CAAC,CAAA;IAC5C,UAAU,CAAC,IAAI,CAAC,kBAAQ,CAAC,CAAA;IACzB,OAAO,UAAU,CAAA;AACnB,CAAC;AArBD,gCAqBC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/items.d.ts b/node_modules/ajv/dist/vocabularies/applicator/items.d.ts new file mode 100644 index 000000000..8e608ca9c --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/items.d.ts @@ -0,0 +1,5 @@ +import type { CodeKeywordDefinition, AnySchema } from "../../types"; +import type { KeywordCxt } from "../../compile/validate"; +declare const def: CodeKeywordDefinition; +export declare function validateTuple(cxt: KeywordCxt, extraItems: string, schArr?: AnySchema[]): void; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/items.js b/node_modules/ajv/dist/vocabularies/applicator/items.js new file mode 100644 index 000000000..26f527bc6 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/items.js @@ -0,0 +1,52 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateTuple = void 0; +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const code_1 = require("../code"); +const def = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) + return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + cxt.ok((0, code_1.validateArray)(cxt)); + }, +}; +function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + } + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._) `${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i, + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } +} +exports.validateTuple = validateTuple; +exports.default = def; +//# sourceMappingURL=items.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/items.js.map b/node_modules/ajv/dist/vocabularies/applicator/items.js.map new file mode 100644 index 000000000..ef5511879 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/items.js.map @@ -0,0 +1 @@ +{"version":3,"file":"items.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/items.ts"],"names":[],"mappings":";;;AAEA,mDAAuC;AACvC,6CAAqF;AACrF,kCAAqC;AAErC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC;IAC1C,MAAM,EAAE,aAAa;IACrB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACxB,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;YAAE,OAAO,aAAa,CAAC,GAAG,EAAE,iBAAiB,EAAE,MAAM,CAAC,CAAA;QAC/E,EAAE,CAAC,KAAK,GAAG,IAAI,CAAA;QACf,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,GAAG,CAAC,EAAE,CAAC,IAAA,oBAAa,EAAC,GAAG,CAAC,CAAC,CAAA;IAC5B,CAAC;CACF,CAAA;AAED,SAAgB,aAAa,CAC3B,GAAe,EACf,UAAkB,EAClB,SAAsB,GAAG,CAAC,MAAM;IAEhC,MAAM,EAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IAClD,gBAAgB,CAAC,YAAY,CAAC,CAAA;IAC9B,IAAI,EAAE,CAAC,IAAI,CAAC,WAAW,IAAI,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;QAC9D,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC,KAA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line at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/items2020.d.ts b/node_modules/ajv/dist/vocabularies/applicator/items2020.d.ts new file mode 100644 index 000000000..a2565b2c2 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/items2020.d.ts @@ -0,0 +1,6 @@ +import type { CodeKeywordDefinition, ErrorObject, AnySchema } from "../../types"; +export type ItemsError = ErrorObject<"items", { + limit: number; +}, AnySchema>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/items2020.js b/node_modules/ajv/dist/vocabularies/applicator/items2020.js new file mode 100644 index 000000000..f2387d7d2 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/items2020.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const code_1 = require("../code"); +const additionalItems_1 = require("./additionalItems"); +const error = { + message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`, +}; +const def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + if (prefixItems) + (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else + cxt.ok((0, code_1.validateArray)(cxt)); + }, +}; +exports.default = def; +//# sourceMappingURL=items2020.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/items2020.js.map b/node_modules/ajv/dist/vocabularies/applicator/items2020.js.map new file mode 100644 index 000000000..5034acda6 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/items2020.js.map @@ -0,0 +1 @@ +{"version":3,"file":"items2020.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/items2020.ts"],"names":[],"mappings":";;AAOA,mDAA4C;AAC5C,6CAAoD;AACpD,kCAAqC;AACrC,uDAAyD;AAIzD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,2BAA2B,GAAG,QAAQ;IACvE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAAG,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,GAAG,GAAG;CAChD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,MAAM,EAAE,aAAa;IACrB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,MAAM,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtC,MAAM,EAAC,WAAW,EAAC,GAAG,YAAY,CAAA;QAClC,EAAE,CAAC,KAAK,GAAG,IAAI,CAAA;QACf,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,IAAI,WAAW;YAAE,IAAA,yCAAuB,EAAC,GAAG,EAAE,WAAW,CAAC,CAAA;;YACrD,GAAG,CAAC,EAAE,CAAC,IAAA,oBAAa,EAAC,GAAG,CAAC,CAAC,CAAA;IACjC,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/not.d.ts b/node_modules/ajv/dist/vocabularies/applicator/not.d.ts new file mode 100644 index 000000000..d2f4888f3 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/not.d.ts @@ -0,0 +1,4 @@ +import type { CodeKeywordDefinition, ErrorNoParams, AnySchema } from "../../types"; +export type NotKeywordError = ErrorNoParams<"not", AnySchema>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/not.js b/node_modules/ajv/dist/vocabularies/applicator/not.js new file mode 100644 index 000000000..89f6fddac --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/not.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("../../compile/util"); +const def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false, + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" }, +}; +exports.default = def; +//# sourceMappingURL=not.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/not.js.map b/node_modules/ajv/dist/vocabularies/applicator/not.js.map new file mode 100644 index 000000000..d99e6ea87 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/not.js.map @@ -0,0 +1 @@ +{"version":3,"file":"not.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/not.ts"],"names":[],"mappings":";;AAEA,6CAAoD;AAIpD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,KAAK;IACd,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,WAAW,EAAE,IAAI;IACjB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC7B,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC;YAClC,GAAG,CAAC,IAAI,EAAE,CAAA;YACV,OAAM;QACR,CAAC;QAED,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,GAAG,CAAC,SAAS,CACX;YACE,OAAO,EAAE,KAAK;YACd,aAAa,EAAE,IAAI;YACnB,YAAY,EAAE,KAAK;YACnB,SAAS,EAAE,KAAK;SACjB,EACD,KAAK,CACN,CAAA;QAED,GAAG,CAAC,UAAU,CACZ,KAAK,EACL,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,EACjB,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAClB,CAAA;IACH,CAAC;IACD,KAAK,EAAE,EAAC,OAAO,EAAE,mBAAmB,EAAC;CACtC,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/oneOf.d.ts b/node_modules/ajv/dist/vocabularies/applicator/oneOf.d.ts new file mode 100644 index 000000000..1e1d34f72 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/oneOf.d.ts @@ -0,0 +1,6 @@ +import type { CodeKeywordDefinition, ErrorObject, AnySchema } from "../../types"; +export type OneOfError = ErrorObject<"oneOf", { + passingSchemas: [number, number] | null; +}, AnySchema[]>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/oneOf.js b/node_modules/ajv/dist/vocabularies/applicator/oneOf.js new file mode 100644 index 000000000..441db2ac0 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/oneOf.js @@ -0,0 +1,60 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const error = { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`, +}; +const def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) + return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) { + gen.var(schValid, true); + } + else { + schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true, + }, schValid); + } + if (i > 0) { + gen + .if((0, codegen_1._) `${schValid} && ${valid}`) + .assign(valid, false) + .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`) + .else(); + } + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) + cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + }, +}; +exports.default = def; +//# sourceMappingURL=oneOf.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/oneOf.js.map b/node_modules/ajv/dist/vocabularies/applicator/oneOf.js.map new file mode 100644 index 000000000..13b8bfe9f --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/oneOf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"oneOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/oneOf.ts"],"names":[],"mappings":";;AAOA,mDAA6C;AAC7C,6CAAoD;AASpD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,wCAAwC;IACjD,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,oBAAoB,MAAM,CAAC,OAAO,GAAG;CAC7D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,WAAW,EAAE,IAAI;IACjB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC3C,wBAAwB;QACxB,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AAA,GAAG,QAAQ,OAAO,KAAK,EAAE,CAAC;yBAC9B,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC;yBACpB,MAAM,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,IAAI,OAAO,KAAK,CAAC,GAAG,CAAC;yBACtC,IAAI,EAAE,CAAA;gBACX,CAAC;gBAED,GAAG,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;oBACpB,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;oBACvB,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,CAAA;oBACtB,IAAI,MAAM;wBAAE,GAAG,CAAC,cAAc,CAAC,MAAM,EAAE,cAAI,CAAC,CAAA;gBAC9C,CAAC,CAAC,CAAA;YACJ,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/patternProperties.d.ts b/node_modules/ajv/dist/vocabularies/applicator/patternProperties.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/patternProperties.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js b/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js new file mode 100644 index 000000000..48501c6e3 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js @@ -0,0 +1,75 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const code_1 = require("../code"); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const util_2 = require("../../compile/util"); +const def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || + (alwaysValidPatterns.length === patterns.length && + (!it.opts.unevaluated || it.props === true))) { + return; + } + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) { + it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + } + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) + checkMatchingProperties(pat); + if (it.allErrors) { + validateProperties(pat); + } + else { + gen.var(valid, true); // TODO var + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + } + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) { + cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str, + }, valid); + } + if (it.opts.unevaluated && props !== true) { + gen.assign((0, codegen_1._) `${props}[${key}]`, true); + } + else if (!alwaysValid && !it.allErrors) { + // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false) + // or if all properties were evaluated (props === true) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + }); + }); + } + }, +}; +exports.default = def; +//# sourceMappingURL=patternProperties.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js.map b/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js.map new file mode 100644 index 000000000..231b08164 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"patternProperties.js","source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AAQ,EAAE,GAAG;4BACb,YAAY,EAAE,WAAI,CAAC,GAAG;yBACvB,EACD,KAAK,CACN,CAAA;oBACH,CAAC;oBAED,IAAI,EAAE,CAAC,IAAI,CAAC,WAAW,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;wBAC1C,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,KAAK,IAAI,GAAG,GAAG,EAAE,IAAI,CAAC,CAAA;oBACvC,CAAC;yBAAM,IAAI,CAAC,WAAW,IAAI,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC;wBACzC,sFAAsF;wBACtF,uDAAuD;wBACvD,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;oBACvC,CAAC;gBACH,CAAC,CAAC,CAAA;YACJ,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/prefixItems.d.ts b/node_modules/ajv/dist/vocabularies/applicator/prefixItems.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/prefixItems.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js b/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js new file mode 100644 index 000000000..727bc23ce --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const items_1 = require("./items"); +const def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items"), +}; +exports.default = def; +//# sourceMappingURL=prefixItems.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js.map b/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js.map new file mode 100644 index 000000000..deef718e6 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js.map @@ -0,0 +1 @@ +{"version":3,"file":"prefixItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/prefixItems.ts"],"names":[],"mappings":";;AACA,mCAAqC;AAErC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,aAAa;IACtB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,CAAC,OAAO,CAAC;IACrB,MAAM,EAAE,aAAa;IACrB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,qBAAa,EAAC,GAAG,EAAE,OAAO,CAAC;CAC3C,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/properties.d.ts b/node_modules/ajv/dist/vocabularies/applicator/properties.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/properties.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/properties.js b/node_modules/ajv/dist/vocabularies/applicator/properties.js new file mode 100644 index 000000000..7347358e2 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/properties.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const validate_1 = require("../../compile/validate"); +const code_1 = require("../code"); +const util_1 = require("../../compile/util"); +const additionalProperties_1 = require("./additionalProperties"); +const def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) { + additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + } + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) { + it.definedProperties.add(prop); + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + } + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) + return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop); + } + else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) + gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop, + }, valid); + } + }, +}; +exports.default = def; +//# sourceMappingURL=properties.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/properties.js.map b/node_modules/ajv/dist/vocabularies/applicator/properties.js.map new file mode 100644 index 000000000..13cd34774 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/properties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"properties.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/properties.ts"],"names":[],"mappings":";;AACA,qDAAiD;AACjD,kCAA2D;AAC3D,6CAA4E;AAC5E,iEAA0C;AAE1C,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,YAAY;IACrB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACjD,IAAI,EAAE,CAAC,IAAI,CAAC,gBAAgB,KAAK,KAAK,IAAI,YAAY,C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AAI,CAAC,EAAE,CAAC,SAAS;oBAAE,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;gBAC9C,GAAG,CAAC,KAAK,EAAE,CAAA;YACb,CAAC;YACD,GAAG,CAAC,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;YAClC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;QACf,CAAC;QAED,SAAS,UAAU,CAAC,IAAY;YAC9B,OAAO,EAAE,CAAC,IAAI,CAAC,WAAW,IAAI,CAAC,EAAE,CAAC,aAAa,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,OAAO,KAAK,SAAS,CAAA;QACvF,CAAC;QAED,SAAS,mBAAmB,CAAC,IAAY;YACvC,GAAG,CAAC,SAAS,CACX;gBACE,OAAO,EAAE,YAAY;gBACrB,UAAU,EAAE,IAAI;gBAChB,QAAQ,EAAE,IAAI;aACf,EACD,KAAK,CACN,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/propertyNames.d.ts b/node_modules/ajv/dist/vocabularies/applicator/propertyNames.d.ts new file mode 100644 index 000000000..a806da32f --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/propertyNames.d.ts @@ -0,0 +1,6 @@ +import type { CodeKeywordDefinition, ErrorObject, AnySchema } from "../../types"; +export type PropertyNamesError = ErrorObject<"propertyNames", { + propertyName: string; +}, AnySchema>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js b/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js new file mode 100644 index 000000000..f3871152d --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const error = { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`, +}; +const def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true, + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) + gen.break(); + }); + }); + cxt.ok(valid); + }, +}; +exports.default = def; +//# sourceMappingURL=propertyNames.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js.map b/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js.map new file mode 100644 index 000000000..835b2bb13 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js.map @@ -0,0 +1 @@ +{"version":3,"file":"propertyNames.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/propertyNames.ts"],"names":[],"mappings":";;AAOA,mDAA4C;AAC5C,6CAAoD;AAIpD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,6BAA6B;IACtC,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,kBAAkB,MAAM,CAAC,YAAY,GAAG;CAChE,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,eAAe;IACxB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAE/B,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE;YAC7B,GAAG,CAAC,SAAS,CAAC,EAAC,YAAY,EAAE,GAAG,EAAC,CAAC,CAAA;YAClC,GAAG,CAAC,SAAS,CACX;gBACE,OAAO,EAAE,eAAe;gBACxB,IAAI,EAAE,GAAG;gBACT,SAAS,EAAE,CAAC,QAAQ,CAAC;gBACrB,YAAY,EAAE,GAAG;gBACjB,aAAa,EAAE,IAAI;aACpB,EACD,KAAK,CACN,CAAA;YACD,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE;gBACtB,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;gBACf,IAAI,CAAC,EAAE,CAAC,SAAS;oBAAE,GAAG,CAAC,KAAK,EAAE,CAAA;YAChC,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/thenElse.d.ts b/node_modules/ajv/dist/vocabularies/applicator/thenElse.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/thenElse.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/applicator/thenElse.js b/node_modules/ajv/dist/vocabularies/applicator/thenElse.js new file mode 100644 index 000000000..1ae639021 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/thenElse.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("../../compile/util"); +const def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === undefined) + (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + }, +}; +exports.default = def; +//# sourceMappingURL=thenElse.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/applicator/thenElse.js.map b/node_modules/ajv/dist/vocabularies/applicator/thenElse.js.map new file mode 100644 index 000000000..2629f4fce --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/applicator/thenElse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"thenElse.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/thenElse.ts"],"names":[],"mappings":";;AAEA,6CAAkD;AAElD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC;IACzB,UAAU,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACjC,IAAI,CAAC,EAAC,OAAO,EAAE,YAAY,EAAE,EAAE,EAAa;QAC1C,IAAI,YAAY,CAAC,EAAE,KAAK,SAAS;YAAE,IAAA,sBAAe,EAAC,EAAE,EAAE,IAAI,OAAO,2BAA2B,CAAC,CAAA;IAChG,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/code.d.ts b/node_modules/ajv/dist/vocabularies/code.d.ts new file mode 100644 index 000000000..f914baca5 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/code.d.ts @@ -0,0 +1,17 @@ +import type { SchemaMap } from "../types"; +import type { SchemaCxt } from "../compile"; +import type { KeywordCxt } from "../compile/validate"; +import { CodeGen, Code, Name } from "../compile/codegen"; +export declare function checkReportMissingProp(cxt: KeywordCxt, prop: string): void; +export declare function checkMissingProp({ gen, data, it: { opts } }: KeywordCxt, properties: string[], missing: Name): Code; +export declare function reportMissingProp(cxt: KeywordCxt, missing: Name): void; +export declare function hasPropFunc(gen: CodeGen): Name; +export declare function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code; +export declare function propertyInData(gen: CodeGen, data: Name, property: Name | string, ownProperties?: boolean): Code; +export declare function noPropertyInData(gen: CodeGen, data: Name, property: Name | string, ownProperties?: boolean): Code; +export declare function allSchemaProperties(schemaMap?: SchemaMap): string[]; +export declare function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[]; +export declare function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }: KeywordCxt, func: Code, context: Code, passSchema?: boolean): Code; +export declare function usePattern({ gen, it: { opts } }: KeywordCxt, pattern: string): Name; +export declare function validateArray(cxt: KeywordCxt): Name; +export declare function validateUnion(cxt: KeywordCxt): void; diff --git a/node_modules/ajv/dist/vocabularies/code.js b/node_modules/ajv/dist/vocabularies/code.js new file mode 100644 index 000000000..8cb899324 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/code.js @@ -0,0 +1,131 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; +const codegen_1 = require("../compile/codegen"); +const util_1 = require("../compile/util"); +const names_1 = require("../compile/names"); +const util_2 = require("../compile/util"); +function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true); + cxt.error(); + }); +} +exports.checkReportMissingProp = checkReportMissingProp; +function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`))); +} +exports.checkMissingProp = checkMissingProp; +function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); +} +exports.reportMissingProp = reportMissingProp; +function hasPropFunc(gen) { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._) `Object.prototype.hasOwnProperty`, + }); +} +exports.hasPropFunc = hasPropFunc; +function isOwnProperty(gen, data, property) { + return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`; +} +exports.isOwnProperty = isOwnProperty; +function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond; +} +exports.propertyInData = propertyInData; +function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; +} +exports.noPropertyInData = noPropertyInData; +function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; +} +exports.allSchemaProperties = allSchemaProperties; +function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); +} +exports.schemaProperties = schemaProperties; +function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData], + ]; + if (it.opts.dynamicRef) + valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`; +} +exports.callValidateCode = callValidateCode; +const newRegExp = (0, codegen_1._) `new RegExp`; +function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`, + }); +} +exports.usePattern = usePattern; +function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._) `${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num, + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } +} +exports.validateArray = validateArray; +function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); + if (alwaysValid && !it.opts.unevaluated) + return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true, + }, schValid); + gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`); + const merged = cxt.mergeValidEvaluated(schCxt, schValid); + // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true) + // or if all properties and items were evaluated (it.props === true && it.items === true) + if (!merged) + gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); +} +exports.validateUnion = validateUnion; +//# sourceMappingURL=code.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/code.js.map b/node_modules/ajv/dist/vocabularies/code.js.map new file mode 100644 index 000000000..ef06de270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/code.js.map @@ -0,0 +1 @@ +{"version":3,"file":"code.js","sourceRoot":"","sources":["../../lib/vocabularies/code.ts"],"names":[],"mappings":";;;AAGA,gDAAoG;AACpG,0CAAuD;AACvD,4CAAgC;AAChC,0CAAuC;AACvC,SAAgB,sBAAsB,CAAC,GAAe,EAAE,IAAY;IAClE,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IAC3B,GAAG,CAAC,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,EAAE,GAAG,EAAE;QACpE,GAAG,CAAC,SAAS,CAAC,EAAC,eAAe,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,EAAE,EAAC,EAAE,IAAI,CAAC,CAAA;QAClD,GAAG,CAAC,KAAK,EAAE,CAAA;IACb,CAAC,CAAC,CAAA;AACJ,CAAC;AAND,wDAMC;AAED,SAAgB,gBAAgB,CAC9B,EAAC,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,EAAC,IAAI,EAAC,EAAa,EACnC,UAAoB,EACpB,OAAa;IAEb,OAAO,IAAA,YAAE,EACP,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACzB,IAAA,aAAG,EAAC,gBAAgB,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,aAAa,CAAC,EAAE,IAAA,WAAC,EAAA,GAAG,OAAO,MAAM,IAAI,EAAE,CAAC,CACpF,CACF,CAAA;AACH,CAAC;AAVD,4C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ts b/node_modules/ajv/dist/vocabularies/core/id.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/core/id.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/core/id.js b/node_modules/ajv/dist/vocabularies/core/id.js new file mode 100644 index 000000000..313598aab --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/core/id.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const def = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + }, +}; +exports.default = def; +//# sourceMappingURL=id.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/core/id.js.map b/node_modules/ajv/dist/vocabularies/core/id.js.map new file mode 100644 index 000000000..4eb27eb33 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/core/id.js.map @@ -0,0 +1 @@ +{"version":3,"file":"id.js","sourceRoot":"","sources":["../../../lib/vocabularies/core/id.ts"],"names":[],"mappings":";;AAEA,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,IAAI;IACb,IAAI;QACF,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAA;IACzE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/core/index.d.ts b/node_modules/ajv/dist/vocabularies/core/index.d.ts new file mode 100644 index 000000000..f2e34ee36 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/core/index.d.ts @@ -0,0 +1,3 @@ +import type { Vocabulary } from "../../types"; +declare const core: Vocabulary; +export default core; diff --git a/node_modules/ajv/dist/vocabularies/core/index.js b/node_modules/ajv/dist/vocabularies/core/index.js new file mode 100644 index 000000000..87656d743 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/core/index.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const id_1 = require("./id"); +const ref_1 = require("./ref"); +const core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default, +]; +exports.default = core; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/core/index.js.map b/node_modules/ajv/dist/vocabularies/core/index.js.map new file mode 100644 index 000000000..5bf65f941 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/core/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/core/index.ts"],"names":[],"mappings":";;AACA,6BAA4B;AAC5B,+BAA8B;AAE9B,MAAM,IAAI,GAAe;IACvB,SAAS;IACT,KAAK;IACL,OAAO;IACP,aAAa;IACb,EAAC,OAAO,EAAE,UAAU,EAAC;IACrB,aAAa;IACb,YAAS;IACT,aAAU;CACX,CAAA;AAED,kBAAe,IAAI,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/core/ref.d.ts b/node_modules/ajv/dist/vocabularies/core/ref.d.ts new file mode 100644 index 000000000..6a0967d15 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/core/ref.d.ts @@ -0,0 +1,8 @@ +import type { CodeKeywordDefinition } from "../../types"; +import type { KeywordCxt } from "../../compile/validate"; +import { Code } from "../../compile/codegen"; +import { SchemaEnv } from "../../compile"; +declare const def: CodeKeywordDefinition; +export declare function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code; +export declare function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/core/ref.js b/node_modules/ajv/dist/vocabularies/core/ref.js new file mode 100644 index 000000000..bac1ae853 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/core/ref.js @@ -0,0 +1,122 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.callRef = exports.getValidate = void 0; +const ref_error_1 = require("../../compile/ref_error"); +const code_1 = require("../code"); +const codegen_1 = require("../../compile/codegen"); +const names_1 = require("../../compile/names"); +const compile_1 = require("../../compile"); +const util_1 = require("../../compile/util"); +const def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) + return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === undefined) + throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) + return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) + return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + const v = getValidate(cxt, sch); + callRef(cxt, v, sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref, + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + }, +}; +function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate + ? gen.scopeValue("validate", { ref: sch.validate }) + : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`; +} +exports.getValidate = getValidate; +function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) + callAsyncRef(); + else + callSyncRef(); + function callAsyncRef() { + if (!env.$async) + throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result + if (!allErrors) + gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) + gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._) `${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged + gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) + return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + // TODO refactor + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== undefined) { + it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } + } + else { + const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== undefined) { + it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } + } + else { + const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } +} +exports.callRef = callRef; +exports.default = def; +//# sourceMappingURL=ref.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/core/ref.js.map b/node_modules/ajv/dist/vocabularies/core/ref.js.map new file mode 100644 index 000000000..3125bb893 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/core/ref.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ref.js","sourceRoot":"","sources":["../../../lib/vocabularies/core/ref.ts"],"names":[],"mappings":";;;AAEA,uDAAqD;AACrD,kCAAwC;AACxC,mDAAmE;AACnE,+CAAmC;AACnC,2CAAmD;AACnD,6CAAiD;AAEjD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,MAAM;IACf,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,MAAM,EAAC,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,EAAC,GAAG,EAAE,CAAA;QAC7D,MAAM,EAAC,IAAI,EAAC,GAAG,GAAG,CAAA;QAClB,IAAI,CAAC,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC,IAAI,MAAM,KAAK,IAAI,CAAC,MAAM;YAAE,OAAO,WAAW,EAAE,CAAA;QACnF,MAAM,QAAQ,GAAG,oBAAU,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAA;QAC1D,IAAI,QAAQ,KAAK,SAAS;YAAE,MAAM,IAAI,mBAAe,CAAC,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAA;QACxF,IAAI,QAAQ,YAAY,mBAAS;YAAE,OAAO,YAAY,CAAC,QAAQ,CAAC,CAAA;QAChE,OAAO,eAAe,CAAC,QAAQ,CAAC,CAAA;QAEhC,SAAS,WAAW;YAClB,IAAI,GAAG,KAAK,IAAI;gBAAE,OAAO,OAAO,CAAC,GAAG,EAAE,YAAY,EAAE,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;YACpE,MA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AC;gBAC/C,IAAI,YAAY,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;oBACrC,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,YAAY,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,CAAA;gBACpE,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,MAAM,kBAAkB,CAAC,CAAA;gBAC5D,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,EAAE,cAAI,CAAC,CAAA;YAC7D,CAAC;QACH,CAAC;QACD,IAAI,EAAE,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YACtB,IAAI,YAAY,IAAI,CAAC,YAAY,CAAC,YAAY,EAAE,CAAC;gBAC/C,IAAI,YAAY,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;oBACrC,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,YAAY,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,CAAA;gBACpE,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,MAAM,kBAAkB,CAAC,CAAA;gBAC5D,EAAE,CAAC,KAAK,GAAG,qBAAc,CAAC,KAAK,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,EAAE,cAAI,CAAC,CAAA;YAC7D,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC;AAhED,0BAgEC;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/discriminator/index.d.ts b/node_modules/ajv/dist/vocabularies/discriminator/index.d.ts new file mode 100644 index 000000000..ab3669a42 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/discriminator/index.d.ts @@ -0,0 +1,5 @@ +import type { CodeKeywordDefinition } from "../../types"; +import { DiscrError, DiscrErrorObj } from "../discriminator/types"; +export type DiscriminatorError = DiscrErrorObj | DiscrErrorObj; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/discriminator/index.js b/node_modules/ajv/dist/vocabularies/discriminator/index.js new file mode 100644 index 000000000..e113aed70 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/discriminator/index.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const types_1 = require("../discriminator/types"); +const compile_1 = require("../../compile"); +const ref_error_1 = require("../../compile/ref_error"); +const util_1 = require("../../compile/util"); +const error = { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag + ? `tag "${tagName}" must be string` + : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`, +}; +const def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option"); + } + const tagName = schema.propertyName; + if (typeof tagName != "string") + throw new Error("discriminator: requires propertyName"); + if (schema.mapping) + throw new Error("discriminator: mapping is not supported"); + if (!oneOf) + throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) + sch = sch.schema; + if (sch === undefined) + throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") { + throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) + throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) { + addMapping(sch.const, i); + } + else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i); + } + } + else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`); + } + oneOfMapping[tagValue] = i; + } + } + }, +}; +exports.default = def; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/discriminator/index.js.map b/node_modules/ajv/dist/vocabularies/discriminator/index.js.map new file mode 100644 index 000000000..f9d69db26 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/discriminator/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/discriminator/index.ts"],"names":[],"mappings":";;AAEA,mDAA0D;AAC1D,kDAAgE;AAChE,2CAAmD;AACnD,uDAAqD;AACrD,6CAAuD;AAIvD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,UAAU,EAAE,OAAO,EAAC,EAAC,EAAE,EAAE,CAC3C,UAAU,KAAK,kBAAU,CAAC,GAAG;QAC3B,CAAC,CAAC,QAAQ,OAAO,kBAAkB;QACnC,CAAC,CAAC,iBAAiB,OAAO,oBAAoB;IAClD,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,UAAU,EAAE,GAAG,EAAE,OAAO,EAAC,EAAC,EAAE,EAAE,CAC/C,IAAA,WAAC,EAAA,WAAW,UAAU,UAAU,OAAO,eAAe,GAAG,GAAG;CAC/D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,eAAe;IACxB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACjD,MAAM,EAAC,KAAK,EAAC,GAAG,YAAY,CAAA;QAC5B,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YAC3B,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAA;QACjE,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,CAAC,YAAY,CAAA;QACnC,IAAI,OAAO,OAAO,IAAI,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,sCAAsC,C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AAmB,OAAO,iCAAiC,CAAC,CAAA;gBAC9E,CAAC;gBACD,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;YAC5B,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/discriminator/types.d.ts b/node_modules/ajv/dist/vocabularies/discriminator/types.d.ts new file mode 100644 index 000000000..8550f6d97 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/discriminator/types.d.ts @@ -0,0 +1,10 @@ +import type { ErrorObject } from "../../types"; +export declare enum DiscrError { + Tag = "tag", + Mapping = "mapping" +} +export type DiscrErrorObj = ErrorObject<"discriminator", { + error: E; + tag: string; + tagValue: unknown; +}, string>; diff --git a/node_modules/ajv/dist/vocabularies/discriminator/types.js b/node_modules/ajv/dist/vocabularies/discriminator/types.js new file mode 100644 index 000000000..edf4da5ed --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/discriminator/types.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DiscrError = void 0; +var DiscrError; +(function (DiscrError) { + DiscrError["Tag"] = "tag"; + DiscrError["Mapping"] = "mapping"; +})(DiscrError || (exports.DiscrError = DiscrError = {})); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/discriminator/types.js.map b/node_modules/ajv/dist/vocabularies/discriminator/types.js.map new file mode 100644 index 000000000..028633bd3 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/discriminator/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/vocabularies/discriminator/types.ts"],"names":[],"mappings":";;;AAEA,IAAY,UAGX;AAHD,WAAY,UAAU;IACpB,yBAAW,CAAA;IACX,iCAAmB,CAAA;AACrB,CAAC,EAHW,UAAU,0BAAV,UAAU,QAGrB"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/draft2020.d.ts b/node_modules/ajv/dist/vocabularies/draft2020.d.ts new file mode 100644 index 000000000..d65752c63 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/draft2020.d.ts @@ -0,0 +1,3 @@ +import type { Vocabulary } from "../types"; +declare const draft2020Vocabularies: Vocabulary[]; +export default draft2020Vocabularies; diff --git a/node_modules/ajv/dist/vocabularies/draft2020.js b/node_modules/ajv/dist/vocabularies/draft2020.js new file mode 100644 index 000000000..23d244aed --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/draft2020.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const core_1 = require("./core"); +const validation_1 = require("./validation"); +const applicator_1 = require("./applicator"); +const dynamic_1 = require("./dynamic"); +const next_1 = require("./next"); +const unevaluated_1 = require("./unevaluated"); +const format_1 = require("./format"); +const metadata_1 = require("./metadata"); +const draft2020Vocabularies = [ + dynamic_1.default, + core_1.default, + validation_1.default, + (0, applicator_1.default)(true), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary, + next_1.default, + unevaluated_1.default, +]; +exports.default = draft2020Vocabularies; +//# sourceMappingURL=draft2020.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/draft2020.js.map b/node_modules/ajv/dist/vocabularies/draft2020.js.map new file mode 100644 index 000000000..ae1a4d833 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/draft2020.js.map @@ -0,0 +1 @@ +{"version":3,"file":"draft2020.js","sourceRoot":"","sources":["../../lib/vocabularies/draft2020.ts"],"names":[],"mappings":";;AACA,iCAAmC;AACnC,6CAA+C;AAC/C,6CAAkD;AAClD,uCAAyC;AACzC,iCAAmC;AACnC,+CAAiD;AACjD,qCAAuC;AACvC,yCAAgE;AAEhE,MAAM,qBAAqB,GAAiB;IAC1C,iBAAiB;IACjB,cAAc;IACd,oBAAoB;IACpB,IAAA,oBAAuB,EAAC,IAAI,CAAC;IAC7B,gBAAgB;IAChB,6BAAkB;IAClB,4BAAiB;IACjB,cAAc;IACd,qBAAqB;CACtB,CAAA;AAED,kBAAe,qBAAqB,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/draft7.d.ts b/node_modules/ajv/dist/vocabularies/draft7.d.ts new file mode 100644 index 000000000..469fb8444 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/draft7.d.ts @@ -0,0 +1,3 @@ +import type { Vocabulary } from "../types"; +declare const draft7Vocabularies: Vocabulary[]; +export default draft7Vocabularies; diff --git a/node_modules/ajv/dist/vocabularies/draft7.js b/node_modules/ajv/dist/vocabularies/draft7.js new file mode 100644 index 000000000..1e993de0e --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/draft7.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const core_1 = require("./core"); +const validation_1 = require("./validation"); +const applicator_1 = require("./applicator"); +const format_1 = require("./format"); +const metadata_1 = require("./metadata"); +const draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary, +]; +exports.default = draft7Vocabularies; +//# sourceMappingURL=draft7.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/draft7.js.map b/node_modules/ajv/dist/vocabularies/draft7.js.map new file mode 100644 index 000000000..bc7389c67 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/draft7.js.map @@ -0,0 +1 @@ +{"version":3,"file":"draft7.js","sourceRoot":"","sources":["../../lib/vocabularies/draft7.ts"],"names":[],"mappings":";;AACA,iCAAmC;AACnC,6CAA+C;AAC/C,6CAAkD;AAClD,qCAAuC;AACvC,yCAAgE;AAEhE,MAAM,kBAAkB,GAAiB;IACvC,cAAc;IACd,oBAAoB;IACpB,IAAA,oBAAuB,GAAE;IACzB,gBAAgB;IAChB,6BAAkB;IAClB,4BAAiB;CAClB,CAAA;AAED,kBAAe,kBAAkB,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.d.ts b/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.d.ts new file mode 100644 index 000000000..562121399 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.d.ts @@ -0,0 +1,5 @@ +import type { CodeKeywordDefinition } from "../../types"; +import type { KeywordCxt } from "../../compile/validate"; +declare const def: CodeKeywordDefinition; +export declare function dynamicAnchor(cxt: KeywordCxt, anchor: string): void; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js b/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js new file mode 100644 index 000000000..972dc35c4 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dynamicAnchor = void 0; +const codegen_1 = require("../../compile/codegen"); +const names_1 = require("../../compile/names"); +const compile_1 = require("../../compile"); +const ref_1 = require("../core/ref"); +const def = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema), +}; +function dynamicAnchor(cxt, anchor) { + const { gen, it } = cxt; + it.schemaEnv.root.dynamicAnchors[anchor] = true; + const v = (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); + gen.if((0, codegen_1._) `!${v}`, () => gen.assign(v, validate)); +} +exports.dynamicAnchor = dynamicAnchor; +function _getValidate(cxt) { + const { schemaEnv, schema, self } = cxt.it; + const { root, baseId, localRefs, meta } = schemaEnv.root; + const { schemaId } = self.opts; + const sch = new compile_1.SchemaEnv({ schema, schemaId, root, baseId, localRefs, meta }); + compile_1.compileSchema.call(self, sch); + return (0, ref_1.getValidate)(cxt, sch); +} +exports.default = def; +//# sourceMappingURL=dynamicAnchor.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js.map b/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js.map new file mode 100644 index 000000000..e70afe30f --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dynamicAnchor.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/dynamicAnchor.ts"],"names":[],"mappings":";;;AAEA,mDAA0D;AAC1D,+CAAmC;AACnC,2CAAsD;AACtD,qCAAuC;AAEvC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,gBAAgB;IACzB,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;CAC9C,CAAA;AAED,SAAgB,aAAa,CAAC,GAAe,EAAE,MAAc;IAC3D,MAAM,EAAC,GAAG,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IACrB,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,CAAA;IAC/C,MAAM,CAAC,GAAG,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,cAAc,GAAG,IAAA,qBAAW,EAAC,MAAM,CAAC,EAAE,CAAA;IACtD,MAAM,QAAQ,GAAG,EAAE,CAAC,aAAa,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,CAAC,CAAA;IAC/E,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAA;AACjD,CAAC;AAND,sCAMC;AAED,SAAS,YAAY,CAAC,GAAe;IACnC,MAAM,EAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAC,EAAE,CAAA;IACxC,MAAM,EAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAC,GAAG,SAAS,CAAC,IAAI,CAAA;IACtD,MAAM,EAAC,QAAQ,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;IAC5B,MAAM,GAAG,GAAG,IAAI,mBAAS,CAAC,EAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAC,CAAC,CAAA;IAC5E,uBAAa,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IAC7B,OAAO,IAAA,iBAAW,EAAC,GAAG,EAAE,GAAG,CAAC,CAAA;AAC9B,CAAC;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.d.ts b/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.d.ts new file mode 100644 index 000000000..fa2f2b81d --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.d.ts @@ -0,0 +1,5 @@ +import type { CodeKeywordDefinition } from "../../types"; +import type { KeywordCxt } from "../../compile/validate"; +declare const def: CodeKeywordDefinition; +export declare function dynamicRef(cxt: KeywordCxt, ref: string): void; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js b/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js new file mode 100644 index 000000000..9f010a0df --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dynamicRef = void 0; +const codegen_1 = require("../../compile/codegen"); +const names_1 = require("../../compile/names"); +const ref_1 = require("../core/ref"); +const def = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema), +}; +function dynamicRef(cxt, ref) { + const { gen, keyword, it } = cxt; + if (ref[0] !== "#") + throw new Error(`"${keyword}" only supports hash fragment reference`); + const anchor = ref.slice(1); + if (it.allErrors) { + _dynamicRef(); + } + else { + const valid = gen.let("valid", false); + _dynamicRef(valid); + cxt.ok(valid); + } + function _dynamicRef(valid) { + // TODO the assumption here is that `recursiveRef: #` always points to the root + // of the schema object, which is not correct, because there may be $id that + // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor. + // Because of that 2 tests in recursiveRef.json fail. + // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`). + // (This problem is not tested in JSON-Schema-Test-Suite) + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); + } + else { + _callRef(it.validateName, valid)(); + } + } + function _callRef(validate, valid) { + return valid + ? () => gen.block(() => { + (0, ref_1.callRef)(cxt, validate); + gen.let(valid, true); + }) + : () => (0, ref_1.callRef)(cxt, validate); + } +} +exports.dynamicRef = dynamicRef; +exports.default = def; +//# sourceMappingURL=dynamicRef.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js.map b/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js.map new file mode 100644 index 000000000..69afd4de8 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dynamicRef.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/dynamicRef.ts"],"names":[],"mappings":";;;AAEA,mDAAgE;AAChE,+CAAmC;AACnC,qCAAmC;AAEnC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,aAAa;IACtB,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;CAC3C,CAAA;AAED,SAAgB,UAAU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CAAC,GAAG,EAAE,CACH,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE;gBACb,IAAA,aAAO,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;gBACtB,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;YACtB,CAAC,CAAC;YACN,CAAC,CAAC,GAAG,EAAE,CAAC,IAAA,aAAO,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;IAClC,CAAC;AACH,CAAC;AApCD,gCAoCC;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/dynamic/index.d.ts b/node_modules/ajv/dist/vocabularies/dynamic/index.d.ts new file mode 100644 index 000000000..0c751d93f --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/index.d.ts @@ -0,0 +1,3 @@ +import type { Vocabulary } from "../../types"; +declare const dynamic: Vocabulary; +export default dynamic; diff --git a/node_modules/ajv/dist/vocabularies/dynamic/index.js b/node_modules/ajv/dist/vocabularies/dynamic/index.js new file mode 100644 index 000000000..f2388a757 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/index.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const dynamicAnchor_1 = require("./dynamicAnchor"); +const dynamicRef_1 = require("./dynamicRef"); +const recursiveAnchor_1 = require("./recursiveAnchor"); +const recursiveRef_1 = require("./recursiveRef"); +const dynamic = [dynamicAnchor_1.default, dynamicRef_1.default, recursiveAnchor_1.default, recursiveRef_1.default]; +exports.default = dynamic; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/dynamic/index.js.map b/node_modules/ajv/dist/vocabularies/dynamic/index.js.map new file mode 100644 index 000000000..f96ba76dd --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/index.ts"],"names":[],"mappings":";;AACA,mDAA2C;AAC3C,6CAAqC;AACrC,uDAA+C;AAC/C,iDAAyC;AAEzC,MAAM,OAAO,GAAe,CAAC,uBAAa,EAAE,oBAAU,EAAE,yBAAe,EAAE,sBAAY,CAAC,CAAA;AAEtF,kBAAe,OAAO,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.d.ts b/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js b/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js new file mode 100644 index 000000000..9fd832353 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const dynamicAnchor_1 = require("./dynamicAnchor"); +const util_1 = require("../../compile/util"); +const def = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) + (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); + else + (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); + }, +}; +exports.default = def; +//# sourceMappingURL=recursiveAnchor.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js.map b/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js.map new file mode 100644 index 000000000..5d5e381b0 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"recursiveAnchor.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/recursiveAnchor.ts"],"names":[],"mappings":";;AACA,mDAA6C;AAC7C,6CAAkD;AAElD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,kBAAkB;IAC3B,UAAU,EAAE,SAAS;IACrB,IAAI,CAAC,GAAG;QACN,IAAI,GAAG,CAAC,MAAM;YAAE,IAAA,6BAAa,EAAC,GAAG,EAAE,EAAE,CAAC,CAAA;;YACjC,IAAA,sBAAe,EAAC,GAAG,CAAC,EAAE,EAAE,oCAAoC,CAAC,CAAA;IACpE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.d.ts b/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js b/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js new file mode 100644 index 000000000..8cd5c6969 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const dynamicRef_1 = require("./dynamicRef"); +const def = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema), +}; +exports.default = def; +//# sourceMappingURL=recursiveRef.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js.map b/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js.map new file mode 100644 index 000000000..f81380446 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js.map @@ -0,0 +1 @@ +{"version":3,"file":"recursiveRef.js","sourceRoot":"","sources":["../../../lib/vocabularies/dynamic/recursiveRef.ts"],"names":[],"mappings":";;AACA,6CAAuC;AAEvC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,eAAe;IACxB,UAAU,EAAE,QAAQ;IACpB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,uBAAU,EAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;CAC3C,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/errors.d.ts b/node_modules/ajv/dist/vocabularies/errors.d.ts new file mode 100644 index 000000000..be67f2e82 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/errors.d.ts @@ -0,0 +1,9 @@ +import type { TypeError } from "../compile/validate/dataType"; +import type { ApplicatorKeywordError } from "./applicator"; +import type { ValidationKeywordError } from "./validation"; +import type { FormatError } from "./format/format"; +import type { UnevaluatedPropertiesError } from "./unevaluated/unevaluatedProperties"; +import type { UnevaluatedItemsError } from "./unevaluated/unevaluatedItems"; +import type { DependentRequiredError } from "./validation/dependentRequired"; +import type { DiscriminatorError } from "./discriminator"; +export type DefinedError = TypeError | ApplicatorKeywordError | ValidationKeywordError | FormatError | UnevaluatedPropertiesError | UnevaluatedItemsError | DependentRequiredError | DiscriminatorError; diff --git a/node_modules/ajv/dist/vocabularies/errors.js b/node_modules/ajv/dist/vocabularies/errors.js new file mode 100644 index 000000000..d4d3fba00 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/errors.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/errors.js.map b/node_modules/ajv/dist/vocabularies/errors.js.map new file mode 100644 index 000000000..56bad7362 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../lib/vocabularies/errors.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/format/format.d.ts b/node_modules/ajv/dist/vocabularies/format/format.d.ts new file mode 100644 index 000000000..04dc98f64 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/format/format.d.ts @@ -0,0 +1,8 @@ +import type { CodeKeywordDefinition, ErrorObject } from "../../types"; +export type FormatError = ErrorObject<"format", { + format: string; +}, string | { + $data: string; +}>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/format/format.js b/node_modules/ajv/dist/vocabularies/format/format.js new file mode 100644 index 000000000..aa667c1ef --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/format/format.js @@ -0,0 +1,92 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const error = { + message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`, +}; +const def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) + return; + if ($data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats, + }); + const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + // TODO simplify + gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) + return codegen_1.nil; + return (0, codegen_1._) `${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async + ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` + : (0, codegen_1._) `${format}(${data})`; + const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) + return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) + cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp + ? (0, codegen_1.regexpCode)(fmtDef) + : opts.code.formats + ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` + : undefined; + const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`]; + } + return ["string", fmtDef, fmt]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) + throw new Error("async format in sync schema"); + return (0, codegen_1._) `await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`; + } + } + }, +}; +exports.default = def; +//# sourceMappingURL=format.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/format/format.js.map b/node_modules/ajv/dist/vocabularies/format/format.js.map new file mode 100644 index 000000000..b6d93c981 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/format/format.js.map @@ -0,0 +1 @@ +{"version":3,"file":"format.js","sourceRoot":"","sources":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,IAAI,IAAI,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,IAAA,WAAC,EAAA,GAAG,GAAG,WAAW,CAAC,CAAA;gBACvE,CAAC;gBAED,OAAO,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,CAAA;YAChC,CAAC;YAED,SAAS,cAAc;gBACrB,IAAI,OAAO,SAAS,IAAI,QAAQ,IAAI,CAAC,CAAC,SAAS,YAAY,MAAM,CAAC,IAAI,SAAS,CAAC,KAAK,EAAE,CAAC;oBACtF,IAAI,CAAC,SAAS,CAAC,MAAM;wBAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAA;oBACrE,OAAO,IAAA,WAAC,EAAA,SAAS,MAAM,IAAI,IAAI,GAAG,CAAA;gBACpC,CAAC;gBACD,OAAO,OAAO,MAAM,IAAI,UAAU,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,SAAS,IAAI,GAAG,CAAA;YACzF,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/format/index.d.ts b/node_modules/ajv/dist/vocabularies/format/index.d.ts new file mode 100644 index 000000000..c8019c9d6 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/format/index.d.ts @@ -0,0 +1,3 @@ +import type { Vocabulary } from "../../types"; +declare const format: Vocabulary; +export default format; diff --git a/node_modules/ajv/dist/vocabularies/format/index.js b/node_modules/ajv/dist/vocabularies/format/index.js new file mode 100644 index 000000000..d19023d24 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/format/index.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const format_1 = require("./format"); +const format = [format_1.default]; +exports.default = format; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/format/index.js.map b/node_modules/ajv/dist/vocabularies/format/index.js.map new file mode 100644 index 000000000..6315bfe1f --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/format/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/format/index.ts"],"names":[],"mappings":";;AACA,qCAAoC;AAEpC,MAAM,MAAM,GAAe,CAAC,gBAAa,CAAC,CAAA;AAE1C,kBAAe,MAAM,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/discriminator.d.ts b/node_modules/ajv/dist/vocabularies/jtd/discriminator.d.ts new file mode 100644 index 000000000..85e16df6a --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/discriminator.d.ts @@ -0,0 +1,6 @@ +import type { CodeKeywordDefinition } from "../../types"; +import { _JTDTypeError } from "./error"; +import { DiscrError, DiscrErrorObj } from "../discriminator/types"; +export type JTDDiscriminatorError = _JTDTypeError<"discriminator", "object", string> | DiscrErrorObj | DiscrErrorObj; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/jtd/discriminator.js b/node_modules/ajv/dist/vocabularies/jtd/discriminator.js new file mode 100644 index 000000000..e7074d279 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/discriminator.js @@ -0,0 +1,71 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const metadata_1 = require("./metadata"); +const nullable_1 = require("./nullable"); +const error_1 = require("./error"); +const types_1 = require("../discriminator/types"); +const error = { + message: (cxt) => { + const { schema, params } = cxt; + return params.discrError + ? params.discrError === types_1.DiscrError.Tag + ? `tag "${schema}" must be string` + : `value of tag "${schema}" must be in mapping` + : (0, error_1.typeErrorMessage)(cxt, "object"); + }, + params: (cxt) => { + const { schema, params } = cxt; + return params.discrError + ? (0, codegen_1._) `{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}` + : (0, error_1.typeErrorParams)(cxt, "object"); + }, +}; +const def = { + keyword: "discriminator", + schemaType: "string", + implements: ["mapping"], + error, + code(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { gen, data, schema, parentSchema } = cxt; + const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data); + gen.if(cond); + validateDiscriminator(); + gen.elseIf((0, codegen_1.not)(valid)); + cxt.error(); + gen.endIf(); + cxt.ok(valid); + function validateDiscriminator() { + const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(schema)}`); + gen.if((0, codegen_1._) `${tag} === undefined`); + cxt.error(false, { discrError: types_1.DiscrError.Tag, tag }); + gen.elseIf((0, codegen_1._) `typeof ${tag} == "string"`); + validateMapping(tag); + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Tag, tag }, { instancePath: schema }); + gen.endIf(); + } + function validateMapping(tag) { + gen.if(false); + for (const tagValue in parentSchema.mapping) { + gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(tagValue)); + } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag }, { instancePath: schema, schemaPath: "mapping", parentSchema: true }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + cxt.subschema({ + keyword: "mapping", + schemaProp, + jtdDiscriminator: schema, + }, _valid); + return _valid; + } + }, +}; +exports.default = def; +//# sourceMappingURL=discriminator.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/discriminator.js.map b/node_modules/ajv/dist/vocabularies/jtd/discriminator.js.map new file mode 100644 index 000000000..ca2a5ab94 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/discriminator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"discriminator.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/discriminator.ts"],"names":[],"mappings":";;AAEA,mDAA+D;AAC/D,yCAAwC;AACxC,yCAA8C;AAC9C,mCAAwE;AACxE,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,UAAU,EAAE,kBAAU,CAAC,OAAO,EAAE,GAAG,EAAC,EACrC,EAAC,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,IAAI,EAAC,CAClE,CAAA;YACD,GAAG,CAAC,KAAK,EAAE,CAAA;QACb,CAAC;QAED,SAAS,cAAc,CAAC,UAAkB;YACxC,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YAChC,GAAG,CAAC,SAAS,CACX;gBACE,OAAO,EAAE,SAAS;gBAClB,UAAU;gBACV,gBAAgB,EAAE,MAAM;aACzB,EACD,MAAM,CACP,CAAA;YACD,OAAO,MAAM,CAAA;QACf,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/elements.d.ts b/node_modules/ajv/dist/vocabularies/jtd/elements.d.ts new file mode 100644 index 000000000..82c942c35 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/elements.d.ts @@ -0,0 +1,5 @@ +import type { CodeKeywordDefinition, SchemaObject } from "../../types"; +import { _JTDTypeError } from "./error"; +export type JTDElementsError = _JTDTypeError<"elements", "array", SchemaObject>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/jtd/elements.js b/node_modules/ajv/dist/vocabularies/jtd/elements.js new file mode 100644 index 000000000..9b8fb548a --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/elements.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("../../compile/util"); +const code_1 = require("../code"); +const codegen_1 = require("../../compile/codegen"); +const metadata_1 = require("./metadata"); +const nullable_1 = require("./nullable"); +const error_1 = require("./error"); +const def = { + keyword: "elements", + schemaType: "object", + error: (0, error_1.typeError)("array"), + code(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { gen, data, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + const [valid] = (0, nullable_1.checkNullable)(cxt); + gen.if((0, codegen_1.not)(valid), () => gen.if((0, codegen_1._) `Array.isArray(${data})`, () => gen.assign(valid, (0, code_1.validateArray)(cxt)), () => cxt.error())); + cxt.ok(valid); + }, +}; +exports.default = def; +//# sourceMappingURL=elements.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/elements.js.map b/node_modules/ajv/dist/vocabularies/jtd/elements.js.map new file mode 100644 index 000000000..38fe3a129 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/elements.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elements.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/elements.ts"],"names":[],"mappings":";;AAEA,6CAAoD;AACpD,kCAAqC;AACrC,mDAA4C;AAC5C,yCAAwC;AACxC,yCAAwC;AACxC,mCAAgD;AAIhD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAA,iBAAS,EAAC,OAAO,CAAC;IACzB,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClC,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CACtB,GAAG,CAAC,EAAE,CACJ,IAAA,WAAC,EAAA,iBAAiB,IAAI,GAAG,EACzB,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAA,oBAAa,EAAC,GAAG,CAAC,CAAC,EAC3C,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAClB,CACF,CAAA;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/enum.d.ts b/node_modules/ajv/dist/vocabularies/jtd/enum.d.ts new file mode 100644 index 000000000..8ba1790d7 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/enum.d.ts @@ -0,0 +1,6 @@ +import type { CodeKeywordDefinition, ErrorObject } from "../../types"; +export type JTDEnumError = ErrorObject<"enum", { + allowedValues: string[]; +}, string[]>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/jtd/enum.js b/node_modules/ajv/dist/vocabularies/jtd/enum.js new file mode 100644 index 000000000..78b01ee37 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/enum.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const metadata_1 = require("./metadata"); +const nullable_1 = require("./nullable"); +const error = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`, +}; +const def = { + keyword: "enum", + schemaType: "array", + error, + code(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { gen, data, schema, schemaValue, parentSchema, it } = cxt; + if (schema.length === 0) + throw new Error("enum must have non-empty array"); + if (schema.length !== new Set(schema).size) + throw new Error("enum items must be unique"); + let valid; + const isString = (0, codegen_1._) `typeof ${data} == "string"`; + if (schema.length >= it.opts.loopEnum) { + let cond; + [valid, cond] = (0, nullable_1.checkNullable)(cxt, isString); + gen.if(cond, loopEnum); + } + else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + valid = (0, codegen_1.and)(isString, (0, codegen_1.or)(...schema.map((value) => (0, codegen_1._) `${data} === ${value}`))); + if (parentSchema.nullable) + valid = (0, codegen_1.or)((0, codegen_1._) `${data} === null`, valid); + } + cxt.pass(valid); + function loopEnum() { + gen.forOf("v", schemaValue, (v) => gen.if((0, codegen_1._) `${valid} = ${data} === ${v}`, () => gen.break())); + } + }, +}; +exports.default = def; +//# sourceMappingURL=enum.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/enum.js.map b/node_modules/ajv/dist/vocabularies/jtd/enum.js.map new file mode 100644 index 000000000..06ee9e206 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/enum.js.map @@ -0,0 +1 @@ +{"version":3,"file":"enum.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/enum.ts"],"names":[],"mappings":";;AAEA,mDAAsD;AACtD,yCAAwC;AACxC,yCAAwC;AAIxC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,4CAA4C;IACrD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,mBAAmB,UAAU,GAAG;CAC5D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,MAAM;IACf,UAAU,EAAE,OAAO;IACnB,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC9D,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;QAC1E,IAAI,MAAM,CAAC,MAAM,KAAK,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI;YAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAA;QACxF,IAAI,KAAW,CAAA;QACf,MAAM,QAAQ,GAAG,IAAA,WAAC,EAAA,UAAU,IAAI,cAAc,CAAA;QAC9C,IAAI,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACtC,IAAI,IAAU,CACb;YAAA,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,IAAA,wBAAa,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;YAC7C,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;QACxB,CAAC;aAAM,CAAC;YACN,wBAAwB;YACxB,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;YACvE,KAAK,GAAG,IAAA,aAAG,EAAC,QAAQ,EAAE,IAAA,YAAE,EAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAa,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,CAAA;YACpF,IAAI,YAAY,CAAC,QAAQ;gBAAE,KAAK,GAAG,IAAA,YAAE,EAAC,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,EAAE,KAAK,CAAC,CAAA;QACnE,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAEf,SAAS,QAAQ;YACf,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,WAAmB,EAAE,CAAC,CAAC,EAAE,EAAE,CACxC,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,KAAK,MAAM,IAAI,QAAQ,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAC1D,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/error.d.ts b/node_modules/ajv/dist/vocabularies/jtd/error.d.ts new file mode 100644 index 000000000..d334ff54c --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/error.d.ts @@ -0,0 +1,9 @@ +import type { KeywordErrorDefinition, KeywordErrorCxt, ErrorObject } from "../../types"; +import { Code } from "../../compile/codegen"; +export type _JTDTypeError = ErrorObject; +export declare function typeError(t: string): KeywordErrorDefinition; +export declare function typeErrorMessage({ parentSchema }: KeywordErrorCxt, t: string): string; +export declare function typeErrorParams({ parentSchema }: KeywordErrorCxt, t: string): Code; diff --git a/node_modules/ajv/dist/vocabularies/jtd/error.js b/node_modules/ajv/dist/vocabularies/jtd/error.js new file mode 100644 index 000000000..1a3920a7e --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/error.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.typeErrorParams = exports.typeErrorMessage = exports.typeError = void 0; +const codegen_1 = require("../../compile/codegen"); +function typeError(t) { + return { + message: (cxt) => typeErrorMessage(cxt, t), + params: (cxt) => typeErrorParams(cxt, t), + }; +} +exports.typeError = typeError; +function typeErrorMessage({ parentSchema }, t) { + return (parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable) ? `must be ${t} or null` : `must be ${t}`; +} +exports.typeErrorMessage = typeErrorMessage; +function typeErrorParams({ parentSchema }, t) { + return (0, codegen_1._) `{type: ${t}, nullable: ${!!(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable)}}`; +} +exports.typeErrorParams = typeErrorParams; +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/error.js.map b/node_modules/ajv/dist/vocabularies/jtd/error.js.map new file mode 100644 index 000000000..db5596787 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/error.ts"],"names":[],"mappings":";;;AACA,mDAA6C;AAQ7C,SAAgB,SAAS,CAAC,CAAS;IACjC,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,CAAC,CAAC;QAC1C,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,CAAC;KACzC,CAAA;AACH,CAAC;AALD,8BAKC;AAED,SAAgB,gBAAgB,CAAC,EAAC,YAAY,EAAkB,EAAE,CAAS;IACzE,OAAO,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,EAAC,CAAC,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,CAAA;AACzE,CAAC;AAFD,4CAEC;AAED,SAAgB,eAAe,CAAC,EAAC,YAAY,EAAkB,EAAE,CAAS;IACxE,OAAO,IAAA,WAAC,EAAA,UAAU,CAAC,eAAe,CAAC,CAAC,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,CAAA,GAAG,CAAA;AAC/D,CAAC;AAFD,0CAEC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/index.d.ts b/node_modules/ajv/dist/vocabularies/jtd/index.d.ts new file mode 100644 index 000000000..c56246b78 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/index.d.ts @@ -0,0 +1,10 @@ +import type { Vocabulary } from "../../types"; +import { JTDTypeError } from "./type"; +import { JTDEnumError } from "./enum"; +import { JTDElementsError } from "./elements"; +import { JTDPropertiesError } from "./properties"; +import { JTDDiscriminatorError } from "./discriminator"; +import { JTDValuesError } from "./values"; +declare const jtdVocabulary: Vocabulary; +export default jtdVocabulary; +export type JTDErrorObject = JTDTypeError | JTDEnumError | JTDElementsError | JTDPropertiesError | JTDDiscriminatorError | JTDValuesError; diff --git a/node_modules/ajv/dist/vocabularies/jtd/index.js b/node_modules/ajv/dist/vocabularies/jtd/index.js new file mode 100644 index 000000000..18f40ab7a --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/index.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ref_1 = require("./ref"); +const type_1 = require("./type"); +const enum_1 = require("./enum"); +const elements_1 = require("./elements"); +const properties_1 = require("./properties"); +const optionalProperties_1 = require("./optionalProperties"); +const discriminator_1 = require("./discriminator"); +const values_1 = require("./values"); +const union_1 = require("./union"); +const metadata_1 = require("./metadata"); +const jtdVocabulary = [ + "definitions", + ref_1.default, + type_1.default, + enum_1.default, + elements_1.default, + properties_1.default, + optionalProperties_1.default, + discriminator_1.default, + values_1.default, + union_1.default, + metadata_1.default, + { keyword: "additionalProperties", schemaType: "boolean" }, + { keyword: "nullable", schemaType: "boolean" }, +]; +exports.default = jtdVocabulary; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/index.js.map b/node_modules/ajv/dist/vocabularies/jtd/index.js.map new file mode 100644 index 000000000..713a1875b --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/index.ts"],"names":[],"mappings":";;AACA,+BAA8B;AAC9B,iCAAgD;AAChD,iCAAgD;AAChD,yCAAqD;AACrD,6CAA2D;AAC3D,6DAAqD;AACrD,mDAAoE;AACpE,qCAA+C;AAC/C,mCAA2B;AAC3B,yCAAiC;AAEjC,MAAM,aAAa,GAAe;IAChC,aAAa;IACb,aAAU;IACV,cAAW;IACX,cAAW;IACX,kBAAQ;IACR,oBAAU;IACV,4BAAkB;IAClB,uBAAa;IACb,gBAAM;IACN,eAAK;IACL,kBAAQ;IACR,EAAC,OAAO,EAAE,sBAAsB,EAAE,UAAU,EAAE,SAAS,EAAC;IACxD,EAAC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAC;CAC7C,CAAA;AAED,kBAAe,aAAa,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/metadata.d.ts b/node_modules/ajv/dist/vocabularies/jtd/metadata.d.ts new file mode 100644 index 000000000..86e15a8ed --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/metadata.d.ts @@ -0,0 +1,5 @@ +import { KeywordCxt } from "../../ajv"; +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export declare function checkMetadata({ it, keyword }: KeywordCxt, metadata?: boolean): void; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/jtd/metadata.js b/node_modules/ajv/dist/vocabularies/jtd/metadata.js new file mode 100644 index 000000000..eeb3c91cd --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/metadata.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.checkMetadata = void 0; +const util_1 = require("../../compile/util"); +const def = { + keyword: "metadata", + schemaType: "object", + code(cxt) { + checkMetadata(cxt); + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + const valid = gen.name("valid"); + cxt.subschema({ keyword: "metadata", jtdMetadata: true }, valid); + cxt.ok(valid); + }, +}; +function checkMetadata({ it, keyword }, metadata) { + if (it.jtdMetadata !== metadata) { + throw new Error(`JTD: "${keyword}" cannot be used in this schema location`); + } +} +exports.checkMetadata = checkMetadata; +exports.default = def; +//# sourceMappingURL=metadata.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/metadata.js.map b/node_modules/ajv/dist/vocabularies/jtd/metadata.js.map new file mode 100644 index 000000000..2fea91ce5 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/metadata.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/metadata.ts"],"names":[],"mappings":";;;AAEA,6CAAoD;AAEpD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,aAAa,CAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC7B,IAAI,IAAA,wBAAiB,EAAC,EAAE,EAAE,MAAM,CAAC;YAAE,OAAM;QACzC,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;QAC9D,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;CACF,CAAA;AAED,SAAgB,aAAa,CAAC,EAAC,EAAE,EAAE,OAAO,EAAa,EAAE,QAAkB;IACzE,IAAI,EAAE,CAAC,WAAW,KAAK,QAAQ,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CAAC,SAAS,OAAO,0CAA0C,CAAC,CAAA;IAC7E,CAAC;AACH,CAAC;AAJD,sCAIC;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/nullable.d.ts b/node_modules/ajv/dist/vocabularies/jtd/nullable.d.ts new file mode 100644 index 000000000..254f76023 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/nullable.d.ts @@ -0,0 +1,4 @@ +import type { KeywordCxt } from "../../compile/validate"; +import { Code, Name } from "../../compile/codegen"; +export declare function checkNullable({ gen, data, parentSchema }: KeywordCxt, cond?: Code): [Name, Code]; +export declare function checkNullableObject(cxt: KeywordCxt, cond: Code): [Name, Code]; diff --git a/node_modules/ajv/dist/vocabularies/jtd/nullable.js b/node_modules/ajv/dist/vocabularies/jtd/nullable.js new file mode 100644 index 000000000..8c92d2cde --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/nullable.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.checkNullableObject = exports.checkNullable = void 0; +const codegen_1 = require("../../compile/codegen"); +function checkNullable({ gen, data, parentSchema }, cond = codegen_1.nil) { + const valid = gen.name("valid"); + if (parentSchema.nullable) { + gen.let(valid, (0, codegen_1._) `${data} === null`); + cond = (0, codegen_1.not)(valid); + } + else { + gen.let(valid, false); + } + return [valid, cond]; +} +exports.checkNullable = checkNullable; +function checkNullableObject(cxt, cond) { + const [valid, cond_] = checkNullable(cxt, cond); + return [valid, (0, codegen_1._) `${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`]; +} +exports.checkNullableObject = checkNullableObject; +//# sourceMappingURL=nullable.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/nullable.js.map b/node_modules/ajv/dist/vocabularies/jtd/nullable.js.map new file mode 100644 index 000000000..7d7a3f192 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/nullable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"nullable.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/nullable.ts"],"names":[],"mappings":";;;AACA,mDAA6D;AAE7D,SAAgB,aAAa,CAC3B,EAAC,GAAG,EAAE,IAAI,EAAE,YAAY,EAAa,EACrC,OAAa,aAAG;IAEhB,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/B,IAAI,YAAY,CAAC,QAAQ,EAAE,CAAC;QAC1B,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,CAAC,CAAA;QACnC,IAAI,GAAG,IAAA,aAAG,EAAC,KAAK,CAAC,CAAA;IACnB,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;IACvB,CAAC;IACD,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;AACtB,CAAC;AAZD,sCAYC;AAED,SAAgB,mBAAmB,CAAC,GAAe,EAAE,IAAU;IAC7D,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;IAC/C,OAAO,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,KAAK,cAAc,GAAG,CAAC,IAAI,kCAAkC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAA;AAC9F,CAAC;AAHD,kDAGC"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.d.ts b/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.js b/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.js new file mode 100644 index 000000000..fe272758f --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const properties_1 = require("./properties"); +const def = { + keyword: "optionalProperties", + schemaType: "object", + error: properties_1.error, + code(cxt) { + if (cxt.parentSchema.properties) + return; + (0, properties_1.validateProperties)(cxt); + }, +}; +exports.default = def; +//# sourceMappingURL=optionalProperties.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.js.map b/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.js.map new file mode 100644 index 000000000..21e5f0d47 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/optionalProperties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"optionalProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/optionalProperties.ts"],"names":[],"mappings":";;AAEA,6CAAsD;AAEtD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,oBAAoB;IAC7B,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAL,kBAAK;IACL,IAAI,CAAC,GAAe;QAClB,IAAI,GAAG,CAAC,YAAY,CAAC,UAAU;YAAE,OAAM;QACvC,IAAA,+BAAkB,EAAC,GAAG,CAAC,CAAA;IACzB,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/properties.d.ts b/node_modules/ajv/dist/vocabularies/jtd/properties.d.ts new file mode 100644 index 000000000..54e3b347c --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/properties.d.ts @@ -0,0 +1,22 @@ +import type { CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition, SchemaObject } from "../../types"; +import type { KeywordCxt } from "../../compile/validate"; +import { _JTDTypeError } from "./error"; +declare enum PropError { + Additional = "additional", + Missing = "missing" +} +type PropKeyword = "properties" | "optionalProperties"; +type PropSchema = { + [P in string]?: SchemaObject; +}; +export type JTDPropertiesError = _JTDTypeError | ErrorObject | ErrorObject; +export declare const error: KeywordErrorDefinition; +declare const def: CodeKeywordDefinition; +export declare function validateProperties(cxt: KeywordCxt): void; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/jtd/properties.js b/node_modules/ajv/dist/vocabularies/jtd/properties.js new file mode 100644 index 000000000..f4e9de458 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/properties.js @@ -0,0 +1,149 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateProperties = exports.error = void 0; +const code_1 = require("../code"); +const util_1 = require("../../compile/util"); +const codegen_1 = require("../../compile/codegen"); +const metadata_1 = require("./metadata"); +const nullable_1 = require("./nullable"); +const error_1 = require("./error"); +var PropError; +(function (PropError) { + PropError["Additional"] = "additional"; + PropError["Missing"] = "missing"; +})(PropError || (PropError = {})); +exports.error = { + message: (cxt) => { + const { params } = cxt; + return params.propError + ? params.propError === PropError.Additional + ? "must NOT have additional properties" + : `must have property '${params.missingProperty}'` + : (0, error_1.typeErrorMessage)(cxt, "object"); + }, + params: (cxt) => { + const { params } = cxt; + return params.propError + ? params.propError === PropError.Additional + ? (0, codegen_1._) `{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}` + : (0, codegen_1._) `{error: ${params.propError}, missingProperty: ${params.missingProperty}}` + : (0, error_1.typeErrorParams)(cxt, "object"); + }, +}; +const def = { + keyword: "properties", + schemaType: "object", + error: exports.error, + code: validateProperties, +}; +// const error: KeywordErrorDefinition = { +// message: "should NOT have additional properties", +// params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`, +// } +function validateProperties(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { gen, data, parentSchema, it } = cxt; + const { additionalProperties, nullable } = parentSchema; + if (it.jtdDiscriminator && nullable) + throw new Error("JTD: nullable inside discriminator mapping"); + if (commonProperties()) { + throw new Error("JTD: properties and optionalProperties have common members"); + } + const [allProps, properties] = schemaProperties("properties"); + const [allOptProps, optProperties] = schemaProperties("optionalProperties"); + if (properties.length === 0 && optProperties.length === 0 && additionalProperties) { + return; + } + const [valid, cond] = it.jtdDiscriminator === undefined + ? (0, nullable_1.checkNullableObject)(cxt, data) + : [gen.let("valid", false), true]; + gen.if(cond, () => gen.assign(valid, true).block(() => { + validateProps(properties, "properties", true); + validateProps(optProperties, "optionalProperties"); + if (!additionalProperties) + validateAdditional(); + })); + cxt.pass(valid); + function commonProperties() { + const props = parentSchema.properties; + const optProps = parentSchema.optionalProperties; + if (!(props && optProps)) + return false; + for (const p in props) { + if (Object.prototype.hasOwnProperty.call(optProps, p)) + return true; + } + return false; + } + function schemaProperties(keyword) { + const schema = parentSchema[keyword]; + const allPs = schema ? (0, code_1.allSchemaProperties)(schema) : []; + if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) { + throw new Error(`JTD: discriminator tag used in ${keyword}`); + } + const ps = allPs.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + return [allPs, ps]; + } + function validateProps(props, keyword, required) { + const _valid = gen.var("valid"); + for (const prop of props) { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => applyPropertySchema(prop, keyword, _valid), () => missingProperty(prop)); + cxt.ok(_valid); + } + function missingProperty(prop) { + if (required) { + gen.assign(_valid, false); + cxt.error(false, { propError: PropError.Missing, missingProperty: prop }, { schemaPath: prop }); + } + else { + gen.assign(_valid, true); + } + } + } + function applyPropertySchema(prop, keyword, _valid) { + cxt.subschema({ + keyword, + schemaProp: prop, + dataProp: prop, + }, _valid); + } + function validateAdditional() { + gen.forIn("key", data, (key) => { + const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator); + const addOptProp = isAdditional(key, allOptProps, "optionalProperties"); + const extra = addProp === true ? addOptProp : addOptProp === true ? addProp : (0, codegen_1.and)(addProp, addOptProp); + gen.if(extra, () => { + if (it.opts.removeAdditional) { + gen.code((0, codegen_1._) `delete ${data}[${key}]`); + } + else { + cxt.error(false, { propError: PropError.Additional, additionalProperty: key }, { instancePath: key, parentSchema: true }); + if (!it.opts.allErrors) + gen.break(); + } + }); + }); + } + function isAdditional(key, props, keyword, jtdDiscriminator) { + let additional; + if (props.length > 8) { + // TODO maybe an option instead of hard-coded 8? + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema[keyword], keyword); + additional = (0, codegen_1.not)((0, code_1.isOwnProperty)(gen, propsSchema, key)); + if (jtdDiscriminator !== undefined) { + additional = (0, codegen_1.and)(additional, (0, codegen_1._) `${key} !== ${jtdDiscriminator}`); + } + } + else if (props.length || jtdDiscriminator !== undefined) { + const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props); + additional = (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`)); + } + else { + additional = true; + } + return additional; + } +} +exports.validateProperties = validateProperties; +exports.default = def; +//# sourceMappingURL=properties.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/properties.js.map b/node_modules/ajv/dist/vocabularies/jtd/properties.js.map new file mode 100644 index 000000000..184111e06 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/properties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"properties.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/properties.ts"],"names":[],"mappings":";;;AAOA,kCAA0E;AAC1E,6CAAoE;AACpE,mDAA6D;AAC7D,yCAAwC;AACxC,yCAA8C;AAC9C,mCAAwE;AAExE,IAAK,SAGJ;AAHD,WAAK,SAAS;IACZ,sCAAyB,CAAA;IACzB,gCAAmB,CAAA;AACrB,CAAC,EAHI,SAAS,KAAT,SAAS,QAGb;AAWY,QAAA,KAAK,GAA2B;IAC3C,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;QACf,MAAM,EAAC,MAAM,EAAC,GAAG,GAAG,CAAA;QACpB,OAAO,MAAM,CAAC,SAAS;YACrB,CAAC,CAAC,MAAM,CAAC,SAAS,KAAK,SAAS,CAAC,UAAU;gBACzC,CAAC,CAAC,qCAAqC;gBACvC,CAAC,CAAC,uBAAuB,MAAM,CAAC,eAAe,GAAG;YACpD,CAAC,CAAC,IAAA,wBAAgB,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;IACrC,CAAC;IACD,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE;QACd,MAAM,EAAC,MAAM,EAAC,GAAG,GAAG,CAAA;QACpB,OAAO,MAAM,CAAC,SAAS;YACrB,CAAC,CAAC,MAAM,CAAC,SAAS,KAAK,SAAS,CAAC,UAAU;gBACzC,CAAC,CAAC,IAAA,WAAC,EAAA,WAAW,MAAM,CAAC,SAAS,yBAAyB,MAAM,CAAC,kBAAkB,GAAG;gBACnF,CAAC,CAAC,IAAA,WAAC,EAAA,WAAW,MAAM,CAAC,SAAS,sBAAsB,MAAM,CAAC,eAAe,GAAG;YAC/E,CAAC,CAAC,IAAA,uBAAe,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;IACpC,CAAC;CACF,CAAA;AAED,MAAM,GAAG,GAA0B;IACj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AAA,aAAG,EAAC,IAAA,oBAAa,EAAC,GAAG,EAAE,WAAmB,EAAE,GAAG,CAAC,CAAC,CAAA;YAC9D,IAAI,gBAAgB,KAAK,SAAS,EAAE,CAAC;gBACnC,UAAU,GAAG,IAAA,aAAG,EAAC,UAAU,EAAE,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,gBAAgB,EAAE,CAAC,CAAA;YACjE,CAAC;QACH,CAAC;aAAM,IAAI,KAAK,CAAC,MAAM,IAAI,gBAAgB,KAAK,SAAS,EAAE,CAAC;YAC1D,MAAM,EAAE,GAAG,gBAAgB,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACpF,UAAU,GAAG,IAAA,aAAG,EAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAA;QACxD,CAAC;aAAM,CAAC;YACN,UAAU,GAAG,IAAI,CAAA;QACnB,CAAC;QACD,OAAO,UAAU,CAAA;IACnB,CAAC;AACH,CAAC;AA1HD,gDA0HC;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/ref.d.ts b/node_modules/ajv/dist/vocabularies/jtd/ref.d.ts new file mode 100644 index 000000000..ccdf84c0b --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/ref.d.ts @@ -0,0 +1,4 @@ +import type { CodeKeywordDefinition, AnySchemaObject } from "../../types"; +declare const def: CodeKeywordDefinition; +export declare function hasRef(schema: AnySchemaObject): boolean; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/jtd/ref.js b/node_modules/ajv/dist/vocabularies/jtd/ref.js new file mode 100644 index 000000000..b7c6b02d7 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/ref.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasRef = void 0; +const compile_1 = require("../../compile"); +const codegen_1 = require("../../compile/codegen"); +const ref_error_1 = require("../../compile/ref_error"); +const names_1 = require("../../compile/names"); +const ref_1 = require("../core/ref"); +const metadata_1 = require("./metadata"); +const def = { + keyword: "ref", + schemaType: "string", + code(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { gen, data, schema: ref, parentSchema, it } = cxt; + const { schemaEnv: { root }, } = it; + const valid = gen.name("valid"); + if (parentSchema.nullable) { + gen.var(valid, (0, codegen_1._) `${data} === null`); + gen.if((0, codegen_1.not)(valid), validateJtdRef); + } + else { + gen.var(valid, false); + validateJtdRef(); + } + cxt.ok(valid); + function validateJtdRef() { + var _a; + const refSchema = (_a = root.schema.definitions) === null || _a === void 0 ? void 0 : _a[ref]; + if (!refSchema) { + throw new ref_error_1.default(it.opts.uriResolver, "", ref, `No definition ${ref}`); + } + if (hasRef(refSchema) || !it.opts.inlineRefs) + callValidate(refSchema); + else + inlineRefSchema(refSchema); + } + function callValidate(schema) { + const sch = compile_1.compileSchema.call(it.self, new compile_1.SchemaEnv({ schema, root, schemaPath: `/definitions/${ref}` })); + const v = (0, ref_1.getValidate)(cxt, sch); + const errsCount = gen.const("_errs", names_1.default.errors); + (0, ref_1.callRef)(cxt, v, sch, sch.$async); + gen.assign(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); + } + function inlineRefSchema(schema) { + const schName = gen.scopeValue("schema", it.opts.code.source === true ? { ref: schema, code: (0, codegen_1.stringify)(schema) } : { ref: schema }); + cxt.subschema({ + schema, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: `/definitions/${ref}`, + }, valid); + } + }, +}; +function hasRef(schema) { + for (const key in schema) { + let sch; + if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch))) + return true; + } + return false; +} +exports.hasRef = hasRef; +exports.default = def; +//# sourceMappingURL=ref.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/ref.js.map b/node_modules/ajv/dist/vocabularies/jtd/ref.js.map new file mode 100644 index 000000000..c15dbf94b --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/ref.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ref.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/ref.ts"],"names":[],"mappings":";;;AAEA,2CAAsD;AACtD,mDAA4D;AAC5D,uDAAqD;AACrD,+CAAmC;AACnC,qCAAgD;AAChD,yCAAwC;AAExC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,KAAK;IACd,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtD,MAAM,EACJ,SAAS,EAAE,EAAC,IAAI,EAAC,GAClB,GAAG,EAAE,CAAA;QACN,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/B,IAAI,YAAY,CAAC,QAAQ,EAAE,CAAC;YAC1B,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,CAAC,CAAA;YACnC,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,cAAc,CAAC,CAAA;QACpC,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;YACrB,cAAc,EAAE,CAAA;QAClB,CAAC;QACD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;QAEb,SAAS,cAAc;;YACrB,MAAM,SAAS,GAAG,MAAC,IAAI,CAAC,MAA0B,CAAC,WAAW,0CAAG,GAAG,CAAC,CAAA;YAC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YACD,GAAG,CAAC,SAAS,CACX;gBACE,MAAM;gBACN,SAAS,EAAE,EAAE;gBACb,UAAU,EAAE,aAAG;gBACf,YAAY,EAAE,OAAO;gBACrB,aAAa,EAAE,gBAAgB,GAAG,EAAE;aACrC,EACD,KAAK,CACN,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,SAAgB,MAAM,CAAC,MAAuB;IAC5C,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;QACzB,IAAI,GAAoB,CAAA;QACxB,IAAI,GAAG,KAAK,KAAK,IAAI,CAAC,OAAO,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,QAAQ,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC;YAAE,OAAO,IAAI,CAAA;IAC3F,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAND,wBAMC;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/type.d.ts b/node_modules/ajv/dist/vocabularies/jtd/type.d.ts new file mode 100644 index 000000000..a115c7dad --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/type.d.ts @@ -0,0 +1,10 @@ +import type { CodeKeywordDefinition } from "../../types"; +import { _JTDTypeError } from "./error"; +export type JTDTypeError = _JTDTypeError<"type", JTDType, JTDType>; +export type IntType = "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32"; +export declare const intRange: { + [T in IntType]: [number, number, number]; +}; +export type JTDType = "boolean" | "string" | "timestamp" | "float32" | "float64" | IntType; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/jtd/type.js b/node_modules/ajv/dist/vocabularies/jtd/type.js new file mode 100644 index 000000000..17a0b5107 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/type.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.intRange = void 0; +const codegen_1 = require("../../compile/codegen"); +const timestamp_1 = require("../../runtime/timestamp"); +const util_1 = require("../../compile/util"); +const metadata_1 = require("./metadata"); +const error_1 = require("./error"); +exports.intRange = { + int8: [-128, 127, 3], + uint8: [0, 255, 3], + int16: [-32768, 32767, 5], + uint16: [0, 65535, 5], + int32: [-2147483648, 2147483647, 10], + uint32: [0, 4294967295, 10], +}; +const error = { + message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema), + params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema), +}; +function timestampCode(cxt) { + const { gen, data, it } = cxt; + const { timestamp, allowDate } = it.opts; + if (timestamp === "date") + return (0, codegen_1._) `${data} instanceof Date `; + const vts = (0, util_1.useFunc)(gen, timestamp_1.default); + const allowDateArg = allowDate ? (0, codegen_1._) `, true` : codegen_1.nil; + const validString = (0, codegen_1._) `typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`; + return timestamp === "string" ? validString : (0, codegen_1.or)((0, codegen_1._) `${data} instanceof Date`, validString); +} +const def = { + keyword: "type", + schemaType: "string", + error, + code(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { data, schema, parentSchema, it } = cxt; + let cond; + switch (schema) { + case "boolean": + case "string": + cond = (0, codegen_1._) `typeof ${data} == ${schema}`; + break; + case "timestamp": { + cond = timestampCode(cxt); + break; + } + case "float32": + case "float64": + cond = (0, codegen_1._) `typeof ${data} == "number"`; + break; + default: { + const sch = schema; + cond = (0, codegen_1._) `typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`; + if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) { + if (sch === "uint32") + cond = (0, codegen_1._) `${cond} && ${data} >= 0`; + } + else { + const [min, max] = exports.intRange[sch]; + cond = (0, codegen_1._) `${cond} && ${data} >= ${min} && ${data} <= ${max}`; + } + } + } + cxt.pass(parentSchema.nullable ? (0, codegen_1.or)((0, codegen_1._) `${data} === null`, cond) : cond); + }, +}; +exports.default = def; +//# sourceMappingURL=type.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/type.js.map b/node_modules/ajv/dist/vocabularies/jtd/type.js.map new file mode 100644 index 000000000..cf538ed03 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/type.js.map @@ -0,0 +1 @@ +{"version":3,"file":"type.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/type.ts"],"names":[],"mappings":";;;AAEA,mDAAsD;AACtD,uDAAoD;AACpD,6CAA0C;AAC1C,yCAAwC;AACxC,mCAAwE;AAM3D,QAAA,QAAQ,GAA+C;IAClE,IAAI,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC;IACpB,KAAK,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;IAClB,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACzB,MAAM,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;IACrB,KAAK,EAAE,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,EAAE,CAAC;IACpC,MAAM,EAAE,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,CAAC;CAC5B,CAAA;AAID,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,wBAAgB,EAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;IACnD,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,uBAAe,EAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC;CAClD,CAAA;AAED,SAAS,aAAa,CAAC,GAAe;IACpC,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;IAC3B,MAAM,EAAC,SAAS,EAAE,SAAS,EAAC,GAAG,EAAE,CAAC,IAAI,CAAA;IACtC,IAAI,SAAS,KAAK,MAAM;QAAE,OAAO,IAAA,WAAC,EAAA,GAAG,IAAI,mBAAmB,CAA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I,OAAO,CAAA;gBAC3E,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,UAAU,IAAI,CAAC,GAAG,KAAK,OAAO,IAAI,GAAG,KAAK,QAAQ,CAAC,EAAE,CAAC;oBACjE,IAAI,GAAG,KAAK,QAAQ;wBAAE,IAAI,GAAG,IAAA,WAAC,EAAA,GAAG,IAAI,OAAO,IAAI,OAAO,CAAA;gBACzD,CAAC;qBAAM,CAAC;oBACN,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,gBAAQ,CAAC,GAAG,CAAC,CAAA;oBAChC,IAAI,GAAG,IAAA,WAAC,EAAA,GAAG,IAAI,OAAO,IAAI,OAAO,GAAG,OAAO,IAAI,OAAO,GAAG,EAAE,CAAA;gBAC7D,CAAC;YACH,CAAC;QACH,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAA,YAAE,EAAC,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;IACxE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/union.d.ts b/node_modules/ajv/dist/vocabularies/jtd/union.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/union.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/jtd/union.js b/node_modules/ajv/dist/vocabularies/jtd/union.js new file mode 100644 index 000000000..01a943994 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/union.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const code_1 = require("../code"); +const def = { + keyword: "union", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in union" }, +}; +exports.default = def; +//# sourceMappingURL=union.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/union.js.map b/node_modules/ajv/dist/vocabularies/jtd/union.js.map new file mode 100644 index 000000000..4d6eb4119 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/union.js.map @@ -0,0 +1 @@ +{"version":3,"file":"union.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/union.ts"],"names":[],"mappings":";;AACA,kCAAqC;AAErC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,WAAW,EAAE,IAAI;IACjB,IAAI,EAAE,oBAAa;IACnB,KAAK,EAAE,EAAC,OAAO,EAAE,8BAA8B,EAAC;CACjD,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/values.d.ts b/node_modules/ajv/dist/vocabularies/jtd/values.d.ts new file mode 100644 index 000000000..1eaa884a5 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/values.d.ts @@ -0,0 +1,5 @@ +import type { CodeKeywordDefinition, SchemaObject } from "../../types"; +import { _JTDTypeError } from "./error"; +export type JTDValuesError = _JTDTypeError<"values", "object", SchemaObject>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/jtd/values.js b/node_modules/ajv/dist/vocabularies/jtd/values.js new file mode 100644 index 000000000..3c2c95f55 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/values.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("../../compile/util"); +const codegen_1 = require("../../compile/codegen"); +const metadata_1 = require("./metadata"); +const nullable_1 = require("./nullable"); +const error_1 = require("./error"); +const def = { + keyword: "values", + schemaType: "object", + error: (0, error_1.typeError)("object"), + code(cxt) { + (0, metadata_1.checkMetadata)(cxt); + const { gen, data, schema, it } = cxt; + const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data); + if ((0, util_1.alwaysValidSchema)(it, schema)) { + gen.if((0, codegen_1.not)((0, codegen_1.or)(cond, valid)), () => cxt.error()); + } + else { + gen.if(cond); + gen.assign(valid, validateMap()); + gen.elseIf((0, codegen_1.not)(valid)); + cxt.error(); + gen.endIf(); + } + cxt.ok(valid); + function validateMap() { + const _valid = gen.name("valid"); + if (it.allErrors) { + const validMap = gen.let("valid", true); + validateValues(() => gen.assign(validMap, false)); + return validMap; + } + gen.var(_valid, true); + validateValues(() => gen.break()); + return _valid; + function validateValues(notValid) { + gen.forIn("key", data, (key) => { + cxt.subschema({ + keyword: "values", + dataProp: key, + dataPropType: util_1.Type.Str, + }, _valid); + gen.if((0, codegen_1.not)(_valid), notValid); + }); + } + } + }, +}; +exports.default = def; +//# sourceMappingURL=values.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/jtd/values.js.map b/node_modules/ajv/dist/vocabularies/jtd/values.js.map new file mode 100644 index 000000000..8a1a5c233 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/jtd/values.js.map @@ -0,0 +1 @@ +{"version":3,"file":"values.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/values.ts"],"names":[],"mappings":";;AAEA,6CAA0D;AAC1D,mDAAmD;AACnD,yCAAwC;AACxC,yCAA8C;AAC9C,mCAAgD;AAIhD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,QAAQ;IACjB,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAA,iBAAS,EAAC,QAAQ,CAAC;IAC1B,IAAI,CAAC,GAAe;QAClB,IAAA,wBAAa,EAAC,GAAG,CAAC,CAAA;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACnC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,IAAA,8BAAmB,EAAC,GAAG,EAAE,IAAI,CAAC,CAA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;wBACjB,QAAQ,EAAE,GAAG;wBACb,YAAY,EAAE,WAAI,CAAC,GAAG;qBACvB,EACD,MAAM,CACP,CAAA;oBACD,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,MAAM,CAAC,EAAE,QAAQ,CAAC,CAAA;gBAC/B,CAAC,CAAC,CAAA;YACJ,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/metadata.d.ts b/node_modules/ajv/dist/vocabularies/metadata.d.ts new file mode 100644 index 000000000..df9cc07ca --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/metadata.d.ts @@ -0,0 +1,3 @@ +import type { Vocabulary } from "../types"; +export declare const metadataVocabulary: Vocabulary; +export declare const contentVocabulary: Vocabulary; diff --git a/node_modules/ajv/dist/vocabularies/metadata.js b/node_modules/ajv/dist/vocabularies/metadata.js new file mode 100644 index 000000000..f07bf28b5 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/metadata.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.contentVocabulary = exports.metadataVocabulary = void 0; +exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples", +]; +exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema", +]; +//# sourceMappingURL=metadata.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/metadata.js.map b/node_modules/ajv/dist/vocabularies/metadata.js.map new file mode 100644 index 000000000..0d61f0831 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/metadata.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../lib/vocabularies/metadata.ts"],"names":[],"mappings":";;;AAEa,QAAA,kBAAkB,GAAe;IAC5C,OAAO;IACP,aAAa;IACb,SAAS;IACT,YAAY;IACZ,UAAU;IACV,WAAW;IACX,UAAU;CACX,CAAA;AAEY,QAAA,iBAAiB,GAAe;IAC3C,kBAAkB;IAClB,iBAAiB;IACjB,eAAe;CAChB,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/next.d.ts b/node_modules/ajv/dist/vocabularies/next.d.ts new file mode 100644 index 000000000..7fd5c644b --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/next.d.ts @@ -0,0 +1,3 @@ +import type { Vocabulary } from "../types"; +declare const next: Vocabulary; +export default next; diff --git a/node_modules/ajv/dist/vocabularies/next.js b/node_modules/ajv/dist/vocabularies/next.js new file mode 100644 index 000000000..c861b3243 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/next.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const dependentRequired_1 = require("./validation/dependentRequired"); +const dependentSchemas_1 = require("./applicator/dependentSchemas"); +const limitContains_1 = require("./validation/limitContains"); +const next = [dependentRequired_1.default, dependentSchemas_1.default, limitContains_1.default]; +exports.default = next; +//# sourceMappingURL=next.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/next.js.map b/node_modules/ajv/dist/vocabularies/next.js.map new file mode 100644 index 000000000..474a6d4e7 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/next.js.map @@ -0,0 +1 @@ +{"version":3,"file":"next.js","sourceRoot":"","sources":["../../lib/vocabularies/next.ts"],"names":[],"mappings":";;AACA,sEAA8D;AAC9D,oEAA4D;AAC5D,8DAAsD;AAEtD,MAAM,IAAI,GAAe,CAAC,2BAAiB,EAAE,0BAAgB,EAAE,uBAAa,CAAC,CAAA;AAE7E,kBAAe,IAAI,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/unevaluated/index.d.ts b/node_modules/ajv/dist/vocabularies/unevaluated/index.d.ts new file mode 100644 index 000000000..ec67e63ea --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/unevaluated/index.d.ts @@ -0,0 +1,3 @@ +import type { Vocabulary } from "../../types"; +declare const unevaluated: Vocabulary; +export default unevaluated; diff --git a/node_modules/ajv/dist/vocabularies/unevaluated/index.js b/node_modules/ajv/dist/vocabularies/unevaluated/index.js new file mode 100644 index 000000000..30e316748 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/unevaluated/index.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const unevaluatedProperties_1 = require("./unevaluatedProperties"); +const unevaluatedItems_1 = require("./unevaluatedItems"); +const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; +exports.default = unevaluated; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/unevaluated/index.js.map b/node_modules/ajv/dist/vocabularies/unevaluated/index.js.map new file mode 100644 index 000000000..a4872ea43 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/unevaluated/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/unevaluated/index.ts"],"names":[],"mappings":";;AACA,mEAA2D;AAC3D,yDAAiD;AAEjD,MAAM,WAAW,GAAe,CAAC,+BAAqB,EAAE,0BAAgB,CAAC,CAAA;AAEzE,kBAAe,WAAW,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.d.ts b/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.d.ts new file mode 100644 index 000000000..06f023926 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.d.ts @@ -0,0 +1,6 @@ +import type { CodeKeywordDefinition, ErrorObject, AnySchema } from "../../types"; +export type UnevaluatedItemsError = ErrorObject<"unevaluatedItems", { + limit: number; +}, AnySchema>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js b/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js new file mode 100644 index 000000000..0a0cd3aa4 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const error = { + message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`, +}; +const def = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error, + code(cxt) { + const { gen, schema, data, it } = cxt; + const items = it.items || 0; + if (items === true) + return; + const len = gen.const("len", (0, codegen_1._) `${data}.length`); + if (schema === false) { + cxt.setParams({ len: items }); + cxt.fail((0, codegen_1._) `${len} > ${items}`); + } + else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); + cxt.ok(valid); + } + it.items = true; + function validateItems(valid, from) { + gen.forRange("i", from, len, (i) => { + cxt.subschema({ keyword: "unevaluatedItems", dataProp: i, dataPropType: util_1.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + }, +}; +exports.default = def; +//# sourceMappingURL=unevaluatedItems.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js.map b/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js.map new file mode 100644 index 000000000..b91f86e27 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js.map @@ -0,0 +1 @@ +{"version":3,"file":"unevaluatedItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/unevaluated/unevaluatedItems.ts"],"names":[],"mappings":";;AAOA,mDAAuD;AACvD,6CAA0D;AAI1D,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,GAA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CAAA;YACrD,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;QACf,CAAC;QACD,EAAE,CAAC,KAAK,GAAG,IAAI,CAAA;QAEf,SAAS,aAAa,CAAC,KAAW,EAAE,IAAmB;YACrD,GAAG,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE;gBACjC,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,CAAC,EAAE,YAAY,EAAE,WAAI,CAAC,GAAG,EAAC,EAAE,KAAK,CAAC,CAAA;gBACxF,IAAI,CAAC,EAAE,CAAC,SAAS;oBAAE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;YAC1D,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.d.ts b/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.d.ts new file mode 100644 index 000000000..ba63f62e8 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.d.ts @@ -0,0 +1,6 @@ +import type { CodeKeywordDefinition, ErrorObject, AnySchema } from "../../types"; +export type UnevaluatedPropertiesError = ErrorObject<"unevaluatedProperties", { + unevaluatedProperty: string; +}, AnySchema>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js b/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js new file mode 100644 index 000000000..ad298499f --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js @@ -0,0 +1,65 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const names_1 = require("../../compile/names"); +const error = { + message: "must NOT have unevaluated properties", + params: ({ params }) => (0, codegen_1._) `{unevaluatedProperty: ${params.unevaluatedProperty}}`, +}; +const def = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error, + code(cxt) { + const { gen, schema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, props } = it; + if (props instanceof codegen_1.Name) { + gen.if((0, codegen_1._) `${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); + } + else if (props !== true) { + gen.forIn("key", data, (key) => props === undefined + ? unevaluatedPropCode(key) + : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); + } + it.props = true; + cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); + function unevaluatedPropCode(key) { + if (schema === false) { + cxt.setParams({ unevaluatedProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; + } + if (!(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: util_1.Type.Str, + }, valid); + if (!allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + function unevaluatedDynamic(evaluatedProps, key) { + return (0, codegen_1._) `!${evaluatedProps} || !${evaluatedProps}[${key}]`; + } + function unevaluatedStatic(evaluatedProps, key) { + const ps = []; + for (const p in evaluatedProps) { + if (evaluatedProps[p] === true) + ps.push((0, codegen_1._) `${key} !== ${p}`); + } + return (0, codegen_1.and)(...ps); + } + }, +}; +exports.default = def; +//# sourceMappingURL=unevaluatedProperties.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js.map b/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js.map new file mode 100644 index 000000000..f83022ebc --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"unevaluatedProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/unevaluated/unevaluatedProperties.ts"],"names":[],"mappings":";;AAMA,mDAA6D;AAC7D,6CAA0D;AAC1D,+CAAmC;AAQnC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,sCAAsC;IAC/C,MAAM,EAAE,CAAC,EAAC,MAAM,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,yBAAyB,MAAM,CAAC,mBAAmB,GAAG;CAC9E,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,uBAAuB;IAChC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC;IACjC,WAAW,EAAE,IAAI;IACjB,KAAK;IACL,IAAI,CAAC,GAAG;QACN,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC9C,wBAAwB;QACxB,IAAI,CAAC,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QAC3D,MAAM,EAAC,SAAS,EAAE,KAAK,EAAC,GAAG,EAAE,CAAA;QAC7B,IAAI,KAAK,YAAY,cAAI,EAAE,CAAC;YAC1B,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,KAAK,WAAW,EAAE,GAAG,EAAE,CAChC,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,GAAS,EAAE,EAAE,CACnC,GAAG,CAAC,EAAE,CAAC,kBAAkB,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC,CACvE,CACF,CAAA;QACH,CAAC;aAAM,IAAI,KAAK,KAAK,IAAI,EAA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AAE,GAAS;YACzD,OAAO,IAAA,WAAC,EAAA,IAAI,cAAc,QAAQ,cAAc,IAAI,GAAG,GAAG,CAAA;QAC5D,CAAC;QAED,SAAS,iBAAiB,CAAC,cAAsC,EAAE,GAAS;YAC1E,MAAM,EAAE,GAAW,EAAE,CAAA;YACrB,KAAK,MAAM,CAAC,IAAI,cAAc,EAAE,CAAC;gBAC/B,IAAI,cAAc,CAAC,CAAC,CAAC,KAAK,IAAI;oBAAE,EAAE,CAAC,IAAI,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAA;YAC7D,CAAC;YACD,OAAO,IAAA,aAAG,EAAC,GAAG,EAAE,CAAC,CAAA;QACnB,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/const.d.ts b/node_modules/ajv/dist/vocabularies/validation/const.d.ts new file mode 100644 index 000000000..af91a9007 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/const.d.ts @@ -0,0 +1,6 @@ +import type { CodeKeywordDefinition, ErrorObject } from "../../types"; +export type ConstError = ErrorObject<"const", { + allowedValue: any; +}>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/validation/const.js b/node_modules/ajv/dist/vocabularies/validation/const.js new file mode 100644 index 000000000..9564496a6 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/const.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const equal_1 = require("../../runtime/equal"); +const error = { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`, +}; +const def = { + keyword: "const", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || (schema && typeof schema == "object")) { + cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + } + else { + cxt.fail((0, codegen_1._) `${schema} !== ${data}`); + } + }, +}; +exports.default = def; +//# sourceMappingURL=const.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/const.js.map b/node_modules/ajv/dist/vocabularies/validation/const.js.map new file mode 100644 index 000000000..63cfe60d6 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/const.js.map @@ -0,0 +1 @@ +{"version":3,"file":"const.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/const.ts"],"names":[],"mappings":";;AAEA,mDAAuC;AACvC,6CAA0C;AAC1C,+CAAuC;AAIvC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,2BAA2B;IACpC,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,kBAAkB,UAAU,GAAG;CAC3D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAC,GAAG,GAAG,CAAA;QAClD,IAAI,KAAK,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,IAAI,QAAQ,CAAC,EAAE,CAAC;YACnD,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,IAAI,IAAA,cAAO,EAAC,GAAG,EAAE,eAAK,CAAC,IAAI,IAAI,KAAK,UAAU,GAAG,CAAC,CAAA;QACnE,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,IAAI,CAAC,IAAA,WAAC,EAAA,GAAG,MAAM,QAAQ,IAAI,EAAE,CAAC,CAAA;QACpC,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/dependentRequired.d.ts b/node_modules/ajv/dist/vocabularies/validation/dependentRequired.d.ts new file mode 100644 index 000000000..00f0d370f --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/dependentRequired.d.ts @@ -0,0 +1,5 @@ +import type { CodeKeywordDefinition, ErrorObject } from "../../types"; +import { DependenciesErrorParams, PropertyDependencies } from "../applicator/dependencies"; +export type DependentRequiredError = ErrorObject<"dependentRequired", DependenciesErrorParams, PropertyDependencies>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js b/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js new file mode 100644 index 000000000..09e59639f --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const dependencies_1 = require("../applicator/dependencies"); +const def = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error: dependencies_1.error, + code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt), +}; +exports.default = def; +//# sourceMappingURL=dependentRequired.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js.map b/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js.map new file mode 100644 index 000000000..c7e88f885 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dependentRequired.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/dependentRequired.ts"],"names":[],"mappings":";;AACA,6DAKmC;AAQnC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,mBAAmB;IAC5B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAL,oBAAK;IACL,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,mCAAoB,EAAC,GAAG,CAAC;CACzC,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/enum.d.ts b/node_modules/ajv/dist/vocabularies/validation/enum.d.ts new file mode 100644 index 000000000..6231082fe --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/enum.d.ts @@ -0,0 +1,8 @@ +import type { CodeKeywordDefinition, ErrorObject } from "../../types"; +export type EnumError = ErrorObject<"enum", { + allowedValues: any[]; +}, any[] | { + $data: string; +}>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/validation/enum.js b/node_modules/ajv/dist/vocabularies/validation/enum.js new file mode 100644 index 000000000..eab6487e9 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/enum.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const equal_1 = require("../../runtime/equal"); +const error = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`, +}; +const def = { + keyword: "enum", + schemaType: "array", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) + throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default))); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } + else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null + ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])` + : (0, codegen_1._) `${data} === ${sch}`; + } + }, +}; +exports.default = def; +//# sourceMappingURL=enum.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/enum.js.map b/node_modules/ajv/dist/vocabularies/validation/enum.js.map new file mode 100644 index 000000000..33afdcf0d --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/enum.js.map @@ -0,0 +1 @@ +{"version":3,"file":"enum.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/enum.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AACvD,6CAA0C;AAC1C,+CAAuC;AAIvC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,4CAA4C;IACrD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,mBAAmB,UAAU,GAAG;CAC5D,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,MAAM;IACf,UAAU,EAAE,OAAO;IACnB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtD,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;QACpF,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAA;QACjD,IAAI,GAAqB,CAAA;QACzB,MAAM,MAAM,GAAG,GAAS,EAAE,CAAC,CAAC,GAAG,aAAH,GAAG,cAAH,GAAG,IAAH,GAAG,GAAK,IAAA,cAAO,EAAC,GAAG,EAAE,eAAK,CAAC,EAAC,CAAA;QAExD,IAAI,KAAW,CAAA;QACf,IAAI,OAAO,IAAI,KAAK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A,WAAC,EAAA,GAAG,IAAI,QAAQ,GAAG,EAAE,CAAA;QAC3B,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/index.d.ts b/node_modules/ajv/dist/vocabularies/validation/index.d.ts new file mode 100644 index 000000000..a078be554 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/index.d.ts @@ -0,0 +1,16 @@ +import type { ErrorObject, Vocabulary } from "../../types"; +import { LimitNumberError } from "./limitNumber"; +import { MultipleOfError } from "./multipleOf"; +import { PatternError } from "./pattern"; +import { RequiredError } from "./required"; +import { UniqueItemsError } from "./uniqueItems"; +import { ConstError } from "./const"; +import { EnumError } from "./enum"; +declare const validation: Vocabulary; +export default validation; +type LimitError = ErrorObject<"maxItems" | "minItems" | "minProperties" | "maxProperties" | "minLength" | "maxLength", { + limit: number; +}, number | { + $data: string; +}>; +export type ValidationKeywordError = LimitError | LimitNumberError | MultipleOfError | PatternError | RequiredError | UniqueItemsError | ConstError | EnumError; diff --git a/node_modules/ajv/dist/vocabularies/validation/index.js b/node_modules/ajv/dist/vocabularies/validation/index.js new file mode 100644 index 000000000..7b56b4e45 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/index.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const limitNumber_1 = require("./limitNumber"); +const multipleOf_1 = require("./multipleOf"); +const limitLength_1 = require("./limitLength"); +const pattern_1 = require("./pattern"); +const limitProperties_1 = require("./limitProperties"); +const required_1 = require("./required"); +const limitItems_1 = require("./limitItems"); +const uniqueItems_1 = require("./uniqueItems"); +const const_1 = require("./const"); +const enum_1 = require("./enum"); +const validation = [ + // number + limitNumber_1.default, + multipleOf_1.default, + // string + limitLength_1.default, + pattern_1.default, + // object + limitProperties_1.default, + required_1.default, + // array + limitItems_1.default, + uniqueItems_1.default, + // any + { keyword: "type", schemaType: ["string", "array"] }, + { keyword: "nullable", schemaType: "boolean" }, + const_1.default, + enum_1.default, +]; +exports.default = validation; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/index.js.map b/node_modules/ajv/dist/vocabularies/validation/index.js.map new file mode 100644 index 000000000..69436fb32 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/index.ts"],"names":[],"mappings":";;AACA,+CAA2D;AAC3D,6CAAwD;AACxD,+CAAuC;AACvC,uCAA+C;AAC/C,uDAA+C;AAC/C,yCAAkD;AAClD,6CAAqC;AACrC,+CAA2D;AAC3D,mCAAgD;AAChD,iCAA6C;AAE7C,MAAM,UAAU,GAAe;IAC7B,SAAS;IACT,qBAAW;IACX,oBAAU;IACV,SAAS;IACT,qBAAW;IACX,iBAAO;IACP,SAAS;IACT,yBAAe;IACf,kBAAQ;IACR,QAAQ;IACR,oBAAU;IACV,qBAAW;IACX,MAAM;IACN,EAAC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAC;IAClD,EAAC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAC;IAC5C,eAAY;IACZ,cAAW;CACZ,CAAA;AAED,kBAAe,UAAU,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/limitContains.d.ts b/node_modules/ajv/dist/vocabularies/validation/limitContains.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitContains.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/validation/limitContains.js b/node_modules/ajv/dist/vocabularies/validation/limitContains.js new file mode 100644 index 000000000..c884dae4b --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitContains.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("../../compile/util"); +const def = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({ keyword, parentSchema, it }) { + if (parentSchema.contains === undefined) { + (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); + } + }, +}; +exports.default = def; +//# sourceMappingURL=limitContains.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/limitContains.js.map b/node_modules/ajv/dist/vocabularies/validation/limitContains.js.map new file mode 100644 index 000000000..084ee2cd2 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitContains.js.map @@ -0,0 +1 @@ +{"version":3,"file":"limitContains.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitContains.ts"],"names":[],"mappings":";;AAEA,6CAAkD;AAElD,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,aAAa,EAAE,aAAa,CAAC;IACvC,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,QAAQ;IACpB,IAAI,CAAC,EAAC,OAAO,EAAE,YAAY,EAAE,EAAE,EAAa;QAC1C,IAAI,YAAY,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;YACxC,IAAA,sBAAe,EAAC,EAAE,EAAE,IAAI,OAAO,iCAAiC,CAAC,CAAA;QACnE,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/limitItems.d.ts b/node_modules/ajv/dist/vocabularies/validation/limitItems.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitItems.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/validation/limitItems.js b/node_modules/ajv/dist/vocabularies/validation/limitItems.js new file mode 100644 index 000000000..e1386f887 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitItems.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const error = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, +}; +const def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`); + }, +}; +exports.default = def; +//# sourceMappingURL=limitItems.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/limitItems.js.map b/node_modules/ajv/dist/vocabularies/validation/limitItems.js.map new file mode 100644 index 000000000..690c73456 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitItems.js.map @@ -0,0 +1 @@ +{"version":3,"file":"limitItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitItems.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AAEvD,MAAM,KAAK,GAA2B;IACpC,OAAO,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;QACtD,OAAO,IAAA,aAAG,EAAA,iBAAiB,IAAI,SAAS,UAAU,QAAQ,CAAA;IAC5D,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,UAAU,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,UAAU,EAAE,UAAU,CAAC;IACjC,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAC,GAAG,GAAG,CAAA;QACvC,MAAM,EAAE,GAAG,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAA;QAC/D,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,WAAW,EAAE,IAAI,UAAU,EAAE,CAAC,CAAA;IACtD,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/limitLength.d.ts b/node_modules/ajv/dist/vocabularies/validation/limitLength.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitLength.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/validation/limitLength.js b/node_modules/ajv/dist/vocabularies/validation/limitLength.js new file mode 100644 index 000000000..6ae5f92e6 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitLength.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const ucs2length_1 = require("../../runtime/ucs2length"); +const error = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, +}; +const def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`); + }, +}; +exports.default = def; +//# sourceMappingURL=limitLength.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/limitLength.js.map b/node_modules/ajv/dist/vocabularies/validation/limitLength.js.map new file mode 100644 index 000000000..f09c35e54 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitLength.js.map @@ -0,0 +1 @@ +{"version":3,"file":"limitLength.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitLength.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AACvD,6CAA0C;AAC1C,yDAAiD;AAEjD,MAAM,KAAK,GAA2B;IACpC,OAAO,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;QACvD,OAAO,IAAA,aAAG,EAAA,iBAAiB,IAAI,SAAS,UAAU,aAAa,CAAA;IACjE,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,UAAU,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,WAAW,EAAE,WAAW,CAAC;IACnC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QAC3C,MAAM,EAAE,GAAG,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAA;QAChE,MAAM,GAAG,GACP,EAAE,CAAC,IAAI,CAAC,OAAO,KAAK,KAAK,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,SAAS,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,IAAA,cAAO,EAAC,GAAG,CAAC,GAAG,EAAE,oBAAU,CAAC,IAAI,IAAI,GAAG,CAAA;QAC7F,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,IAAI,EAAE,IAAI,UAAU,EAAE,CAAC,CAAA;IAC9C,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/limitNumber.d.ts b/node_modules/ajv/dist/vocabularies/validation/limitNumber.d.ts new file mode 100644 index 000000000..7b35096df --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitNumber.d.ts @@ -0,0 +1,11 @@ +import type { CodeKeywordDefinition, ErrorObject } from "../../types"; +type Kwd = "maximum" | "minimum" | "exclusiveMaximum" | "exclusiveMinimum"; +type Comparison = "<=" | ">=" | "<" | ">"; +export type LimitNumberError = ErrorObject; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/validation/limitNumber.js b/node_modules/ajv/dist/vocabularies/validation/limitNumber.js new file mode 100644 index 000000000..a97c0eb9d --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitNumber.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const ops = codegen_1.operators; +const KWDs = { + maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }, +}; +const error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`, +}; +const def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + }, +}; +exports.default = def; +//# sourceMappingURL=limitNumber.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/limitNumber.js.map b/node_modules/ajv/dist/vocabularies/validation/limitNumber.js.map new file mode 100644 index 000000000..18a365337 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitNumber.js.map @@ -0,0 +1 @@ +{"version":3,"file":"limitNumber.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitNumber.ts"],"names":[],"mappings":";;AAEA,mDAA6D;AAE7D,MAAM,GAAG,GAAG,mBAAS,CAAA;AAMrB,MAAM,IAAI,GAA4D;IACpE,OAAO,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACjD,OAAO,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,EAAC;IACjD,gBAAgB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;IACzD,gBAAgB,EAAE,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,EAAC;CAC1D,CAAA;AAQD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,WAAW,IAAI,CAAC,OAAc,CAAC,CAAC,KAAK,IAAI,UAAU,EAAE;IAC5F,MAAM,EAAE,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC,EAAE,EAAE,CAChC,IAAA,WAAC,EAAA,gBAAgB,IAAI,CAAC,OAAc,CAAC,CAAC,KAAK,YAAY,UAAU,GAAG;CACvE,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC;IAC1B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAC,GAAG,GAAG,CAAA;QACvC,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,IAAI,IAAI,CAAC,OAAc,CAAC,CAAC,IAAI,IAAI,UAAU,aAAa,IAAI,GAAG,CAAC,CAAA;IACxF,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/limitProperties.d.ts b/node_modules/ajv/dist/vocabularies/validation/limitProperties.d.ts new file mode 100644 index 000000000..cde2aa270 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitProperties.d.ts @@ -0,0 +1,3 @@ +import type { CodeKeywordDefinition } from "../../types"; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/validation/limitProperties.js b/node_modules/ajv/dist/vocabularies/validation/limitProperties.js new file mode 100644 index 000000000..e6fc40cc6 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitProperties.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const error = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, +}; +const def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`); + }, +}; +exports.default = def; +//# sourceMappingURL=limitProperties.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/limitProperties.js.map b/node_modules/ajv/dist/vocabularies/validation/limitProperties.js.map new file mode 100644 index 000000000..a695943a9 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/limitProperties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"limitProperties.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/limitProperties.ts"],"names":[],"mappings":";;AAEA,mDAAuD;AAEvD,MAAM,KAAK,GAA2B;IACpC,OAAO,CAAC,EAAC,OAAO,EAAE,UAAU,EAAC;QAC3B,MAAM,IAAI,GAAG,OAAO,KAAK,eAAe,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;QAC3D,OAAO,IAAA,aAAG,EAAA,iBAAiB,IAAI,SAAS,UAAU,aAAa,CAAA;IACjE,CAAC;IACD,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,WAAW,UAAU,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,CAAC,eAAe,EAAE,eAAe,CAAC;IAC3C,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAC,GAAG,GAAG,CAAA;QACvC,MAAM,EAAE,GAAG,OAAO,KAAK,eAAe,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAC,CAAC,CAAC,mBAAS,CAAC,EAAE,CAAA;QACpE,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,eAAe,IAAI,YAAY,EAAE,IAAI,UAAU,EAAE,CAAC,CAAA;IACnE,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/multipleOf.d.ts b/node_modules/ajv/dist/vocabularies/validation/multipleOf.d.ts new file mode 100644 index 000000000..67685dcd3 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/multipleOf.d.ts @@ -0,0 +1,8 @@ +import type { CodeKeywordDefinition, ErrorObject } from "../../types"; +export type MultipleOfError = ErrorObject<"multipleOf", { + multipleOf: number; +}, number | { + $data: string; +}>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/validation/multipleOf.js b/node_modules/ajv/dist/vocabularies/validation/multipleOf.js new file mode 100644 index 000000000..43cf67b77 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/multipleOf.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("../../compile/codegen"); +const error = { + message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`, +}; +const def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + // const bdt = bad$DataType(schemaCode, def.schemaType, $data) + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec + ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` + : (0, codegen_1._) `${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + }, +}; +exports.default = def; +//# sourceMappingURL=multipleOf.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/multipleOf.js.map b/node_modules/ajv/dist/vocabularies/validation/multipleOf.js.map new file mode 100644 index 000000000..9ef825b74 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/multipleOf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"multipleOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/multipleOf.ts"],"names":[],"mappings":";;AAEA,mDAA4C;AAQ5C,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,uBAAuB,UAAU,EAAE;IACjE,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,gBAAgB,UAAU,GAAG;CACzD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,YAAY;IACrB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACvC,sEAAsE;QACtE,MAAM,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC,mBAAmB,CAAA;QACxC,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QAC1B,MAAM,OAAO,GAAG,IAAI;YAClB,CAAC,CAAC,IAAA,WAAC,EAAA,uBAAuB,GAAG,OAAO,GAAG,UAAU,IAAI,EAAE;YACvD,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,iBAAiB,GAAG,GAAG,CAAA;QAClC,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,IAAI,UAAU,cAAc,GAAG,MAAM,IAAI,IAAI,UAAU,KAAK,OAAO,IAAI,CAAC,CAAA;IACzF,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/pattern.d.ts b/node_modules/ajv/dist/vocabularies/validation/pattern.d.ts new file mode 100644 index 000000000..7edbfda93 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/pattern.d.ts @@ -0,0 +1,8 @@ +import type { CodeKeywordDefinition, ErrorObject } from "../../types"; +export type PatternError = ErrorObject<"pattern", { + pattern: string; +}, string | { + $data: string; +}>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/validation/pattern.js b/node_modules/ajv/dist/vocabularies/validation/pattern.js new file mode 100644 index 000000000..f8ccdf295 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/pattern.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const code_1 = require("../code"); +const codegen_1 = require("../../compile/codegen"); +const error = { + message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`, +}; +const def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { data, $data, schema, schemaCode, it } = cxt; + // TODO regexp should be wrapped in try/catchs + const u = it.opts.unicodeRegExp ? "u" : ""; + const regExp = $data ? (0, codegen_1._) `(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`); + }, +}; +exports.default = def; +//# sourceMappingURL=pattern.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/pattern.js.map b/node_modules/ajv/dist/vocabularies/validation/pattern.js.map new file mode 100644 index 000000000..82fa5d74c --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/pattern.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/pattern.ts"],"names":[],"mappings":";;AAEA,kCAAkC;AAClC,mDAA4C;AAI5C,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,uBAAuB,UAAU,GAAG;IAClE,MAAM,EAAE,CAAC,EAAC,UAAU,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,aAAa,UAAU,GAAG;CACtD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,SAAS;IAClB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,QAAQ;IACpB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACjD,8CAA8C;QAC9C,MAAM,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAA;QAC1C,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,eAAe,UAAU,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,IAAA,iBAAU,EAAC,GAAG,EAAE,MAAM,CAAC,CAAA;QACrF,GAAG,CAAC,SAAS,CAAC,IAAA,WAAC,EAAA,IAAI,MAAM,SAAS,IAAI,GAAG,CAAC,CAAA;IAC5C,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/required.d.ts b/node_modules/ajv/dist/vocabularies/validation/required.d.ts new file mode 100644 index 000000000..c9cffda1e --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/required.d.ts @@ -0,0 +1,8 @@ +import type { CodeKeywordDefinition, ErrorObject } from "../../types"; +export type RequiredError = ErrorObject<"required", { + missingProperty: string; +}, string[] | { + $data: string; +}>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/validation/required.js b/node_modules/ajv/dist/vocabularies/validation/required.js new file mode 100644 index 000000000..1d8e29263 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/required.js @@ -0,0 +1,79 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const code_1 = require("../code"); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const error = { + message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`, +}; +const def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) + return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) + allErrorsMode(); + else + exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) { + if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + } + function allErrorsMode() { + if (useLoop || $data) { + cxt.block$data(codegen_1.nil, loopAllRequired); + } + else { + for (const prop of schema) { + (0, code_1.checkReportMissingProp)(cxt, prop); + } + } + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } + else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + }, +}; +exports.default = def; +//# sourceMappingURL=required.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/required.js.map b/node_modules/ajv/dist/vocabularies/validation/required.js.map new file mode 100644 index 000000000..9ec186fa1 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/required.js.map @@ -0,0 +1 @@ +{"version":3,"file":"required.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/required.ts"],"names":[],"mappings":";;AAEA,kCAMgB;AAChB,mDAAkE;AAClE,6CAAkD;AAQlD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,eAAe,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,gCAAgC,eAAe,GAAG;IAC/F,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,eAAe,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,qBAAqB,eAAe,GAAG;CAClF,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,OAAO;IACnB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,IAAI,EA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qBAAc,EAAC,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,CAAA;gBACzE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE;oBACtB,GAAG,CAAC,KAAK,EAAE,CAAA;oBACX,GAAG,CAAC,KAAK,EAAE,CAAA;gBACb,CAAC,CAAC,CAAA;YACJ,CAAC,EACD,aAAG,CACJ,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/uniqueItems.d.ts b/node_modules/ajv/dist/vocabularies/validation/uniqueItems.d.ts new file mode 100644 index 000000000..e7c241b98 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/uniqueItems.d.ts @@ -0,0 +1,9 @@ +import type { CodeKeywordDefinition, ErrorObject } from "../../types"; +export type UniqueItemsError = ErrorObject<"uniqueItems", { + i: number; + j: number; +}, boolean | { + $data: string; +}>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js b/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js new file mode 100644 index 000000000..cdbecea12 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js @@ -0,0 +1,64 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const dataType_1 = require("../../compile/validate/dataType"); +const codegen_1 = require("../../compile/codegen"); +const util_1 = require("../../compile/util"); +const equal_1 = require("../../runtime/equal"); +const error = { + message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`, +}; +const def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) + return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._) `${data}.length`); + const j = gen.let("j"); + cxt.setParams({ i, j }); + gen.assign(valid, true); + gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._) `{}`); + gen.for((0, codegen_1._) `;${i}--;`, () => { + gen.let(item, (0, codegen_1._) `${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._) `continue`); + if (itemTypes.length > 1) + gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`); + gen + .if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._) `${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }) + .code((0, codegen_1._) `${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + }, +}; +exports.default = def; +//# sourceMappingURL=uniqueItems.js.map \ No newline at end of file diff --git a/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js.map b/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js.map new file mode 100644 index 000000000..46eb7a2a0 --- /dev/null +++ b/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uniqueItems.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/uniqueItems.ts"],"names":[],"mappings":";;AAEA,8DAAwF;AACxF,mDAAkD;AAClD,6CAA0C;AAC1C,+CAAuC;AAQvC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,CAAC,EAAE,CAAC,EAAC,EAAC,EAAE,EAAE,CAC5B,IAAA,aAAG,EAAA,2CAA2C,CAAC,QAAQ,CAAC,iBAAiB;IAC3E,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,CAAC,EAAE,CAAC,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,OAAO,CAAC,QAAQ,CAAC,GAAG;CACpD,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,aAAa;IACtB,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,SAAS;IACrB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACpE,IAAI,CAAC,KAAK,IAAI,CAAC,MAAM;YAAE,OAAM;QAC7B,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;QAC9B,MAAM,SAAS,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,IAAA,yBAAc,EAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;QAC9E,GAAG,CAAC,UAAU,CAAC,KAAK,EAAE,mBAAmB,EAAE,IAAA,WAAC,EAAA,GAAG,UAAU,YAAY,CAAC,CAAA;QACtE,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;QA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MAAM,IAAI,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE;gBACnD,GAAG,CAAC,KAAK,EAAE,CAAA;gBACX,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;YACvC,CAAC,CAAC,CACH,CACF,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/node_modules/ajv/lib/2019.ts b/node_modules/ajv/lib/2019.ts new file mode 100644 index 000000000..3f7194f1b --- /dev/null +++ b/node_modules/ajv/lib/2019.ts @@ -0,0 +1,81 @@ +import type {AnySchemaObject} from "./types" +import AjvCore, {Options} from "./core" + +import draft7Vocabularies from "./vocabularies/draft7" +import dynamicVocabulary from "./vocabularies/dynamic" +import nextVocabulary from "./vocabularies/next" +import unevaluatedVocabulary from "./vocabularies/unevaluated" +import discriminator from "./vocabularies/discriminator" +import addMetaSchema2019 from "./refs/json-schema-2019-09" + +const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema" + +export class Ajv2019 extends AjvCore { + constructor(opts: Options = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true, + }) + } + + _addVocabularies(): void { + super._addVocabularies() + this.addVocabulary(dynamicVocabulary) + draft7Vocabularies.forEach((v) => this.addVocabulary(v)) + this.addVocabulary(nextVocabulary) + this.addVocabulary(unevaluatedVocabulary) + if (this.opts.discriminator) this.addKeyword(discriminator) + } + + _addDefaultMetaSchema(): void { + super._addDefaultMetaSchema() + const {$data, meta} = this.opts + if (!meta) return + addMetaSchema2019.call(this, $data) + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID + } + + defaultMeta(): string | AnySchemaObject | undefined { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) + } +} + +module.exports = exports = Ajv2019 +module.exports.Ajv2019 = Ajv2019 +Object.defineProperty(exports, "__esModule", {value: true}) + +export default Ajv2019 + +export { + Format, + FormatDefinition, + AsyncFormatDefinition, + KeywordDefinition, + KeywordErrorDefinition, + CodeKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, + Vocabulary, + Schema, + SchemaObject, + AnySchemaObject, + AsyncSchema, + AnySchema, + ValidateFunction, + AsyncValidateFunction, + ErrorObject, + ErrorNoParams, +} from "./types" + +export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core" +export {SchemaCxt, SchemaObjCxt} from "./compile" +export {KeywordCxt} from "./compile/validate" +export {DefinedError} from "./vocabularies/errors" +export {JSONType} from "./compile/rules" +export {JSONSchemaType} from "./types/json-schema" +export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" +export {default as ValidationError} from "./runtime/validation_error" +export {default as MissingRefError} from "./compile/ref_error" diff --git a/node_modules/ajv/lib/2020.ts b/node_modules/ajv/lib/2020.ts new file mode 100644 index 000000000..cfb36af9d --- /dev/null +++ b/node_modules/ajv/lib/2020.ts @@ -0,0 +1,75 @@ +import type {AnySchemaObject} from "./types" +import AjvCore, {Options} from "./core" + +import draft2020Vocabularies from "./vocabularies/draft2020" +import discriminator from "./vocabularies/discriminator" +import addMetaSchema2020 from "./refs/json-schema-2020-12" + +const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema" + +export class Ajv2020 extends AjvCore { + constructor(opts: Options = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true, + }) + } + + _addVocabularies(): void { + super._addVocabularies() + draft2020Vocabularies.forEach((v) => this.addVocabulary(v)) + if (this.opts.discriminator) this.addKeyword(discriminator) + } + + _addDefaultMetaSchema(): void { + super._addDefaultMetaSchema() + const {$data, meta} = this.opts + if (!meta) return + addMetaSchema2020.call(this, $data) + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID + } + + defaultMeta(): string | AnySchemaObject | undefined { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) + } +} + +module.exports = exports = Ajv2020 +module.exports.Ajv2020 = Ajv2020 +Object.defineProperty(exports, "__esModule", {value: true}) + +export default Ajv2020 + +export { + Format, + FormatDefinition, + AsyncFormatDefinition, + KeywordDefinition, + KeywordErrorDefinition, + CodeKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, + Vocabulary, + Schema, + SchemaObject, + AnySchemaObject, + AsyncSchema, + AnySchema, + ValidateFunction, + AsyncValidateFunction, + ErrorObject, + ErrorNoParams, +} from "./types" + +export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core" +export {SchemaCxt, SchemaObjCxt} from "./compile" +export {KeywordCxt} from "./compile/validate" +export {DefinedError} from "./vocabularies/errors" +export {JSONType} from "./compile/rules" +export {JSONSchemaType} from "./types/json-schema" +export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" +export {default as ValidationError} from "./runtime/validation_error" +export {default as MissingRefError} from "./compile/ref_error" diff --git a/node_modules/ajv/lib/ajv.ts b/node_modules/ajv/lib/ajv.ts new file mode 100644 index 000000000..8275b93a8 --- /dev/null +++ b/node_modules/ajv/lib/ajv.ts @@ -0,0 +1,70 @@ +import type {AnySchemaObject} from "./types" +import AjvCore from "./core" +import draft7Vocabularies from "./vocabularies/draft7" +import discriminator from "./vocabularies/discriminator" +import * as draft7MetaSchema from "./refs/json-schema-draft-07.json" + +const META_SUPPORT_DATA = ["/properties"] + +const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema" + +export class Ajv extends AjvCore { + _addVocabularies(): void { + super._addVocabularies() + draft7Vocabularies.forEach((v) => this.addVocabulary(v)) + if (this.opts.discriminator) this.addKeyword(discriminator) + } + + _addDefaultMetaSchema(): void { + super._addDefaultMetaSchema() + if (!this.opts.meta) return + const metaSchema = this.opts.$data + ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) + : draft7MetaSchema + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false) + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID + } + + defaultMeta(): string | AnySchemaObject | undefined { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) + } +} + +module.exports = exports = Ajv +module.exports.Ajv = Ajv +Object.defineProperty(exports, "__esModule", {value: true}) + +export default Ajv + +export { + Format, + FormatDefinition, + AsyncFormatDefinition, + KeywordDefinition, + KeywordErrorDefinition, + CodeKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, + Vocabulary, + Schema, + SchemaObject, + AnySchemaObject, + AsyncSchema, + AnySchema, + ValidateFunction, + AsyncValidateFunction, + SchemaValidateFunction, + ErrorObject, + ErrorNoParams, +} from "./types" + +export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core" +export {SchemaCxt, SchemaObjCxt} from "./compile" +export {KeywordCxt} from "./compile/validate" +export {DefinedError} from "./vocabularies/errors" +export {JSONType} from "./compile/rules" +export {JSONSchemaType} from "./types/json-schema" +export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" +export {default as ValidationError} from "./runtime/validation_error" +export {default as MissingRefError} from "./compile/ref_error" diff --git a/node_modules/ajv/lib/compile/codegen/code.ts b/node_modules/ajv/lib/compile/codegen/code.ts new file mode 100644 index 000000000..9d4de6149 --- /dev/null +++ b/node_modules/ajv/lib/compile/codegen/code.ts @@ -0,0 +1,169 @@ +// eslint-disable-next-line @typescript-eslint/no-extraneous-class +export abstract class _CodeOrName { + abstract readonly str: string + abstract readonly names: UsedNames + abstract toString(): string + abstract emptyStr(): boolean +} + +export const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i + +export class Name extends _CodeOrName { + readonly str: string + constructor(s: string) { + super() + if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier") + this.str = s + } + + toString(): string { + return this.str + } + + emptyStr(): boolean { + return false + } + + get names(): UsedNames { + return {[this.str]: 1} + } +} + +export class _Code extends _CodeOrName { + readonly _items: readonly CodeItem[] + private _str?: string + private _names?: UsedNames + + constructor(code: string | readonly CodeItem[]) { + super() + this._items = typeof code === "string" ? [code] : code + } + + toString(): string { + return this.str + } + + emptyStr(): boolean { + if (this._items.length > 1) return false + const item = this._items[0] + return item === "" || item === '""' + } + + get str(): string { + return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, "")) + } + + get names(): UsedNames { + return (this._names ??= this._items.reduce((names: UsedNames, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1 + return names + }, {})) + } +} + +export type CodeItem = Name | string | number | boolean | null + +export type UsedNames = Record + +export type Code = _Code | Name + +export type SafeExpr = Code | number | boolean | null + +export const nil = new _Code("") + +type CodeArg = SafeExpr | string | undefined + +export function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code { + const code: CodeItem[] = [strs[0]] + let i = 0 + while (i < args.length) { + addCodeArg(code, args[i]) + code.push(strs[++i]) + } + return new _Code(code) +} + +const plus = new _Code("+") + +export function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code { + const expr: CodeItem[] = [safeStringify(strs[0])] + let i = 0 + while (i < args.length) { + expr.push(plus) + addCodeArg(expr, args[i]) + expr.push(plus, safeStringify(strs[++i])) + } + optimize(expr) + return new _Code(expr) +} + +export function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void { + if (arg instanceof _Code) code.push(...arg._items) + else if (arg instanceof Name) code.push(arg) + else code.push(interpolate(arg)) +} + +function optimize(expr: CodeItem[]): void { + let i = 1 + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]) + if (res !== undefined) { + expr.splice(i - 1, 3, res) + continue + } + expr[i++] = "+" + } + i++ + } +} + +function mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined { + if (b === '""') return a + if (a === '""') return b + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== '"') return + if (typeof b != "string") return `${a.slice(0, -1)}${b}"` + if (b[0] === '"') return a.slice(0, -1) + b.slice(1) + return + } + if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}` + return +} + +export function strConcat(c1: Code, c2: Code): Code { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}` +} + +// TODO do not allow arrays here +function interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string { + return typeof x == "number" || typeof x == "boolean" || x === null + ? x + : safeStringify(Array.isArray(x) ? x.join(",") : x) +} + +export function stringify(x: unknown): Code { + return new _Code(safeStringify(x)) +} + +export function safeStringify(x: unknown): string { + return JSON.stringify(x) + .replace(/\u2028/g, "\\u2028") + .replace(/\u2029/g, "\\u2029") +} + +export function getProperty(key: Code | string | number): Code { + return typeof key == "string" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]` +} + +//Does best effort to format the name properly +export function getEsmExportName(key: Code | string | number): Code { + if (typeof key == "string" && IDENTIFIER.test(key)) { + return new _Code(`${key}`) + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`) +} + +export function regexpCode(rx: RegExp): Code { + return new _Code(rx.toString()) +} diff --git a/node_modules/ajv/lib/compile/codegen/index.ts b/node_modules/ajv/lib/compile/codegen/index.ts new file mode 100644 index 000000000..5a6d1ee58 --- /dev/null +++ b/node_modules/ajv/lib/compile/codegen/index.ts @@ -0,0 +1,852 @@ +import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from "./scope" +import {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from "./code" +import {Scope, varKinds} from "./scope" + +export {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from "./code" +export {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from "./scope" + +// type for expressions that can be safely inserted in code without quotes +export type SafeExpr = Code | number | boolean | null + +// type that is either Code of function that adds code to CodeGen instance using its methods +export type Block = Code | (() => void) + +export const operators = { + GT: new _Code(">"), + GTE: new _Code(">="), + LT: new _Code("<"), + LTE: new _Code("<="), + EQ: new _Code("==="), + NEQ: new _Code("!=="), + NOT: new _Code("!"), + OR: new _Code("||"), + AND: new _Code("&&"), + ADD: new _Code("+"), +} + +abstract class Node { + abstract readonly names: UsedNames + + optimizeNodes(): this | ChildNode | ChildNode[] | undefined { + return this + } + + optimizeNames(_names: UsedNames, _constants: Constants): this | undefined { + return this + } + + // get count(): number { + // return 1 + // } +} + +class Def extends Node { + constructor( + private readonly varKind: Name, + private readonly name: Name, + private rhs?: SafeExpr + ) { + super() + } + + render({es5, _n}: CGOptions): string { + const varKind = es5 ? varKinds.var : this.varKind + const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}` + return `${varKind} ${this.name}${rhs};` + _n + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (!names[this.name.str]) return + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants) + return this + } + + get names(): UsedNames { + return this.rhs instanceof _CodeOrName ? this.rhs.names : {} + } +} + +class Assign extends Node { + constructor( + readonly lhs: Code, + public rhs: SafeExpr, + private readonly sideEffects?: boolean + ) { + super() + } + + render({_n}: CGOptions): string { + return `${this.lhs} = ${this.rhs};` + _n + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return + this.rhs = optimizeExpr(this.rhs, names, constants) + return this + } + + get names(): UsedNames { + const names = this.lhs instanceof Name ? {} : {...this.lhs.names} + return addExprNames(names, this.rhs) + } +} + +class AssignOp extends Assign { + constructor( + lhs: Code, + private readonly op: Code, + rhs: SafeExpr, + sideEffects?: boolean + ) { + super(lhs, rhs, sideEffects) + } + + render({_n}: CGOptions): string { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n + } +} + +class Label extends Node { + readonly names: UsedNames = {} + constructor(readonly label: Name) { + super() + } + + render({_n}: CGOptions): string { + return `${this.label}:` + _n + } +} + +class Break extends Node { + readonly names: UsedNames = {} + constructor(readonly label?: Code) { + super() + } + + render({_n}: CGOptions): string { + const label = this.label ? ` ${this.label}` : "" + return `break${label};` + _n + } +} + +class Throw extends Node { + constructor(readonly error: Code) { + super() + } + + render({_n}: CGOptions): string { + return `throw ${this.error};` + _n + } + + get names(): UsedNames { + return this.error.names + } +} + +class AnyCode extends Node { + constructor(private code: SafeExpr) { + super() + } + + render({_n}: CGOptions): string { + return `${this.code};` + _n + } + + optimizeNodes(): this | undefined { + return `${this.code}` ? this : undefined + } + + optimizeNames(names: UsedNames, constants: Constants): this { + this.code = optimizeExpr(this.code, names, constants) + return this + } + + get names(): UsedNames { + return this.code instanceof _CodeOrName ? this.code.names : {} + } +} + +abstract class ParentNode extends Node { + constructor(readonly nodes: ChildNode[] = []) { + super() + } + + render(opts: CGOptions): string { + return this.nodes.reduce((code, n) => code + n.render(opts), "") + } + + optimizeNodes(): this | ChildNode | ChildNode[] | undefined { + const {nodes} = this + let i = nodes.length + while (i--) { + const n = nodes[i].optimizeNodes() + if (Array.isArray(n)) nodes.splice(i, 1, ...n) + else if (n) nodes[i] = n + else nodes.splice(i, 1) + } + return nodes.length > 0 ? this : undefined + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + const {nodes} = this + let i = nodes.length + while (i--) { + // iterating backwards improves 1-pass optimization + const n = nodes[i] + if (n.optimizeNames(names, constants)) continue + subtractNames(names, n.names) + nodes.splice(i, 1) + } + return nodes.length > 0 ? this : undefined + } + + get names(): UsedNames { + return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {}) + } + + // get count(): number { + // return this.nodes.reduce((c, n) => c + n.count, 1) + // } +} + +abstract class BlockNode extends ParentNode { + render(opts: CGOptions): string { + return "{" + opts._n + super.render(opts) + "}" + opts._n + } +} + +class Root extends ParentNode {} + +class Else extends BlockNode { + static readonly kind = "else" +} + +class If extends BlockNode { + static readonly kind = "if" + else?: If | Else + constructor( + private condition: Code | boolean, + nodes?: ChildNode[] + ) { + super(nodes) + } + + render(opts: CGOptions): string { + let code = `if(${this.condition})` + super.render(opts) + if (this.else) code += "else " + this.else.render(opts) + return code + } + + optimizeNodes(): If | ChildNode[] | undefined { + super.optimizeNodes() + const cond = this.condition + if (cond === true) return this.nodes // else is ignored here + let e = this.else + if (e) { + const ns = e.optimizeNodes() + e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined) + } + if (e) { + if (cond === false) return e instanceof If ? e : e.nodes + if (this.nodes.length) return this + return new If(not(cond), e instanceof If ? [e] : e.nodes) + } + if (cond === false || !this.nodes.length) return undefined + return this + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + this.else = this.else?.optimizeNames(names, constants) + if (!(super.optimizeNames(names, constants) || this.else)) return + this.condition = optimizeExpr(this.condition, names, constants) + return this + } + + get names(): UsedNames { + const names = super.names + addExprNames(names, this.condition) + if (this.else) addNames(names, this.else.names) + return names + } + + // get count(): number { + // return super.count + (this.else?.count || 0) + // } +} + +abstract class For extends BlockNode { + static readonly kind = "for" +} + +class ForLoop extends For { + constructor(private iteration: Code) { + super() + } + + render(opts: CGOptions): string { + return `for(${this.iteration})` + super.render(opts) + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (!super.optimizeNames(names, constants)) return + this.iteration = optimizeExpr(this.iteration, names, constants) + return this + } + + get names(): UsedNames { + return addNames(super.names, this.iteration.names) + } +} + +class ForRange extends For { + constructor( + private readonly varKind: Name, + private readonly name: Name, + private readonly from: SafeExpr, + private readonly to: SafeExpr + ) { + super() + } + + render(opts: CGOptions): string { + const varKind = opts.es5 ? varKinds.var : this.varKind + const {name, from, to} = this + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts) + } + + get names(): UsedNames { + const names = addExprNames(super.names, this.from) + return addExprNames(names, this.to) + } +} + +class ForIter extends For { + constructor( + private readonly loop: "of" | "in", + private readonly varKind: Name, + private readonly name: Name, + private iterable: Code + ) { + super() + } + + render(opts: CGOptions): string { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts) + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (!super.optimizeNames(names, constants)) return + this.iterable = optimizeExpr(this.iterable, names, constants) + return this + } + + get names(): UsedNames { + return addNames(super.names, this.iterable.names) + } +} + +class Func extends BlockNode { + static readonly kind = "func" + constructor( + public name: Name, + public args: Code, + public async?: boolean + ) { + super() + } + + render(opts: CGOptions): string { + const _async = this.async ? "async " : "" + return `${_async}function ${this.name}(${this.args})` + super.render(opts) + } +} + +class Return extends ParentNode { + static readonly kind = "return" + + render(opts: CGOptions): string { + return "return " + super.render(opts) + } +} + +class Try extends BlockNode { + catch?: Catch + finally?: Finally + + render(opts: CGOptions): string { + let code = "try" + super.render(opts) + if (this.catch) code += this.catch.render(opts) + if (this.finally) code += this.finally.render(opts) + return code + } + + optimizeNodes(): this { + super.optimizeNodes() + this.catch?.optimizeNodes() as Catch | undefined + this.finally?.optimizeNodes() as Finally | undefined + return this + } + + optimizeNames(names: UsedNames, constants: Constants): this { + super.optimizeNames(names, constants) + this.catch?.optimizeNames(names, constants) + this.finally?.optimizeNames(names, constants) + return this + } + + get names(): UsedNames { + const names = super.names + if (this.catch) addNames(names, this.catch.names) + if (this.finally) addNames(names, this.finally.names) + return names + } + + // get count(): number { + // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0) + // } +} + +class Catch extends BlockNode { + static readonly kind = "catch" + constructor(readonly error: Name) { + super() + } + + render(opts: CGOptions): string { + return `catch(${this.error})` + super.render(opts) + } +} + +class Finally extends BlockNode { + static readonly kind = "finally" + render(opts: CGOptions): string { + return "finally" + super.render(opts) + } +} + +type StartBlockNode = If | For | Func | Return | Try + +type LeafNode = Def | Assign | Label | Break | Throw | AnyCode + +type ChildNode = StartBlockNode | LeafNode + +type EndBlockNodeType = + | typeof If + | typeof Else + | typeof For + | typeof Func + | typeof Return + | typeof Catch + | typeof Finally + +type Constants = Record + +export interface CodeGenOptions { + es5?: boolean + lines?: boolean + ownProperties?: boolean +} + +interface CGOptions extends CodeGenOptions { + _n: "\n" | "" +} + +export class CodeGen { + readonly _scope: Scope + readonly _extScope: ValueScope + readonly _values: ScopeValueSets = {} + private readonly _nodes: ParentNode[] + private readonly _blockStarts: number[] = [] + private readonly _constants: Constants = {} + private readonly opts: CGOptions + + constructor(extScope: ValueScope, opts: CodeGenOptions = {}) { + this.opts = {...opts, _n: opts.lines ? "\n" : ""} + this._extScope = extScope + this._scope = new Scope({parent: extScope}) + this._nodes = [new Root()] + } + + toString(): string { + return this._root.render(this.opts) + } + + // returns unique name in the internal scope + name(prefix: string): Name { + return this._scope.name(prefix) + } + + // reserves unique name in the external scope + scopeName(prefix: string): ValueScopeName { + return this._extScope.name(prefix) + } + + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name { + const name = this._extScope.value(prefixOrName, value) + const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()) + vs.add(name) + return name + } + + getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined { + return this._extScope.getValue(prefix, keyOrRef) + } + + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName: Name): Code { + return this._extScope.scopeRefs(scopeName, this._values) + } + + scopeCode(): Code { + return this._extScope.scopeCode(this._values) + } + + private _def( + varKind: Name, + nameOrPrefix: Name | string, + rhs?: SafeExpr, + constant?: boolean + ): Name { + const name = this._scope.toName(nameOrPrefix) + if (rhs !== undefined && constant) this._constants[name.str] = rhs + this._leafNode(new Def(varKind, name, rhs)) + return name + } + + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name { + return this._def(varKinds.const, nameOrPrefix, rhs, _constant) + } + + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { + return this._def(varKinds.let, nameOrPrefix, rhs, _constant) + } + + // `var` declaration with optional assignment + var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { + return this._def(varKinds.var, nameOrPrefix, rhs, _constant) + } + + // assignment code + assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen { + return this._leafNode(new Assign(lhs, rhs, sideEffects)) + } + + // `+=` code + add(lhs: Code, rhs: SafeExpr): CodeGen { + return this._leafNode(new AssignOp(lhs, operators.ADD, rhs)) + } + + // appends passed SafeExpr to code or executes Block + code(c: Block | SafeExpr): CodeGen { + if (typeof c == "function") c() + else if (c !== nil) this._leafNode(new AnyCode(c)) + return this + } + + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues: [Name | string, SafeExpr | string][]): _Code { + const code: CodeItem[] = ["{"] + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(",") + code.push(key) + if (key !== value || this.opts.es5) { + code.push(":") + addCodeArg(code, value) + } + } + code.push("}") + return new _Code(code) + } + + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen { + this._blockNode(new If(condition)) + + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf() + } else if (thenBody) { + this.code(thenBody).endIf() + } else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body') + } + return this + } + + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition: Code | boolean): CodeGen { + return this._elseNode(new If(condition)) + } + + // `else` clause - only valid after `if` or `else if` clauses + else(): CodeGen { + return this._elseNode(new Else()) + } + + // end `if` statement (needed if gen.if was used only with condition) + endIf(): CodeGen { + return this._endBlockNode(If, Else) + } + + private _for(node: For, forBody?: Block): CodeGen { + this._blockNode(node) + if (forBody) this.code(forBody).endFor() + return this + } + + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration: Code, forBody?: Block): CodeGen { + return this._for(new ForLoop(iteration), forBody) + } + + // `for` statement for a range of values + forRange( + nameOrPrefix: Name | string, + from: SafeExpr, + to: SafeExpr, + forBody: (index: Name) => void, + varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let + ): CodeGen { + const name = this._scope.toName(nameOrPrefix) + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)) + } + + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf( + nameOrPrefix: Name | string, + iterable: Code, + forBody: (item: Name) => void, + varKind: Code = varKinds.const + ): CodeGen { + const name = this._scope.toName(nameOrPrefix) + if (this.opts.es5) { + const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable) + return this.forRange("_i", 0, _`${arr}.length`, (i) => { + this.var(name, _`${arr}[${i}]`) + forBody(name) + }) + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)) + } + + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn( + nameOrPrefix: Name | string, + obj: Code, + forBody: (item: Name) => void, + varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const + ): CodeGen { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody) + } + const name = this._scope.toName(nameOrPrefix) + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)) + } + + // end `for` loop + endFor(): CodeGen { + return this._endBlockNode(For) + } + + // `label` statement + label(label: Name): CodeGen { + return this._leafNode(new Label(label)) + } + + // `break` statement + break(label?: Code): CodeGen { + return this._leafNode(new Break(label)) + } + + // `return` statement + return(value: Block | SafeExpr): CodeGen { + const node = new Return() + this._blockNode(node) + this.code(value) + if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node') + return this._endBlockNode(Return) + } + + // `try` statement + try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen { + if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"') + const node = new Try() + this._blockNode(node) + this.code(tryBody) + if (catchCode) { + const error = this.name("e") + this._currNode = node.catch = new Catch(error) + catchCode(error) + } + if (finallyCode) { + this._currNode = node.finally = new Finally() + this.code(finallyCode) + } + return this._endBlockNode(Catch, Finally) + } + + // `throw` statement + throw(error: Code): CodeGen { + return this._leafNode(new Throw(error)) + } + + // start self-balancing block + block(body?: Block, nodeCount?: number): CodeGen { + this._blockStarts.push(this._nodes.length) + if (body) this.code(body).endBlock(nodeCount) + return this + } + + // end the current self-balancing block + endBlock(nodeCount?: number): CodeGen { + const len = this._blockStarts.pop() + if (len === undefined) throw new Error("CodeGen: not in self-balancing block") + const toClose = this._nodes.length - len + if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`) + } + this._nodes.length = len + return this + } + + // `function` heading (or definition if funcBody is passed) + func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen { + this._blockNode(new Func(name, args, async)) + if (funcBody) this.code(funcBody).endFunc() + return this + } + + // end function definition + endFunc(): CodeGen { + return this._endBlockNode(Func) + } + + optimize(n = 1): void { + while (n-- > 0) { + this._root.optimizeNodes() + this._root.optimizeNames(this._root.names, this._constants) + } + } + + private _leafNode(node: LeafNode): CodeGen { + this._currNode.nodes.push(node) + return this + } + + private _blockNode(node: StartBlockNode): void { + this._currNode.nodes.push(node) + this._nodes.push(node) + } + + private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen { + const n = this._currNode + if (n instanceof N1 || (N2 && n instanceof N2)) { + this._nodes.pop() + return this + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`) + } + + private _elseNode(node: If | Else): CodeGen { + const n = this._currNode + if (!(n instanceof If)) { + throw new Error('CodeGen: "else" without "if"') + } + this._currNode = n.else = node + return this + } + + private get _root(): Root { + return this._nodes[0] as Root + } + + private get _currNode(): ParentNode { + const ns = this._nodes + return ns[ns.length - 1] + } + + private set _currNode(node: ParentNode) { + const ns = this._nodes + ns[ns.length - 1] = node + } + + // get nodeCount(): number { + // return this._root.count + // } +} + +function addNames(names: UsedNames, from: UsedNames): UsedNames { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0) + return names +} + +function addExprNames(names: UsedNames, from: SafeExpr): UsedNames { + return from instanceof _CodeOrName ? addNames(names, from.names) : names +} + +function optimizeExpr(expr: T, names: UsedNames, constants: Constants): T +function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr { + if (expr instanceof Name) return replaceName(expr) + if (!canOptimize(expr)) return expr + return new _Code( + expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => { + if (c instanceof Name) c = replaceName(c) + if (c instanceof _Code) items.push(...c._items) + else items.push(c) + return items + }, []) + ) + + function replaceName(n: Name): SafeExpr { + const c = constants[n.str] + if (c === undefined || names[n.str] !== 1) return n + delete names[n.str] + return c + } + + function canOptimize(e: SafeExpr): e is _Code { + return ( + e instanceof _Code && + e._items.some( + (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined + ) + ) + } +} + +function subtractNames(names: UsedNames, from: UsedNames): void { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0) +} + +export function not(x: T): T +export function not(x: Code | SafeExpr): Code | SafeExpr { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : _`!${par(x)}` +} + +const andCode = mappend(operators.AND) + +// boolean AND (&&) expression with the passed arguments +export function and(...args: Code[]): Code { + return args.reduce(andCode) +} + +const orCode = mappend(operators.OR) + +// boolean OR (||) expression with the passed arguments +export function or(...args: Code[]): Code { + return args.reduce(orCode) +} + +type MAppend = (x: Code, y: Code) => Code + +function mappend(op: Code): MAppend { + return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`) +} + +function par(x: Code): Code { + return x instanceof Name ? x : _`(${x})` +} diff --git a/node_modules/ajv/lib/compile/codegen/scope.ts b/node_modules/ajv/lib/compile/codegen/scope.ts new file mode 100644 index 000000000..511992297 --- /dev/null +++ b/node_modules/ajv/lib/compile/codegen/scope.ts @@ -0,0 +1,215 @@ +import {_, nil, Code, Name} from "./code" + +interface NameGroup { + prefix: string + index: number +} + +export interface NameValue { + ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure + key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used + code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`) +} + +export type ValueReference = unknown // possibly make CodeGen parameterized type on this type + +class ValueError extends Error { + readonly value?: NameValue + constructor(name: ValueScopeName) { + super(`CodeGen: "code" for ${name} not defined`) + this.value = name.value + } +} + +interface ScopeOptions { + prefixes?: Set + parent?: Scope +} + +interface ValueScopeOptions extends ScopeOptions { + scope: ScopeStore + es5?: boolean + lines?: boolean +} + +export type ScopeStore = Record + +type ScopeValues = { + [Prefix in string]?: Map +} + +export type ScopeValueSets = { + [Prefix in string]?: Set +} + +export enum UsedValueState { + Started, + Completed, +} + +export type UsedScopeValues = { + [Prefix in string]?: Map +} + +export const varKinds = { + const: new Name("const"), + let: new Name("let"), + var: new Name("var"), +} + +export class Scope { + protected readonly _names: {[Prefix in string]?: NameGroup} = {} + protected readonly _prefixes?: Set + protected readonly _parent?: Scope + + constructor({prefixes, parent}: ScopeOptions = {}) { + this._prefixes = prefixes + this._parent = parent + } + + toName(nameOrPrefix: Name | string): Name { + return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix) + } + + name(prefix: string): Name { + return new Name(this._newName(prefix)) + } + + protected _newName(prefix: string): string { + const ng = this._names[prefix] || this._nameGroup(prefix) + return `${prefix}${ng.index++}` + } + + private _nameGroup(prefix: string): NameGroup { + if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`) + } + return (this._names[prefix] = {prefix, index: 0}) + } +} + +interface ScopePath { + property: string + itemIndex: number +} + +export class ValueScopeName extends Name { + readonly prefix: string + value?: NameValue + scopePath?: Code + + constructor(prefix: string, nameStr: string) { + super(nameStr) + this.prefix = prefix + } + + setValue(value: NameValue, {property, itemIndex}: ScopePath): void { + this.value = value + this.scopePath = _`.${new Name(property)}[${itemIndex}]` + } +} + +interface VSOptions extends ValueScopeOptions { + _n: Code +} + +const line = _`\n` + +export class ValueScope extends Scope { + protected readonly _values: ScopeValues = {} + protected readonly _scope: ScopeStore + readonly opts: VSOptions + + constructor(opts: ValueScopeOptions) { + super(opts) + this._scope = opts.scope + this.opts = {...opts, _n: opts.lines ? line : nil} + } + + get(): ScopeStore { + return this._scope + } + + name(prefix: string): ValueScopeName { + return new ValueScopeName(prefix, this._newName(prefix)) + } + + value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName { + if (value.ref === undefined) throw new Error("CodeGen: ref must be passed in value") + const name = this.toName(nameOrPrefix) as ValueScopeName + const {prefix} = name + const valueKey = value.key ?? value.ref + let vs = this._values[prefix] + if (vs) { + const _name = vs.get(valueKey) + if (_name) return _name + } else { + vs = this._values[prefix] = new Map() + } + vs.set(valueKey, name) + + const s = this._scope[prefix] || (this._scope[prefix] = []) + const itemIndex = s.length + s[itemIndex] = value.ref + name.setValue(value, {property: prefix, itemIndex}) + return name + } + + getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined { + const vs = this._values[prefix] + if (!vs) return + return vs.get(keyOrRef) + } + + scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code { + return this._reduceValues(values, (name: ValueScopeName) => { + if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`) + return _`${scopeName}${name.scopePath}` + }) + } + + scopeCode( + values: ScopeValues | ScopeValueSets = this._values, + usedValues?: UsedScopeValues, + getCode?: (n: ValueScopeName) => Code | undefined + ): Code { + return this._reduceValues( + values, + (name: ValueScopeName) => { + if (name.value === undefined) throw new Error(`CodeGen: name "${name}" has no value`) + return name.value.code + }, + usedValues, + getCode + ) + } + + private _reduceValues( + values: ScopeValues | ScopeValueSets, + valueCode: (n: ValueScopeName) => Code | undefined, + usedValues: UsedScopeValues = {}, + getCode?: (n: ValueScopeName) => Code | undefined + ): Code { + let code: Code = nil + for (const prefix in values) { + const vs = values[prefix] + if (!vs) continue + const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map()) + vs.forEach((name: ValueScopeName) => { + if (nameSet.has(name)) return + nameSet.set(name, UsedValueState.Started) + let c = valueCode(name) + if (c) { + const def = this.opts.es5 ? varKinds.var : varKinds.const + code = _`${code}${def} ${name} = ${c};${this.opts._n}` + } else if ((c = getCode?.(name))) { + code = _`${code}${c}${this.opts._n}` + } else { + throw new ValueError(name) + } + nameSet.set(name, UsedValueState.Completed) + }) + } + return code + } +} diff --git a/node_modules/ajv/lib/compile/errors.ts b/node_modules/ajv/lib/compile/errors.ts new file mode 100644 index 000000000..18424a0fc --- /dev/null +++ b/node_modules/ajv/lib/compile/errors.ts @@ -0,0 +1,184 @@ +import type {KeywordErrorCxt, KeywordErrorDefinition} from "../types" +import type {SchemaCxt} from "./index" +import {CodeGen, _, str, strConcat, Code, Name} from "./codegen" +import {SafeExpr} from "./codegen/code" +import {getErrorPath, Type} from "./util" +import N from "./names" + +export const keywordError: KeywordErrorDefinition = { + message: ({keyword}) => str`must pass "${keyword}" keyword validation`, +} + +export const keyword$DataError: KeywordErrorDefinition = { + message: ({keyword, schemaType}) => + schemaType + ? str`"${keyword}" keyword must be ${schemaType} ($data)` + : str`"${keyword}" keyword is invalid ($data)`, +} + +export interface ErrorPaths { + instancePath?: Code + schemaPath?: string + parentSchema?: boolean +} + +export function reportError( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition = keywordError, + errorPaths?: ErrorPaths, + overrideAllErrors?: boolean +): void { + const {it} = cxt + const {gen, compositeRule, allErrors} = it + const errObj = errorObjectCode(cxt, error, errorPaths) + if (overrideAllErrors ?? (compositeRule || allErrors)) { + addError(gen, errObj) + } else { + returnErrors(it, _`[${errObj}]`) + } +} + +export function reportExtraError( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition = keywordError, + errorPaths?: ErrorPaths +): void { + const {it} = cxt + const {gen, compositeRule, allErrors} = it + const errObj = errorObjectCode(cxt, error, errorPaths) + addError(gen, errObj) + if (!(compositeRule || allErrors)) { + returnErrors(it, N.vErrors) + } +} + +export function resetErrorsCount(gen: CodeGen, errsCount: Name): void { + gen.assign(N.errors, errsCount) + gen.if(_`${N.vErrors} !== null`, () => + gen.if( + errsCount, + () => gen.assign(_`${N.vErrors}.length`, errsCount), + () => gen.assign(N.vErrors, null) + ) + ) +} + +export function extendErrors({ + gen, + keyword, + schemaValue, + data, + errsCount, + it, +}: KeywordErrorCxt): void { + /* istanbul ignore if */ + if (errsCount === undefined) throw new Error("ajv implementation error") + const err = gen.name("err") + gen.forRange("i", errsCount, N.errors, (i) => { + gen.const(err, _`${N.vErrors}[${i}]`) + gen.if(_`${err}.instancePath === undefined`, () => + gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath)) + ) + gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`) + if (it.opts.verbose) { + gen.assign(_`${err}.schema`, schemaValue) + gen.assign(_`${err}.data`, data) + } + }) +} + +function addError(gen: CodeGen, errObj: Code): void { + const err = gen.const("err", errObj) + gen.if( + _`${N.vErrors} === null`, + () => gen.assign(N.vErrors, _`[${err}]`), + _`${N.vErrors}.push(${err})` + ) + gen.code(_`${N.errors}++`) +} + +function returnErrors(it: SchemaCxt, errs: Code): void { + const {gen, validateName, schemaEnv} = it + if (schemaEnv.$async) { + gen.throw(_`new ${it.ValidationError as Name}(${errs})`) + } else { + gen.assign(_`${validateName}.errors`, errs) + gen.return(false) + } +} + +const E = { + keyword: new Name("keyword"), + schemaPath: new Name("schemaPath"), // also used in JTD errors + params: new Name("params"), + propertyName: new Name("propertyName"), + message: new Name("message"), + schema: new Name("schema"), + parentSchema: new Name("parentSchema"), +} + +function errorObjectCode( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition, + errorPaths?: ErrorPaths +): Code { + const {createErrors} = cxt.it + if (createErrors === false) return _`{}` + return errorObject(cxt, error, errorPaths) +} + +function errorObject( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition, + errorPaths: ErrorPaths = {} +): Code { + const {gen, it} = cxt + const keyValues: [Name, SafeExpr | string][] = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths), + ] + extraErrorProps(cxt, error, keyValues) + return gen.object(...keyValues) +} + +function errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] { + const instPath = instancePath + ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}` + : errorPath + return [N.instancePath, strConcat(N.instancePath, instPath)] +} + +function errorSchemaPath( + {keyword, it: {errSchemaPath}}: KeywordErrorCxt, + {schemaPath, parentSchema}: ErrorPaths +): [Name, string | Code] { + let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}` + if (schemaPath) { + schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}` + } + return [E.schemaPath, schPath] +} + +function extraErrorProps( + cxt: KeywordErrorCxt, + {params, message}: KeywordErrorDefinition, + keyValues: [Name, SafeExpr | string][] +): void { + const {keyword, data, schemaValue, it} = cxt + const {opts, propertyName, topSchemaRef, schemaPath} = it + keyValues.push( + [E.keyword, keyword], + [E.params, typeof params == "function" ? params(cxt) : params || _`{}`] + ) + if (opts.messages) { + keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]) + } + if (opts.verbose) { + keyValues.push( + [E.schema, schemaValue], + [E.parentSchema, _`${topSchemaRef}${schemaPath}`], + [N.data, data] + ) + } + if (propertyName) keyValues.push([E.propertyName, propertyName]) +} diff --git a/node_modules/ajv/lib/compile/index.ts b/node_modules/ajv/lib/compile/index.ts new file mode 100644 index 000000000..bfc393455 --- /dev/null +++ b/node_modules/ajv/lib/compile/index.ts @@ -0,0 +1,324 @@ +import type { + AnySchema, + AnySchemaObject, + AnyValidateFunction, + AsyncValidateFunction, + EvaluatedProperties, + EvaluatedItems, +} from "../types" +import type Ajv from "../core" +import type {InstanceOptions} from "../core" +import {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from "./codegen" +import ValidationError from "../runtime/validation_error" +import N from "./names" +import {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from "./resolve" +import {schemaHasRulesButRef, unescapeFragment} from "./util" +import {validateFunctionCode} from "./validate" +import {URIComponent} from "fast-uri" +import {JSONType} from "./rules" + +export type SchemaRefs = { + [Ref in string]?: SchemaEnv | AnySchema +} + +export interface SchemaCxt { + readonly gen: CodeGen + readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error + readonly data: Name // Name with reference to the current part of data instance + readonly parentData: Name // should be used in keywords modifying data + readonly parentDataProperty: Code | number // should be used in keywords modifying data + readonly dataNames: Name[] + readonly dataPathArr: (Code | number)[] + readonly dataLevel: number // the level of the currently validated data, + // it can be used to access both the property names and the data on all levels from the top. + dataTypes: JSONType[] // data types applied to the current part of data instance + definedProperties: Set // set of properties to keep track of for required checks + readonly topSchemaRef: Code + readonly validateName: Name + evaluated?: Name + readonly ValidationError?: Name + readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt + readonly schemaEnv: SchemaEnv + readonly rootId: string + baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref) + readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema + readonly errSchemaPath: string // this is actual string, should not be changed to Code + readonly errorPath: Code + readonly propertyName?: Name + readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword, + // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`). + // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true. + // You only need to use it if you have many steps in your keywords and potentially can define multiple errors. + props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function + items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function + jtdDiscriminator?: string + jtdMetadata?: boolean + readonly createErrors?: boolean + readonly opts: InstanceOptions // Ajv instance option. + readonly self: Ajv // current Ajv instance +} + +export interface SchemaObjCxt extends SchemaCxt { + readonly schema: AnySchemaObject +} +interface SchemaEnvArgs { + readonly schema: AnySchema + readonly schemaId?: "$id" | "id" + readonly root?: SchemaEnv + readonly baseId?: string + readonly schemaPath?: string + readonly localRefs?: LocalRefs + readonly meta?: boolean +} + +export class SchemaEnv implements SchemaEnvArgs { + readonly schema: AnySchema + readonly schemaId?: "$id" | "id" + readonly root: SchemaEnv + baseId: string // TODO possibly, it should be readonly + schemaPath?: string + localRefs?: LocalRefs + readonly meta?: boolean + readonly $async?: boolean // true if the current schema is asynchronous. + readonly refs: SchemaRefs = {} + readonly dynamicAnchors: {[Ref in string]?: true} = {} + validate?: AnyValidateFunction + validateName?: ValueScopeName + serialize?: (data: unknown) => string + serializeName?: ValueScopeName + parse?: (data: string) => unknown + parseName?: ValueScopeName + + constructor(env: SchemaEnvArgs) { + let schema: AnySchemaObject | undefined + if (typeof env.schema == "object") schema = env.schema + this.schema = env.schema + this.schemaId = env.schemaId + this.root = env.root || this + this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"]) + this.schemaPath = env.schemaPath + this.localRefs = env.localRefs + this.meta = env.meta + this.$async = schema?.$async + this.refs = {} + } +} + +// let codeSize = 0 +// let nodeCount = 0 + +// Compiles schema in SchemaEnv +export function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv { + // TODO refactor - remove compilations + const _sch = getCompilingSchema.call(this, sch) + if (_sch) return _sch + const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails + const {es5, lines} = this.opts.code + const {ownProperties} = this.opts + const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) + let _ValidationError + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: ValidationError, + code: _`require("ajv/dist/runtime/validation_error").default`, + }) + } + + const validateName = gen.scopeName("validate") + sch.validateName = validateName + + const schemaCxt: SchemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: N.data, + parentData: N.parentData, + parentDataProperty: N.parentDataProperty, + dataNames: [N.data], + dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: new Set(), + topSchemaRef: gen.scopeValue( + "schema", + this.opts.code.source === true + ? {ref: sch.schema, code: stringify(sch.schema)} + : {ref: sch.schema} + ), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: _`""`, + opts: this.opts, + self: this, + } + + let sourceCode: string | undefined + try { + this._compilations.add(sch) + validateFunctionCode(schemaCxt) + gen.optimize(this.opts.code.optimize) + // gen.optimize(1) + const validateCode = gen.toString() + sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}` + // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch) + // console.log("\n\n\n *** \n", sourceCode) + const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode) + const validate: AnyValidateFunction = makeValidate(this, this.scope.get()) + this.scope.value(validateName, {ref: validate}) + + validate.errors = null + validate.schema = sch.schema + validate.schemaEnv = sch + if (sch.$async) (validate as AsyncValidateFunction).$async = true + if (this.opts.code.source === true) { + validate.source = {validateName, validateCode, scopeValues: gen._values} + } + if (this.opts.unevaluated) { + const {props, items} = schemaCxt + validate.evaluated = { + props: props instanceof Name ? undefined : props, + items: items instanceof Name ? undefined : items, + dynamicProps: props instanceof Name, + dynamicItems: items instanceof Name, + } + if (validate.source) validate.source.evaluated = stringify(validate.evaluated) + } + sch.validate = validate + return sch + } catch (e) { + delete sch.validate + delete sch.validateName + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode) + // console.log("\n\n\n *** \n", sourceCode, this.opts) + throw e + } finally { + this._compilations.delete(sch) + } +} + +export function resolveRef( + this: Ajv, + root: SchemaEnv, + baseId: string, + ref: string +): AnySchema | SchemaEnv | undefined { + ref = resolveUrl(this.opts.uriResolver, baseId, ref) + const schOrFunc = root.refs[ref] + if (schOrFunc) return schOrFunc + + let _sch = resolve.call(this, root, ref) + if (_sch === undefined) { + const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv + const {schemaId} = this.opts + if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId}) + } + + if (_sch === undefined) return + return (root.refs[ref] = inlineOrCompile.call(this, _sch)) +} + +function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv { + if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema + return sch.validate ? sch : compileSchema.call(this, sch) +} + +// Index of schema compilation in the currently compiled list +export function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) return sch + } +} + +function sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId +} + +// resolve and compile the references ($ref) +// TODO returns AnySchemaObject (if the schema can be inlined) or validation function +function resolve( + this: Ajv, + root: SchemaEnv, // information about the root schema for the current schema + ref: string // reference to resolve +): SchemaEnv | undefined { + let sch + while (typeof (sch = this.refs[ref]) == "string") ref = sch + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref) +} + +// Resolve schema, its root and baseId +export function resolveSchema( + this: Ajv, + root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it + ref: string // reference to resolve +): SchemaEnv | undefined { + const p = this.opts.uriResolver.parse(ref) + const refPath = _getFullPath(this.opts.uriResolver, p) + let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined) + // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p, root) + } + + const id = normalizeId(refPath) + const schOrRef = this.refs[id] || this.schemas[id] + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef) + if (typeof sch?.schema !== "object") return + return getJsonPointer.call(this, p, sch) + } + + if (typeof schOrRef?.schema !== "object") return + if (!schOrRef.validate) compileSchema.call(this, schOrRef) + if (id === normalizeId(ref)) { + const {schema} = schOrRef + const {schemaId} = this.opts + const schId = schema[schemaId] + if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId) + return new SchemaEnv({schema, schemaId, root, baseId}) + } + return getJsonPointer.call(this, p, schOrRef) +} + +const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions", +]) + +function getJsonPointer( + this: Ajv, + parsedRef: URIComponent, + {baseId, schema, root}: SchemaEnv +): SchemaEnv | undefined { + if (parsedRef.fragment?.[0] !== "/") return + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return + const partSchema = schema[unescapeFragment(part)] + if (partSchema === undefined) return + schema = partSchema + // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def? + const schId = typeof schema === "object" && schema[this.opts.schemaId] + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = resolveUrl(this.opts.uriResolver, baseId, schId) + } + } + let env: SchemaEnv | undefined + if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) { + const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref) + env = resolveSchema.call(this, root, $ref) + } + // even though resolution failed we need to return SchemaEnv to throw exception + // so that compileAsync loads missing schema. + const {schemaId} = this.opts + env = env || new SchemaEnv({schema, schemaId, root, baseId}) + if (env.schema !== env.root.schema) return env + return undefined +} diff --git a/node_modules/ajv/lib/compile/jtd/parse.ts b/node_modules/ajv/lib/compile/jtd/parse.ts new file mode 100644 index 000000000..a0141c770 --- /dev/null +++ b/node_modules/ajv/lib/compile/jtd/parse.ts @@ -0,0 +1,411 @@ +import type Ajv from "../../core" +import type {SchemaObject} from "../../types" +import {jtdForms, JTDForm, SchemaObjectMap} from "./types" +import {SchemaEnv, getCompilingSchema} from ".." +import {_, str, and, or, nil, not, CodeGen, Code, Name, SafeExpr} from "../codegen" +import MissingRefError from "../ref_error" +import N from "../names" +import {hasPropFunc} from "../../vocabularies/code" +import {hasRef} from "../../vocabularies/jtd/ref" +import {intRange, IntType} from "../../vocabularies/jtd/type" +import {parseJson, parseJsonNumber, parseJsonString} from "../../runtime/parseJson" +import {useFunc} from "../util" +import validTimestamp from "../../runtime/timestamp" + +type GenParse = (cxt: ParseCxt) => void + +const genParse: {[F in JTDForm]: GenParse} = { + elements: parseElements, + values: parseValues, + discriminator: parseDiscriminator, + properties: parseProperties, + optionalProperties: parseProperties, + enum: parseEnum, + type: parseType, + ref: parseRef, +} + +interface ParseCxt { + readonly gen: CodeGen + readonly self: Ajv // current Ajv instance + readonly schemaEnv: SchemaEnv + readonly definitions: SchemaObjectMap + schema: SchemaObject + data: Code + parseName: Name + char: Name +} + +export default function compileParser( + this: Ajv, + sch: SchemaEnv, + definitions: SchemaObjectMap +): SchemaEnv { + const _sch = getCompilingSchema.call(this, sch) + if (_sch) return _sch + const {es5, lines} = this.opts.code + const {ownProperties} = this.opts + const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) + const parseName = gen.scopeName("parse") + const cxt: ParseCxt = { + self: this, + gen, + schema: sch.schema as SchemaObject, + schemaEnv: sch, + definitions, + data: N.data, + parseName, + char: gen.name("c"), + } + + let sourceCode: string | undefined + try { + this._compilations.add(sch) + sch.parseName = parseName + parserFunction(cxt) + gen.optimize(this.opts.code.optimize) + const parseFuncCode = gen.toString() + sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}` + const makeParse = new Function(`${N.scope}`, sourceCode) + const parse: (json: string) => unknown = makeParse(this.scope.get()) + this.scope.value(parseName, {ref: parse}) + sch.parse = parse + } catch (e) { + if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode) + delete sch.parse + delete sch.parseName + throw e + } finally { + this._compilations.delete(sch) + } + return sch +} + +const undef = _`undefined` + +function parserFunction(cxt: ParseCxt): void { + const {gen, parseName, char} = cxt + gen.func(parseName, _`${N.json}, ${N.jsonPos}, ${N.jsonPart}`, false, () => { + gen.let(N.data) + gen.let(char) + gen.assign(_`${parseName}.message`, undef) + gen.assign(_`${parseName}.position`, undef) + gen.assign(N.jsonPos, _`${N.jsonPos} || 0`) + gen.const(N.jsonLen, _`${N.json}.length`) + parseCode(cxt) + skipWhitespace(cxt) + gen.if(N.jsonPart, () => { + gen.assign(_`${parseName}.position`, N.jsonPos) + gen.return(N.data) + }) + gen.if(_`${N.jsonPos} === ${N.jsonLen}`, () => gen.return(N.data)) + jsonSyntaxError(cxt) + }) +} + +function parseCode(cxt: ParseCxt): void { + let form: JTDForm | undefined + for (const key of jtdForms) { + if (key in cxt.schema) { + form = key + break + } + } + if (form) parseNullable(cxt, genParse[form]) + else parseEmpty(cxt) +} + +const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError)) + +function parseNullable(cxt: ParseCxt, parseForm: GenParse): void { + const {gen, schema, data} = cxt + if (!schema.nullable) return parseForm(cxt) + tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null)) +} + +function parseElements(cxt: ParseCxt): void { + const {gen, schema, data} = cxt + parseToken(cxt, "[") + const ix = gen.let("i", 0) + gen.assign(data, _`[]`) + parseItems(cxt, "]", () => { + const el = gen.let("el") + parseCode({...cxt, schema: schema.elements, data: el}) + gen.assign(_`${data}[${ix}++]`, el) + }) +} + +function parseValues(cxt: ParseCxt): void { + const {gen, schema, data} = cxt + parseToken(cxt, "{") + gen.assign(data, _`{}`) + parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values)) +} + +function parseItems(cxt: ParseCxt, endToken: string, block: () => void): void { + tryParseItems(cxt, endToken, block) + parseToken(cxt, endToken) +} + +function tryParseItems(cxt: ParseCxt, endToken: string, block: () => void): void { + const {gen} = cxt + gen.for(_`;${N.jsonPos}<${N.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => { + block() + tryParseToken(cxt, ",", () => gen.break(), hasItem) + }) + + function hasItem(): void { + tryParseToken(cxt, endToken, () => {}, jsonSyntaxError) + } +} + +function parseKeyValue(cxt: ParseCxt, schema: SchemaObject): void { + const {gen} = cxt + const key = gen.let("key") + parseString({...cxt, data: key}) + parseToken(cxt, ":") + parsePropertyValue(cxt, key, schema) +} + +function parseDiscriminator(cxt: ParseCxt): void { + const {gen, data, schema} = cxt + const {discriminator, mapping} = schema + parseToken(cxt, "{") + gen.assign(data, _`{}`) + const startPos = gen.const("pos", N.jsonPos) + const value = gen.let("value") + const tag = gen.let("tag") + tryParseItems(cxt, "}", () => { + const key = gen.let("key") + parseString({...cxt, data: key}) + parseToken(cxt, ":") + gen.if( + _`${key} === ${discriminator}`, + () => { + parseString({...cxt, data: tag}) + gen.assign(_`${data}[${key}]`, tag) + gen.break() + }, + () => parseEmpty({...cxt, data: value}) // can be discarded/skipped + ) + }) + gen.assign(N.jsonPos, startPos) + gen.if(_`${tag} === undefined`) + parsingError(cxt, str`discriminator tag not found`) + for (const tagValue in mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + parseSchemaProperties({...cxt, schema: mapping[tagValue]}, discriminator) + } + gen.else() + parsingError(cxt, str`discriminator value not in schema`) + gen.endIf() +} + +function parseProperties(cxt: ParseCxt): void { + const {gen, data} = cxt + parseToken(cxt, "{") + gen.assign(data, _`{}`) + parseSchemaProperties(cxt) +} + +function parseSchemaProperties(cxt: ParseCxt, discriminator?: string): void { + const {gen, schema, data} = cxt + const {properties, optionalProperties, additionalProperties} = schema + parseItems(cxt, "}", () => { + const key = gen.let("key") + parseString({...cxt, data: key}) + parseToken(cxt, ":") + gen.if(false) + parseDefinedProperty(cxt, key, properties) + parseDefinedProperty(cxt, key, optionalProperties) + if (discriminator) { + gen.elseIf(_`${key} === ${discriminator}`) + const tag = gen.let("tag") + parseString({...cxt, data: tag}) // can be discarded, it is already assigned + } + gen.else() + if (additionalProperties) { + parseEmpty({...cxt, data: _`${data}[${key}]`}) + } else { + parsingError(cxt, str`property ${key} not allowed`) + } + gen.endIf() + }) + if (properties) { + const hasProp = hasPropFunc(gen) + const allProps: Code = and( + ...Object.keys(properties).map((p): Code => _`${hasProp}.call(${data}, ${p})`) + ) + gen.if(not(allProps), () => parsingError(cxt, str`missing required properties`)) + } +} + +function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void { + const {gen} = cxt + for (const prop in schemas) { + gen.elseIf(_`${key} === ${prop}`) + parsePropertyValue(cxt, key, schemas[prop] as SchemaObject) + } +} + +function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void { + parseCode({...cxt, schema, data: _`${cxt.data}[${key}]`}) +} + +function parseType(cxt: ParseCxt): void { + const {gen, schema, data, self} = cxt + switch (schema.type) { + case "boolean": + parseBoolean(cxt) + break + case "string": + parseString(cxt) + break + case "timestamp": { + parseString(cxt) + const vts = useFunc(gen, validTimestamp) + const {allowDate, parseDate} = self.opts + const notValid = allowDate ? _`!${vts}(${data}, true)` : _`!${vts}(${data})` + const fail: Code = parseDate + ? or(notValid, _`(${data} = new Date(${data}), false)`, _`isNaN(${data}.valueOf())`) + : notValid + gen.if(fail, () => parsingError(cxt, str`invalid timestamp`)) + break + } + case "float32": + case "float64": + parseNumber(cxt) + break + default: { + const t = schema.type as IntType + if (!self.opts.int32range && (t === "int32" || t === "uint32")) { + parseNumber(cxt, 16) // 2 ** 53 - max safe integer + if (t === "uint32") { + gen.if(_`${data} < 0`, () => parsingError(cxt, str`integer out of range`)) + } + } else { + const [min, max, maxDigits] = intRange[t] + parseNumber(cxt, maxDigits) + gen.if(_`${data} < ${min} || ${data} > ${max}`, () => + parsingError(cxt, str`integer out of range`) + ) + } + } + } +} + +function parseString(cxt: ParseCxt): void { + parseToken(cxt, '"') + parseWith(cxt, parseJsonString) +} + +function parseEnum(cxt: ParseCxt): void { + const {gen, data, schema} = cxt + const enumSch = schema.enum + parseToken(cxt, '"') + // TODO loopEnum + gen.if(false) + for (const value of enumSch) { + const valueStr = JSON.stringify(value).slice(1) // remove starting quote + gen.elseIf(_`${jsonSlice(valueStr.length)} === ${valueStr}`) + gen.assign(data, str`${value}`) + gen.add(N.jsonPos, valueStr.length) + } + gen.else() + jsonSyntaxError(cxt) + gen.endIf() +} + +function parseNumber(cxt: ParseCxt, maxDigits?: number): void { + const {gen} = cxt + skipWhitespace(cxt) + gen.if( + _`"-0123456789".indexOf(${jsonSlice(1)}) < 0`, + () => jsonSyntaxError(cxt), + () => parseWith(cxt, parseJsonNumber, maxDigits) + ) +} + +function parseBooleanToken(bool: boolean, fail: GenParse): GenParse { + return (cxt) => { + const {gen, data} = cxt + tryParseToken( + cxt, + `${bool}`, + () => fail(cxt), + () => gen.assign(data, bool) + ) + } +} + +function parseRef(cxt: ParseCxt): void { + const {gen, self, definitions, schema, schemaEnv} = cxt + const {ref} = schema + const refSchema = definitions[ref] + if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`) + if (!hasRef(refSchema)) return parseCode({...cxt, schema: refSchema}) + const {root} = schemaEnv + const sch = compileParser.call(self, new SchemaEnv({schema: refSchema, root}), definitions) + partialParse(cxt, getParser(gen, sch), true) +} + +function getParser(gen: CodeGen, sch: SchemaEnv): Code { + return sch.parse + ? gen.scopeValue("parse", {ref: sch.parse}) + : _`${gen.scopeValue("wrapper", {ref: sch})}.parse` +} + +function parseEmpty(cxt: ParseCxt): void { + parseWith(cxt, parseJson) +} + +function parseWith(cxt: ParseCxt, parseFunc: {code: string}, args?: SafeExpr): void { + partialParse(cxt, useFunc(cxt.gen, parseFunc), args) +} + +function partialParse(cxt: ParseCxt, parseFunc: Name, args?: SafeExpr): void { + const {gen, data} = cxt + gen.assign(data, _`${parseFunc}(${N.json}, ${N.jsonPos}${args ? _`, ${args}` : nil})`) + gen.assign(N.jsonPos, _`${parseFunc}.position`) + gen.if(_`${data} === undefined`, () => parsingError(cxt, _`${parseFunc}.message`)) +} + +function parseToken(cxt: ParseCxt, tok: string): void { + tryParseToken(cxt, tok, jsonSyntaxError) +} + +function tryParseToken(cxt: ParseCxt, tok: string, fail: GenParse, success?: GenParse): void { + const {gen} = cxt + const n = tok.length + skipWhitespace(cxt) + gen.if( + _`${jsonSlice(n)} === ${tok}`, + () => { + gen.add(N.jsonPos, n) + success?.(cxt) + }, + () => fail(cxt) + ) +} + +function skipWhitespace({gen, char: c}: ParseCxt): void { + gen.code( + _`while((${c}=${N.json}[${N.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${N.jsonPos}++;` + ) +} + +function jsonSlice(len: number | Name): Code { + return len === 1 + ? _`${N.json}[${N.jsonPos}]` + : _`${N.json}.slice(${N.jsonPos}, ${N.jsonPos}+${len})` +} + +function jsonSyntaxError(cxt: ParseCxt): void { + parsingError(cxt, _`"unexpected token " + ${N.json}[${N.jsonPos}]`) +} + +function parsingError({gen, parseName}: ParseCxt, msg: Code): void { + gen.assign(_`${parseName}.message`, msg) + gen.assign(_`${parseName}.position`, N.jsonPos) + gen.return(undef) +} diff --git a/node_modules/ajv/lib/compile/jtd/serialize.ts b/node_modules/ajv/lib/compile/jtd/serialize.ts new file mode 100644 index 000000000..1d228826d --- /dev/null +++ b/node_modules/ajv/lib/compile/jtd/serialize.ts @@ -0,0 +1,266 @@ +import type Ajv from "../../core" +import type {SchemaObject} from "../../types" +import {jtdForms, JTDForm, SchemaObjectMap} from "./types" +import {SchemaEnv, getCompilingSchema} from ".." +import {_, str, and, getProperty, CodeGen, Code, Name} from "../codegen" +import MissingRefError from "../ref_error" +import N from "../names" +import {isOwnProperty} from "../../vocabularies/code" +import {hasRef} from "../../vocabularies/jtd/ref" +import {useFunc} from "../util" +import quote from "../../runtime/quote" + +const genSerialize: {[F in JTDForm]: (cxt: SerializeCxt) => void} = { + elements: serializeElements, + values: serializeValues, + discriminator: serializeDiscriminator, + properties: serializeProperties, + optionalProperties: serializeProperties, + enum: serializeString, + type: serializeType, + ref: serializeRef, +} + +interface SerializeCxt { + readonly gen: CodeGen + readonly self: Ajv // current Ajv instance + readonly schemaEnv: SchemaEnv + readonly definitions: SchemaObjectMap + schema: SchemaObject + data: Code +} + +export default function compileSerializer( + this: Ajv, + sch: SchemaEnv, + definitions: SchemaObjectMap +): SchemaEnv { + const _sch = getCompilingSchema.call(this, sch) + if (_sch) return _sch + const {es5, lines} = this.opts.code + const {ownProperties} = this.opts + const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) + const serializeName = gen.scopeName("serialize") + const cxt: SerializeCxt = { + self: this, + gen, + schema: sch.schema as SchemaObject, + schemaEnv: sch, + definitions, + data: N.data, + } + + let sourceCode: string | undefined + try { + this._compilations.add(sch) + sch.serializeName = serializeName + gen.func(serializeName, N.data, false, () => { + gen.let(N.json, str``) + serializeCode(cxt) + gen.return(N.json) + }) + gen.optimize(this.opts.code.optimize) + const serializeFuncCode = gen.toString() + sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}` + const makeSerialize = new Function(`${N.scope}`, sourceCode) + const serialize: (data: unknown) => string = makeSerialize(this.scope.get()) + this.scope.value(serializeName, {ref: serialize}) + sch.serialize = serialize + } catch (e) { + if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode) + delete sch.serialize + delete sch.serializeName + throw e + } finally { + this._compilations.delete(sch) + } + return sch +} + +function serializeCode(cxt: SerializeCxt): void { + let form: JTDForm | undefined + for (const key of jtdForms) { + if (key in cxt.schema) { + form = key + break + } + } + serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty) +} + +function serializeNullable(cxt: SerializeCxt, serializeForm: (_cxt: SerializeCxt) => void): void { + const {gen, schema, data} = cxt + if (!schema.nullable) return serializeForm(cxt) + gen.if( + _`${data} === undefined || ${data} === null`, + () => gen.add(N.json, _`"null"`), + () => serializeForm(cxt) + ) +} + +function serializeElements(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + gen.add(N.json, str`[`) + const first = gen.let("first", true) + gen.forOf("el", data, (el) => { + addComma(cxt, first) + serializeCode({...cxt, schema: schema.elements, data: el}) + }) + gen.add(N.json, str`]`) +} + +function serializeValues(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + gen.add(N.json, str`{`) + const first = gen.let("first", true) + gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first)) + gen.add(N.json, str`}`) +} + +function serializeKeyValue(cxt: SerializeCxt, key: Name, schema: SchemaObject, first?: Name): void { + const {gen, data} = cxt + addComma(cxt, first) + serializeString({...cxt, data: key}) + gen.add(N.json, str`:`) + const value = gen.const("value", _`${data}${getProperty(key)}`) + serializeCode({...cxt, schema, data: value}) +} + +function serializeDiscriminator(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + const {discriminator} = schema + gen.add(N.json, str`{${JSON.stringify(discriminator)}:`) + const tag = gen.const("tag", _`${data}${getProperty(discriminator)}`) + serializeString({...cxt, data: tag}) + gen.if(false) + for (const tagValue in schema.mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + const sch = schema.mapping[tagValue] + serializeSchemaProperties({...cxt, schema: sch}, discriminator) + } + gen.endIf() + gen.add(N.json, str`}`) +} + +function serializeProperties(cxt: SerializeCxt): void { + const {gen} = cxt + gen.add(N.json, str`{`) + serializeSchemaProperties(cxt) + gen.add(N.json, str`}`) +} + +function serializeSchemaProperties(cxt: SerializeCxt, discriminator?: string): void { + const {gen, schema, data} = cxt + const {properties, optionalProperties} = schema + const props = keys(properties) + const optProps = keys(optionalProperties) + const allProps = allProperties(props.concat(optProps)) + let first = !discriminator + let firstProp: Name | undefined + + for (const key of props) { + if (first) first = false + else gen.add(N.json, str`,`) + serializeProperty(key, properties[key], keyValue(key)) + } + if (first) firstProp = gen.let("first", true) + for (const key of optProps) { + const value = keyValue(key) + gen.if(and(_`${value} !== undefined`, isOwnProperty(gen, data, key)), () => { + addComma(cxt, firstProp) + serializeProperty(key, optionalProperties[key], value) + }) + } + if (schema.additionalProperties) { + gen.forIn("key", data, (key) => + gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp)) + ) + } + + function keys(ps?: SchemaObjectMap): string[] { + return ps ? Object.keys(ps) : [] + } + + function allProperties(ps: string[]): string[] { + if (discriminator) ps.push(discriminator) + if (new Set(ps).size !== ps.length) { + throw new Error("JTD: properties/optionalProperties/disciminator overlap") + } + return ps + } + + function keyValue(key: string): Name { + return gen.const("value", _`${data}${getProperty(key)}`) + } + + function serializeProperty(key: string, propSchema: SchemaObject, value: Name): void { + gen.add(N.json, str`${JSON.stringify(key)}:`) + serializeCode({...cxt, schema: propSchema, data: value}) + } + + function isAdditional(key: Name, ps: string[]): Code | true { + return ps.length ? and(...ps.map((p) => _`${key} !== ${p}`)) : true + } +} + +function serializeType(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + switch (schema.type) { + case "boolean": + gen.add(N.json, _`${data} ? "true" : "false"`) + break + case "string": + serializeString(cxt) + break + case "timestamp": + gen.if( + _`${data} instanceof Date`, + () => gen.add(N.json, _`'"' + ${data}.toISOString() + '"'`), + () => serializeString(cxt) + ) + break + default: + serializeNumber(cxt) + } +} + +function serializeString({gen, data}: SerializeCxt): void { + gen.add(N.json, _`${useFunc(gen, quote)}(${data})`) +} + +function serializeNumber({gen, data}: SerializeCxt): void { + gen.add(N.json, _`"" + ${data}`) +} + +function serializeRef(cxt: SerializeCxt): void { + const {gen, self, data, definitions, schema, schemaEnv} = cxt + const {ref} = schema + const refSchema = definitions[ref] + if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`) + if (!hasRef(refSchema)) return serializeCode({...cxt, schema: refSchema}) + const {root} = schemaEnv + const sch = compileSerializer.call(self, new SchemaEnv({schema: refSchema, root}), definitions) + gen.add(N.json, _`${getSerialize(gen, sch)}(${data})`) +} + +function getSerialize(gen: CodeGen, sch: SchemaEnv): Code { + return sch.serialize + ? gen.scopeValue("serialize", {ref: sch.serialize}) + : _`${gen.scopeValue("wrapper", {ref: sch})}.serialize` +} + +function serializeEmpty({gen, data}: SerializeCxt): void { + gen.add(N.json, _`JSON.stringify(${data})`) +} + +function addComma({gen}: SerializeCxt, first?: Name): void { + if (first) { + gen.if( + first, + () => gen.assign(first, false), + () => gen.add(N.json, str`,`) + ) + } else { + gen.add(N.json, str`,`) + } +} diff --git a/node_modules/ajv/lib/compile/jtd/types.ts b/node_modules/ajv/lib/compile/jtd/types.ts new file mode 100644 index 000000000..1258050fd --- /dev/null +++ b/node_modules/ajv/lib/compile/jtd/types.ts @@ -0,0 +1,16 @@ +import type {SchemaObject} from "../../types" + +export type SchemaObjectMap = {[Ref in string]?: SchemaObject} + +export const jtdForms = [ + "elements", + "values", + "discriminator", + "properties", + "optionalProperties", + "enum", + "type", + "ref", +] as const + +export type JTDForm = (typeof jtdForms)[number] diff --git a/node_modules/ajv/lib/compile/names.ts b/node_modules/ajv/lib/compile/names.ts new file mode 100644 index 000000000..b4b242e17 --- /dev/null +++ b/node_modules/ajv/lib/compile/names.ts @@ -0,0 +1,27 @@ +import {Name} from "./codegen" + +const names = { + // validation function arguments + data: new Name("data"), // data passed to validation function + // args passed from referencing schema + valCxt: new Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below + instancePath: new Name("instancePath"), + parentData: new Name("parentData"), + parentDataProperty: new Name("parentDataProperty"), + rootData: new Name("rootData"), // root data - same as the data passed to the first/top validation function + dynamicAnchors: new Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef + // function scoped variables + vErrors: new Name("vErrors"), // null or array of validation errors + errors: new Name("errors"), // counter of validation errors + this: new Name("this"), + // "globals" + self: new Name("self"), + scope: new Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new Name("json"), + jsonPos: new Name("jsonPos"), + jsonLen: new Name("jsonLen"), + jsonPart: new Name("jsonPart"), +} + +export default names diff --git a/node_modules/ajv/lib/compile/ref_error.ts b/node_modules/ajv/lib/compile/ref_error.ts new file mode 100644 index 000000000..386bf0499 --- /dev/null +++ b/node_modules/ajv/lib/compile/ref_error.ts @@ -0,0 +1,13 @@ +import {resolveUrl, normalizeId, getFullPath} from "./resolve" +import type {UriResolver} from "../types" + +export default class MissingRefError extends Error { + readonly missingRef: string + readonly missingSchema: string + + constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`) + this.missingRef = resolveUrl(resolver, baseId, ref) + this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef)) + } +} diff --git a/node_modules/ajv/lib/compile/resolve.ts b/node_modules/ajv/lib/compile/resolve.ts new file mode 100644 index 000000000..b8c4aca39 --- /dev/null +++ b/node_modules/ajv/lib/compile/resolve.ts @@ -0,0 +1,149 @@ +import type {AnySchema, AnySchemaObject, UriResolver} from "../types" +import type Ajv from "../ajv" +import type {URIComponent} from "fast-uri" +import {eachItem} from "./util" +import * as equal from "fast-deep-equal" +import * as traverse from "json-schema-traverse" + +// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution +export type LocalRefs = {[Ref in string]?: AnySchemaObject} + +// TODO refactor to use keyword definitions +const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const", +]) + +export function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean { + if (typeof schema == "boolean") return true + if (limit === true) return !hasRef(schema) + if (!limit) return false + return countKeys(schema) <= limit +} + +const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor", +]) + +function hasRef(schema: AnySchemaObject): boolean { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true + const sch = schema[key] + if (Array.isArray(sch) && sch.some(hasRef)) return true + if (typeof sch == "object" && hasRef(sch)) return true + } + return false +} + +function countKeys(schema: AnySchemaObject): number { + let count = 0 + for (const key in schema) { + if (key === "$ref") return Infinity + count++ + if (SIMPLE_INLINED.has(key)) continue + if (typeof schema[key] == "object") { + eachItem(schema[key], (sch) => (count += countKeys(sch))) + } + if (count === Infinity) return Infinity + } + return count +} + +export function getFullPath(resolver: UriResolver, id = "", normalize?: boolean): string { + if (normalize !== false) id = normalizeId(id) + const p = resolver.parse(id) + return _getFullPath(resolver, p) +} + +export function _getFullPath(resolver: UriResolver, p: URIComponent): string { + const serialized = resolver.serialize(p) + return serialized.split("#")[0] + "#" +} + +const TRAILING_SLASH_HASH = /#\/?$/ +export function normalizeId(id: string | undefined): string { + return id ? id.replace(TRAILING_SLASH_HASH, "") : "" +} + +export function resolveUrl(resolver: UriResolver, baseId: string, id: string): string { + id = normalizeId(id) + return resolver.resolve(baseId, id) +} + +const ANCHOR = /^[a-z_][-a-z0-9._]*$/i + +export function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs { + if (typeof schema == "boolean") return {} + const {schemaId, uriResolver} = this.opts + const schId = normalizeId(schema[schemaId] || baseId) + const baseIds: {[JsonPtr in string]?: string} = {"": schId} + const pathPrefix = getFullPath(uriResolver, schId, false) + const localRefs: LocalRefs = {} + const schemaRefs: Set = new Set() + + traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === undefined) return + const fullPath = pathPrefix + jsonPtr + let innerBaseId = baseIds[parentJsonPtr] + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]) + addAnchor.call(this, sch.$anchor) + addAnchor.call(this, sch.$dynamicAnchor) + baseIds[jsonPtr] = innerBaseId + + function addRef(this: Ajv, ref: string): string { + // eslint-disable-next-line @typescript-eslint/unbound-method + const _resolve = this.opts.uriResolver.resolve + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref) + if (schemaRefs.has(ref)) throw ambiguos(ref) + schemaRefs.add(ref) + let schOrRef = this.refs[ref] + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef] + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref) + } else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref) + localRefs[ref] = sch + } else { + this.refs[ref] = fullPath + } + } + return ref + } + + function addAnchor(this: Ajv, anchor: unknown): void { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`) + addRef.call(this, `#${anchor}`) + } + } + }) + + return localRefs + + function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void { + if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref) + } + + function ambiguos(ref: string): Error { + return new Error(`reference "${ref}" resolves to more than one schema`) + } +} diff --git a/node_modules/ajv/lib/compile/rules.ts b/node_modules/ajv/lib/compile/rules.ts new file mode 100644 index 000000000..7dbf7ab9e --- /dev/null +++ b/node_modules/ajv/lib/compile/rules.ts @@ -0,0 +1,50 @@ +import type {AddedKeywordDefinition} from "../types" + +const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"] as const + +export type JSONType = (typeof _jsonTypes)[number] + +const jsonTypes: Set = new Set(_jsonTypes) + +export function isJSONType(x: unknown): x is JSONType { + return typeof x == "string" && jsonTypes.has(x) +} + +type ValidationTypes = { + [K in JSONType]: boolean | RuleGroup | undefined +} + +export interface ValidationRules { + rules: RuleGroup[] + post: RuleGroup + all: {[Key in string]?: boolean | Rule} // rules that have to be validated + keywords: {[Key in string]?: boolean} // all known keywords (superset of "all") + types: ValidationTypes +} + +export interface RuleGroup { + type?: JSONType + rules: Rule[] +} + +// This interface wraps KeywordDefinition because definition can have multiple keywords +export interface Rule { + keyword: string + definition: AddedKeywordDefinition +} + +export function getRules(): ValidationRules { + const groups: Record<"number" | "string" | "array" | "object", RuleGroup> = { + number: {type: "number", rules: []}, + string: {type: "string", rules: []}, + array: {type: "array", rules: []}, + object: {type: "object", rules: []}, + } + return { + types: {...groups, integer: true, boolean: true, null: true}, + rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object], + post: {rules: []}, + all: {}, + keywords: {}, + } +} diff --git a/node_modules/ajv/lib/compile/util.ts b/node_modules/ajv/lib/compile/util.ts new file mode 100644 index 000000000..cefae51c2 --- /dev/null +++ b/node_modules/ajv/lib/compile/util.ts @@ -0,0 +1,213 @@ +import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types" +import type {SchemaCxt, SchemaObjCxt} from "." +import {_, getProperty, Code, Name, CodeGen} from "./codegen" +import {_Code} from "./codegen/code" +import type {Rule, ValidationRules} from "./rules" + +// TODO refactor to use Set +export function toHash(arr: T[]): {[K in T]?: true} { + const hash: {[K in T]?: true} = {} + for (const item of arr) hash[item] = true + return hash +} + +export function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void { + if (typeof schema == "boolean") return schema + if (Object.keys(schema).length === 0) return true + checkUnknownRules(it, schema) + return !schemaHasRules(schema, it.self.RULES.all) +} + +export function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void { + const {opts, self} = it + if (!opts.strictSchema) return + if (typeof schema === "boolean") return + const rules = self.RULES.keywords + for (const key in schema) { + if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`) + } +} + +export function schemaHasRules( + schema: AnySchema, + rules: {[Key in string]?: boolean | Rule} +): boolean { + if (typeof schema == "boolean") return !schema + for (const key in schema) if (rules[key]) return true + return false +} + +export function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean { + if (typeof schema == "boolean") return !schema + for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true + return false +} + +export function schemaRefOrVal( + {topSchemaRef, schemaPath}: SchemaObjCxt, + schema: unknown, + keyword: string, + $data?: string | false +): Code | number | boolean { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") return schema + if (typeof schema == "string") return _`${schema}` + } + return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}` +} + +export function unescapeFragment(str: string): string { + return unescapeJsonPointer(decodeURIComponent(str)) +} + +export function escapeFragment(str: string | number): string { + return encodeURIComponent(escapeJsonPointer(str)) +} + +export function escapeJsonPointer(str: string | number): string { + if (typeof str == "number") return `${str}` + return str.replace(/~/g, "~0").replace(/\//g, "~1") +} + +export function unescapeJsonPointer(str: string): string { + return str.replace(/~1/g, "/").replace(/~0/g, "~") +} + +export function eachItem(xs: T | T[], f: (x: T) => void): void { + if (Array.isArray(xs)) { + for (const x of xs) f(x) + } else { + f(xs) + } +} + +type SomeEvaluated = EvaluatedProperties | EvaluatedItems + +type MergeEvaluatedFunc = ( + gen: CodeGen, + from: Name | T, + to: Name | Exclude | undefined, + toName?: typeof Name +) => Name | T + +interface MakeMergeFuncArgs { + mergeNames: (gen: CodeGen, from: Name, to: Name) => void + mergeToName: (gen: CodeGen, from: T, to: Name) => void + mergeValues: (from: T, to: Exclude) => T + resultToName: (gen: CodeGen, res?: T) => Name +} + +function makeMergeEvaluated({ + mergeNames, + mergeToName, + mergeValues, + resultToName, +}: MakeMergeFuncArgs): MergeEvaluatedFunc { + return (gen, from, to, toName) => { + const res = + to === undefined + ? from + : to instanceof Name + ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) + : from instanceof Name + ? (mergeToName(gen, to, from), from) + : mergeValues(from, to) + return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res + } +} + +interface MergeEvaluated { + props: MergeEvaluatedFunc + items: MergeEvaluatedFunc +} + +export const mergeEvaluated: MergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => + gen.if(_`${to} !== true && ${from} !== undefined`, () => { + gen.if( + _`${from} === true`, + () => gen.assign(to, true), + () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`) + ) + }), + mergeToName: (gen, from, to) => + gen.if(_`${to} !== true`, () => { + if (from === true) { + gen.assign(to, true) + } else { + gen.assign(to, _`${to} || {}`) + setEvaluated(gen, to, from) + } + }), + mergeValues: (from, to) => (from === true ? true : {...from, ...to}), + resultToName: evaluatedPropsToName, + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => + gen.if(_`${to} !== true && ${from} !== undefined`, () => + gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`) + ), + mergeToName: (gen, from, to) => + gen.if(_`${to} !== true`, () => + gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`) + ), + mergeValues: (from, to) => (from === true ? true : Math.max(from, to)), + resultToName: (gen, items) => gen.var("items", items), + }), +} + +export function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name { + if (ps === true) return gen.var("props", true) + const props = gen.var("props", _`{}`) + if (ps !== undefined) setEvaluated(gen, props, ps) + return props +} + +export function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void { + Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true)) +} + +const snippets: {[S in string]?: _Code} = {} + +export function useFunc(gen: CodeGen, f: {code: string}): Name { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)), + }) +} + +export enum Type { + Num, + Str, +} + +export function getErrorPath( + dataProp: Name | string | number, + dataPropType?: Type, + jsPropertySyntax?: boolean +): Code | string { + // let path + if (dataProp instanceof Name) { + const isNumber = dataPropType === Type.Num + return jsPropertySyntax + ? isNumber + ? _`"[" + ${dataProp} + "]"` + : _`"['" + ${dataProp} + "']"` + : isNumber + ? _`"/" + ${dataProp}` + : _`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")` // TODO maybe use global escapePointer + } + return jsPropertySyntax ? getProperty(dataProp).toString() : "/" + escapeJsonPointer(dataProp) +} + +export function checkStrictMode( + it: SchemaCxt, + msg: string, + mode: boolean | "log" = it.opts.strictSchema +): void { + if (!mode) return + msg = `strict mode: ${msg}` + if (mode === true) throw new Error(msg) + it.self.logger.warn(msg) +} diff --git a/node_modules/ajv/lib/compile/validate/applicability.ts b/node_modules/ajv/lib/compile/validate/applicability.ts new file mode 100644 index 000000000..478b704ac --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/applicability.ts @@ -0,0 +1,22 @@ +import type {AnySchemaObject} from "../../types" +import type {SchemaObjCxt} from ".." +import type {JSONType, RuleGroup, Rule} from "../rules" + +export function schemaHasRulesForType( + {schema, self}: SchemaObjCxt, + type: JSONType +): boolean | undefined { + const group = self.RULES.types[type] + return group && group !== true && shouldUseGroup(schema, group) +} + +export function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean { + return group.rules.some((rule) => shouldUseRule(schema, rule)) +} + +export function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined { + return ( + schema[rule.keyword] !== undefined || + rule.definition.implements?.some((kwd) => schema[kwd] !== undefined) + ) +} diff --git a/node_modules/ajv/lib/compile/validate/boolSchema.ts b/node_modules/ajv/lib/compile/validate/boolSchema.ts new file mode 100644 index 000000000..156355016 --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/boolSchema.ts @@ -0,0 +1,47 @@ +import type {KeywordErrorDefinition, KeywordErrorCxt} from "../../types" +import type {SchemaCxt} from ".." +import {reportError} from "../errors" +import {_, Name} from "../codegen" +import N from "../names" + +const boolError: KeywordErrorDefinition = { + message: "boolean schema is false", +} + +export function topBoolOrEmptySchema(it: SchemaCxt): void { + const {gen, schema, validateName} = it + if (schema === false) { + falseSchemaError(it, false) + } else if (typeof schema == "object" && schema.$async === true) { + gen.return(N.data) + } else { + gen.assign(_`${validateName}.errors`, null) + gen.return(true) + } +} + +export function boolOrEmptySchema(it: SchemaCxt, valid: Name): void { + const {gen, schema} = it + if (schema === false) { + gen.var(valid, false) // TODO var + falseSchemaError(it) + } else { + gen.var(valid, true) // TODO var + } +} + +function falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void { + const {gen, data} = it + // TODO maybe some other interface should be used for non-keyword validation errors... + const cxt: KeywordErrorCxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it, + } + reportError(cxt, boolError, undefined, overrideAllErrors) +} diff --git a/node_modules/ajv/lib/compile/validate/dataType.ts b/node_modules/ajv/lib/compile/validate/dataType.ts new file mode 100644 index 000000000..d8142b3e1 --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/dataType.ts @@ -0,0 +1,230 @@ +import type { + KeywordErrorDefinition, + KeywordErrorCxt, + ErrorObject, + AnySchemaObject, +} from "../../types" +import type {SchemaObjCxt} from ".." +import {isJSONType, JSONType} from "../rules" +import {schemaHasRulesForType} from "./applicability" +import {reportError} from "../errors" +import {_, nil, and, not, operators, Code, Name} from "../codegen" +import {toHash, schemaRefOrVal} from "../util" + +export enum DataType { + Correct, + Wrong, +} + +export function getSchemaTypes(schema: AnySchemaObject): JSONType[] { + const types = getJSONTypes(schema.type) + const hasNull = types.includes("null") + if (hasNull) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false") + } else { + if (!types.length && schema.nullable !== undefined) { + throw new Error('"nullable" cannot be used without "type"') + } + if (schema.nullable === true) types.push("null") + } + return types +} + +// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents +export function getJSONTypes(ts: unknown | unknown[]): JSONType[] { + const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : [] + if (types.every(isJSONType)) return types + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")) +} + +export function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean { + const {gen, data, opts} = it + const coerceTo = coerceToTypes(types, opts.coerceTypes) + const checkTypes = + types.length > 0 && + !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0])) + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong) + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo) + else reportTypeError(it) + }) + } + return checkTypes +} + +const COERCIBLE: Set = new Set(["string", "number", "integer", "boolean", "null"]) +function coerceToTypes(types: JSONType[], coerceTypes?: boolean | "array"): JSONType[] { + return coerceTypes + ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array")) + : [] +} + +function coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void { + const {gen, data, opts} = it + const dataType = gen.let("dataType", _`typeof ${data}`) + const coerced = gen.let("coerced", _`undefined`) + if (opts.coerceTypes === "array") { + gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => + gen + .assign(data, _`${data}[0]`) + .assign(dataType, _`typeof ${data}`) + .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)) + ) + } + gen.if(_`${coerced} !== undefined`) + for (const t of coerceTo) { + if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) { + coerceSpecificType(t) + } + } + gen.else() + reportTypeError(it) + gen.endIf() + + gen.if(_`${coerced} !== undefined`, () => { + gen.assign(data, coerced) + assignParentData(it, coerced) + }) + + function coerceSpecificType(t: string): void { + switch (t) { + case "string": + gen + .elseIf(_`${dataType} == "number" || ${dataType} == "boolean"`) + .assign(coerced, _`"" + ${data}`) + .elseIf(_`${data} === null`) + .assign(coerced, _`""`) + return + case "number": + gen + .elseIf( + _`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})` + ) + .assign(coerced, _`+${data}`) + return + case "integer": + gen + .elseIf( + _`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))` + ) + .assign(coerced, _`+${data}`) + return + case "boolean": + gen + .elseIf(_`${data} === "false" || ${data} === 0 || ${data} === null`) + .assign(coerced, false) + .elseIf(_`${data} === "true" || ${data} === 1`) + .assign(coerced, true) + return + case "null": + gen.elseIf(_`${data} === "" || ${data} === 0 || ${data} === false`) + gen.assign(coerced, null) + return + + case "array": + gen + .elseIf( + _`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null` + ) + .assign(coerced, _`[${data}]`) + } + } +} + +function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void { + // TODO use gen.property + gen.if(_`${parentData} !== undefined`, () => + gen.assign(_`${parentData}[${parentDataProperty}]`, expr) + ) +} + +export function checkDataType( + dataType: JSONType, + data: Name, + strictNums?: boolean | "log", + correct = DataType.Correct +): Code { + const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ + let cond: Code + switch (dataType) { + case "null": + return _`${data} ${EQ} null` + case "array": + cond = _`Array.isArray(${data})` + break + case "object": + cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})` + break + case "integer": + cond = numCond(_`!(${data} % 1) && !isNaN(${data})`) + break + case "number": + cond = numCond() + break + default: + return _`typeof ${data} ${EQ} ${dataType}` + } + return correct === DataType.Correct ? cond : not(cond) + + function numCond(_cond: Code = nil): Code { + return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil) + } +} + +export function checkDataTypes( + dataTypes: JSONType[], + data: Name, + strictNums?: boolean | "log", + correct?: DataType +): Code { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct) + } + let cond: Code + const types = toHash(dataTypes) + if (types.array && types.object) { + const notObj = _`typeof ${data} != "object"` + cond = types.null ? notObj : _`!${data} || ${notObj}` + delete types.null + delete types.array + delete types.object + } else { + cond = nil + } + if (types.number) delete types.integer + for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct)) + return cond +} + +export type TypeError = ErrorObject<"type", {type: string}> + +const typeError: KeywordErrorDefinition = { + message: ({schema}) => `must be ${schema}`, + params: ({schema, schemaValue}) => + typeof schema == "string" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`, +} + +export function reportTypeError(it: SchemaObjCxt): void { + const cxt = getTypeErrorContext(it) + reportError(cxt, typeError) +} + +function getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt { + const {gen, data, schema} = it + const schemaCode = schemaRefOrVal(it, schema, "type") + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it, + } +} diff --git a/node_modules/ajv/lib/compile/validate/defaults.ts b/node_modules/ajv/lib/compile/validate/defaults.ts new file mode 100644 index 000000000..2ad3d4df8 --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/defaults.ts @@ -0,0 +1,32 @@ +import type {SchemaObjCxt} from ".." +import {_, getProperty, stringify} from "../codegen" +import {checkStrictMode} from "../util" + +export function assignDefaults(it: SchemaObjCxt, ty?: string): void { + const {properties, items} = it.schema + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default) + } + } else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i: number) => assignDefault(it, i, sch.default)) + } +} + +function assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void { + const {gen, compositeRule, data, opts} = it + if (defaultValue === undefined) return + const childData = _`${data}${getProperty(prop)}` + if (compositeRule) { + checkStrictMode(it, `default is ignored for: ${childData}`) + return + } + + let condition = _`${childData} === undefined` + if (opts.useDefaults === "empty") { + condition = _`${condition} || ${childData} === null || ${childData} === ""` + } + // `${childData} === undefined` + + // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "") + gen.if(condition, _`${childData} = ${stringify(defaultValue)}`) +} diff --git a/node_modules/ajv/lib/compile/validate/index.ts b/node_modules/ajv/lib/compile/validate/index.ts new file mode 100644 index 000000000..15ecabd85 --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/index.ts @@ -0,0 +1,582 @@ +import type { + AddedKeywordDefinition, + AnySchema, + AnySchemaObject, + KeywordErrorCxt, + KeywordCxtParams, +} from "../../types" +import type {SchemaCxt, SchemaObjCxt} from ".." +import type {InstanceOptions} from "../../core" +import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema" +import {coerceAndCheckDataType, getSchemaTypes} from "./dataType" +import {shouldUseGroup, shouldUseRule} from "./applicability" +import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType" +import {assignDefaults} from "./defaults" +import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword" +import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema" +import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen" +import N from "../names" +import {resolveUrl} from "../resolve" +import { + schemaRefOrVal, + schemaHasRulesButRef, + checkUnknownRules, + checkStrictMode, + unescapeJsonPointer, + mergeEvaluated, +} from "../util" +import type {JSONType, Rule, RuleGroup} from "../rules" +import { + ErrorPaths, + reportError, + reportExtraError, + resetErrorsCount, + keyword$DataError, +} from "../errors" + +// schema compilation - generates validation function, subschemaCode (below) is used for subschemas +export function validateFunctionCode(it: SchemaCxt): void { + if (isSchemaObj(it)) { + checkKeywords(it) + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it) + return + } + } + validateFunction(it, () => topBoolOrEmptySchema(it)) +} + +function validateFunction( + {gen, validateName, schema, schemaEnv, opts}: SchemaCxt, + body: Block +): void { + if (opts.code.es5) { + gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => { + gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`) + destructureValCxtES5(gen, opts) + gen.code(body) + }) + } else { + gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => + gen.code(funcSourceUrl(schema, opts)).code(body) + ) + } +} + +function destructureValCxt(opts: InstanceOptions): Code { + return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${ + N.data + }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}` +} + +function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void { + gen.if( + N.valCxt, + () => { + gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`) + gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`) + gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`) + gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`) + if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`) + }, + () => { + gen.var(N.instancePath, _`""`) + gen.var(N.parentData, _`undefined`) + gen.var(N.parentDataProperty, _`undefined`) + gen.var(N.rootData, N.data) + if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`) + } + ) +} + +function topSchemaObjCode(it: SchemaObjCxt): void { + const {schema, opts, gen} = it + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it) + checkNoDefault(it) + gen.let(N.vErrors, null) + gen.let(N.errors, 0) + if (opts.unevaluated) resetEvaluated(it) + typeAndKeywords(it) + returnResults(it) + }) + return +} + +function resetEvaluated(it: SchemaObjCxt): void { + // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated + const {gen, validateName} = it + it.evaluated = gen.const("evaluated", _`${validateName}.evaluated`) + gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`)) + gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`)) +} + +function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code { + const schId = typeof schema == "object" && schema[opts.schemaId] + return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil +} + +// schema compilation - this function is used recursively to generate code for sub-schemas +function subschemaCode(it: SchemaCxt, valid: Name): void { + if (isSchemaObj(it)) { + checkKeywords(it) + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid) + return + } + } + boolOrEmptySchema(it, valid) +} + +function schemaCxtHasRules({schema, self}: SchemaCxt): boolean { + if (typeof schema == "boolean") return !schema + for (const key in schema) if (self.RULES.all[key]) return true + return false +} + +function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt { + return typeof it.schema != "boolean" +} + +function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void { + const {schema, gen, opts} = it + if (opts.$comment && schema.$comment) commentKeyword(it) + updateContext(it) + checkAsyncSchema(it) + const errsCount = gen.const("_errs", N.errors) + typeAndKeywords(it, errsCount) + // TODO var + gen.var(valid, _`${errsCount} === ${N.errors}`) +} + +function checkKeywords(it: SchemaObjCxt): void { + checkUnknownRules(it) + checkRefsAndKeywords(it) +} + +function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount) + const types = getSchemaTypes(it.schema) + const checkedTypes = coerceAndCheckDataType(it, types) + schemaKeywords(it, types, !checkedTypes, errsCount) +} + +function checkRefsAndKeywords(it: SchemaObjCxt): void { + const {schema, errSchemaPath, opts, self} = it + if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) { + self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`) + } +} + +function checkNoDefault(it: SchemaObjCxt): void { + const {schema, opts} = it + if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) { + checkStrictMode(it, "default is ignored in the schema root") + } +} + +function updateContext(it: SchemaObjCxt): void { + const schId = it.schema[it.opts.schemaId] + if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId) +} + +function checkAsyncSchema(it: SchemaObjCxt): void { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema") +} + +function commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void { + const msg = schema.$comment + if (opts.$comment === true) { + gen.code(_`${N.self}.logger.log(${msg})`) + } else if (typeof opts.$comment == "function") { + const schemaPath = str`${errSchemaPath}/$comment` + const rootName = gen.scopeValue("root", {ref: schemaEnv.root}) + gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`) + } +} + +function returnResults(it: SchemaCxt): void { + const {gen, schemaEnv, validateName, ValidationError, opts} = it + if (schemaEnv.$async) { + // TODO assign unevaluated + gen.if( + _`${N.errors} === 0`, + () => gen.return(N.data), + () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`) + ) + } else { + gen.assign(_`${validateName}.errors`, N.vErrors) + if (opts.unevaluated) assignEvaluated(it) + gen.return(_`${N.errors} === 0`) + } +} + +function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void { + if (props instanceof Name) gen.assign(_`${evaluated}.props`, props) + if (items instanceof Name) gen.assign(_`${evaluated}.items`, items) +} + +function schemaKeywords( + it: SchemaObjCxt, + types: JSONType[], + typeErrors: boolean, + errsCount?: Name +): void { + const {gen, schema, data, allErrors, opts, self} = it + const {RULES} = self + if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast + return + } + if (!opts.jtd) checkStrictTypes(it, types) + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group) + groupKeywords(RULES.post) + }) + + function groupKeywords(group: RuleGroup): void { + if (!shouldUseGroup(schema, group)) return + if (group.type) { + gen.if(checkDataType(group.type, data, opts.strictNumbers)) + iterateKeywords(it, group) + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else() + reportTypeError(it) + } + gen.endIf() + } else { + iterateKeywords(it, group) + } + // TODO make it "ok" call? + if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`) + } +} + +function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void { + const { + gen, + schema, + opts: {useDefaults}, + } = it + if (useDefaults) assignDefaults(it, group.type) + gen.block(() => { + for (const rule of group.rules) { + if (shouldUseRule(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type) + } + } + }) +} + +function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void { + if (it.schemaEnv.meta || !it.opts.strictTypes) return + checkContextTypes(it, types) + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types) + checkKeywordTypes(it, it.dataTypes) +} + +function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void { + if (!types.length) return + if (!it.dataTypes.length) { + it.dataTypes = types + return + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) { + strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`) + } + }) + narrowSchemaTypes(it, types) +} + +function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword") + } +} + +function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void { + const rules = it.self.RULES.all + for (const keyword in rules) { + const rule = rules[keyword] + if (typeof rule == "object" && shouldUseRule(it.schema, rule)) { + const {type} = rule.definition + if (type.length && !type.some((t) => hasApplicableType(ts, t))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`) + } + } + } +} + +function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean { + return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer")) +} + +function includesType(ts: JSONType[], t: JSONType): boolean { + return ts.includes(t) || (t === "integer" && ts.includes("number")) +} + +function narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void { + const ts: JSONType[] = [] + for (const t of it.dataTypes) { + if (includesType(withTypes, t)) ts.push(t) + else if (withTypes.includes("integer") && t === "number") ts.push("integer") + } + it.dataTypes = ts +} + +function strictTypesError(it: SchemaObjCxt, msg: string): void { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath + msg += ` at "${schemaPath}" (strictTypes)` + checkStrictMode(it, msg, it.opts.strictTypes) +} + +export class KeywordCxt implements KeywordErrorCxt { + readonly gen: CodeGen + readonly allErrors?: boolean + readonly keyword: string + readonly data: Name // Name referencing the current level of the data instance + readonly $data?: string | false + schema: any // keyword value in the schema + readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value + readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) + readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema + readonly parentSchema: AnySchemaObject + readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, + // requires option trackErrors in keyword definition + params: KeywordCxtParams // object to pass parameters to error messages from keyword code + readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) + readonly def: AddedKeywordDefinition + + constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { + validateKeywordUsage(it, def, keyword) + this.gen = it.gen + this.allErrors = it.allErrors + this.keyword = keyword + this.data = it.data + this.schema = it.schema[keyword] + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data + this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) + this.schemaType = def.schemaType + this.parentSchema = it.schema + this.params = {} + this.it = it + this.def = def + + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) + } else { + this.schemaCode = this.schemaValue + if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) + } + } + + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", N.errors) + } + } + + result(condition: Code, successAction?: () => void, failAction?: () => void): void { + this.failResult(not(condition), successAction, failAction) + } + + failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { + this.gen.if(condition) + if (failAction) failAction() + else this.error() + if (successAction) { + this.gen.else() + successAction() + if (this.allErrors) this.gen.endIf() + } else { + if (this.allErrors) this.gen.endIf() + else this.gen.else() + } + } + + pass(condition: Code, failAction?: () => void): void { + this.failResult(not(condition), undefined, failAction) + } + + fail(condition?: Code): void { + if (condition === undefined) { + this.error() + if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize + return + } + this.gen.if(condition) + this.error() + if (this.allErrors) this.gen.endIf() + else this.gen.else() + } + + fail$data(condition: Code): void { + if (!this.$data) return this.fail(condition) + const {schemaCode} = this + this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) + } + + error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { + if (errorParams) { + this.setParams(errorParams) + this._error(append, errorPaths) + this.setParams({}) + return + } + this._error(append, errorPaths) + } + + private _error(append?: boolean, errorPaths?: ErrorPaths): void { + ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) + } + + $dataError(): void { + reportError(this, this.def.$dataError || keyword$DataError) + } + + reset(): void { + if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') + resetErrorsCount(this.gen, this.errsCount) + } + + ok(cond: Code | boolean): void { + if (!this.allErrors) this.gen.if(cond) + } + + setParams(obj: KeywordCxtParams, assign?: true): void { + if (assign) Object.assign(this.params, obj) + else this.params = obj + } + + block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { + this.gen.block(() => { + this.check$data(valid, $dataValid) + codeBlock() + }) + } + + check$data(valid: Name = nil, $dataValid: Code = nil): void { + if (!this.$data) return + const {gen, schemaCode, schemaType, def} = this + gen.if(or(_`${schemaCode} === undefined`, $dataValid)) + if (valid !== nil) gen.assign(valid, true) + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()) + this.$dataError() + if (valid !== nil) gen.assign(valid, false) + } + gen.else() + } + + invalid$data(): Code { + const {gen, schemaCode, schemaType, def, it} = this + return or(wrong$DataType(), invalid$DataSchema()) + + function wrong$DataType(): Code { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") + const st = Array.isArray(schemaType) ? schemaType : [schemaType] + return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` + } + return nil + } + + function invalid$DataSchema(): Code { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone + return _`!${validateSchemaRef}(${schemaCode})` + } + return nil + } + } + + subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { + const subschema = getSubschema(this.it, appl) + extendSubschemaData(subschema, this.it, appl) + extendSubschemaMode(subschema, appl) + const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} + subschemaCode(nextContext, valid) + return nextContext + } + + mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { + const {it, gen} = this + if (!it.opts.unevaluated) return + if (it.props !== true && schemaCxt.props !== undefined) { + it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) + } + if (it.items !== true && schemaCxt.items !== undefined) { + it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) + } + } + + mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { + const {it, gen} = this + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) + return true + } + } +} + +function keywordCode( + it: SchemaObjCxt, + keyword: string, + def: AddedKeywordDefinition, + ruleType?: JSONType +): void { + const cxt = new KeywordCxt(it, def, keyword) + if ("code" in def) { + def.code(cxt, ruleType) + } else if (cxt.$data && def.validate) { + funcKeywordCode(cxt, def) + } else if ("macro" in def) { + macroKeywordCode(cxt, def) + } else if (def.compile || def.validate) { + funcKeywordCode(cxt, def) + } +} + +const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/ +const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/ +export function getData( + $data: string, + {dataLevel, dataNames, dataPathArr}: SchemaCxt +): Code | number { + let jsonPointer + let data: Code + if ($data === "") return N.rootData + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`) + jsonPointer = $data + data = N.rootData + } else { + const matches = RELATIVE_JSON_POINTER.exec($data) + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`) + const up: number = +matches[1] + jsonPointer = matches[2] + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)) + return dataPathArr[dataLevel - up] + } + if (up > dataLevel) throw new Error(errorMsg("data", up)) + data = dataNames[dataLevel - up] + if (!jsonPointer) return data + } + + let expr = data + const segments = jsonPointer.split("/") + for (const segment of segments) { + if (segment) { + data = _`${data}${getProperty(unescapeJsonPointer(segment))}` + expr = _`${expr} && ${data}` + } + } + return expr + + function errorMsg(pointerType: string, up: number): string { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}` + } +} diff --git a/node_modules/ajv/lib/compile/validate/keyword.ts b/node_modules/ajv/lib/compile/validate/keyword.ts new file mode 100644 index 000000000..f854aa710 --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/keyword.ts @@ -0,0 +1,171 @@ +import type {KeywordCxt} from "." +import type { + AnySchema, + SchemaValidateFunction, + AnyValidateFunction, + AddedKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, +} from "../../types" +import type {SchemaObjCxt} from ".." +import {_, nil, not, stringify, Code, Name, CodeGen} from "../codegen" +import N from "../names" +import type {JSONType} from "../rules" +import {callValidateCode} from "../../vocabularies/code" +import {extendErrors} from "../errors" + +type KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction + +export function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void { + const {gen, keyword, schema, parentSchema, it} = cxt + const macroSchema = def.macro.call(it.self, schema, parentSchema, it) + const schemaRef = useKeyword(gen, keyword, macroSchema) + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true) + + const valid = gen.name("valid") + cxt.subschema( + { + schema: macroSchema, + schemaPath: nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true, + }, + valid + ) + cxt.pass(valid, () => cxt.error(true)) +} + +export function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void { + const {gen, keyword, schema, parentSchema, $data, it} = cxt + checkAsyncKeyword(it, def) + const validate = + !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate + const validateRef = useKeyword(gen, keyword, validate) + const valid = gen.let("valid") + cxt.block$data(valid, validateKeyword) + cxt.ok(def.valid ?? valid) + + function validateKeyword(): void { + if (def.errors === false) { + assignValid() + if (def.modifying) modifyData(cxt) + reportErrs(() => cxt.error()) + } else { + const ruleErrs = def.async ? validateAsync() : validateSync() + if (def.modifying) modifyData(cxt) + reportErrs(() => addErrs(cxt, ruleErrs)) + } + } + + function validateAsync(): Name { + const ruleErrs = gen.let("ruleErrs", null) + gen.try( + () => assignValid(_`await `), + (e) => + gen.assign(valid, false).if( + _`${e} instanceof ${it.ValidationError as Name}`, + () => gen.assign(ruleErrs, _`${e}.errors`), + () => gen.throw(e) + ) + ) + return ruleErrs + } + + function validateSync(): Code { + const validateErrs = _`${validateRef}.errors` + gen.assign(validateErrs, null) + assignValid(nil) + return validateErrs + } + + function assignValid(_await: Code = def.async ? _`await ` : nil): void { + const passCxt = it.opts.passContext ? N.this : N.self + const passSchema = !(("compile" in def && !$data) || def.schema === false) + gen.assign( + valid, + _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`, + def.modifying + ) + } + + function reportErrs(errors: () => void): void { + gen.if(not(def.valid ?? valid), errors) + } +} + +function modifyData(cxt: KeywordCxt): void { + const {gen, data, it} = cxt + gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`)) +} + +function addErrs(cxt: KeywordCxt, errs: Code): void { + const {gen} = cxt + gen.if( + _`Array.isArray(${errs})`, + () => { + gen + .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) + .assign(N.errors, _`${N.vErrors}.length`) + extendErrors(cxt) + }, + () => cxt.error() + ) +} + +function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void { + if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema") +} + +function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name { + if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`) + return gen.scopeValue( + "keyword", + typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)} + ) +} + +export function validSchemaType( + schema: unknown, + schemaType: JSONType[], + allowUndefined = false +): boolean { + // TODO add tests + return ( + !schemaType.length || + schemaType.some((st) => + st === "array" + ? Array.isArray(schema) + : st === "object" + ? schema && typeof schema == "object" && !Array.isArray(schema) + : typeof schema == st || (allowUndefined && typeof schema == "undefined") + ) + ) +} + +export function validateKeywordUsage( + {schema, opts, self, errSchemaPath}: SchemaObjCxt, + def: AddedKeywordDefinition, + keyword: string +): void { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error") + } + + const deps = def.dependencies + if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`) + } + + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]) + if (!valid) { + const msg = + `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + + self.errorsText(def.validateSchema.errors) + if (opts.validateSchema === "log") self.logger.error(msg) + else throw new Error(msg) + } + } +} diff --git a/node_modules/ajv/lib/compile/validate/subschema.ts b/node_modules/ajv/lib/compile/validate/subschema.ts new file mode 100644 index 000000000..9072ed774 --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/subschema.ts @@ -0,0 +1,135 @@ +import type {AnySchema} from "../../types" +import type {SchemaObjCxt} from ".." +import {_, str, getProperty, Code, Name} from "../codegen" +import {escapeFragment, getErrorPath, Type} from "../util" +import type {JSONType} from "../rules" + +export interface SubschemaContext { + // TODO use Optional? align with SchemCxt property types + schema: AnySchema + schemaPath: Code + errSchemaPath: string + topSchemaRef?: Code + errorPath?: Code + dataLevel?: number + dataTypes?: JSONType[] + data?: Name + parentData?: Name + parentDataProperty?: Code | number + dataNames?: Name[] + dataPathArr?: (Code | number)[] + propertyName?: Name + jtdDiscriminator?: string + jtdMetadata?: boolean + compositeRule?: true + createErrors?: boolean + allErrors?: boolean +} + +export type SubschemaArgs = Partial<{ + keyword: string + schemaProp: string | number + schema: AnySchema + schemaPath: Code + errSchemaPath: string + topSchemaRef: Code + data: Name | Code + dataProp: Code | string | number + dataTypes: JSONType[] + definedProperties: Set + propertyName: Name + dataPropType: Type + jtdDiscriminator: string + jtdMetadata: boolean + compositeRule: true + createErrors: boolean + allErrors: boolean +}> + +export function getSubschema( + it: SchemaObjCxt, + {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs +): SubschemaContext { + if (keyword !== undefined && schema !== undefined) { + throw new Error('both "keyword" and "schema" passed, only one allowed') + } + + if (keyword !== undefined) { + const sch = it.schema[keyword] + return schemaProp === undefined + ? { + schema: sch, + schemaPath: _`${it.schemaPath}${getProperty(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + } + : { + schema: sch[schemaProp], + schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`, + } + } + + if (schema !== undefined) { + if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"') + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath, + } + } + + throw new Error('either "keyword" or "schema" must be passed') +} + +export function extendSubschemaData( + subschema: SubschemaContext, + it: SchemaObjCxt, + {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs +): void { + if (data !== undefined && dataProp !== undefined) { + throw new Error('both "data" and "dataProp" passed, only one allowed') + } + + const {gen} = it + + if (dataProp !== undefined) { + const {errorPath, dataPathArr, opts} = it + const nextData = gen.let("data", _`${it.data}${getProperty(dataProp)}`, true) + dataContextProps(nextData) + subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}` + subschema.parentDataProperty = _`${dataProp}` + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty] + } + + if (data !== undefined) { + const nextData = data instanceof Name ? data : gen.let("data", data, true) // replaceable if used once? + dataContextProps(nextData) + if (propertyName !== undefined) subschema.propertyName = propertyName + // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr + } + + if (dataTypes) subschema.dataTypes = dataTypes + + function dataContextProps(_nextData: Name): void { + subschema.data = _nextData + subschema.dataLevel = it.dataLevel + 1 + subschema.dataTypes = [] + it.definedProperties = new Set() + subschema.parentData = it.data + subschema.dataNames = [...it.dataNames, _nextData] + } +} + +export function extendSubschemaMode( + subschema: SubschemaContext, + {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs +): void { + if (compositeRule !== undefined) subschema.compositeRule = compositeRule + if (createErrors !== undefined) subschema.createErrors = createErrors + if (allErrors !== undefined) subschema.allErrors = allErrors + subschema.jtdDiscriminator = jtdDiscriminator // not inherited + subschema.jtdMetadata = jtdMetadata // not inherited +} diff --git a/node_modules/ajv/lib/core.ts b/node_modules/ajv/lib/core.ts new file mode 100644 index 000000000..e41ca3e2a --- /dev/null +++ b/node_modules/ajv/lib/core.ts @@ -0,0 +1,891 @@ +export { + Format, + FormatDefinition, + AsyncFormatDefinition, + KeywordDefinition, + KeywordErrorDefinition, + CodeKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, + Vocabulary, + Schema, + SchemaObject, + AnySchemaObject, + AsyncSchema, + AnySchema, + ValidateFunction, + AsyncValidateFunction, + AnyValidateFunction, + ErrorObject, + ErrorNoParams, +} from "./types" + +export {SchemaCxt, SchemaObjCxt} from "./compile" +export interface Plugin { + (ajv: Ajv, options?: Opts): Ajv + [prop: string]: any +} + +export {KeywordCxt} from "./compile/validate" +export {DefinedError} from "./vocabularies/errors" +export {JSONType} from "./compile/rules" +export {JSONSchemaType} from "./types/json-schema" +export {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema" +export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" + +import type { + Schema, + AnySchema, + AnySchemaObject, + SchemaObject, + AsyncSchema, + Vocabulary, + KeywordDefinition, + AddedKeywordDefinition, + AnyValidateFunction, + ValidateFunction, + AsyncValidateFunction, + ErrorObject, + Format, + AddedFormat, + RegExpEngine, + UriResolver, +} from "./types" +import type {JSONSchemaType} from "./types/json-schema" +import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema" +import ValidationError from "./runtime/validation_error" +import MissingRefError from "./compile/ref_error" +import {getRules, ValidationRules, Rule, RuleGroup, JSONType} from "./compile/rules" +import {SchemaEnv, compileSchema, resolveSchema} from "./compile" +import {Code, ValueScope} from "./compile/codegen" +import {normalizeId, getSchemaRefs} from "./compile/resolve" +import {getJSONTypes} from "./compile/validate/dataType" +import {eachItem} from "./compile/util" +import * as $dataRefSchema from "./refs/data.json" + +import DefaultUriResolver from "./runtime/uri" + +const defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags) +defaultRegExp.code = "new RegExp" + +const META_IGNORE_OPTIONS: (keyof Options)[] = ["removeAdditional", "useDefaults", "coerceTypes"] +const EXT_SCOPE_NAMES = new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error", +]) + +export type Options = CurrentOptions & DeprecatedOptions + +export interface CurrentOptions { + // strict mode options (NEW) + strict?: boolean | "log" + strictSchema?: boolean | "log" + strictNumbers?: boolean | "log" + strictTypes?: boolean | "log" + strictTuples?: boolean | "log" + strictRequired?: boolean | "log" + allowMatchingProperties?: boolean // disables a strict mode restriction + allowUnionTypes?: boolean + validateFormats?: boolean + // validation and reporting options: + $data?: boolean + allErrors?: boolean + verbose?: boolean + discriminator?: boolean + unicodeRegExp?: boolean + timestamp?: "string" | "date" // JTD only + parseDate?: boolean // JTD only + allowDate?: boolean // JTD only + $comment?: + | true + | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown) + formats?: {[Name in string]?: Format} + keywords?: Vocabulary + schemas?: AnySchema[] | {[Key in string]?: AnySchema} + logger?: Logger | false + loadSchema?: (uri: string) => Promise + // options to modify validated data: + removeAdditional?: boolean | "all" | "failing" + useDefaults?: boolean | "empty" + coerceTypes?: boolean | "array" + // advanced options: + next?: boolean // NEW + unevaluated?: boolean // NEW + dynamicRef?: boolean // NEW + schemaId?: "id" | "$id" + jtd?: boolean // NEW + meta?: SchemaObject | boolean + defaultMeta?: string | AnySchemaObject + validateSchema?: boolean | "log" + addUsedSchema?: boolean + inlineRefs?: boolean | number + passContext?: boolean + loopRequired?: number + loopEnum?: number // NEW + ownProperties?: boolean + multipleOfPrecision?: number + int32range?: boolean // JTD only + messages?: boolean + code?: CodeOptions // NEW + uriResolver?: UriResolver +} + +export interface CodeOptions { + es5?: boolean + esm?: boolean + lines?: boolean + optimize?: boolean | number + formats?: Code // code to require (or construct) map of available formats - for standalone code + source?: boolean + process?: (code: string, schema?: SchemaEnv) => string + regExp?: RegExpEngine +} + +interface InstanceCodeOptions extends CodeOptions { + regExp: RegExpEngine + optimize: number +} + +interface DeprecatedOptions { + /** @deprecated */ + ignoreKeywordsWithRef?: boolean + /** @deprecated */ + jsPropertySyntax?: boolean // added instead of jsonPointers + /** @deprecated */ + unicode?: boolean +} + +interface RemovedOptions { + format?: boolean + errorDataPath?: "object" | "property" + nullable?: boolean // "nullable" keyword is supported by default + jsonPointers?: boolean + extendRefs?: true | "ignore" | "fail" + missingRefs?: true | "ignore" | "fail" + processCode?: (code: string, schema?: SchemaEnv) => string + sourceCode?: boolean + strictDefaults?: boolean + strictKeywords?: boolean + uniqueItems?: boolean + unknownFormats?: true | string[] | "ignore" + cache?: any + serialize?: (schema: AnySchema) => unknown + ajvErrors?: boolean +} + +type OptionsInfo = { + [K in keyof T]-?: string | undefined +} + +const removedOptions: OptionsInfo = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now.", +} + +const deprecatedOptions: OptionsInfo = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.', +} + +type RequiredInstanceOptions = { + [K in + | "strictSchema" + | "strictNumbers" + | "strictTypes" + | "strictTuples" + | "strictRequired" + | "inlineRefs" + | "loopRequired" + | "loopEnum" + | "meta" + | "messages" + | "schemaId" + | "addUsedSchema" + | "validateSchema" + | "validateFormats" + | "int32range" + | "unicodeRegExp" + | "uriResolver"]: NonNullable +} & {code: InstanceCodeOptions} + +export type InstanceOptions = Options & RequiredInstanceOptions + +const MAX_EXPRESSION = 200 + +// eslint-disable-next-line complexity +function requiredOptions(o: Options): RequiredInstanceOptions { + const s = o.strict + const _optz = o.code?.optimize + const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0 + const regExp = o.code?.regExp ?? defaultRegExp + const uriResolver = o.uriResolver ?? DefaultUriResolver + return { + strictSchema: o.strictSchema ?? s ?? true, + strictNumbers: o.strictNumbers ?? s ?? true, + strictTypes: o.strictTypes ?? s ?? "log", + strictTuples: o.strictTuples ?? s ?? "log", + strictRequired: o.strictRequired ?? s ?? false, + code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp}, + loopRequired: o.loopRequired ?? MAX_EXPRESSION, + loopEnum: o.loopEnum ?? MAX_EXPRESSION, + meta: o.meta ?? true, + messages: o.messages ?? true, + inlineRefs: o.inlineRefs ?? true, + schemaId: o.schemaId ?? "$id", + addUsedSchema: o.addUsedSchema ?? true, + validateSchema: o.validateSchema ?? true, + validateFormats: o.validateFormats ?? true, + unicodeRegExp: o.unicodeRegExp ?? true, + int32range: o.int32range ?? true, + uriResolver: uriResolver, + } +} + +export interface Logger { + log(...args: unknown[]): unknown + warn(...args: unknown[]): unknown + error(...args: unknown[]): unknown +} + +export default class Ajv { + opts: InstanceOptions + errors?: ErrorObject[] | null // errors from the last validation + logger: Logger + // shared external scope values for compiled functions + readonly scope: ValueScope + readonly schemas: {[Key in string]?: SchemaEnv} = {} + readonly refs: {[Ref in string]?: SchemaEnv | string} = {} + readonly formats: {[Name in string]?: AddedFormat} = {} + readonly RULES: ValidationRules + readonly _compilations: Set = new Set() + private readonly _loading: {[Ref in string]?: Promise} = {} + private readonly _cache: Map = new Map() + private readonly _metaOpts: InstanceOptions + + static ValidationError = ValidationError + static MissingRefError = MissingRefError + + constructor(opts: Options = {}) { + opts = this.opts = {...opts, ...requiredOptions(opts)} + const {es5, lines} = this.opts.code + + this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines}) + this.logger = getLogger(opts.logger) + const formatOpt = opts.validateFormats + opts.validateFormats = false + + this.RULES = getRules() + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED") + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn") + this._metaOpts = getMetaSchemaOptions.call(this) + + if (opts.formats) addInitialFormats.call(this) + this._addVocabularies() + this._addDefaultMetaSchema() + if (opts.keywords) addInitialKeywords.call(this, opts.keywords) + if (typeof opts.meta == "object") this.addMetaSchema(opts.meta) + addInitialSchemas.call(this) + opts.validateFormats = formatOpt + } + + _addVocabularies(): void { + this.addKeyword("$async") + } + + _addDefaultMetaSchema(): void { + const {$data, meta, schemaId} = this.opts + let _dataRefSchema: SchemaObject = $dataRefSchema + if (schemaId === "id") { + _dataRefSchema = {...$dataRefSchema} + _dataRefSchema.id = _dataRefSchema.$id + delete _dataRefSchema.$id + } + if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false) + } + + defaultMeta(): string | AnySchemaObject | undefined { + const {meta, schemaId} = this.opts + return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined) + } + + // Validate data using schema + // AnySchema will be compiled and cached using schema itself as a key for Map + validate(schema: Schema | string, data: unknown): boolean + validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise + validate(schema: Schema | JSONSchemaType | string, data: unknown): data is T + // Separated for type inference to work + // eslint-disable-next-line @typescript-eslint/unified-signatures + validate(schema: JTDSchemaType, data: unknown): data is T + // This overload is only intended for typescript inference, the first + // argument prevents manual type annotation from matching this overload + // eslint-disable-next-line @typescript-eslint/no-unused-vars + validate( + schema: T, + data: unknown + ): data is JTDDataType + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents + validate(schema: AsyncSchema, data: unknown | T): Promise + validate(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise + validate( + schemaKeyRef: AnySchema | string, // key, ref or schema object + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents + data: unknown | T // to be validated + ): boolean | Promise { + let v: AnyValidateFunction | undefined + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef) + if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`) + } else { + v = this.compile(schemaKeyRef) + } + + const valid = v(data) + if (!("$async" in v)) this.errors = v.errors + return valid + } + + // Create validation function for passed schema + // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords. + compile(schema: Schema | JSONSchemaType, _meta?: boolean): ValidateFunction + // Separated for type inference to work + // eslint-disable-next-line @typescript-eslint/unified-signatures + compile(schema: JTDSchemaType, _meta?: boolean): ValidateFunction + // This overload is only intended for typescript inference, the first + // argument prevents manual type annotation from matching this overload + // eslint-disable-next-line @typescript-eslint/no-unused-vars + compile( + schema: T, + _meta?: boolean + ): ValidateFunction> + compile(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction + compile(schema: AnySchema, _meta?: boolean): AnyValidateFunction + compile(schema: AnySchema, _meta?: boolean): AnyValidateFunction { + const sch = this._addSchema(schema, _meta) + return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction + } + + // Creates validating function for passed schema with asynchronous loading of missing schemas. + // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. + // TODO allow passing schema URI + // meta - optional true to compile meta-schema + compileAsync( + schema: SchemaObject | JSONSchemaType, + _meta?: boolean + ): Promise> + // Separated for type inference to work + // eslint-disable-next-line @typescript-eslint/unified-signatures + compileAsync(schema: JTDSchemaType, _meta?: boolean): Promise> + compileAsync(schema: AsyncSchema, meta?: boolean): Promise> + // eslint-disable-next-line @typescript-eslint/unified-signatures + compileAsync( + schema: AnySchemaObject, + meta?: boolean + ): Promise> + compileAsync( + schema: AnySchemaObject, + meta?: boolean + ): Promise> { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function") + } + const {loadSchema} = this.opts + return runCompileAsync.call(this, schema, meta) + + async function runCompileAsync( + this: Ajv, + _schema: AnySchemaObject, + _meta?: boolean + ): Promise { + await loadMetaSchema.call(this, _schema.$schema) + const sch = this._addSchema(_schema, _meta) + return sch.validate || _compileAsync.call(this, sch) + } + + async function loadMetaSchema(this: Ajv, $ref?: string): Promise { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, {$ref}, true) + } + } + + async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise { + try { + return this._compileSchemaEnv(sch) + } catch (e) { + if (!(e instanceof MissingRefError)) throw e + checkLoaded.call(this, e) + await loadMissingSchema.call(this, e.missingSchema) + return _compileAsync.call(this, sch) + } + } + + function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`) + } + } + + async function loadMissingSchema(this: Ajv, ref: string): Promise { + const _schema = await _loadSchema.call(this, ref) + if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema) + if (!this.refs[ref]) this.addSchema(_schema, ref, meta) + } + + async function _loadSchema(this: Ajv, ref: string): Promise { + const p = this._loading[ref] + if (p) return p + try { + return await (this._loading[ref] = loadSchema(ref)) + } finally { + delete this._loading[ref] + } + } + } + + // Adds schema to the instance + addSchema( + schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored + key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead. + ): Ajv { + if (Array.isArray(schema)) { + for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema) + return this + } + let id: string | undefined + if (typeof schema === "object") { + const {schemaId} = this.opts + id = schema[schemaId] + if (id !== undefined && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`) + } + } + key = normalizeId(key || id) + this._checkUnique(key) + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true) + return this + } + + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema( + schema: AnySchemaObject, + key?: string, // schema key + _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema + ): Ajv { + this.addSchema(schema, key, true, _validateSchema) + return this + } + + // Validate schema against its meta-schema + validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise { + if (typeof schema == "boolean") return true + let $schema: string | AnySchemaObject | undefined + $schema = schema.$schema + if ($schema !== undefined && typeof $schema != "string") { + throw new Error("$schema must be a string") + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta() + if (!$schema) { + this.logger.warn("meta-schema not available") + this.errors = null + return true + } + const valid = this.validate($schema, schema) + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText() + if (this.opts.validateSchema === "log") this.logger.error(message) + else throw new Error(message) + } + return valid + } + + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef: string): AnyValidateFunction | undefined { + let sch + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch + if (sch === undefined) { + const {schemaId} = this.opts + const root = new SchemaEnv({schema: {}, schemaId}) + sch = resolveSchema.call(this, root, keyRef) + if (!sch) return + this.refs[keyRef] = sch + } + return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction | undefined + } + + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef) + this._removeAllSchemas(this.refs, schemaKeyRef) + return this + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas) + this._removeAllSchemas(this.refs) + this._cache.clear() + return this + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef) + if (typeof sch == "object") this._cache.delete(sch.schema) + delete this.schemas[schemaKeyRef] + delete this.refs[schemaKeyRef] + return this + } + case "object": { + const cacheKey = schemaKeyRef + this._cache.delete(cacheKey) + let id = schemaKeyRef[this.opts.schemaId] + if (id) { + id = normalizeId(id) + delete this.schemas[id] + delete this.refs[id] + } + return this + } + default: + throw new Error("ajv.removeSchema: invalid parameter") + } + } + + // add "vocabulary" - a collection of keywords + addVocabulary(definitions: Vocabulary): Ajv { + for (const def of definitions) this.addKeyword(def) + return this + } + + addKeyword( + kwdOrDef: string | KeywordDefinition, + def?: KeywordDefinition // deprecated + ): Ajv { + let keyword: string | string[] + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword") + def.keyword = keyword + } + } else if (typeof kwdOrDef == "object" && def === undefined) { + def = kwdOrDef + keyword = def.keyword + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array") + } + } else { + throw new Error("invalid addKeywords parameters") + } + + checkKeyword.call(this, keyword, def) + if (!def) { + eachItem(keyword, (kwd) => addRule.call(this, kwd)) + return this + } + keywordMetaschema.call(this, def) + const definition: AddedKeywordDefinition = { + ...def, + type: getJSONTypes(def.type), + schemaType: getJSONTypes(def.schemaType), + } + eachItem( + keyword, + definition.type.length === 0 + ? (k) => addRule.call(this, k, definition) + : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)) + ) + return this + } + + getKeyword(keyword: string): AddedKeywordDefinition | boolean { + const rule = this.RULES.all[keyword] + return typeof rule == "object" ? rule.definition : !!rule + } + + // Remove keyword + removeKeyword(keyword: string): Ajv { + // TODO return type should be Ajv + const {RULES} = this + delete RULES.keywords[keyword] + delete RULES.all[keyword] + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword) + if (i >= 0) group.rules.splice(i, 1) + } + return this + } + + // Add format + addFormat(name: string, format: Format): Ajv { + if (typeof format == "string") format = new RegExp(format) + this.formats[name] = format + return this + } + + errorsText( + errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors + {separator = ", ", dataVar = "data"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar` + ): string { + if (!errors || errors.length === 0) return "No errors" + return errors + .map((e) => `${dataVar}${e.instancePath} ${e.message}`) + .reduce((text, msg) => text + separator + msg) + } + + $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject { + const rules = this.RULES.all + metaSchema = JSON.parse(JSON.stringify(metaSchema)) + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1) // first segment is an empty string + let keywords = metaSchema + for (const seg of segments) keywords = keywords[seg] as AnySchemaObject + + for (const key in rules) { + const rule = rules[key] + if (typeof rule != "object") continue + const {$data} = rule.definition + const schema = keywords[key] as AnySchemaObject | undefined + if ($data && schema) keywords[key] = schemaOrData(schema) + } + } + + return metaSchema + } + + private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void { + for (const keyRef in schemas) { + const sch = schemas[keyRef] + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef] + } else if (sch && !sch.meta) { + this._cache.delete(sch.schema) + delete schemas[keyRef] + } + } + } + } + + _addSchema( + schema: AnySchema, + meta?: boolean, + baseId?: string, + validateSchema = this.opts.validateSchema, + addSchema = this.opts.addUsedSchema + ): SchemaEnv { + let id: string | undefined + const {schemaId} = this.opts + if (typeof schema == "object") { + id = schema[schemaId] + } else { + if (this.opts.jtd) throw new Error("schema must be object") + else if (typeof schema != "boolean") throw new Error("schema must be object or boolean") + } + let sch = this._cache.get(schema) + if (sch !== undefined) return sch + + baseId = normalizeId(id || baseId) + const localRefs = getSchemaRefs.call(this, schema, baseId) + sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs}) + this._cache.set(sch.schema, sch) + if (addSchema && !baseId.startsWith("#")) { + // TODO atm it is allowed to overwrite schemas without id (instead of not adding them) + if (baseId) this._checkUnique(baseId) + this.refs[baseId] = sch + } + if (validateSchema) this.validateSchema(schema, true) + return sch + } + + private _checkUnique(id: string): void { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`) + } + } + + private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction { + if (sch.meta) this._compileMetaSchema(sch) + else compileSchema.call(this, sch) + + /* istanbul ignore if */ + if (!sch.validate) throw new Error("ajv implementation error") + return sch.validate + } + + private _compileMetaSchema(sch: SchemaEnv): void { + const currentOpts = this.opts + this.opts = this._metaOpts + try { + compileSchema.call(this, sch) + } finally { + this.opts = currentOpts + } + } +} + +export interface ErrorsTextOptions { + separator?: string + dataVar?: string +} + +function checkOptions( + this: Ajv, + checkOpts: OptionsInfo, + options: Options & RemovedOptions, + msg: string, + log: "warn" | "error" = "error" +): void { + for (const key in checkOpts) { + const opt = key as keyof typeof checkOpts + if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`) + } +} + +function getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined { + keyRef = normalizeId(keyRef) // TODO tests fail without this line + return this.schemas[keyRef] || this.refs[keyRef] +} + +function addInitialSchemas(this: Ajv): void { + const optsSchemas = this.opts.schemas + if (!optsSchemas) return + if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas) + else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key) +} + +function addInitialFormats(this: Ajv): void { + for (const name in this.opts.formats) { + const format = this.opts.formats[name] + if (format) this.addFormat(name, format) + } +} + +function addInitialKeywords( + this: Ajv, + defs: Vocabulary | {[K in string]?: KeywordDefinition} +): void { + if (Array.isArray(defs)) { + this.addVocabulary(defs) + return + } + this.logger.warn("keywords option as map is deprecated, pass array") + for (const keyword in defs) { + const def = defs[keyword] as KeywordDefinition + if (!def.keyword) def.keyword = keyword + this.addKeyword(def) + } +} + +function getMetaSchemaOptions(this: Ajv): InstanceOptions { + const metaOpts = {...this.opts} + for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt] + return metaOpts +} + +const noLogs = {log() {}, warn() {}, error() {}} + +function getLogger(logger?: Partial | false): Logger { + if (logger === false) return noLogs + if (logger === undefined) return console + if (logger.log && logger.warn && logger.error) return logger as Logger + throw new Error("logger must implement log, warn and error methods") +} + +const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i + +function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void { + const {RULES} = this + eachItem(keyword, (kwd) => { + if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`) + if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`) + }) + if (!def) return + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function') + } +} + +function addRule( + this: Ajv, + keyword: string, + definition?: AddedKeywordDefinition, + dataType?: JSONType +): void { + const post = definition?.post + if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"') + const {RULES} = this + let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType) + if (!ruleGroup) { + ruleGroup = {type: dataType, rules: []} + RULES.rules.push(ruleGroup) + } + RULES.keywords[keyword] = true + if (!definition) return + + const rule: Rule = { + keyword, + definition: { + ...definition, + type: getJSONTypes(definition.type), + schemaType: getJSONTypes(definition.schemaType), + }, + } + if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before) + else ruleGroup.rules.push(rule) + RULES.all[keyword] = rule + definition.implements?.forEach((kwd) => this.addKeyword(kwd)) +} + +function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before) + if (i >= 0) { + ruleGroup.rules.splice(i, 0, rule) + } else { + ruleGroup.rules.push(rule) + this.logger.warn(`rule ${before} is not defined`) + } +} + +function keywordMetaschema(this: Ajv, def: KeywordDefinition): void { + let {metaSchema} = def + if (metaSchema === undefined) return + if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema) + def.validateSchema = this.compile(metaSchema, true) +} + +const $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", +} + +function schemaOrData(schema: AnySchema): AnySchemaObject { + return {anyOf: [schema, $dataRef]} +} diff --git a/node_modules/ajv/lib/jtd.ts b/node_modules/ajv/lib/jtd.ts new file mode 100644 index 000000000..a7e7bce3b --- /dev/null +++ b/node_modules/ajv/lib/jtd.ts @@ -0,0 +1,132 @@ +import type {AnySchemaObject, SchemaObject, JTDParser} from "./types" +import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema" +import AjvCore, {CurrentOptions} from "./core" +import jtdVocabulary from "./vocabularies/jtd" +import jtdMetaSchema from "./refs/jtd-schema" +import compileSerializer from "./compile/jtd/serialize" +import compileParser from "./compile/jtd/parse" +import {SchemaEnv} from "./compile" + +const META_SCHEMA_ID = "JTD-meta-schema" + +type JTDOptions = CurrentOptions & { + // strict mode options not supported with JTD: + strict?: never + allowMatchingProperties?: never + allowUnionTypes?: never + validateFormats?: never + // validation and reporting options not supported with JTD: + $data?: never + verbose?: boolean + $comment?: never + formats?: never + loadSchema?: never + // options to modify validated data: + useDefaults?: never + coerceTypes?: never + // advanced options: + next?: never + unevaluated?: never + dynamicRef?: never + meta?: boolean + defaultMeta?: never + inlineRefs?: boolean + loopRequired?: never + multipleOfPrecision?: never +} + +export class Ajv extends AjvCore { + constructor(opts: JTDOptions = {}) { + super({ + ...opts, + jtd: true, + }) + } + + _addVocabularies(): void { + super._addVocabularies() + this.addVocabulary(jtdVocabulary) + } + + _addDefaultMetaSchema(): void { + super._addDefaultMetaSchema() + if (!this.opts.meta) return + this.addMetaSchema(jtdMetaSchema, META_SCHEMA_ID, false) + } + + defaultMeta(): string | AnySchemaObject | undefined { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) + } + + compileSerializer(schema: SchemaObject): (data: T) => string + // Separated for type inference to work + // eslint-disable-next-line @typescript-eslint/unified-signatures + compileSerializer(schema: JTDSchemaType): (data: T) => string + compileSerializer(schema: SchemaObject): (data: T) => string { + const sch = this._addSchema(schema) + return sch.serialize || this._compileSerializer(sch) + } + + compileParser(schema: SchemaObject): JTDParser + // Separated for type inference to work + // eslint-disable-next-line @typescript-eslint/unified-signatures + compileParser(schema: JTDSchemaType): JTDParser + compileParser(schema: SchemaObject): JTDParser { + const sch = this._addSchema(schema) + return (sch.parse || this._compileParser(sch)) as JTDParser + } + + private _compileSerializer(sch: SchemaEnv): (data: T) => string { + compileSerializer.call(this, sch, (sch.schema as AnySchemaObject).definitions || {}) + /* istanbul ignore if */ + if (!sch.serialize) throw new Error("ajv implementation error") + return sch.serialize + } + + private _compileParser(sch: SchemaEnv): JTDParser { + compileParser.call(this, sch, (sch.schema as AnySchemaObject).definitions || {}) + /* istanbul ignore if */ + if (!sch.parse) throw new Error("ajv implementation error") + return sch.parse + } +} + +module.exports = exports = Ajv +module.exports.Ajv = Ajv +Object.defineProperty(exports, "__esModule", {value: true}) + +export default Ajv + +export { + Format, + FormatDefinition, + AsyncFormatDefinition, + KeywordDefinition, + KeywordErrorDefinition, + CodeKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, + Vocabulary, + Schema, + SchemaObject, + AnySchemaObject, + AsyncSchema, + AnySchema, + ValidateFunction, + AsyncValidateFunction, + ErrorObject, + ErrorNoParams, + JTDParser, +} from "./types" + +export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core" +export {SchemaCxt, SchemaObjCxt} from "./compile" +export {KeywordCxt} from "./compile/validate" +export {JTDErrorObject} from "./vocabularies/jtd" +export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" + +export {JTDSchemaType, SomeJTDSchemaType, JTDDataType} +export {JTDOptions} +export {default as ValidationError} from "./runtime/validation_error" +export {default as MissingRefError} from "./compile/ref_error" diff --git a/node_modules/ajv/lib/refs/data.json b/node_modules/ajv/lib/refs/data.json new file mode 100644 index 000000000..9ffc9f5ce --- /dev/null +++ b/node_modules/ajv/lib/refs/data.json @@ -0,0 +1,13 @@ +{ + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", + "type": "object", + "required": ["$data"], + "properties": { + "$data": { + "type": "string", + "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}] + } + }, + "additionalProperties": false +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts b/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts new file mode 100644 index 000000000..b6ea7195f --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts @@ -0,0 +1,28 @@ +import type Ajv from "../../core" +import type {AnySchemaObject} from "../../types" +import * as metaSchema from "./schema.json" +import * as applicator from "./meta/applicator.json" +import * as content from "./meta/content.json" +import * as core from "./meta/core.json" +import * as format from "./meta/format.json" +import * as metadata from "./meta/meta-data.json" +import * as validation from "./meta/validation.json" + +const META_SUPPORT_DATA = ["/properties"] + +export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv { + ;[ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) + return this + + function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/meta/applicator.json b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/applicator.json new file mode 100644 index 000000000..c5e91cf2a --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/applicator.json @@ -0,0 +1,53 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/applicator": true + }, + "$recursiveAnchor": true, + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "additionalItems": {"$recursiveRef": "#"}, + "unevaluatedItems": {"$recursiveRef": "#"}, + "items": { + "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}] + }, + "contains": {"$recursiveRef": "#"}, + "additionalProperties": {"$recursiveRef": "#"}, + "unevaluatedProperties": {"$recursiveRef": "#"}, + "properties": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { + "$recursiveRef": "#" + } + }, + "propertyNames": {"$recursiveRef": "#"}, + "if": {"$recursiveRef": "#"}, + "then": {"$recursiveRef": "#"}, + "else": {"$recursiveRef": "#"}, + "allOf": {"$ref": "#/$defs/schemaArray"}, + "anyOf": {"$ref": "#/$defs/schemaArray"}, + "oneOf": {"$ref": "#/$defs/schemaArray"}, + "not": {"$recursiveRef": "#"} + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$recursiveRef": "#"} + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/meta/content.json b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/content.json new file mode 100644 index 000000000..b8f637343 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/content.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentMediaType": {"type": "string"}, + "contentEncoding": {"type": "string"}, + "contentSchema": {"$recursiveRef": "#"} + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/meta/core.json b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/core.json new file mode 100644 index 000000000..f71adbff0 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/core.json @@ -0,0 +1,57 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true + }, + "$recursiveAnchor": true, + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$anchor": { + "type": "string", + "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveRef": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveAnchor": { + "type": "boolean", + "default": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/meta/format.json b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/format.json new file mode 100644 index 000000000..03ccfce26 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/format.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/format", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/format": true + }, + "$recursiveAnchor": true, + + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "format": {"type": "string"} + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/meta/meta-data.json b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/meta-data.json new file mode 100644 index 000000000..0e194326f --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/meta-data.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/meta-data": true + }, + "$recursiveAnchor": true, + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/meta/validation.json b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/validation.json new file mode 100644 index 000000000..7027a1279 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/validation.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/validation": true + }, + "$recursiveAnchor": true, + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, + "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, + "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, + "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/$defs/stringArray"}, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "type": { + "anyOf": [ + {"$ref": "#/$defs/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/$defs/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/schema.json b/node_modules/ajv/lib/refs/json-schema-2019-09/schema.json new file mode 100644 index 000000000..54eb7157a --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/schema.json @@ -0,0 +1,39 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", + "type": "object", + "additionalProperties": { + "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}] + } + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts b/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts new file mode 100644 index 000000000..8e850d08b --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts @@ -0,0 +1,30 @@ +import type Ajv from "../../core" +import type {AnySchemaObject} from "../../types" +import * as metaSchema from "./schema.json" +import * as applicator from "./meta/applicator.json" +import * as unevaluated from "./meta/unevaluated.json" +import * as content from "./meta/content.json" +import * as core from "./meta/core.json" +import * as format from "./meta/format-annotation.json" +import * as metadata from "./meta/meta-data.json" +import * as validation from "./meta/validation.json" + +const META_SUPPORT_DATA = ["/properties"] + +export default function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv { + ;[ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) + return this + + function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/applicator.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/applicator.json new file mode 100644 index 000000000..674c913da --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/applicator.json @@ -0,0 +1,48 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/applicator": true + }, + "$dynamicAnchor": "meta", + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "prefixItems": {"$ref": "#/$defs/schemaArray"}, + "items": {"$dynamicRef": "#meta"}, + "contains": {"$dynamicRef": "#meta"}, + "additionalProperties": {"$dynamicRef": "#meta"}, + "properties": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "default": {} + }, + "propertyNames": {"$dynamicRef": "#meta"}, + "if": {"$dynamicRef": "#meta"}, + "then": {"$dynamicRef": "#meta"}, + "else": {"$dynamicRef": "#meta"}, + "allOf": {"$ref": "#/$defs/schemaArray"}, + "anyOf": {"$ref": "#/$defs/schemaArray"}, + "oneOf": {"$ref": "#/$defs/schemaArray"}, + "not": {"$dynamicRef": "#meta"} + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$dynamicRef": "#meta"} + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/content.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/content.json new file mode 100644 index 000000000..2ae23ddb5 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/content.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentEncoding": {"type": "string"}, + "contentMediaType": {"type": "string"}, + "contentSchema": {"$dynamicRef": "#meta"} + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/core.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/core.json new file mode 100644 index 000000000..4c8e5cb61 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/core.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true + }, + "$dynamicAnchor": "meta", + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "$ref": "#/$defs/uriReferenceString", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": {"$ref": "#/$defs/uriString"}, + "$ref": {"$ref": "#/$defs/uriReferenceString"}, + "$anchor": {"$ref": "#/$defs/anchorString"}, + "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"}, + "$dynamicAnchor": {"$ref": "#/$defs/anchorString"}, + "$vocabulary": { + "type": "object", + "propertyNames": {"$ref": "#/$defs/uriString"}, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"} + } + }, + "$defs": { + "anchorString": { + "type": "string", + "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "uriReferenceString": { + "type": "string", + "format": "uri-reference" + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/format-annotation.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/format-annotation.json new file mode 100644 index 000000000..83c26e35f --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/format-annotation.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true + }, + "$dynamicAnchor": "meta", + + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { + "format": {"type": "string"} + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/meta-data.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/meta-data.json new file mode 100644 index 000000000..11946fb50 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/meta-data.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/meta-data": true + }, + "$dynamicAnchor": "meta", + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/unevaluated.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/unevaluated.json new file mode 100644 index 000000000..5e4b203b2 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/unevaluated.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true + }, + "$dynamicAnchor": "meta", + + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": {"$dynamicRef": "#meta"}, + "unevaluatedProperties": {"$dynamicRef": "#meta"} + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/validation.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/validation.json new file mode 100644 index 000000000..e0ae13d9d --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/validation.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/validation": true + }, + "$dynamicAnchor": "meta", + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "type": { + "anyOf": [ + {"$ref": "#/$defs/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/$defs/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, + "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, + "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, + "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/$defs/stringArray"}, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/schema.json b/node_modules/ajv/lib/refs/json-schema-2020-12/schema.json new file mode 100644 index 000000000..1c68270fd --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/schema.json @@ -0,0 +1,55 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/unevaluated"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format-annotation"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", + "properties": { + "definitions": { + "$comment": "\"definitions\" has been replaced by \"$defs\".", + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "deprecated": true, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", + "type": "object", + "additionalProperties": { + "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}] + }, + "deprecated": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-draft-06.json b/node_modules/ajv/lib/refs/json-schema-draft-06.json new file mode 100644 index 000000000..5410064ba --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-draft-06.json @@ -0,0 +1,137 @@ +{ + "$schema": "http://json-schema.org/draft-06/schema#", + "$id": "http://json-schema.org/draft-06/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "examples": { + "type": "array", + "items": {} + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, + "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": {"$ref": "#"}, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], + "default": {} + }, + "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, + "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": {"$ref": "#"}, + "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, + "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/definitions/stringArray"}, + "additionalProperties": {"$ref": "#"}, + "definitions": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] + } + }, + "propertyNames": {"$ref": "#"}, + "const": {}, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + {"$ref": "#/definitions/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/definitions/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": {"type": "string"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"} + }, + "default": {} +} diff --git a/node_modules/ajv/lib/refs/json-schema-draft-07.json b/node_modules/ajv/lib/refs/json-schema-draft-07.json new file mode 100644 index 000000000..6a7485104 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-draft-07.json @@ -0,0 +1,151 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, + "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": {"$ref": "#"}, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], + "default": true + }, + "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, + "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": {"$ref": "#"}, + "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, + "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/definitions/stringArray"}, + "additionalProperties": {"$ref": "#"}, + "definitions": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] + } + }, + "propertyNames": {"$ref": "#"}, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + {"$ref": "#/definitions/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/definitions/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": {"type": "string"}, + "contentMediaType": {"type": "string"}, + "contentEncoding": {"type": "string"}, + "if": {"$ref": "#"}, + "then": {"$ref": "#"}, + "else": {"$ref": "#"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"} + }, + "default": true +} diff --git a/node_modules/ajv/lib/refs/json-schema-secure.json b/node_modules/ajv/lib/refs/json-schema-secure.json new file mode 100644 index 000000000..3968abd5d --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-secure.json @@ -0,0 +1,88 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#", + "title": "Meta-schema for the security assessment of JSON Schemas", + "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + } + }, + "dependencies": { + "patternProperties": { + "description": "prevent slow validation of large property names", + "required": ["propertyNames"], + "properties": { + "propertyNames": { + "required": ["maxLength"] + } + } + }, + "uniqueItems": { + "description": "prevent slow validation of large non-scalar arrays", + "if": { + "properties": { + "uniqueItems": {"const": true}, + "items": { + "properties": { + "type": { + "anyOf": [ + { + "enum": ["object", "array"] + }, + { + "type": "array", + "contains": {"enum": ["object", "array"]} + } + ] + } + } + } + } + }, + "then": { + "required": ["maxItems"] + } + }, + "pattern": { + "description": "prevent slow pattern matching of large strings", + "required": ["maxLength"] + }, + "format": { + "description": "prevent slow format validation of large strings", + "required": ["maxLength"] + } + }, + "properties": { + "additionalItems": {"$ref": "#"}, + "additionalProperties": {"$ref": "#"}, + "dependencies": { + "additionalProperties": { + "anyOf": [{"type": "array"}, {"$ref": "#"}] + } + }, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}] + }, + "definitions": { + "additionalProperties": {"$ref": "#"} + }, + "patternProperties": { + "additionalProperties": {"$ref": "#"} + }, + "properties": { + "additionalProperties": {"$ref": "#"} + }, + "if": {"$ref": "#"}, + "then": {"$ref": "#"}, + "else": {"$ref": "#"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"}, + "contains": {"$ref": "#"}, + "propertyNames": {"$ref": "#"} + } +} diff --git a/node_modules/ajv/lib/refs/jtd-schema.ts b/node_modules/ajv/lib/refs/jtd-schema.ts new file mode 100644 index 000000000..c01981289 --- /dev/null +++ b/node_modules/ajv/lib/refs/jtd-schema.ts @@ -0,0 +1,130 @@ +import {SchemaObject} from "../types" + +type MetaSchema = (root: boolean) => SchemaObject + +const shared: MetaSchema = (root) => { + const sch: SchemaObject = { + nullable: {type: "boolean"}, + metadata: { + optionalProperties: { + union: {elements: {ref: "schema"}}, + }, + additionalProperties: true, + }, + } + if (root) sch.definitions = {values: {ref: "schema"}} + return sch +} + +const emptyForm: MetaSchema = (root) => ({ + optionalProperties: shared(root), +}) + +const refForm: MetaSchema = (root) => ({ + properties: { + ref: {type: "string"}, + }, + optionalProperties: shared(root), +}) + +const typeForm: MetaSchema = (root) => ({ + properties: { + type: { + enum: [ + "boolean", + "timestamp", + "string", + "float32", + "float64", + "int8", + "uint8", + "int16", + "uint16", + "int32", + "uint32", + ], + }, + }, + optionalProperties: shared(root), +}) + +const enumForm: MetaSchema = (root) => ({ + properties: { + enum: {elements: {type: "string"}}, + }, + optionalProperties: shared(root), +}) + +const elementsForm: MetaSchema = (root) => ({ + properties: { + elements: {ref: "schema"}, + }, + optionalProperties: shared(root), +}) + +const propertiesForm: MetaSchema = (root) => ({ + properties: { + properties: {values: {ref: "schema"}}, + }, + optionalProperties: { + optionalProperties: {values: {ref: "schema"}}, + additionalProperties: {type: "boolean"}, + ...shared(root), + }, +}) + +const optionalPropertiesForm: MetaSchema = (root) => ({ + properties: { + optionalProperties: {values: {ref: "schema"}}, + }, + optionalProperties: { + additionalProperties: {type: "boolean"}, + ...shared(root), + }, +}) + +const discriminatorForm: MetaSchema = (root) => ({ + properties: { + discriminator: {type: "string"}, + mapping: { + values: { + metadata: { + union: [propertiesForm(false), optionalPropertiesForm(false)], + }, + }, + }, + }, + optionalProperties: shared(root), +}) + +const valuesForm: MetaSchema = (root) => ({ + properties: { + values: {ref: "schema"}, + }, + optionalProperties: shared(root), +}) + +const schema: MetaSchema = (root) => ({ + metadata: { + union: [ + emptyForm, + refForm, + typeForm, + enumForm, + elementsForm, + propertiesForm, + optionalPropertiesForm, + discriminatorForm, + valuesForm, + ].map((s) => s(root)), + }, +}) + +const jtdMetaSchema: SchemaObject = { + definitions: { + schema: schema(false), + }, + ...schema(true), +} + +export default jtdMetaSchema diff --git a/node_modules/ajv/lib/runtime/equal.ts b/node_modules/ajv/lib/runtime/equal.ts new file mode 100644 index 000000000..3cb00631a --- /dev/null +++ b/node_modules/ajv/lib/runtime/equal.ts @@ -0,0 +1,7 @@ +// https://github.com/ajv-validator/ajv/issues/889 +import * as equal from "fast-deep-equal" + +type Equal = typeof equal & {code: string} +;(equal as Equal).code = 'require("ajv/dist/runtime/equal").default' + +export default equal as Equal diff --git a/node_modules/ajv/lib/runtime/parseJson.ts b/node_modules/ajv/lib/runtime/parseJson.ts new file mode 100644 index 000000000..472e5e507 --- /dev/null +++ b/node_modules/ajv/lib/runtime/parseJson.ts @@ -0,0 +1,177 @@ +const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/ + +export function parseJson(s: string, pos: number): unknown { + let endPos: number | undefined + parseJson.message = undefined + let matches: RegExpExecArray | null + if (pos) s = s.slice(pos) + try { + parseJson.position = pos + s.length + return JSON.parse(s) + } catch (e) { + matches = rxParseJson.exec((e as Error).message) + if (!matches) { + parseJson.message = "unexpected end" + return undefined + } + endPos = +matches[1] + const c = s[endPos] + s = s.slice(0, endPos) + parseJson.position = pos + endPos + try { + return JSON.parse(s) + } catch (e1) { + parseJson.message = `unexpected token ${c}` + return undefined + } + } +} + +parseJson.message = undefined as string | undefined +parseJson.position = 0 as number +parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson' + +export function parseJsonNumber(s: string, pos: number, maxDigits?: number): number | undefined { + let numStr = "" + let c: string + parseJsonNumber.message = undefined + if (s[pos] === "-") { + numStr += "-" + pos++ + } + if (s[pos] === "0") { + numStr += "0" + pos++ + } else { + if (!parseDigits(maxDigits)) { + errorMessage() + return undefined + } + } + if (maxDigits) { + parseJsonNumber.position = pos + return +numStr + } + if (s[pos] === ".") { + numStr += "." + pos++ + if (!parseDigits()) { + errorMessage() + return undefined + } + } + if (((c = s[pos]), c === "e" || c === "E")) { + numStr += "e" + pos++ + if (((c = s[pos]), c === "+" || c === "-")) { + numStr += c + pos++ + } + if (!parseDigits()) { + errorMessage() + return undefined + } + } + parseJsonNumber.position = pos + return +numStr + + function parseDigits(maxLen?: number): boolean { + let digit = false + while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) { + digit = true + numStr += c + pos++ + } + return digit + } + + function errorMessage(): void { + parseJsonNumber.position = pos + parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end" + } +} + +parseJsonNumber.message = undefined as string | undefined +parseJsonNumber.position = 0 as number +parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber' + +const escapedChars: {[X in string]?: string} = { + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t", + '"': '"', + "/": "/", + "\\": "\\", +} + +const CODE_A: number = "a".charCodeAt(0) +const CODE_0: number = "0".charCodeAt(0) + +export function parseJsonString(s: string, pos: number): string | undefined { + let str = "" + let c: string | undefined + parseJsonString.message = undefined + // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition + while (true) { + c = s[pos++] + if (c === '"') break + if (c === "\\") { + c = s[pos] + if (c in escapedChars) { + str += escapedChars[c] + pos++ + } else if (c === "u") { + pos++ + let count = 4 + let code = 0 + while (count--) { + code <<= 4 + c = s[pos] + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (c === undefined) { + errorMessage("unexpected end") + return undefined + } + c = c.toLowerCase() + if (c >= "a" && c <= "f") { + code += c.charCodeAt(0) - CODE_A + 10 + } else if (c >= "0" && c <= "9") { + code += c.charCodeAt(0) - CODE_0 + } else { + errorMessage(`unexpected token ${c}`) + return undefined + } + pos++ + } + str += String.fromCharCode(code) + } else { + errorMessage(`unexpected token ${c}`) + return undefined + } + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + } else if (c === undefined) { + errorMessage("unexpected end") + return undefined + } else { + if (c.charCodeAt(0) >= 0x20) { + str += c + } else { + errorMessage(`unexpected token ${c}`) + return undefined + } + } + } + parseJsonString.position = pos + return str + + function errorMessage(msg: string): void { + parseJsonString.position = pos + parseJsonString.message = msg + } +} + +parseJsonString.message = undefined as string | undefined +parseJsonString.position = 0 as number +parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString' diff --git a/node_modules/ajv/lib/runtime/quote.ts b/node_modules/ajv/lib/runtime/quote.ts new file mode 100644 index 000000000..1160e6a23 --- /dev/null +++ b/node_modules/ajv/lib/runtime/quote.ts @@ -0,0 +1,31 @@ +const rxEscapable = + // eslint-disable-next-line no-control-regex, no-misleading-character-class + /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g + +const escaped: {[K in string]?: string} = { + "\b": "\\b", + "\t": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + '"': '\\"', + "\\": "\\\\", +} + +export default function quote(s: string): string { + rxEscapable.lastIndex = 0 + return ( + '"' + + (rxEscapable.test(s) + ? s.replace(rxEscapable, (a) => { + const c = escaped[a] + return typeof c === "string" + ? c + : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4) + }) + : s) + + '"' + ) +} + +quote.code = 'require("ajv/dist/runtime/quote").default' diff --git a/node_modules/ajv/lib/runtime/re2.ts b/node_modules/ajv/lib/runtime/re2.ts new file mode 100644 index 000000000..0c769bc7a --- /dev/null +++ b/node_modules/ajv/lib/runtime/re2.ts @@ -0,0 +1,6 @@ +import * as re2 from "re2" + +type Re2 = typeof re2 & {code: string} +;(re2 as Re2).code = 'require("ajv/dist/runtime/re2").default' + +export default re2 as Re2 diff --git a/node_modules/ajv/lib/runtime/timestamp.ts b/node_modules/ajv/lib/runtime/timestamp.ts new file mode 100644 index 000000000..1625f9a40 --- /dev/null +++ b/node_modules/ajv/lib/runtime/timestamp.ts @@ -0,0 +1,46 @@ +const DT_SEPARATOR = /t|\s/i +const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/ +const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i +const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + +export default function validTimestamp(str: string, allowDate: boolean): boolean { + // http://tools.ietf.org/html/rfc3339#section-5.6 + const dt: string[] = str.split(DT_SEPARATOR) + return ( + (dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) || + (allowDate && dt.length === 1 && validDate(dt[0])) + ) +} + +function validDate(str: string): boolean { + const matches: string[] | null = DATE.exec(str) + if (!matches) return false + const y: number = +matches[1] + const m: number = +matches[2] + const d: number = +matches[3] + return ( + m >= 1 && + m <= 12 && + d >= 1 && + (d <= DAYS[m] || + // leap year: https://tools.ietf.org/html/rfc3339#appendix-C + (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0))) + ) +} + +function validTime(str: string): boolean { + const matches: string[] | null = TIME.exec(str) + if (!matches) return false + const hr: number = +matches[1] + const min: number = +matches[2] + const sec: number = +matches[3] + const tzH: number = +(matches[4] || 0) + const tzM: number = +(matches[5] || 0) + return ( + (hr <= 23 && min <= 59 && sec <= 59) || + // leap second + (hr - tzH === 23 && min - tzM === 59 && sec === 60) + ) +} + +validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default' diff --git a/node_modules/ajv/lib/runtime/ucs2length.ts b/node_modules/ajv/lib/runtime/ucs2length.ts new file mode 100644 index 000000000..47d8292b8 --- /dev/null +++ b/node_modules/ajv/lib/runtime/ucs2length.ts @@ -0,0 +1,20 @@ +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode +export default function ucs2length(str: string): number { + const len = str.length + let length = 0 + let pos = 0 + let value: number + while (pos < len) { + length++ + value = str.charCodeAt(pos++) + if (value >= 0xd800 && value <= 0xdbff && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos) + if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate + } + } + return length +} + +ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default' diff --git a/node_modules/ajv/lib/runtime/uri.ts b/node_modules/ajv/lib/runtime/uri.ts new file mode 100644 index 000000000..5450549cd --- /dev/null +++ b/node_modules/ajv/lib/runtime/uri.ts @@ -0,0 +1,6 @@ +import * as uri from "fast-uri" + +type URI = typeof uri & {code: string} +;(uri as URI).code = 'require("ajv/dist/runtime/uri").default' + +export default uri as URI diff --git a/node_modules/ajv/lib/runtime/validation_error.ts b/node_modules/ajv/lib/runtime/validation_error.ts new file mode 100644 index 000000000..2d19a46a2 --- /dev/null +++ b/node_modules/ajv/lib/runtime/validation_error.ts @@ -0,0 +1,13 @@ +import type {ErrorObject} from "../types" + +export default class ValidationError extends Error { + readonly errors: Partial[] + readonly ajv: true + readonly validation: true + + constructor(errors: Partial[]) { + super("validation failed") + this.errors = errors + this.ajv = this.validation = true + } +} diff --git a/node_modules/ajv/lib/standalone/index.ts b/node_modules/ajv/lib/standalone/index.ts new file mode 100644 index 000000000..b6129ce9e --- /dev/null +++ b/node_modules/ajv/lib/standalone/index.ts @@ -0,0 +1,100 @@ +import type AjvCore from "../core" +import type {AnyValidateFunction, SourceCode} from "../types" +import type {SchemaEnv} from "../compile" +import {UsedScopeValues, UsedValueState, ValueScopeName, varKinds} from "../compile/codegen/scope" +import {_, nil, _Code, Code, getProperty, getEsmExportName} from "../compile/codegen/code" + +function standaloneCode( + ajv: AjvCore, + refsOrFunc?: {[K in string]?: string} | AnyValidateFunction +): string { + if (!ajv.opts.code.source) { + throw new Error("moduleCode: ajv instance must have code.source option") + } + const {_n} = ajv.scope.opts + return typeof refsOrFunc == "function" + ? funcExportCode(refsOrFunc.source) + : refsOrFunc !== undefined + ? multiExportsCode(refsOrFunc, getValidate) + : multiExportsCode(ajv.schemas, (sch) => + sch.meta ? undefined : ajv.compile(sch.schema) + ) + + function getValidate(id: string): AnyValidateFunction { + const v = ajv.getSchema(id) + if (!v) throw new Error(`moduleCode: no schema with id ${id}`) + return v + } + + function funcExportCode(source?: SourceCode): string { + const usedValues: UsedScopeValues = {} + const n = source?.validateName + const vCode = validateCode(usedValues, source) + if (ajv.opts.code.esm) { + // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value + return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}` + } + return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}` + } + + function multiExportsCode( + schemas: {[K in string]?: T}, + getValidateFunc: (schOrId: T) => AnyValidateFunction | undefined + ): string { + const usedValues: UsedScopeValues = {} + let code = _`"use strict";` + for (const name in schemas) { + const v = getValidateFunc(schemas[name] as T) + if (v) { + const vCode = validateCode(usedValues, v.source) + const exportSyntax = ajv.opts.code.esm + ? _`export const ${getEsmExportName(name)}` + : _`exports${getProperty(name)}` + code = _`${code}${_n}${exportSyntax} = ${v.source?.validateName};${_n}${vCode}` + } + } + return `${code}` + } + + function validateCode(usedValues: UsedScopeValues, s?: SourceCode): Code { + if (!s) throw new Error('moduleCode: function does not have "source" property') + if (usedState(s.validateName) === UsedValueState.Completed) return nil + setUsedState(s.validateName, UsedValueState.Started) + + const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode) + const code = new _Code(`${scopeCode}${_n}${s.validateCode}`) + return s.evaluated ? _`${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code + + function refValidateCode(n: ValueScopeName): Code | undefined { + const vRef = n.value?.ref + if (n.prefix === "validate" && typeof vRef == "function") { + const v = vRef as AnyValidateFunction + return validateCode(usedValues, v.source) + } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { + const {validate, validateName} = vRef as SchemaEnv + if (!validateName) throw new Error("ajv internal error") + const def = ajv.opts.code.es5 ? varKinds.var : varKinds.const + const wrapper = _`${def} ${n} = {validate: ${validateName}};` + if (usedState(validateName) === UsedValueState.Started) return wrapper + const vCode = validateCode(usedValues, validate?.source) + return _`${wrapper}${_n}${vCode}` + } + return undefined + } + + function usedState(name: ValueScopeName): UsedValueState | undefined { + return usedValues[name.prefix]?.get(name) + } + + function setUsedState(name: ValueScopeName, state: UsedValueState): void { + const {prefix} = name + const names = (usedValues[prefix] = usedValues[prefix] || new Map()) + names.set(name, state) + } + } +} + +module.exports = exports = standaloneCode +Object.defineProperty(exports, "__esModule", {value: true}) + +export default standaloneCode diff --git a/node_modules/ajv/lib/standalone/instance.ts b/node_modules/ajv/lib/standalone/instance.ts new file mode 100644 index 000000000..c4b2c30b5 --- /dev/null +++ b/node_modules/ajv/lib/standalone/instance.ts @@ -0,0 +1,36 @@ +import Ajv, {AnySchema, AnyValidateFunction, ErrorObject} from "../core" +import standaloneCode from "." +import * as requireFromString from "require-from-string" + +export default class AjvPack { + errors?: ErrorObject[] | null // errors from the last validation + constructor(readonly ajv: Ajv) {} + + validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise { + return Ajv.prototype.validate.call(this, schemaKeyRef, data) + } + + compile(schema: AnySchema, meta?: boolean): AnyValidateFunction { + return this.getStandalone(this.ajv.compile(schema, meta)) + } + + getSchema(keyRef: string): AnyValidateFunction | undefined { + const v = this.ajv.getSchema(keyRef) + if (!v) return undefined + return this.getStandalone(v) + } + + private getStandalone(v: AnyValidateFunction): AnyValidateFunction { + return requireFromString(standaloneCode(this.ajv, v)) as AnyValidateFunction + } + + addSchema(...args: Parameters): AjvPack { + this.ajv.addSchema.call(this.ajv, ...args) + return this + } + + addKeyword(...args: Parameters): AjvPack { + this.ajv.addKeyword.call(this.ajv, ...args) + return this + } +} diff --git a/node_modules/ajv/lib/types/index.ts b/node_modules/ajv/lib/types/index.ts new file mode 100644 index 000000000..39bc51b0b --- /dev/null +++ b/node_modules/ajv/lib/types/index.ts @@ -0,0 +1,244 @@ +import {URIComponent} from "fast-uri" +import type {CodeGen, Code, Name, ScopeValueSets, ValueScopeName} from "../compile/codegen" +import type {SchemaEnv, SchemaCxt, SchemaObjCxt} from "../compile" +import type {JSONType} from "../compile/rules" +import type {KeywordCxt} from "../compile/validate" +import type Ajv from "../core" + +interface _SchemaObject { + id?: string + $id?: string + $schema?: string + [x: string]: any // TODO +} + +export interface SchemaObject extends _SchemaObject { + id?: string + $id?: string + $schema?: string + $async?: false + [x: string]: any // TODO +} + +export interface AsyncSchema extends _SchemaObject { + $async: true +} + +export type AnySchemaObject = SchemaObject | AsyncSchema + +export type Schema = SchemaObject | boolean + +export type AnySchema = Schema | AsyncSchema + +export type SchemaMap = {[Key in string]?: AnySchema} + +export interface SourceCode { + validateName: ValueScopeName + validateCode: string + scopeValues: ScopeValueSets + evaluated?: Code +} + +export interface DataValidationCxt { + instancePath: string + parentData: {[K in T]: any} // object or array + parentDataProperty: T // string or number + rootData: Record | any[] + dynamicAnchors: {[Ref in string]?: ValidateFunction} +} + +export interface ValidateFunction { + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents + (this: Ajv | any, data: any, dataCxt?: DataValidationCxt): data is T + errors?: null | ErrorObject[] + evaluated?: Evaluated + schema: AnySchema + schemaEnv: SchemaEnv + source?: SourceCode +} + +export interface JTDParser { + (json: string): T | undefined + message?: string + position?: number +} + +export type EvaluatedProperties = {[K in string]?: true} | true + +export type EvaluatedItems = number | true + +export interface Evaluated { + // determined at compile time if staticProps/Items is true + props?: EvaluatedProperties + items?: EvaluatedItems + // whether props/items determined at compile time + dynamicProps: boolean + dynamicItems: boolean +} + +export interface AsyncValidateFunction extends ValidateFunction { + (...args: Parameters>): Promise + $async: true +} + +export type AnyValidateFunction = ValidateFunction | AsyncValidateFunction + +export interface ErrorObject, S = unknown> { + keyword: K + instancePath: string + schemaPath: string + params: P + // Added to validation errors of "propertyNames" keyword schema + propertyName?: string + // Excluded if option `messages` set to false. + message?: string + // These are added with the `verbose` option. + schema?: S + parentSchema?: AnySchemaObject + data?: unknown +} + +export type ErrorNoParams = ErrorObject, S> + +interface _KeywordDef { + keyword: string | string[] + type?: JSONType | JSONType[] // data types that keyword applies to + schemaType?: JSONType | JSONType[] // allowed type(s) of keyword value in the schema + allowUndefined?: boolean // used for keywords that can be invoked by other keywords, not being present in the schema + $data?: boolean // keyword supports [$data reference](../../docs/guide/combining-schemas.md#data-reference) + implements?: string[] // other schema keywords that this keyword implements + before?: string // keyword should be executed before this keyword (should be applicable to the same type) + post?: boolean // keyword should be executed after other keywords without post flag + metaSchema?: AnySchemaObject // meta-schema for keyword schema value - it is better to use schemaType where applicable + validateSchema?: AnyValidateFunction // compiled keyword metaSchema - should not be passed + dependencies?: string[] // keywords that must be present in the same schema + error?: KeywordErrorDefinition + $dataError?: KeywordErrorDefinition +} + +export interface CodeKeywordDefinition extends _KeywordDef { + code: (cxt: KeywordCxt, ruleType?: string) => void + trackErrors?: boolean +} + +export type MacroKeywordFunc = ( + schema: any, + parentSchema: AnySchemaObject, + it: SchemaCxt +) => AnySchema + +export type CompileKeywordFunc = ( + schema: any, + parentSchema: AnySchemaObject, + it: SchemaObjCxt +) => DataValidateFunction + +export interface DataValidateFunction { + (...args: Parameters): boolean | Promise + errors?: Partial[] +} + +export interface SchemaValidateFunction { + ( + schema: any, + data: any, + parentSchema?: AnySchemaObject, + dataCxt?: DataValidationCxt + ): boolean | Promise + errors?: Partial[] +} + +export interface FuncKeywordDefinition extends _KeywordDef { + validate?: SchemaValidateFunction | DataValidateFunction + compile?: CompileKeywordFunc + // schema: false makes validate not to expect schema (DataValidateFunction) + schema?: boolean // requires "validate" + modifying?: boolean + async?: boolean + valid?: boolean + errors?: boolean | "full" +} + +export interface MacroKeywordDefinition extends FuncKeywordDefinition { + macro: MacroKeywordFunc +} + +export type KeywordDefinition = + | CodeKeywordDefinition + | FuncKeywordDefinition + | MacroKeywordDefinition + +export type AddedKeywordDefinition = KeywordDefinition & { + type: JSONType[] + schemaType: JSONType[] +} + +export interface KeywordErrorDefinition { + message: string | Code | ((cxt: KeywordErrorCxt) => string | Code) + params?: Code | ((cxt: KeywordErrorCxt) => Code) +} + +export type Vocabulary = (KeywordDefinition | string)[] + +export interface KeywordErrorCxt { + gen: CodeGen + keyword: string + data: Name + $data?: string | false + schema: any // TODO + parentSchema?: AnySchemaObject + schemaCode: Code | number | boolean + schemaValue: Code | number | boolean + schemaType?: JSONType[] + errsCount?: Name + params: KeywordCxtParams + it: SchemaCxt +} + +export type KeywordCxtParams = {[P in string]?: Code | string | number} + +export type FormatValidator = (data: T) => boolean + +export type FormatCompare = (data1: T, data2: T) => number | undefined + +export type AsyncFormatValidator = (data: T) => Promise + +export interface FormatDefinition { + type?: T extends string ? "string" | undefined : "number" + validate: FormatValidator | (T extends string ? string | RegExp : never) + async?: false | undefined + compare?: FormatCompare +} + +export interface AsyncFormatDefinition { + type?: T extends string ? "string" | undefined : "number" + validate: AsyncFormatValidator + async: true + compare?: FormatCompare +} + +export type AddedFormat = + | true + | RegExp + | FormatValidator + | FormatDefinition + | FormatDefinition + | AsyncFormatDefinition + | AsyncFormatDefinition + +export type Format = AddedFormat | string + +export interface RegExpEngine { + (pattern: string, u: string): RegExpLike + code: string +} + +export interface RegExpLike { + test: (s: string) => boolean +} + +export interface UriResolver { + parse(uri: string): URIComponent + resolve(base: string, path: string): string + serialize(component: URIComponent): string +} diff --git a/node_modules/ajv/lib/types/json-schema.ts b/node_modules/ajv/lib/types/json-schema.ts new file mode 100644 index 000000000..065c972e5 --- /dev/null +++ b/node_modules/ajv/lib/types/json-schema.ts @@ -0,0 +1,187 @@ +/* eslint-disable @typescript-eslint/no-empty-interface */ +type StrictNullChecksWrapper = undefined extends null + ? `strictNullChecks must be true in tsconfig to use ${Name}` + : Type + +type UnionToIntersection = (U extends any ? (_: U) => void : never) extends (_: infer I) => void + ? I + : never + +export type SomeJSONSchema = UncheckedJSONSchemaType + +type UncheckedPartialSchema = Partial> + +export type PartialSchema = StrictNullChecksWrapper<"PartialSchema", UncheckedPartialSchema> + +type JSONType = IsPartial extends true + ? T | undefined + : T + +interface NumberKeywords { + minimum?: number + maximum?: number + exclusiveMinimum?: number + exclusiveMaximum?: number + multipleOf?: number + format?: string +} + +interface StringKeywords { + minLength?: number + maxLength?: number + pattern?: string + format?: string +} + +type UncheckedJSONSchemaType = ( + | // these two unions allow arbitrary unions of types + { + anyOf: readonly UncheckedJSONSchemaType[] + } + | { + oneOf: readonly UncheckedJSONSchemaType[] + } + // this union allows for { type: (primitive)[] } style schemas + | ({ + type: readonly (T extends number + ? JSONType<"number" | "integer", IsPartial> + : T extends string + ? JSONType<"string", IsPartial> + : T extends boolean + ? JSONType<"boolean", IsPartial> + : never)[] + } & UnionToIntersection< + T extends number + ? NumberKeywords + : T extends string + ? StringKeywords + : T extends boolean + ? // eslint-disable-next-line @typescript-eslint/ban-types + {} + : never + >) + // this covers "normal" types; it's last so typescript looks to it first for errors + | ((T extends number + ? { + type: JSONType<"number" | "integer", IsPartial> + } & NumberKeywords + : T extends string + ? { + type: JSONType<"string", IsPartial> + } & StringKeywords + : T extends boolean + ? { + type: JSONType<"boolean", IsPartial> + } + : T extends readonly [any, ...any[]] + ? { + // JSON AnySchema for tuple + type: JSONType<"array", IsPartial> + items: { + readonly [K in keyof T]-?: UncheckedJSONSchemaType & Nullable + } & {length: T["length"]} + minItems: T["length"] + } & ({maxItems: T["length"]} | {additionalItems: false}) + : T extends readonly any[] + ? { + type: JSONType<"array", IsPartial> + items: UncheckedJSONSchemaType + contains?: UncheckedPartialSchema + minItems?: number + maxItems?: number + minContains?: number + maxContains?: number + uniqueItems?: true + additionalItems?: never + } + : T extends Record + ? { + // JSON AnySchema for records and dictionaries + // "required" is not optional because it is often forgotten + // "properties" are optional for more concise dictionary schemas + // "patternProperties" and can be only used with interfaces that have string index + type: JSONType<"object", IsPartial> + additionalProperties?: boolean | UncheckedJSONSchemaType + unevaluatedProperties?: boolean | UncheckedJSONSchemaType + properties?: IsPartial extends true + ? Partial> + : UncheckedPropertiesSchema + patternProperties?: Record> + propertyNames?: Omit, "type"> & {type?: "string"} + dependencies?: {[K in keyof T]?: readonly (keyof T)[] | UncheckedPartialSchema} + dependentRequired?: {[K in keyof T]?: readonly (keyof T)[]} + dependentSchemas?: {[K in keyof T]?: UncheckedPartialSchema} + minProperties?: number + maxProperties?: number + } & (IsPartial extends true // "required" is not necessary if it's a non-partial type with no required keys // are listed it only asserts that optional cannot be listed. // "required" type does not guarantee that all required properties + ? {required: readonly (keyof T)[]} + : [UncheckedRequiredMembers] extends [never] + ? {required?: readonly UncheckedRequiredMembers[]} + : {required: readonly UncheckedRequiredMembers[]}) + : T extends null + ? { + type: JSONType<"null", IsPartial> + nullable: true + } + : never) & { + allOf?: readonly UncheckedPartialSchema[] + anyOf?: readonly UncheckedPartialSchema[] + oneOf?: readonly UncheckedPartialSchema[] + if?: UncheckedPartialSchema + then?: UncheckedPartialSchema + else?: UncheckedPartialSchema + not?: UncheckedPartialSchema + }) +) & { + [keyword: string]: any + $id?: string + $ref?: string + $defs?: Record> + definitions?: Record> +} + +export type JSONSchemaType = StrictNullChecksWrapper< + "JSONSchemaType", + UncheckedJSONSchemaType +> + +type Known = + | {[key: string]: Known} + | [Known, ...Known[]] + | Known[] + | number + | string + | boolean + | null + +type UncheckedPropertiesSchema = { + [K in keyof T]-?: (UncheckedJSONSchemaType & Nullable) | {$ref: string} +} + +export type PropertiesSchema = StrictNullChecksWrapper< + "PropertiesSchema", + UncheckedPropertiesSchema +> + +type UncheckedRequiredMembers = { + [K in keyof T]-?: undefined extends T[K] ? never : K +}[keyof T] + +export type RequiredMembers = StrictNullChecksWrapper< + "RequiredMembers", + UncheckedRequiredMembers +> + +type Nullable = undefined extends T + ? { + nullable: true + const?: null // any non-null value would fail `const: null`, `null` would fail any other value in const + enum?: readonly (T | null)[] // `null` must be explicitly included in "enum" for `null` to pass + default?: T | null + } + : { + nullable?: false + const?: T + enum?: readonly T[] + default?: T + } diff --git a/node_modules/ajv/lib/types/jtd-schema.ts b/node_modules/ajv/lib/types/jtd-schema.ts new file mode 100644 index 000000000..61b2bde81 --- /dev/null +++ b/node_modules/ajv/lib/types/jtd-schema.ts @@ -0,0 +1,273 @@ +/** numeric strings */ +type NumberType = "float32" | "float64" | "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" + +/** string strings */ +type StringType = "string" | "timestamp" + +/** Generic JTD Schema without inference of the represented type */ +export type SomeJTDSchemaType = ( + | // ref + {ref: string} + // primitives + | {type: NumberType | StringType | "boolean"} + // enum + | {enum: string[]} + // elements + | {elements: SomeJTDSchemaType} + // values + | {values: SomeJTDSchemaType} + // properties + | { + properties: Record + optionalProperties?: Record + additionalProperties?: boolean + } + | { + properties?: Record + optionalProperties: Record + additionalProperties?: boolean + } + // discriminator + | {discriminator: string; mapping: Record} + // empty + // NOTE see the end of + // https://github.com/typescript-eslint/typescript-eslint/issues/2063#issuecomment-675156492 + // eslint-disable-next-line @typescript-eslint/ban-types + | {} +) & { + nullable?: boolean + metadata?: Record + definitions?: Record +} + +/** required keys of an object, not undefined */ +type RequiredKeys = { + [K in keyof T]-?: undefined extends T[K] ? never : K +}[keyof T] + +/** optional or undifined-able keys of an object */ +type OptionalKeys = { + [K in keyof T]-?: undefined extends T[K] ? K : never +}[keyof T] + +/** type is true if T is a union type */ +type IsUnion_ = false extends ( + T extends unknown ? ([U] extends [T] ? false : true) : never +) + ? false + : true +type IsUnion = IsUnion_ + +/** type is true if T is identically E */ +type TypeEquality = [T] extends [E] ? ([E] extends [T] ? true : false) : false + +/** type is true if T or null is identically E or null*/ +type NullTypeEquality = TypeEquality + +/** gets only the string literals of a type or null if a type isn't a string literal */ +type EnumString = [T] extends [never] + ? null + : T extends string + ? string extends T + ? null + : T + : null + +/** true if type is a union of string literals */ +type IsEnum = null extends EnumString ? false : true + +/** true only if all types are array types (not tuples) */ +// NOTE relies on the fact that tuples don't have an index at 0.5, but arrays +// have an index at every number +type IsElements = false extends IsUnion + ? [T] extends [readonly unknown[]] + ? undefined extends T[0.5] + ? false + : true + : false + : false + +/** true if the the type is a values type */ +type IsValues = false extends IsUnion ? TypeEquality : false + +/** true if type is a properties type and Union is false, or type is a discriminator type and Union is true */ +type IsRecord = Union extends IsUnion + ? null extends EnumString + ? false + : true + : false + +/** true if type represents an empty record */ +type IsEmptyRecord = [T] extends [Record] + ? [T] extends [never] + ? false + : true + : false + +/** actual schema */ +export type JTDSchemaType = Record> = ( + | // refs - where null wasn't specified, must match exactly + (null extends EnumString + ? never + : + | ({[K in keyof D]: [T] extends [D[K]] ? {ref: K} : never}[keyof D] & {nullable?: false}) + // nulled refs - if ref is nullable and nullable is specified, then it can + // match either null or non-null definitions + | (null extends T + ? { + [K in keyof D]: [Exclude] extends [Exclude] + ? {ref: K} + : never + }[keyof D] & {nullable: true} + : never)) + // empty - empty schemas also treat nullable differently in that it's now fully ignored + | (unknown extends T ? {nullable?: boolean} : never) + // all other types // numbers - only accepts the type number + | ((true extends NullTypeEquality + ? {type: NumberType} + : // booleans - accepts the type boolean + true extends NullTypeEquality + ? {type: "boolean"} + : // strings - only accepts the type string + true extends NullTypeEquality + ? {type: StringType} + : // strings - only accepts the type Date + true extends NullTypeEquality + ? {type: "timestamp"} + : // enums - only accepts union of string literals + // TODO we can't actually check that everything in the union was specified + true extends IsEnum> + ? {enum: EnumString>[]} + : // arrays - only accepts arrays, could be array of unions to be resolved later + true extends IsElements> + ? T extends readonly (infer E)[] + ? { + elements: JTDSchemaType + } + : never + : // empty properties + true extends IsEmptyRecord> + ? + | {properties: Record; optionalProperties?: Record} + | {optionalProperties: Record} + : // values + true extends IsValues> + ? T extends Record + ? { + values: JTDSchemaType + } + : never + : // properties + true extends IsRecord, false> + ? ([RequiredKeys>] extends [never] + ? { + properties?: Record + } + : { + properties: {[K in RequiredKeys]: JTDSchemaType} + }) & + ([OptionalKeys>] extends [never] + ? { + optionalProperties?: Record + } + : { + optionalProperties: { + [K in OptionalKeys]: JTDSchemaType, D> + } + }) & { + additionalProperties?: boolean + } + : // discriminator + true extends IsRecord, true> + ? { + [K in keyof Exclude]-?: Exclude[K] extends string + ? { + discriminator: K + mapping: { + // TODO currently allows descriminator to be present in schema + [M in Exclude[K]]: JTDSchemaType< + Omit ? T : never, K>, + D + > + } + } + : never + }[keyof Exclude] + : never) & + (null extends T + ? { + nullable: true + } + : {nullable?: false})) +) & { + // extra properties + metadata?: Record + // TODO these should only be allowed at the top level + definitions?: {[K in keyof D]: JTDSchemaType} +} + +type JTDDataDef> = + | // ref + (S extends {ref: string} + ? D extends {[K in S["ref"]]: infer V} + ? JTDDataDef + : never + : // type + S extends {type: NumberType} + ? number + : S extends {type: "boolean"} + ? boolean + : S extends {type: "string"} + ? string + : S extends {type: "timestamp"} + ? string | Date + : // enum + S extends {enum: readonly (infer E)[]} + ? string extends E + ? never + : [E] extends [string] + ? E + : never + : // elements + S extends {elements: infer E} + ? JTDDataDef[] + : // properties + S extends { + properties: Record + optionalProperties?: Record + additionalProperties?: boolean + } + ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef} & { + -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef< + S["optionalProperties"][K], + D + > + } & ([S["additionalProperties"]] extends [true] ? Record : unknown) + : S extends { + properties?: Record + optionalProperties: Record + additionalProperties?: boolean + } + ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef} & { + -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef< + S["optionalProperties"][K], + D + > + } & ([S["additionalProperties"]] extends [true] ? Record : unknown) + : // values + S extends {values: infer V} + ? Record> + : // discriminator + S extends {discriminator: infer M; mapping: Record} + ? [M] extends [string] + ? { + [K in keyof S["mapping"]]: JTDDataDef & {[KM in M]: K} + }[keyof S["mapping"]] + : never + : // empty + unknown) + | (S extends {nullable: true} ? null : never) + +export type JTDDataType = S extends {definitions: Record} + ? JTDDataDef + : JTDDataDef> diff --git a/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts b/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts new file mode 100644 index 000000000..755e5b3da --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts @@ -0,0 +1,56 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util" + +export type AdditionalItemsError = ErrorObject<"additionalItems", {limit: number}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params: {len}}) => str`must NOT have more than ${len} items`, + params: ({params: {len}}) => _`{limit: ${len}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "additionalItems" as const, + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error, + code(cxt: KeywordCxt) { + const {parentSchema, it} = cxt + const {items} = parentSchema + if (!Array.isArray(items)) { + checkStrictMode(it, '"additionalItems" is ignored when "items" is not an array of schemas') + return + } + validateAdditionalItems(cxt, items) + }, +} + +export function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void { + const {gen, schema, data, keyword, it} = cxt + it.items = true + const len = gen.const("len", _`${data}.length`) + if (schema === false) { + cxt.setParams({len: items.length}) + cxt.pass(_`${len} <= ${items.length}`) + } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { + const valid = gen.var("valid", _`${len} <= ${items.length}`) // TODO var + gen.if(not(valid), () => validateItems(valid)) + cxt.ok(valid) + } + + function validateItems(valid: Name): void { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid) + if (!it.allErrors) gen.if(not(valid), () => gen.break()) + }) + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts b/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts new file mode 100644 index 000000000..bfb511ce5 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts @@ -0,0 +1,118 @@ +import type { + CodeKeywordDefinition, + AddedKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import {allSchemaProperties, usePattern, isOwnProperty} from "../code" +import {_, nil, or, not, Code, Name} from "../../compile/codegen" +import N from "../../compile/names" +import type {SubschemaArgs} from "../../compile/validate/subschema" +import {alwaysValidSchema, schemaRefOrVal, Type} from "../../compile/util" + +export type AdditionalPropertiesError = ErrorObject< + "additionalProperties", + {additionalProperty: string}, + AnySchema +> + +const error: KeywordErrorDefinition = { + message: "must NOT have additional properties", + params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`, +} + +const def: CodeKeywordDefinition & AddedKeywordDefinition = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error, + code(cxt) { + const {gen, schema, parentSchema, data, errsCount, it} = cxt + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error") + const {allErrors, opts} = it + it.props = true + if (opts.removeAdditional !== "all" && alwaysValidSchema(it, schema)) return + const props = allSchemaProperties(parentSchema.properties) + const patProps = allSchemaProperties(parentSchema.patternProperties) + checkAdditionalProperties() + cxt.ok(_`${errsCount} === ${N.errors}`) + + function checkAdditionalProperties(): void { + gen.forIn("key", data, (key: Name) => { + if (!props.length && !patProps.length) additionalPropertyCode(key) + else gen.if(isAdditional(key), () => additionalPropertyCode(key)) + }) + } + + function isAdditional(key: Name): Code { + let definedProp: Code + if (props.length > 8) { + // TODO maybe an option instead of hard-coded 8? + const propsSchema = schemaRefOrVal(it, parentSchema.properties, "properties") + definedProp = isOwnProperty(gen, propsSchema as Code, key) + } else if (props.length) { + definedProp = or(...props.map((p) => _`${key} === ${p}`)) + } else { + definedProp = nil + } + if (patProps.length) { + definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`)) + } + return not(definedProp) + } + + function deleteAdditional(key: Name): void { + gen.code(_`delete ${data}[${key}]`) + } + + function additionalPropertyCode(key: Name): void { + if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) { + deleteAdditional(key) + return + } + + if (schema === false) { + cxt.setParams({additionalProperty: key}) + cxt.error() + if (!allErrors) gen.break() + return + } + + if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { + const valid = gen.name("valid") + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false) + gen.if(not(valid), () => { + cxt.reset() + deleteAdditional(key) + }) + } else { + applyAdditionalSchema(key, valid) + if (!allErrors) gen.if(not(valid), () => gen.break()) + } + } + } + + function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void { + const subschema: SubschemaArgs = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: Type.Str, + } + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false, + }) + } + cxt.subschema(subschema, valid) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/allOf.ts b/node_modules/ajv/lib/vocabularies/applicator/allOf.ts new file mode 100644 index 000000000..cdfa86ff4 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/allOf.ts @@ -0,0 +1,22 @@ +import type {CodeKeywordDefinition, AnySchema} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "allOf", + schemaType: "array", + code(cxt: KeywordCxt) { + const {gen, schema, it} = cxt + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + const valid = gen.name("valid") + schema.forEach((sch: AnySchema, i: number) => { + if (alwaysValidSchema(it, sch)) return + const schCxt = cxt.subschema({keyword: "allOf", schemaProp: i}, valid) + cxt.ok(valid) + cxt.mergeEvaluated(schCxt) + }) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts b/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts new file mode 100644 index 000000000..bd331b5ae --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts @@ -0,0 +1,14 @@ +import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types" +import {validateUnion} from "../code" + +export type AnyOfError = ErrorNoParams<"anyOf", AnySchema[]> + +const def: CodeKeywordDefinition = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: validateUnion, + error: {message: "must match a schema in anyOf"}, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/contains.ts b/node_modules/ajv/lib/vocabularies/applicator/contains.ts new file mode 100644 index 000000000..d88675c6c --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/contains.ts @@ -0,0 +1,109 @@ +import type { + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util" + +export type ContainsError = ErrorObject< + "contains", + {minContains: number; maxContains?: number}, + AnySchema +> + +const error: KeywordErrorDefinition = { + message: ({params: {min, max}}) => + max === undefined + ? str`must contain at least ${min} valid item(s)` + : str`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({params: {min, max}}) => + max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error, + code(cxt: KeywordCxt) { + const {gen, schema, parentSchema, data, it} = cxt + let min: number + let max: number | undefined + const {minContains, maxContains} = parentSchema + if (it.opts.next) { + min = minContains === undefined ? 1 : minContains + max = maxContains + } else { + min = 1 + } + const len = gen.const("len", _`${data}.length`) + cxt.setParams({min, max}) + if (max === undefined && min === 0) { + checkStrictMode(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`) + return + } + if (max !== undefined && min > max) { + checkStrictMode(it, `"minContains" > "maxContains" is always invalid`) + cxt.fail() + return + } + if (alwaysValidSchema(it, schema)) { + let cond = _`${len} >= ${min}` + if (max !== undefined) cond = _`${cond} && ${len} <= ${max}` + cxt.pass(cond) + return + } + + it.items = true + const valid = gen.name("valid") + if (max === undefined && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())) + } else if (min === 0) { + gen.let(valid, true) + if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount) + } else { + gen.let(valid, false) + validateItemsWithCount() + } + cxt.result(valid, () => cxt.reset()) + + function validateItemsWithCount(): void { + const schValid = gen.name("_valid") + const count = gen.let("count", 0) + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))) + } + + function validateItems(_valid: Name, block: () => void): void { + gen.forRange("i", 0, len, (i) => { + cxt.subschema( + { + keyword: "contains", + dataProp: i, + dataPropType: Type.Num, + compositeRule: true, + }, + _valid + ) + block() + }) + } + + function checkLimits(count: Name): void { + gen.code(_`${count}++`) + if (max === undefined) { + gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break()) + } else { + gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break()) + if (min === 1) gen.assign(valid, true) + else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true)) + } + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts b/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts new file mode 100644 index 000000000..f67611286 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts @@ -0,0 +1,112 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + SchemaMap, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" +import {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from "../code" + +export type PropertyDependencies = {[K in string]?: string[]} + +export interface DependenciesErrorParams { + property: string + missingProperty: string + depsCount: number + deps: string // TODO change to string[] +} + +type SchemaDependencies = SchemaMap + +export type DependenciesError = ErrorObject< + "dependencies", + DependenciesErrorParams, + {[K in string]?: string[] | AnySchema} +> + +export const error: KeywordErrorDefinition = { + message: ({params: {property, depsCount, deps}}) => { + const property_ies = depsCount === 1 ? "property" : "properties" + return str`must have ${property_ies} ${deps} when property ${property} is present` + }, + params: ({params: {property, depsCount, deps, missingProperty}}) => + _`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}`, // TODO change to reference +} + +const def: CodeKeywordDefinition = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error, + code(cxt: KeywordCxt) { + const [propDeps, schDeps] = splitDependencies(cxt) + validatePropertyDeps(cxt, propDeps) + validateSchemaDeps(cxt, schDeps) + }, +} + +function splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] { + const propertyDeps: PropertyDependencies = {} + const schemaDeps: SchemaDependencies = {} + for (const key in schema) { + if (key === "__proto__") continue + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps + deps[key] = schema[key] + } + return [propertyDeps, schemaDeps] +} + +export function validatePropertyDeps( + cxt: KeywordCxt, + propertyDeps: {[K in string]?: string[]} = cxt.schema +): void { + const {gen, data, it} = cxt + if (Object.keys(propertyDeps).length === 0) return + const missing = gen.let("missing") + for (const prop in propertyDeps) { + const deps = propertyDeps[prop] as string[] + if (deps.length === 0) continue + const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties) + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", "), + }) + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + checkReportMissingProp(cxt, depProp) + } + }) + } else { + gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`) + reportMissingProp(cxt, missing) + gen.else() + } + } +} + +export function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void { + const {gen, data, keyword, it} = cxt + const valid = gen.name("valid") + for (const prop in schemaDeps) { + if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue + gen.if( + propertyInData(gen, data, prop, it.opts.ownProperties), + () => { + const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid) + cxt.mergeValidEvaluated(schCxt, valid) + }, + () => gen.var(valid, true) // TODO var + ) + cxt.ok(valid) + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts b/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts new file mode 100644 index 000000000..dbd3ae45c --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts @@ -0,0 +1,11 @@ +import type {CodeKeywordDefinition} from "../../types" +import {validateSchemaDeps} from "./dependencies" + +const def: CodeKeywordDefinition = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => validateSchemaDeps(cxt), +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/if.ts b/node_modules/ajv/lib/vocabularies/applicator/if.ts new file mode 100644 index 000000000..5a40d5e3a --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/if.ts @@ -0,0 +1,80 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {SchemaObjCxt} from "../../compile" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode} from "../../compile/util" + +export type IfKeywordError = ErrorObject<"if", {failingKeyword: string}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params}) => str`must match "${params.ifClause}" schema`, + params: ({params}) => _`{failingKeyword: ${params.ifClause}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error, + code(cxt: KeywordCxt) { + const {gen, parentSchema, it} = cxt + if (parentSchema.then === undefined && parentSchema.else === undefined) { + checkStrictMode(it, '"if" without "then" and "else" is ignored') + } + const hasThen = hasSchema(it, "then") + const hasElse = hasSchema(it, "else") + if (!hasThen && !hasElse) return + + const valid = gen.let("valid", true) + const schValid = gen.name("_valid") + validateIf() + cxt.reset() + + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause") + cxt.setParams({ifClause}) + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)) + } else if (hasThen) { + gen.if(schValid, validateClause("then")) + } else { + gen.if(not(schValid), validateClause("else")) + } + + cxt.pass(valid, () => cxt.error(true)) + + function validateIf(): void { + const schCxt = cxt.subschema( + { + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false, + }, + schValid + ) + cxt.mergeEvaluated(schCxt) + } + + function validateClause(keyword: string, ifClause?: Name): () => void { + return () => { + const schCxt = cxt.subschema({keyword}, schValid) + gen.assign(valid, schValid) + cxt.mergeValidEvaluated(schCxt, valid) + if (ifClause) gen.assign(ifClause, _`${keyword}`) + else cxt.setParams({ifClause: keyword}) + } + } + }, +} + +function hasSchema(it: SchemaObjCxt, keyword: string): boolean { + const schema = it.schema[keyword] + return schema !== undefined && !alwaysValidSchema(it, schema) +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/index.ts b/node_modules/ajv/lib/vocabularies/applicator/index.ts new file mode 100644 index 000000000..fc5271699 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/index.ts @@ -0,0 +1,53 @@ +import type {ErrorNoParams, Vocabulary} from "../../types" +import additionalItems, {AdditionalItemsError} from "./additionalItems" +import prefixItems from "./prefixItems" +import items from "./items" +import items2020, {ItemsError} from "./items2020" +import contains, {ContainsError} from "./contains" +import dependencies, {DependenciesError} from "./dependencies" +import propertyNames, {PropertyNamesError} from "./propertyNames" +import additionalProperties, {AdditionalPropertiesError} from "./additionalProperties" +import properties from "./properties" +import patternProperties from "./patternProperties" +import notKeyword, {NotKeywordError} from "./not" +import anyOf, {AnyOfError} from "./anyOf" +import oneOf, {OneOfError} from "./oneOf" +import allOf from "./allOf" +import ifKeyword, {IfKeywordError} from "./if" +import thenElse from "./thenElse" + +export default function getApplicator(draft2020 = false): Vocabulary { + const applicator = [ + // any + notKeyword, + anyOf, + oneOf, + allOf, + ifKeyword, + thenElse, + // object + propertyNames, + additionalProperties, + dependencies, + properties, + patternProperties, + ] + // array + if (draft2020) applicator.push(prefixItems, items2020) + else applicator.push(additionalItems, items) + applicator.push(contains) + return applicator +} + +export type ApplicatorKeywordError = + | ErrorNoParams<"false schema"> + | AdditionalItemsError + | ItemsError + | ContainsError + | AdditionalPropertiesError + | DependenciesError + | IfKeywordError + | AnyOfError + | OneOfError + | NotKeywordError + | PropertyNamesError diff --git a/node_modules/ajv/lib/vocabularies/applicator/items.ts b/node_modules/ajv/lib/vocabularies/applicator/items.ts new file mode 100644 index 000000000..033cb3977 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/items.ts @@ -0,0 +1,59 @@ +import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_} from "../../compile/codegen" +import {alwaysValidSchema, mergeEvaluated, checkStrictMode} from "../../compile/util" +import {validateArray} from "../code" + +const def: CodeKeywordDefinition = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt: KeywordCxt) { + const {schema, it} = cxt + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema) + it.items = true + if (alwaysValidSchema(it, schema)) return + cxt.ok(validateArray(cxt)) + }, +} + +export function validateTuple( + cxt: KeywordCxt, + extraItems: string, + schArr: AnySchema[] = cxt.schema +): void { + const {gen, parentSchema, data, keyword, it} = cxt + checkStrictTuple(parentSchema) + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = mergeEvaluated.items(gen, schArr.length, it.items) + } + const valid = gen.name("valid") + const len = gen.const("len", _`${data}.length`) + schArr.forEach((sch: AnySchema, i: number) => { + if (alwaysValidSchema(it, sch)) return + gen.if(_`${len} > ${i}`, () => + cxt.subschema( + { + keyword, + schemaProp: i, + dataProp: i, + }, + valid + ) + ) + cxt.ok(valid) + }) + + function checkStrictTuple(sch: AnySchemaObject): void { + const {opts, errSchemaPath} = it + const l = schArr.length + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false) + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"` + checkStrictMode(it, msg, opts.strictTuples) + } + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/items2020.ts b/node_modules/ajv/lib/vocabularies/applicator/items2020.ts new file mode 100644 index 000000000..2a99b08d5 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/items2020.ts @@ -0,0 +1,36 @@ +import type { + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" +import {validateArray} from "../code" +import {validateAdditionalItems} from "./additionalItems" + +export type ItemsError = ErrorObject<"items", {limit: number}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params: {len}}) => str`must NOT have more than ${len} items`, + params: ({params: {len}}) => _`{limit: ${len}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error, + code(cxt: KeywordCxt) { + const {schema, parentSchema, it} = cxt + const {prefixItems} = parentSchema + it.items = true + if (alwaysValidSchema(it, schema)) return + if (prefixItems) validateAdditionalItems(cxt, prefixItems) + else cxt.ok(validateArray(cxt)) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/not.ts b/node_modules/ajv/lib/vocabularies/applicator/not.ts new file mode 100644 index 000000000..8691db0bf --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/not.ts @@ -0,0 +1,38 @@ +import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema} from "../../compile/util" + +export type NotKeywordError = ErrorNoParams<"not", AnySchema> + +const def: CodeKeywordDefinition = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt: KeywordCxt) { + const {gen, schema, it} = cxt + if (alwaysValidSchema(it, schema)) { + cxt.fail() + return + } + + const valid = gen.name("valid") + cxt.subschema( + { + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false, + }, + valid + ) + + cxt.failResult( + valid, + () => cxt.reset(), + () => cxt.error() + ) + }, + error: {message: "must NOT be valid"}, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts b/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts new file mode 100644 index 000000000..c25353ffd --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts @@ -0,0 +1,82 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, Name} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" +import {SchemaCxt} from "../../compile" + +export type OneOfError = ErrorObject< + "oneOf", + {passingSchemas: [number, number] | null}, + AnySchema[] +> + +const error: KeywordErrorDefinition = { + message: "must match exactly one schema in oneOf", + params: ({params}) => _`{passingSchemas: ${params.passing}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error, + code(cxt: KeywordCxt) { + const {gen, schema, parentSchema, it} = cxt + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + if (it.opts.discriminator && parentSchema.discriminator) return + const schArr: AnySchema[] = schema + const valid = gen.let("valid", false) + const passing = gen.let("passing", null) + const schValid = gen.name("_valid") + cxt.setParams({passing}) + // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas + + gen.block(validateOneOf) + + cxt.result( + valid, + () => cxt.reset(), + () => cxt.error(true) + ) + + function validateOneOf(): void { + schArr.forEach((sch: AnySchema, i: number) => { + let schCxt: SchemaCxt | undefined + if (alwaysValidSchema(it, sch)) { + gen.var(schValid, true) + } else { + schCxt = cxt.subschema( + { + keyword: "oneOf", + schemaProp: i, + compositeRule: true, + }, + schValid + ) + } + + if (i > 0) { + gen + .if(_`${schValid} && ${valid}`) + .assign(valid, false) + .assign(passing, _`[${passing}, ${i}]`) + .else() + } + + gen.if(schValid, () => { + gen.assign(valid, true) + gen.assign(passing, i) + if (schCxt) cxt.mergeEvaluated(schCxt, Name) + }) + }) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts b/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts new file mode 100644 index 000000000..ea624e230 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts @@ -0,0 +1,91 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {allSchemaProperties, usePattern} from "../code" +import {_, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode} from "../../compile/util" +import {evaluatedPropsToName, Type} from "../../compile/util" +import {AnySchema} from "../../types" + +const def: CodeKeywordDefinition = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt: KeywordCxt) { + const {gen, schema, data, parentSchema, it} = cxt + const {opts} = it + const patterns = allSchemaProperties(schema) + const alwaysValidPatterns = patterns.filter((p) => + alwaysValidSchema(it, schema[p] as AnySchema) + ) + + if ( + patterns.length === 0 || + (alwaysValidPatterns.length === patterns.length && + (!it.opts.unevaluated || it.props === true)) + ) { + return + } + + const checkProperties = + opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties + const valid = gen.name("valid") + if (it.props !== true && !(it.props instanceof Name)) { + it.props = evaluatedPropsToName(gen, it.props) + } + const {props} = it + validatePatternProperties() + + function validatePatternProperties(): void { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat) + if (it.allErrors) { + validateProperties(pat) + } else { + gen.var(valid, true) // TODO var + validateProperties(pat) + gen.if(valid) + } + } + } + + function checkMatchingProperties(pat: string): void { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + checkStrictMode( + it, + `property ${prop} matches pattern ${pat} (use allowMatchingProperties)` + ) + } + } + } + + function validateProperties(pat: string): void { + gen.forIn("key", data, (key) => { + gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat) + if (!alwaysValid) { + cxt.subschema( + { + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: Type.Str, + }, + valid + ) + } + + if (it.opts.unevaluated && props !== true) { + gen.assign(_`${props}[${key}]`, true) + } else if (!alwaysValid && !it.allErrors) { + // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false) + // or if all properties were evaluated (props === true) + gen.if(not(valid), () => gen.break()) + } + }) + }) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts b/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts new file mode 100644 index 000000000..008fb2db1 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts @@ -0,0 +1,12 @@ +import type {CodeKeywordDefinition} from "../../types" +import {validateTuple} from "./items" + +const def: CodeKeywordDefinition = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => validateTuple(cxt, "items"), +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/properties.ts b/node_modules/ajv/lib/vocabularies/applicator/properties.ts new file mode 100644 index 000000000..a55b19ce5 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/properties.ts @@ -0,0 +1,57 @@ +import type {CodeKeywordDefinition} from "../../types" +import {KeywordCxt} from "../../compile/validate" +import {propertyInData, allSchemaProperties} from "../code" +import {alwaysValidSchema, toHash, mergeEvaluated} from "../../compile/util" +import apDef from "./additionalProperties" + +const def: CodeKeywordDefinition = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt: KeywordCxt) { + const {gen, schema, parentSchema, data, it} = cxt + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) { + apDef.code(new KeywordCxt(it, apDef, "additionalProperties")) + } + const allProps = allSchemaProperties(schema) + for (const prop of allProps) { + it.definedProperties.add(prop) + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = mergeEvaluated.props(gen, toHash(allProps), it.props) + } + const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p])) + if (properties.length === 0) return + const valid = gen.name("valid") + + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop) + } else { + gen.if(propertyInData(gen, data, prop, it.opts.ownProperties)) + applyPropertySchema(prop) + if (!it.allErrors) gen.else().var(valid, true) + gen.endIf() + } + cxt.it.definedProperties.add(prop) + cxt.ok(valid) + } + + function hasDefault(prop: string): boolean | undefined { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined + } + + function applyPropertySchema(prop: string): void { + cxt.subschema( + { + keyword: "properties", + schemaProp: prop, + dataProp: prop, + }, + valid + ) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts b/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts new file mode 100644 index 000000000..1c54d6052 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts @@ -0,0 +1,50 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, not} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" + +export type PropertyNamesError = ErrorObject<"propertyNames", {propertyName: string}, AnySchema> + +const error: KeywordErrorDefinition = { + message: "property name must be valid", + params: ({params}) => _`{propertyName: ${params.propertyName}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error, + code(cxt: KeywordCxt) { + const {gen, schema, data, it} = cxt + if (alwaysValidSchema(it, schema)) return + const valid = gen.name("valid") + + gen.forIn("key", data, (key) => { + cxt.setParams({propertyName: key}) + cxt.subschema( + { + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true, + }, + valid + ) + gen.if(not(valid), () => { + cxt.error(true) + if (!it.allErrors) gen.break() + }) + }) + + cxt.ok(valid) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts b/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts new file mode 100644 index 000000000..5055182e8 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts @@ -0,0 +1,13 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {checkStrictMode} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({keyword, parentSchema, it}: KeywordCxt) { + if (parentSchema.if === undefined) checkStrictMode(it, `"${keyword}" without "if" is ignored`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/code.ts b/node_modules/ajv/lib/vocabularies/code.ts new file mode 100644 index 000000000..92cdd5b04 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/code.ts @@ -0,0 +1,168 @@ +import type {AnySchema, SchemaMap} from "../types" +import type {SchemaCxt} from "../compile" +import type {KeywordCxt} from "../compile/validate" +import {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from "../compile/codegen" +import {alwaysValidSchema, Type} from "../compile/util" +import N from "../compile/names" +import {useFunc} from "../compile/util" +export function checkReportMissingProp(cxt: KeywordCxt, prop: string): void { + const {gen, data, it} = cxt + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({missingProperty: _`${prop}`}, true) + cxt.error() + }) +} + +export function checkMissingProp( + {gen, data, it: {opts}}: KeywordCxt, + properties: string[], + missing: Name +): Code { + return or( + ...properties.map((prop) => + and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`) + ) + ) +} + +export function reportMissingProp(cxt: KeywordCxt, missing: Name): void { + cxt.setParams({missingProperty: missing}, true) + cxt.error() +} + +export function hasPropFunc(gen: CodeGen): Name { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: _`Object.prototype.hasOwnProperty`, + }) +} + +export function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code { + return _`${hasPropFunc(gen)}.call(${data}, ${property})` +} + +export function propertyInData( + gen: CodeGen, + data: Name, + property: Name | string, + ownProperties?: boolean +): Code { + const cond = _`${data}${getProperty(property)} !== undefined` + return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond +} + +export function noPropertyInData( + gen: CodeGen, + data: Name, + property: Name | string, + ownProperties?: boolean +): Code { + const cond = _`${data}${getProperty(property)} === undefined` + return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond +} + +export function allSchemaProperties(schemaMap?: SchemaMap): string[] { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [] +} + +export function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] { + return allSchemaProperties(schemaMap).filter( + (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema) + ) +} + +export function callValidateCode( + {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt, + func: Code, + context: Code, + passSchema?: boolean +): Code { + const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data + const valCxt: [Name, Code | number][] = [ + [N.instancePath, strConcat(N.instancePath, errorPath)], + [N.parentData, it.parentData], + [N.parentDataProperty, it.parentDataProperty], + [N.rootData, N.rootData], + ] + if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors]) + const args = _`${dataAndSchema}, ${gen.object(...valCxt)}` + return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})` +} + +const newRegExp = _`new RegExp` + +export function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name { + const u = opts.unicodeRegExp ? "u" : "" + const {regExp} = opts.code + const rx = regExp(pattern, u) + + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: _`${regExp.code === "new RegExp" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`, + }) +} + +export function validateArray(cxt: KeywordCxt): Name { + const {gen, data, keyword, it} = cxt + const valid = gen.name("valid") + if (it.allErrors) { + const validArr = gen.let("valid", true) + validateItems(() => gen.assign(validArr, false)) + return validArr + } + gen.var(valid, true) + validateItems(() => gen.break()) + return valid + + function validateItems(notValid: () => void): void { + const len = gen.const("len", _`${data}.length`) + gen.forRange("i", 0, len, (i) => { + cxt.subschema( + { + keyword, + dataProp: i, + dataPropType: Type.Num, + }, + valid + ) + gen.if(not(valid), notValid) + }) + } +} + +export function validateUnion(cxt: KeywordCxt): void { + const {gen, schema, keyword, it} = cxt + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch)) + if (alwaysValid && !it.opts.unevaluated) return + + const valid = gen.let("valid", false) + const schValid = gen.name("_valid") + + gen.block(() => + schema.forEach((_sch: AnySchema, i: number) => { + const schCxt = cxt.subschema( + { + keyword, + schemaProp: i, + compositeRule: true, + }, + schValid + ) + gen.assign(valid, _`${valid} || ${schValid}`) + const merged = cxt.mergeValidEvaluated(schCxt, schValid) + // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true) + // or if all properties and items were evaluated (it.props === true && it.items === true) + if (!merged) gen.if(not(valid)) + }) + ) + + cxt.result( + valid, + () => cxt.reset(), + () => cxt.error(true) + ) +} diff --git a/node_modules/ajv/lib/vocabularies/core/id.ts b/node_modules/ajv/lib/vocabularies/core/id.ts new file mode 100644 index 000000000..aa36c4bb2 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/core/id.ts @@ -0,0 +1,10 @@ +import type {CodeKeywordDefinition} from "../../types" + +const def: CodeKeywordDefinition = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID') + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/core/index.ts b/node_modules/ajv/lib/vocabularies/core/index.ts new file mode 100644 index 000000000..e63e2895d --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/core/index.ts @@ -0,0 +1,16 @@ +import type {Vocabulary} from "../../types" +import idKeyword from "./id" +import refKeyword from "./ref" + +const core: Vocabulary = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + {keyword: "$comment"}, + "definitions", + idKeyword, + refKeyword, +] + +export default core diff --git a/node_modules/ajv/lib/vocabularies/core/ref.ts b/node_modules/ajv/lib/vocabularies/core/ref.ts new file mode 100644 index 000000000..5d59fbcb2 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/core/ref.ts @@ -0,0 +1,129 @@ +import type {CodeKeywordDefinition, AnySchema} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import MissingRefError from "../../compile/ref_error" +import {callValidateCode} from "../code" +import {_, nil, stringify, Code, Name} from "../../compile/codegen" +import N from "../../compile/names" +import {SchemaEnv, resolveRef} from "../../compile" +import {mergeEvaluated} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "$ref", + schemaType: "string", + code(cxt: KeywordCxt): void { + const {gen, schema: $ref, it} = cxt + const {baseId, schemaEnv: env, validateName, opts, self} = it + const {root} = env + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef() + const schOrEnv = resolveRef.call(self, root, baseId, $ref) + if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref) + if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv) + return inlineRefSchema(schOrEnv) + + function callRootRef(): void { + if (env === root) return callRef(cxt, validateName, env, env.$async) + const rootName = gen.scopeValue("root", {ref: root}) + return callRef(cxt, _`${rootName}.validate`, root, root.$async) + } + + function callValidate(sch: SchemaEnv): void { + const v = getValidate(cxt, sch) + callRef(cxt, v, sch, sch.$async) + } + + function inlineRefSchema(sch: AnySchema): void { + const schName = gen.scopeValue( + "schema", + opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch} + ) + const valid = gen.name("valid") + const schCxt = cxt.subschema( + { + schema: sch, + dataTypes: [], + schemaPath: nil, + topSchemaRef: schName, + errSchemaPath: $ref, + }, + valid + ) + cxt.mergeEvaluated(schCxt) + cxt.ok(valid) + } + }, +} + +export function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code { + const {gen} = cxt + return sch.validate + ? gen.scopeValue("validate", {ref: sch.validate}) + : _`${gen.scopeValue("wrapper", {ref: sch})}.validate` +} + +export function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void { + const {gen, it} = cxt + const {allErrors, schemaEnv: env, opts} = it + const passCxt = opts.passContext ? N.this : nil + if ($async) callAsyncRef() + else callSyncRef() + + function callAsyncRef(): void { + if (!env.$async) throw new Error("async schema referenced by sync schema") + const valid = gen.let("valid") + gen.try( + () => { + gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`) + addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result + if (!allErrors) gen.assign(valid, true) + }, + (e) => { + gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e)) + addErrorsFrom(e) + if (!allErrors) gen.assign(valid, false) + } + ) + cxt.ok(valid) + } + + function callSyncRef(): void { + cxt.result( + callValidateCode(cxt, v, passCxt), + () => addEvaluatedFrom(v), + () => addErrorsFrom(v) + ) + } + + function addErrorsFrom(source: Code): void { + const errs = _`${source}.errors` + gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged + gen.assign(N.errors, _`${N.vErrors}.length`) + } + + function addEvaluatedFrom(source: Code): void { + if (!it.opts.unevaluated) return + const schEvaluated = sch?.validate?.evaluated + // TODO refactor + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== undefined) { + it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props) + } + } else { + const props = gen.var("props", _`${source}.evaluated.props`) + it.props = mergeEvaluated.props(gen, props, it.props, Name) + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== undefined) { + it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items) + } + } else { + const items = gen.var("items", _`${source}.evaluated.items`) + it.items = mergeEvaluated.items(gen, items, it.items, Name) + } + } + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/discriminator/index.ts b/node_modules/ajv/lib/vocabularies/discriminator/index.ts new file mode 100644 index 000000000..19ae6049f --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/discriminator/index.ts @@ -0,0 +1,113 @@ +import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, getProperty, Name} from "../../compile/codegen" +import {DiscrError, DiscrErrorObj} from "../discriminator/types" +import {resolveRef, SchemaEnv} from "../../compile" +import MissingRefError from "../../compile/ref_error" +import {schemaHasRulesButRef} from "../../compile/util" + +export type DiscriminatorError = DiscrErrorObj | DiscrErrorObj + +const error: KeywordErrorDefinition = { + message: ({params: {discrError, tagName}}) => + discrError === DiscrError.Tag + ? `tag "${tagName}" must be string` + : `value of tag "${tagName}" must be in oneOf`, + params: ({params: {discrError, tag, tagName}}) => + _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error, + code(cxt: KeywordCxt) { + const {gen, data, schema, parentSchema, it} = cxt + const {oneOf} = parentSchema + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option") + } + const tagName = schema.propertyName + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName") + if (schema.mapping) throw new Error("discriminator: mapping is not supported") + if (!oneOf) throw new Error("discriminator: requires oneOf keyword") + const valid = gen.let("valid", false) + const tag = gen.const("tag", _`${data}${getProperty(tagName)}`) + gen.if( + _`typeof ${tag} == "string"`, + () => validateMapping(), + () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName}) + ) + cxt.ok(valid) + + function validateMapping(): void { + const mapping = getMapping() + gen.if(false) + for (const tagValue in mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + gen.assign(valid, applyTagSchema(mapping[tagValue])) + } + gen.else() + cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName}) + gen.endIf() + } + + function applyTagSchema(schemaProp?: number): Name { + const _valid = gen.name("valid") + const schCxt = cxt.subschema({keyword: "oneOf", schemaProp}, _valid) + cxt.mergeEvaluated(schCxt, Name) + return _valid + } + + function getMapping(): {[T in string]?: number} { + const oneOfMapping: {[T in string]?: number} = {} + const topRequired = hasRequired(parentSchema) + let tagRequired = true + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i] + if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) { + const ref = sch.$ref + sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref) + if (sch instanceof SchemaEnv) sch = sch.schema + if (sch === undefined) throw new MissingRefError(it.opts.uriResolver, it.baseId, ref) + } + const propSch = sch?.properties?.[tagName] + if (typeof propSch != "object") { + throw new Error( + `discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"` + ) + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)) + addMappings(propSch, i) + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`) + return oneOfMapping + + function hasRequired({required}: AnySchemaObject): boolean { + return Array.isArray(required) && required.includes(tagName) + } + + function addMappings(sch: AnySchemaObject, i: number): void { + if (sch.const) { + addMapping(sch.const, i) + } else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i) + } + } else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`) + } + } + + function addMapping(tagValue: unknown, i: number): void { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`) + } + oneOfMapping[tagValue] = i + } + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/discriminator/types.ts b/node_modules/ajv/lib/vocabularies/discriminator/types.ts new file mode 100644 index 000000000..bee5a2785 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/discriminator/types.ts @@ -0,0 +1,12 @@ +import type {ErrorObject} from "../../types" + +export enum DiscrError { + Tag = "tag", + Mapping = "mapping", +} + +export type DiscrErrorObj = ErrorObject< + "discriminator", + {error: E; tag: string; tagValue: unknown}, + string +> diff --git a/node_modules/ajv/lib/vocabularies/draft2020.ts b/node_modules/ajv/lib/vocabularies/draft2020.ts new file mode 100644 index 000000000..47fbf0ee6 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/draft2020.ts @@ -0,0 +1,23 @@ +import type {Vocabulary} from "../types" +import coreVocabulary from "./core" +import validationVocabulary from "./validation" +import getApplicatorVocabulary from "./applicator" +import dynamicVocabulary from "./dynamic" +import nextVocabulary from "./next" +import unevaluatedVocabulary from "./unevaluated" +import formatVocabulary from "./format" +import {metadataVocabulary, contentVocabulary} from "./metadata" + +const draft2020Vocabularies: Vocabulary[] = [ + dynamicVocabulary, + coreVocabulary, + validationVocabulary, + getApplicatorVocabulary(true), + formatVocabulary, + metadataVocabulary, + contentVocabulary, + nextVocabulary, + unevaluatedVocabulary, +] + +export default draft2020Vocabularies diff --git a/node_modules/ajv/lib/vocabularies/draft7.ts b/node_modules/ajv/lib/vocabularies/draft7.ts new file mode 100644 index 000000000..226a644aa --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/draft7.ts @@ -0,0 +1,17 @@ +import type {Vocabulary} from "../types" +import coreVocabulary from "./core" +import validationVocabulary from "./validation" +import getApplicatorVocabulary from "./applicator" +import formatVocabulary from "./format" +import {metadataVocabulary, contentVocabulary} from "./metadata" + +const draft7Vocabularies: Vocabulary[] = [ + coreVocabulary, + validationVocabulary, + getApplicatorVocabulary(), + formatVocabulary, + metadataVocabulary, + contentVocabulary, +] + +export default draft7Vocabularies diff --git a/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts b/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts new file mode 100644 index 000000000..ca1adb912 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts @@ -0,0 +1,31 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, getProperty, Code} from "../../compile/codegen" +import N from "../../compile/names" +import {SchemaEnv, compileSchema} from "../../compile" +import {getValidate} from "../core/ref" + +const def: CodeKeywordDefinition = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema), +} + +export function dynamicAnchor(cxt: KeywordCxt, anchor: string): void { + const {gen, it} = cxt + it.schemaEnv.root.dynamicAnchors[anchor] = true + const v = _`${N.dynamicAnchors}${getProperty(anchor)}` + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt) + gen.if(_`!${v}`, () => gen.assign(v, validate)) +} + +function _getValidate(cxt: KeywordCxt): Code { + const {schemaEnv, schema, self} = cxt.it + const {root, baseId, localRefs, meta} = schemaEnv.root + const {schemaId} = self.opts + const sch = new SchemaEnv({schema, schemaId, root, baseId, localRefs, meta}) + compileSchema.call(self, sch) + return getValidate(cxt, sch) +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts b/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts new file mode 100644 index 000000000..6a573f330 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts @@ -0,0 +1,51 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, getProperty, Code, Name} from "../../compile/codegen" +import N from "../../compile/names" +import {callRef} from "../core/ref" + +const def: CodeKeywordDefinition = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema), +} + +export function dynamicRef(cxt: KeywordCxt, ref: string): void { + const {gen, keyword, it} = cxt + if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`) + const anchor = ref.slice(1) + if (it.allErrors) { + _dynamicRef() + } else { + const valid = gen.let("valid", false) + _dynamicRef(valid) + cxt.ok(valid) + } + + function _dynamicRef(valid?: Name): void { + // TODO the assumption here is that `recursiveRef: #` always points to the root + // of the schema object, which is not correct, because there may be $id that + // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor. + // Because of that 2 tests in recursiveRef.json fail. + // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`). + // (This problem is not tested in JSON-Schema-Test-Suite) + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", _`${N.dynamicAnchors}${getProperty(anchor)}`) + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)) + } else { + _callRef(it.validateName, valid)() + } + } + + function _callRef(validate: Code, valid?: Name): () => void { + return valid + ? () => + gen.block(() => { + callRef(cxt, validate) + gen.let(valid, true) + }) + : () => callRef(cxt, validate) + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/dynamic/index.ts b/node_modules/ajv/lib/vocabularies/dynamic/index.ts new file mode 100644 index 000000000..6d521db66 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/dynamic/index.ts @@ -0,0 +1,9 @@ +import type {Vocabulary} from "../../types" +import dynamicAnchor from "./dynamicAnchor" +import dynamicRef from "./dynamicRef" +import recursiveAnchor from "./recursiveAnchor" +import recursiveRef from "./recursiveRef" + +const dynamic: Vocabulary = [dynamicAnchor, dynamicRef, recursiveAnchor, recursiveRef] + +export default dynamic diff --git a/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts b/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts new file mode 100644 index 000000000..25f3db96b --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts @@ -0,0 +1,14 @@ +import type {CodeKeywordDefinition} from "../../types" +import {dynamicAnchor} from "./dynamicAnchor" +import {checkStrictMode} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) dynamicAnchor(cxt, "") + else checkStrictMode(cxt.it, "$recursiveAnchor: false is ignored") + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts b/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts new file mode 100644 index 000000000..c84af0f05 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts @@ -0,0 +1,10 @@ +import type {CodeKeywordDefinition} from "../../types" +import {dynamicRef} from "./dynamicRef" + +const def: CodeKeywordDefinition = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema), +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/errors.ts b/node_modules/ajv/lib/vocabularies/errors.ts new file mode 100644 index 000000000..c9ca3f02f --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/errors.ts @@ -0,0 +1,18 @@ +import type {TypeError} from "../compile/validate/dataType" +import type {ApplicatorKeywordError} from "./applicator" +import type {ValidationKeywordError} from "./validation" +import type {FormatError} from "./format/format" +import type {UnevaluatedPropertiesError} from "./unevaluated/unevaluatedProperties" +import type {UnevaluatedItemsError} from "./unevaluated/unevaluatedItems" +import type {DependentRequiredError} from "./validation/dependentRequired" +import type {DiscriminatorError} from "./discriminator" + +export type DefinedError = + | TypeError + | ApplicatorKeywordError + | ValidationKeywordError + | FormatError + | UnevaluatedPropertiesError + | UnevaluatedItemsError + | DependentRequiredError + | DiscriminatorError diff --git a/node_modules/ajv/lib/vocabularies/format/format.ts b/node_modules/ajv/lib/vocabularies/format/format.ts new file mode 100644 index 000000000..4b1c13e76 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/format/format.ts @@ -0,0 +1,120 @@ +import type { + AddedFormat, + FormatValidator, + AsyncFormatValidator, + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, nil, or, Code, getProperty, regexpCode} from "../../compile/codegen" + +type FormatValidate = + | FormatValidator + | FormatValidator + | AsyncFormatValidator + | AsyncFormatValidator + | RegExp + | string + | true + +export type FormatError = ErrorObject<"format", {format: string}, string | {$data: string}> + +const error: KeywordErrorDefinition = { + message: ({schemaCode}) => str`must match format "${schemaCode}"`, + params: ({schemaCode}) => _`{format: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error, + code(cxt: KeywordCxt, ruleType?: string) { + const {gen, data, $data, schema, schemaCode, it} = cxt + const {opts, errSchemaPath, schemaEnv, self} = it + if (!opts.validateFormats) return + + if ($data) validate$DataFormat() + else validateFormat() + + function validate$DataFormat(): void { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats, + }) + const fDef = gen.const("fDef", _`${fmts}[${schemaCode}]`) + const fType = gen.let("fType") + const format = gen.let("format") + // TODO simplify + gen.if( + _`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, + () => gen.assign(fType, _`${fDef}.type || "string"`).assign(format, _`${fDef}.validate`), + () => gen.assign(fType, _`"string"`).assign(format, fDef) + ) + cxt.fail$data(or(unknownFmt(), invalidFmt())) + + function unknownFmt(): Code { + if (opts.strictSchema === false) return nil + return _`${schemaCode} && !${format}` + } + + function invalidFmt(): Code { + const callFormat = schemaEnv.$async + ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` + : _`${format}(${data})` + const validData = _`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))` + return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}` + } + } + + function validateFormat(): void { + const formatDef: AddedFormat | undefined = self.formats[schema] + if (!formatDef) { + unknownFormat() + return + } + if (formatDef === true) return + const [fmtType, format, fmtRef] = getFormat(formatDef) + if (fmtType === ruleType) cxt.pass(validCondition()) + + function unknownFormat(): void { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()) + return + } + throw new Error(unknownMsg()) + + function unknownMsg(): string { + return `unknown format "${schema as string}" ignored in schema at path "${errSchemaPath}"` + } + } + + function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] { + const code = + fmtDef instanceof RegExp + ? regexpCode(fmtDef) + : opts.code.formats + ? _`${opts.code.formats}${getProperty(schema)}` + : undefined + const fmt = gen.scopeValue("formats", {key: schema, ref: fmtDef, code}) + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, _`${fmt}.validate`] + } + + return ["string", fmtDef, fmt] + } + + function validCondition(): Code { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema") + return _`await ${fmtRef}(${data})` + } + return typeof format == "function" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})` + } + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/format/index.ts b/node_modules/ajv/lib/vocabularies/format/index.ts new file mode 100644 index 000000000..bca2f5b3d --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/format/index.ts @@ -0,0 +1,6 @@ +import type {Vocabulary} from "../../types" +import formatKeyword from "./format" + +const format: Vocabulary = [formatKeyword] + +export default format diff --git a/node_modules/ajv/lib/vocabularies/jtd/discriminator.ts b/node_modules/ajv/lib/vocabularies/jtd/discriminator.ts new file mode 100644 index 000000000..f487c97f8 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/discriminator.ts @@ -0,0 +1,89 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, not, getProperty, Name} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullableObject} from "./nullable" +import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" +import {DiscrError, DiscrErrorObj} from "../discriminator/types" + +export type JTDDiscriminatorError = + | _JTDTypeError<"discriminator", "object", string> + | DiscrErrorObj + | DiscrErrorObj + +const error: KeywordErrorDefinition = { + message: (cxt) => { + const {schema, params} = cxt + return params.discrError + ? params.discrError === DiscrError.Tag + ? `tag "${schema}" must be string` + : `value of tag "${schema}" must be in mapping` + : typeErrorMessage(cxt, "object") + }, + params: (cxt) => { + const {schema, params} = cxt + return params.discrError + ? _`{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}` + : typeErrorParams(cxt, "object") + }, +} + +const def: CodeKeywordDefinition = { + keyword: "discriminator", + schemaType: "string", + implements: ["mapping"], + error, + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, parentSchema} = cxt + const [valid, cond] = checkNullableObject(cxt, data) + + gen.if(cond) + validateDiscriminator() + gen.elseIf(not(valid)) + cxt.error() + gen.endIf() + cxt.ok(valid) + + function validateDiscriminator(): void { + const tag = gen.const("tag", _`${data}${getProperty(schema)}`) + gen.if(_`${tag} === undefined`) + cxt.error(false, {discrError: DiscrError.Tag, tag}) + gen.elseIf(_`typeof ${tag} == "string"`) + validateMapping(tag) + gen.else() + cxt.error(false, {discrError: DiscrError.Tag, tag}, {instancePath: schema}) + gen.endIf() + } + + function validateMapping(tag: Name): void { + gen.if(false) + for (const tagValue in parentSchema.mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + gen.assign(valid, applyTagSchema(tagValue)) + } + gen.else() + cxt.error( + false, + {discrError: DiscrError.Mapping, tag}, + {instancePath: schema, schemaPath: "mapping", parentSchema: true} + ) + gen.endIf() + } + + function applyTagSchema(schemaProp: string): Name { + const _valid = gen.name("valid") + cxt.subschema( + { + keyword: "mapping", + schemaProp, + jtdDiscriminator: schema, + }, + _valid + ) + return _valid + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/elements.ts b/node_modules/ajv/lib/vocabularies/jtd/elements.ts new file mode 100644 index 000000000..983af7c02 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/elements.ts @@ -0,0 +1,32 @@ +import type {CodeKeywordDefinition, SchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema} from "../../compile/util" +import {validateArray} from "../code" +import {_, not} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullable} from "./nullable" +import {typeError, _JTDTypeError} from "./error" + +export type JTDElementsError = _JTDTypeError<"elements", "array", SchemaObject> + +const def: CodeKeywordDefinition = { + keyword: "elements", + schemaType: "object", + error: typeError("array"), + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, it} = cxt + if (alwaysValidSchema(it, schema)) return + const [valid] = checkNullable(cxt) + gen.if(not(valid), () => + gen.if( + _`Array.isArray(${data})`, + () => gen.assign(valid, validateArray(cxt)), + () => cxt.error() + ) + ) + cxt.ok(valid) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/enum.ts b/node_modules/ajv/lib/vocabularies/jtd/enum.ts new file mode 100644 index 000000000..75464ff8e --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/enum.ts @@ -0,0 +1,45 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, or, and, Code} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullable} from "./nullable" + +export type JTDEnumError = ErrorObject<"enum", {allowedValues: string[]}, string[]> + +const error: KeywordErrorDefinition = { + message: "must be equal to one of the allowed values", + params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "enum", + schemaType: "array", + error, + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, schemaValue, parentSchema, it} = cxt + if (schema.length === 0) throw new Error("enum must have non-empty array") + if (schema.length !== new Set(schema).size) throw new Error("enum items must be unique") + let valid: Code + const isString = _`typeof ${data} == "string"` + if (schema.length >= it.opts.loopEnum) { + let cond: Code + ;[valid, cond] = checkNullable(cxt, isString) + gen.if(cond, loopEnum) + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + valid = and(isString, or(...schema.map((value: string) => _`${data} === ${value}`))) + if (parentSchema.nullable) valid = or(_`${data} === null`, valid) + } + cxt.pass(valid) + + function loopEnum(): void { + gen.forOf("v", schemaValue as Code, (v) => + gen.if(_`${valid} = ${data} === ${v}`, () => gen.break()) + ) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/error.ts b/node_modules/ajv/lib/vocabularies/jtd/error.ts new file mode 100644 index 000000000..506932258 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/error.ts @@ -0,0 +1,23 @@ +import type {KeywordErrorDefinition, KeywordErrorCxt, ErrorObject} from "../../types" +import {_, Code} from "../../compile/codegen" + +export type _JTDTypeError = ErrorObject< + K, + {type: T; nullable: boolean}, + S +> + +export function typeError(t: string): KeywordErrorDefinition { + return { + message: (cxt) => typeErrorMessage(cxt, t), + params: (cxt) => typeErrorParams(cxt, t), + } +} + +export function typeErrorMessage({parentSchema}: KeywordErrorCxt, t: string): string { + return parentSchema?.nullable ? `must be ${t} or null` : `must be ${t}` +} + +export function typeErrorParams({parentSchema}: KeywordErrorCxt, t: string): Code { + return _`{type: ${t}, nullable: ${!!parentSchema?.nullable}}` +} diff --git a/node_modules/ajv/lib/vocabularies/jtd/index.ts b/node_modules/ajv/lib/vocabularies/jtd/index.ts new file mode 100644 index 000000000..f7baebc30 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/index.ts @@ -0,0 +1,37 @@ +import type {Vocabulary} from "../../types" +import refKeyword from "./ref" +import typeKeyword, {JTDTypeError} from "./type" +import enumKeyword, {JTDEnumError} from "./enum" +import elements, {JTDElementsError} from "./elements" +import properties, {JTDPropertiesError} from "./properties" +import optionalProperties from "./optionalProperties" +import discriminator, {JTDDiscriminatorError} from "./discriminator" +import values, {JTDValuesError} from "./values" +import union from "./union" +import metadata from "./metadata" + +const jtdVocabulary: Vocabulary = [ + "definitions", + refKeyword, + typeKeyword, + enumKeyword, + elements, + properties, + optionalProperties, + discriminator, + values, + union, + metadata, + {keyword: "additionalProperties", schemaType: "boolean"}, + {keyword: "nullable", schemaType: "boolean"}, +] + +export default jtdVocabulary + +export type JTDErrorObject = + | JTDTypeError + | JTDEnumError + | JTDElementsError + | JTDPropertiesError + | JTDDiscriminatorError + | JTDValuesError diff --git a/node_modules/ajv/lib/vocabularies/jtd/metadata.ts b/node_modules/ajv/lib/vocabularies/jtd/metadata.ts new file mode 100644 index 000000000..19eeb8c7d --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/metadata.ts @@ -0,0 +1,24 @@ +import {KeywordCxt} from "../../ajv" +import type {CodeKeywordDefinition} from "../../types" +import {alwaysValidSchema} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "metadata", + schemaType: "object", + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, schema, it} = cxt + if (alwaysValidSchema(it, schema)) return + const valid = gen.name("valid") + cxt.subschema({keyword: "metadata", jtdMetadata: true}, valid) + cxt.ok(valid) + }, +} + +export function checkMetadata({it, keyword}: KeywordCxt, metadata?: boolean): void { + if (it.jtdMetadata !== metadata) { + throw new Error(`JTD: "${keyword}" cannot be used in this schema location`) + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/nullable.ts b/node_modules/ajv/lib/vocabularies/jtd/nullable.ts new file mode 100644 index 000000000..c74b05da7 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/nullable.ts @@ -0,0 +1,21 @@ +import type {KeywordCxt} from "../../compile/validate" +import {_, not, nil, Code, Name} from "../../compile/codegen" + +export function checkNullable( + {gen, data, parentSchema}: KeywordCxt, + cond: Code = nil +): [Name, Code] { + const valid = gen.name("valid") + if (parentSchema.nullable) { + gen.let(valid, _`${data} === null`) + cond = not(valid) + } else { + gen.let(valid, false) + } + return [valid, cond] +} + +export function checkNullableObject(cxt: KeywordCxt, cond: Code): [Name, Code] { + const [valid, cond_] = checkNullable(cxt, cond) + return [valid, _`${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`] +} diff --git a/node_modules/ajv/lib/vocabularies/jtd/optionalProperties.ts b/node_modules/ajv/lib/vocabularies/jtd/optionalProperties.ts new file mode 100644 index 000000000..8e91c8d91 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/optionalProperties.ts @@ -0,0 +1,15 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {validateProperties, error} from "./properties" + +const def: CodeKeywordDefinition = { + keyword: "optionalProperties", + schemaType: "object", + error, + code(cxt: KeywordCxt) { + if (cxt.parentSchema.properties) return + validateProperties(cxt) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/properties.ts b/node_modules/ajv/lib/vocabularies/jtd/properties.ts new file mode 100644 index 000000000..9dd24c5cd --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/properties.ts @@ -0,0 +1,184 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + SchemaObject, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {propertyInData, allSchemaProperties, isOwnProperty} from "../code" +import {alwaysValidSchema, schemaRefOrVal} from "../../compile/util" +import {_, and, not, Code, Name} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullableObject} from "./nullable" +import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" + +enum PropError { + Additional = "additional", + Missing = "missing", +} + +type PropKeyword = "properties" | "optionalProperties" + +type PropSchema = {[P in string]?: SchemaObject} + +export type JTDPropertiesError = + | _JTDTypeError + | ErrorObject + | ErrorObject + +export const error: KeywordErrorDefinition = { + message: (cxt) => { + const {params} = cxt + return params.propError + ? params.propError === PropError.Additional + ? "must NOT have additional properties" + : `must have property '${params.missingProperty}'` + : typeErrorMessage(cxt, "object") + }, + params: (cxt) => { + const {params} = cxt + return params.propError + ? params.propError === PropError.Additional + ? _`{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}` + : _`{error: ${params.propError}, missingProperty: ${params.missingProperty}}` + : typeErrorParams(cxt, "object") + }, +} + +const def: CodeKeywordDefinition = { + keyword: "properties", + schemaType: "object", + error, + code: validateProperties, +} + +// const error: KeywordErrorDefinition = { +// message: "should NOT have additional properties", +// params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`, +// } + +export function validateProperties(cxt: KeywordCxt): void { + checkMetadata(cxt) + const {gen, data, parentSchema, it} = cxt + const {additionalProperties, nullable} = parentSchema + if (it.jtdDiscriminator && nullable) throw new Error("JTD: nullable inside discriminator mapping") + if (commonProperties()) { + throw new Error("JTD: properties and optionalProperties have common members") + } + const [allProps, properties] = schemaProperties("properties") + const [allOptProps, optProperties] = schemaProperties("optionalProperties") + if (properties.length === 0 && optProperties.length === 0 && additionalProperties) { + return + } + + const [valid, cond] = + it.jtdDiscriminator === undefined + ? checkNullableObject(cxt, data) + : [gen.let("valid", false), true] + gen.if(cond, () => + gen.assign(valid, true).block(() => { + validateProps(properties, "properties", true) + validateProps(optProperties, "optionalProperties") + if (!additionalProperties) validateAdditional() + }) + ) + cxt.pass(valid) + + function commonProperties(): boolean { + const props = parentSchema.properties as Record | undefined + const optProps = parentSchema.optionalProperties as Record | undefined + if (!(props && optProps)) return false + for (const p in props) { + if (Object.prototype.hasOwnProperty.call(optProps, p)) return true + } + return false + } + + function schemaProperties(keyword: string): [string[], string[]] { + const schema = parentSchema[keyword] + const allPs = schema ? allSchemaProperties(schema) : [] + if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) { + throw new Error(`JTD: discriminator tag used in ${keyword}`) + } + const ps = allPs.filter((p) => !alwaysValidSchema(it, schema[p])) + return [allPs, ps] + } + + function validateProps(props: string[], keyword: string, required?: boolean): void { + const _valid = gen.var("valid") + for (const prop of props) { + gen.if( + propertyInData(gen, data, prop, it.opts.ownProperties), + () => applyPropertySchema(prop, keyword, _valid), + () => missingProperty(prop) + ) + cxt.ok(_valid) + } + + function missingProperty(prop: string): void { + if (required) { + gen.assign(_valid, false) + cxt.error(false, {propError: PropError.Missing, missingProperty: prop}, {schemaPath: prop}) + } else { + gen.assign(_valid, true) + } + } + } + + function applyPropertySchema(prop: string, keyword: string, _valid: Name): void { + cxt.subschema( + { + keyword, + schemaProp: prop, + dataProp: prop, + }, + _valid + ) + } + + function validateAdditional(): void { + gen.forIn("key", data, (key: Name) => { + const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator) + const addOptProp = isAdditional(key, allOptProps, "optionalProperties") + const extra = + addProp === true ? addOptProp : addOptProp === true ? addProp : and(addProp, addOptProp) + gen.if(extra, () => { + if (it.opts.removeAdditional) { + gen.code(_`delete ${data}[${key}]`) + } else { + cxt.error( + false, + {propError: PropError.Additional, additionalProperty: key}, + {instancePath: key, parentSchema: true} + ) + if (!it.opts.allErrors) gen.break() + } + }) + }) + } + + function isAdditional( + key: Name, + props: string[], + keyword: string, + jtdDiscriminator?: string + ): Code | true { + let additional: Code | boolean + if (props.length > 8) { + // TODO maybe an option instead of hard-coded 8? + const propsSchema = schemaRefOrVal(it, parentSchema[keyword], keyword) + additional = not(isOwnProperty(gen, propsSchema as Code, key)) + if (jtdDiscriminator !== undefined) { + additional = and(additional, _`${key} !== ${jtdDiscriminator}`) + } + } else if (props.length || jtdDiscriminator !== undefined) { + const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props) + additional = and(...ps.map((p) => _`${key} !== ${p}`)) + } else { + additional = true + } + return additional + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/ref.ts b/node_modules/ajv/lib/vocabularies/jtd/ref.ts new file mode 100644 index 000000000..97646ee1b --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/ref.ts @@ -0,0 +1,76 @@ +import type {CodeKeywordDefinition, AnySchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {compileSchema, SchemaEnv} from "../../compile" +import {_, not, nil, stringify} from "../../compile/codegen" +import MissingRefError from "../../compile/ref_error" +import N from "../../compile/names" +import {getValidate, callRef} from "../core/ref" +import {checkMetadata} from "./metadata" + +const def: CodeKeywordDefinition = { + keyword: "ref", + schemaType: "string", + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema: ref, parentSchema, it} = cxt + const { + schemaEnv: {root}, + } = it + const valid = gen.name("valid") + if (parentSchema.nullable) { + gen.var(valid, _`${data} === null`) + gen.if(not(valid), validateJtdRef) + } else { + gen.var(valid, false) + validateJtdRef() + } + cxt.ok(valid) + + function validateJtdRef(): void { + const refSchema = (root.schema as AnySchemaObject).definitions?.[ref] + if (!refSchema) { + throw new MissingRefError(it.opts.uriResolver, "", ref, `No definition ${ref}`) + } + if (hasRef(refSchema) || !it.opts.inlineRefs) callValidate(refSchema) + else inlineRefSchema(refSchema) + } + + function callValidate(schema: AnySchemaObject): void { + const sch = compileSchema.call( + it.self, + new SchemaEnv({schema, root, schemaPath: `/definitions/${ref}`}) + ) + const v = getValidate(cxt, sch) + const errsCount = gen.const("_errs", N.errors) + callRef(cxt, v, sch, sch.$async) + gen.assign(valid, _`${errsCount} === ${N.errors}`) + } + + function inlineRefSchema(schema: AnySchemaObject): void { + const schName = gen.scopeValue( + "schema", + it.opts.code.source === true ? {ref: schema, code: stringify(schema)} : {ref: schema} + ) + cxt.subschema( + { + schema, + dataTypes: [], + schemaPath: nil, + topSchemaRef: schName, + errSchemaPath: `/definitions/${ref}`, + }, + valid + ) + } + }, +} + +export function hasRef(schema: AnySchemaObject): boolean { + for (const key in schema) { + let sch: AnySchemaObject + if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch))) return true + } + return false +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/type.ts b/node_modules/ajv/lib/vocabularies/jtd/type.ts new file mode 100644 index 000000000..17274300b --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/type.ts @@ -0,0 +1,75 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, nil, or, Code} from "../../compile/codegen" +import validTimestamp from "../../runtime/timestamp" +import {useFunc} from "../../compile/util" +import {checkMetadata} from "./metadata" +import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" + +export type JTDTypeError = _JTDTypeError<"type", JTDType, JTDType> + +export type IntType = "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" + +export const intRange: {[T in IntType]: [number, number, number]} = { + int8: [-128, 127, 3], + uint8: [0, 255, 3], + int16: [-32768, 32767, 5], + uint16: [0, 65535, 5], + int32: [-2147483648, 2147483647, 10], + uint32: [0, 4294967295, 10], +} + +export type JTDType = "boolean" | "string" | "timestamp" | "float32" | "float64" | IntType + +const error: KeywordErrorDefinition = { + message: (cxt) => typeErrorMessage(cxt, cxt.schema), + params: (cxt) => typeErrorParams(cxt, cxt.schema), +} + +function timestampCode(cxt: KeywordCxt): Code { + const {gen, data, it} = cxt + const {timestamp, allowDate} = it.opts + if (timestamp === "date") return _`${data} instanceof Date ` + const vts = useFunc(gen, validTimestamp) + const allowDateArg = allowDate ? _`, true` : nil + const validString = _`typeof ${data} == "string" && ${vts}(${data}${allowDateArg})` + return timestamp === "string" ? validString : or(_`${data} instanceof Date`, validString) +} + +const def: CodeKeywordDefinition = { + keyword: "type", + schemaType: "string", + error, + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {data, schema, parentSchema, it} = cxt + let cond: Code + switch (schema) { + case "boolean": + case "string": + cond = _`typeof ${data} == ${schema}` + break + case "timestamp": { + cond = timestampCode(cxt) + break + } + case "float32": + case "float64": + cond = _`typeof ${data} == "number"` + break + default: { + const sch = schema as IntType + cond = _`typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)` + if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) { + if (sch === "uint32") cond = _`${cond} && ${data} >= 0` + } else { + const [min, max] = intRange[sch] + cond = _`${cond} && ${data} >= ${min} && ${data} <= ${max}` + } + } + } + cxt.pass(parentSchema.nullable ? or(_`${data} === null`, cond) : cond) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/union.ts b/node_modules/ajv/lib/vocabularies/jtd/union.ts new file mode 100644 index 000000000..588f07ab4 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/union.ts @@ -0,0 +1,12 @@ +import type {CodeKeywordDefinition} from "../../types" +import {validateUnion} from "../code" + +const def: CodeKeywordDefinition = { + keyword: "union", + schemaType: "array", + trackErrors: true, + code: validateUnion, + error: {message: "must match a schema in union"}, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/values.ts b/node_modules/ajv/lib/vocabularies/jtd/values.ts new file mode 100644 index 000000000..e64945077 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/values.ts @@ -0,0 +1,58 @@ +import type {CodeKeywordDefinition, SchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema, Type} from "../../compile/util" +import {not, or, Name} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullableObject} from "./nullable" +import {typeError, _JTDTypeError} from "./error" + +export type JTDValuesError = _JTDTypeError<"values", "object", SchemaObject> + +const def: CodeKeywordDefinition = { + keyword: "values", + schemaType: "object", + error: typeError("object"), + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, it} = cxt + const [valid, cond] = checkNullableObject(cxt, data) + if (alwaysValidSchema(it, schema)) { + gen.if(not(or(cond, valid)), () => cxt.error()) + } else { + gen.if(cond) + gen.assign(valid, validateMap()) + gen.elseIf(not(valid)) + cxt.error() + gen.endIf() + } + cxt.ok(valid) + + function validateMap(): Name | boolean { + const _valid = gen.name("valid") + if (it.allErrors) { + const validMap = gen.let("valid", true) + validateValues(() => gen.assign(validMap, false)) + return validMap + } + gen.var(_valid, true) + validateValues(() => gen.break()) + return _valid + + function validateValues(notValid: () => void): void { + gen.forIn("key", data, (key) => { + cxt.subschema( + { + keyword: "values", + dataProp: key, + dataPropType: Type.Str, + }, + _valid + ) + gen.if(not(_valid), notValid) + }) + } + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/metadata.ts b/node_modules/ajv/lib/vocabularies/metadata.ts new file mode 100644 index 000000000..b9d5af85f --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/metadata.ts @@ -0,0 +1,17 @@ +import type {Vocabulary} from "../types" + +export const metadataVocabulary: Vocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples", +] + +export const contentVocabulary: Vocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema", +] diff --git a/node_modules/ajv/lib/vocabularies/next.ts b/node_modules/ajv/lib/vocabularies/next.ts new file mode 100644 index 000000000..1e987ad21 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/next.ts @@ -0,0 +1,8 @@ +import type {Vocabulary} from "../types" +import dependentRequired from "./validation/dependentRequired" +import dependentSchemas from "./applicator/dependentSchemas" +import limitContains from "./validation/limitContains" + +const next: Vocabulary = [dependentRequired, dependentSchemas, limitContains] + +export default next diff --git a/node_modules/ajv/lib/vocabularies/unevaluated/index.ts b/node_modules/ajv/lib/vocabularies/unevaluated/index.ts new file mode 100644 index 000000000..f7f0815db --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/unevaluated/index.ts @@ -0,0 +1,7 @@ +import type {Vocabulary} from "../../types" +import unevaluatedProperties from "./unevaluatedProperties" +import unevaluatedItems from "./unevaluatedItems" + +const unevaluated: Vocabulary = [unevaluatedProperties, unevaluatedItems] + +export default unevaluated diff --git a/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts b/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts new file mode 100644 index 000000000..50bf0e7c1 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts @@ -0,0 +1,47 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, Type} from "../../compile/util" + +export type UnevaluatedItemsError = ErrorObject<"unevaluatedItems", {limit: number}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params: {len}}) => str`must NOT have more than ${len} items`, + params: ({params: {len}}) => _`{limit: ${len}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error, + code(cxt: KeywordCxt) { + const {gen, schema, data, it} = cxt + const items = it.items || 0 + if (items === true) return + const len = gen.const("len", _`${data}.length`) + if (schema === false) { + cxt.setParams({len: items}) + cxt.fail(_`${len} > ${items}`) + } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { + const valid = gen.var("valid", _`${len} <= ${items}`) + gen.if(not(valid), () => validateItems(valid, items)) + cxt.ok(valid) + } + it.items = true + + function validateItems(valid: Name, from: Name | number): void { + gen.forRange("i", from, len, (i) => { + cxt.subschema({keyword: "unevaluatedItems", dataProp: i, dataPropType: Type.Num}, valid) + if (!it.allErrors) gen.if(not(valid), () => gen.break()) + }) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts b/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts new file mode 100644 index 000000000..0e6868fa3 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts @@ -0,0 +1,85 @@ +import type { + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, + AnySchema, +} from "../../types" +import {_, not, and, Name, Code} from "../../compile/codegen" +import {alwaysValidSchema, Type} from "../../compile/util" +import N from "../../compile/names" + +export type UnevaluatedPropertiesError = ErrorObject< + "unevaluatedProperties", + {unevaluatedProperty: string}, + AnySchema +> + +const error: KeywordErrorDefinition = { + message: "must NOT have unevaluated properties", + params: ({params}) => _`{unevaluatedProperty: ${params.unevaluatedProperty}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error, + code(cxt) { + const {gen, schema, data, errsCount, it} = cxt + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error") + const {allErrors, props} = it + if (props instanceof Name) { + gen.if(_`${props} !== true`, () => + gen.forIn("key", data, (key: Name) => + gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)) + ) + ) + } else if (props !== true) { + gen.forIn("key", data, (key: Name) => + props === undefined + ? unevaluatedPropCode(key) + : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)) + ) + } + it.props = true + cxt.ok(_`${errsCount} === ${N.errors}`) + + function unevaluatedPropCode(key: Name): void { + if (schema === false) { + cxt.setParams({unevaluatedProperty: key}) + cxt.error() + if (!allErrors) gen.break() + return + } + + if (!alwaysValidSchema(it, schema)) { + const valid = gen.name("valid") + cxt.subschema( + { + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: Type.Str, + }, + valid + ) + if (!allErrors) gen.if(not(valid), () => gen.break()) + } + } + + function unevaluatedDynamic(evaluatedProps: Name, key: Name): Code { + return _`!${evaluatedProps} || !${evaluatedProps}[${key}]` + } + + function unevaluatedStatic(evaluatedProps: {[K in string]?: true}, key: Name): Code { + const ps: Code[] = [] + for (const p in evaluatedProps) { + if (evaluatedProps[p] === true) ps.push(_`${key} !== ${p}`) + } + return and(...ps) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/const.ts b/node_modules/ajv/lib/vocabularies/validation/const.ts new file mode 100644 index 000000000..a3b94a5dc --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/const.ts @@ -0,0 +1,28 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import equal from "../../runtime/equal" + +export type ConstError = ErrorObject<"const", {allowedValue: any}> + +const error: KeywordErrorDefinition = { + message: "must be equal to constant", + params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "const", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schemaCode, schema} = cxt + if ($data || (schema && typeof schema == "object")) { + cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`) + } else { + cxt.fail(_`${schema} !== ${data}`) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts b/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts new file mode 100644 index 000000000..4c616cfa9 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts @@ -0,0 +1,23 @@ +import type {CodeKeywordDefinition, ErrorObject} from "../../types" +import { + validatePropertyDeps, + error, + DependenciesErrorParams, + PropertyDependencies, +} from "../applicator/dependencies" + +export type DependentRequiredError = ErrorObject< + "dependentRequired", + DependenciesErrorParams, + PropertyDependencies +> + +const def: CodeKeywordDefinition = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error, + code: (cxt) => validatePropertyDeps(cxt), +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/enum.ts b/node_modules/ajv/lib/vocabularies/validation/enum.ts new file mode 100644 index 000000000..76377fb02 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/enum.ts @@ -0,0 +1,54 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, or, Name, Code} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import equal from "../../runtime/equal" + +export type EnumError = ErrorObject<"enum", {allowedValues: any[]}, any[] | {$data: string}> + +const error: KeywordErrorDefinition = { + message: "must be equal to one of the allowed values", + params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "enum", + schemaType: "array", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schema, schemaCode, it} = cxt + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array") + const useLoop = schema.length >= it.opts.loopEnum + let eql: Name | undefined + const getEql = (): Name => (eql ??= useFunc(gen, equal)) + + let valid: Code + if (useLoop || $data) { + valid = gen.let("valid") + cxt.block$data(valid, loopEnum) + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + const vSchema = gen.const("vSchema", schemaCode) + valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i))) + } + cxt.pass(valid) + + function loopEnum(): void { + gen.assign(valid, false) + gen.forOf("v", schemaCode as Code, (v) => + gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()) + ) + } + + function equalCode(vSchema: Name, i: number): Code { + const sch = schema[i] + return typeof sch === "object" && sch !== null + ? _`${getEql()}(${data}, ${vSchema}[${i}])` + : _`${data} === ${sch}` + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/index.ts b/node_modules/ajv/lib/vocabularies/validation/index.ts new file mode 100644 index 000000000..3531b1962 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/index.ts @@ -0,0 +1,49 @@ +import type {ErrorObject, Vocabulary} from "../../types" +import limitNumber, {LimitNumberError} from "./limitNumber" +import multipleOf, {MultipleOfError} from "./multipleOf" +import limitLength from "./limitLength" +import pattern, {PatternError} from "./pattern" +import limitProperties from "./limitProperties" +import required, {RequiredError} from "./required" +import limitItems from "./limitItems" +import uniqueItems, {UniqueItemsError} from "./uniqueItems" +import constKeyword, {ConstError} from "./const" +import enumKeyword, {EnumError} from "./enum" + +const validation: Vocabulary = [ + // number + limitNumber, + multipleOf, + // string + limitLength, + pattern, + // object + limitProperties, + required, + // array + limitItems, + uniqueItems, + // any + {keyword: "type", schemaType: ["string", "array"]}, + {keyword: "nullable", schemaType: "boolean"}, + constKeyword, + enumKeyword, +] + +export default validation + +type LimitError = ErrorObject< + "maxItems" | "minItems" | "minProperties" | "maxProperties" | "minLength" | "maxLength", + {limit: number}, + number | {$data: string} +> + +export type ValidationKeywordError = + | LimitError + | LimitNumberError + | MultipleOfError + | PatternError + | RequiredError + | UniqueItemsError + | ConstError + | EnumError diff --git a/node_modules/ajv/lib/vocabularies/validation/limitContains.ts b/node_modules/ajv/lib/vocabularies/validation/limitContains.ts new file mode 100644 index 000000000..8bb43c1a4 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/limitContains.ts @@ -0,0 +1,16 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {checkStrictMode} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({keyword, parentSchema, it}: KeywordCxt) { + if (parentSchema.contains === undefined) { + checkStrictMode(it, `"${keyword}" without "contains" is ignored`) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/limitItems.ts b/node_modules/ajv/lib/vocabularies/validation/limitItems.ts new file mode 100644 index 000000000..566de8588 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/limitItems.ts @@ -0,0 +1,26 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators} from "../../compile/codegen" + +const error: KeywordErrorDefinition = { + message({keyword, schemaCode}) { + const comp = keyword === "maxItems" ? "more" : "fewer" + return str`must NOT have ${comp} than ${schemaCode} items` + }, + params: ({schemaCode}) => _`{limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode} = cxt + const op = keyword === "maxItems" ? operators.GT : operators.LT + cxt.fail$data(_`${data}.length ${op} ${schemaCode}`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/limitLength.ts b/node_modules/ajv/lib/vocabularies/validation/limitLength.ts new file mode 100644 index 000000000..f4f947259 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/limitLength.ts @@ -0,0 +1,30 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import ucs2length from "../../runtime/ucs2length" + +const error: KeywordErrorDefinition = { + message({keyword, schemaCode}) { + const comp = keyword === "maxLength" ? "more" : "fewer" + return str`must NOT have ${comp} than ${schemaCode} characters` + }, + params: ({schemaCode}) => _`{limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode, it} = cxt + const op = keyword === "maxLength" ? operators.GT : operators.LT + const len = + it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})` + cxt.fail$data(_`${len} ${op} ${schemaCode}`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts b/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts new file mode 100644 index 000000000..5499202ef --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts @@ -0,0 +1,42 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators, Code} from "../../compile/codegen" + +const ops = operators + +type Kwd = "maximum" | "minimum" | "exclusiveMaximum" | "exclusiveMinimum" + +type Comparison = "<=" | ">=" | "<" | ">" + +const KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = { + maximum: {okStr: "<=", ok: ops.LTE, fail: ops.GT}, + minimum: {okStr: ">=", ok: ops.GTE, fail: ops.LT}, + exclusiveMaximum: {okStr: "<", ok: ops.LT, fail: ops.GTE}, + exclusiveMinimum: {okStr: ">", ok: ops.GT, fail: ops.LTE}, +} + +export type LimitNumberError = ErrorObject< + Kwd, + {limit: number; comparison: Comparison}, + number | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`, + params: ({keyword, schemaCode}) => + _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode} = cxt + cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts b/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts new file mode 100644 index 000000000..07fffa8b3 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts @@ -0,0 +1,26 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators} from "../../compile/codegen" + +const error: KeywordErrorDefinition = { + message({keyword, schemaCode}) { + const comp = keyword === "maxProperties" ? "more" : "fewer" + return str`must NOT have ${comp} than ${schemaCode} properties` + }, + params: ({schemaCode}) => _`{limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode} = cxt + const op = keyword === "maxProperties" ? operators.GT : operators.LT + cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts b/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts new file mode 100644 index 000000000..1fd79abbd --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts @@ -0,0 +1,34 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str} from "../../compile/codegen" + +export type MultipleOfError = ErrorObject< + "multipleOf", + {multipleOf: number}, + number | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({schemaCode}) => str`must be multiple of ${schemaCode}`, + params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, schemaCode, it} = cxt + // const bdt = bad$DataType(schemaCode, def.schemaType, $data) + const prec = it.opts.multipleOfPrecision + const res = gen.let("res") + const invalid = prec + ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` + : _`${res} !== parseInt(${res})` + cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/pattern.ts b/node_modules/ajv/lib/vocabularies/validation/pattern.ts new file mode 100644 index 000000000..7b27b7d3c --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/pattern.ts @@ -0,0 +1,28 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {usePattern} from "../code" +import {_, str} from "../../compile/codegen" + +export type PatternError = ErrorObject<"pattern", {pattern: string}, string | {$data: string}> + +const error: KeywordErrorDefinition = { + message: ({schemaCode}) => str`must match pattern "${schemaCode}"`, + params: ({schemaCode}) => _`{pattern: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt: KeywordCxt) { + const {data, $data, schema, schemaCode, it} = cxt + // TODO regexp should be wrapped in try/catchs + const u = it.opts.unicodeRegExp ? "u" : "" + const regExp = $data ? _`(new RegExp(${schemaCode}, ${u}))` : usePattern(cxt, schema) + cxt.fail$data(_`!${regExp}.test(${data})`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/required.ts b/node_modules/ajv/lib/vocabularies/validation/required.ts new file mode 100644 index 000000000..fea7367ed --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/required.ts @@ -0,0 +1,98 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import { + checkReportMissingProp, + checkMissingProp, + reportMissingProp, + propertyInData, + noPropertyInData, +} from "../code" +import {_, str, nil, not, Name, Code} from "../../compile/codegen" +import {checkStrictMode} from "../../compile/util" + +export type RequiredError = ErrorObject< + "required", + {missingProperty: string}, + string[] | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`, + params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, schema, schemaCode, data, $data, it} = cxt + const {opts} = it + if (!$data && schema.length === 0) return + const useLoop = schema.length >= opts.loopRequired + if (it.allErrors) allErrorsMode() + else exitOnErrorMode() + + if (opts.strictRequired) { + const props = cxt.parentSchema.properties + const {definedProperties} = cxt.it + for (const requiredKey of schema) { + if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)` + checkStrictMode(it, msg, it.opts.strictRequired) + } + } + } + + function allErrorsMode(): void { + if (useLoop || $data) { + cxt.block$data(nil, loopAllRequired) + } else { + for (const prop of schema) { + checkReportMissingProp(cxt, prop) + } + } + } + + function exitOnErrorMode(): void { + const missing = gen.let("missing") + if (useLoop || $data) { + const valid = gen.let("valid", true) + cxt.block$data(valid, () => loopUntilMissing(missing, valid)) + cxt.ok(valid) + } else { + gen.if(checkMissingProp(cxt, schema, missing)) + reportMissingProp(cxt, missing) + gen.else() + } + } + + function loopAllRequired(): void { + gen.forOf("prop", schemaCode as Code, (prop) => { + cxt.setParams({missingProperty: prop}) + gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error()) + }) + } + + function loopUntilMissing(missing: Name, valid: Name): void { + cxt.setParams({missingProperty: missing}) + gen.forOf( + missing, + schemaCode as Code, + () => { + gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties)) + gen.if(not(valid), () => { + cxt.error() + gen.break() + }) + }, + nil + ) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts b/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts new file mode 100644 index 000000000..765c4d04f --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts @@ -0,0 +1,79 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {checkDataTypes, getSchemaTypes, DataType} from "../../compile/validate/dataType" +import {_, str, Name} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import equal from "../../runtime/equal" + +export type UniqueItemsError = ErrorObject< + "uniqueItems", + {i: number; j: number}, + boolean | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({params: {i, j}}) => + str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt + if (!$data && !schema) return + const valid = gen.let("valid") + const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : [] + cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`) + cxt.ok(valid) + + function validateUniqueItems(): void { + const i = gen.let("i", _`${data}.length`) + const j = gen.let("j") + cxt.setParams({i, j}) + gen.assign(valid, true) + gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)) + } + + function canOptimize(): boolean { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array") + } + + function loopN(i: Name, j: Name): void { + const item = gen.name("item") + const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong) + const indices = gen.const("indices", _`{}`) + gen.for(_`;${i}--;`, () => { + gen.let(item, _`${data}[${i}]`) + gen.if(wrongType, _`continue`) + if (itemTypes.length > 1) gen.if(_`typeof ${item} == "string"`, _`${item} += "_"`) + gen + .if(_`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, _`${indices}[${item}]`) + cxt.error() + gen.assign(valid, false).break() + }) + .code(_`${indices}[${item}] = ${i}`) + }) + } + + function loopN2(i: Name, j: Name): void { + const eql = useFunc(gen, equal) + const outer = gen.name("outer") + gen.label(outer).for(_`;${i}--;`, () => + gen.for(_`${j} = ${i}; ${j}--;`, () => + gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error() + gen.assign(valid, false).break(outer) + }) + ) + ) + } + }, +} + +export default def diff --git a/node_modules/ajv/package.json b/node_modules/ajv/package.json new file mode 100644 index 000000000..17df7b147 --- /dev/null +++ b/node_modules/ajv/package.json @@ -0,0 +1,126 @@ +{ + "name": "ajv", + "version": "8.17.1", + "description": "Another JSON Schema Validator", + "main": "dist/ajv.js", + "types": "dist/ajv.d.ts", + "files": [ + "lib/", + "dist/", + ".runkit_example.js" + ], + "scripts": { + "eslint": "eslint \"lib/**/*.ts\" \"spec/**/*.*s\" --ignore-pattern spec/JSON-Schema-Test-Suite", + "prettier:write": "prettier --write \"./**/*.{json,yaml,js,ts}\"", + "prettier:check": "prettier --list-different \"./**/*.{json,yaml,js,ts}\"", + "test-spec": "cross-env TS_NODE_PROJECT=spec/tsconfig.json mocha -r ts-node/register \"spec/**/*.spec.{ts,js}\" -R dot", + "test-codegen": "nyc cross-env TS_NODE_PROJECT=spec/tsconfig.json mocha -r ts-node/register 'spec/codegen.spec.ts' -R spec", + "test-debug": "npm run test-spec -- --inspect-brk", + "test-cov": "nyc npm run test-spec", + "rollup": "rm -rf bundle && rollup -c", + "bundle": "rm -rf bundle && node ./scripts/bundle.js ajv ajv7 ajv7 && node ./scripts/bundle.js 2019 ajv2019 ajv2019 && node ./scripts/bundle.js 2020 ajv2020 ajv2020 && node ./scripts/bundle.js jtd ajvJTD ajvJTD", + "build": "rm -rf dist && tsc && cp -r lib/refs dist && rm dist/refs/json-schema-2019-09/index.ts && rm dist/refs/json-schema-2020-12/index.ts && rm dist/refs/jtd-schema.ts", + "json-tests": "rm -rf spec/_json/*.js && node scripts/jsontests", + "test-karma": "karma start", + "test-browser": "rm -rf .browser && npm run bundle && scripts/prepare-tests && karma start", + "test-all": "npm run test-cov && if-node-version 12 npm run test-browser", + "test": "npm run json-tests && npm run prettier:check && npm run eslint && npm link && npm link --legacy-peer-deps ajv && npm run test-cov", + "test-ci": "AJV_FULL_TEST=true npm test", + "prepublish": "npm run build", + "benchmark": "npm i && npm run build && npm link && cd ./benchmark && npm link --legacy-peer-deps ajv && npm i && node ./jtd", + "docs:dev": "./scripts/prepare-site && vuepress dev docs", + "docs:build": "./scripts/prepare-site && vuepress build docs" + }, + "nyc": { + "exclude": [ + "**/spec/**", + "node_modules" + ], + "reporter": [ + "lcov", + "text-summary" + ] + }, + "repository": "ajv-validator/ajv", + "keywords": [ + "JSON", + "schema", + "validator", + "validation", + "jsonschema", + "json-schema", + "json-schema-validator", + "json-schema-validation" + ], + "author": "Evgeny Poberezkin", + "license": "MIT", + "bugs": "https://github.com/ajv-validator/ajv/issues", + "homepage": "https://ajv.js.org", + "runkitExampleFilename": ".runkit_example.js", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "devDependencies": { + "@ajv-validator/config": "^0.5.0", + "@rollup/plugin-commonjs": "^25.0.7", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-typescript": "^11.1.6", + "@types/chai": "^4.3.11", + "@types/mocha": "^10.0.6", + "@types/node": "^20.11.30", + "@types/require-from-string": "^1.2.3", + "@typescript-eslint/eslint-plugin": "^7.3.1", + "@typescript-eslint/parser": "^7.3.1", + "ajv-formats": "^3.0.1", + "browserify": "^17.0.0", + "chai": "^4.4.1", + "cross-env": "^7.0.3", + "dayjs": "^1.11.10", + "dayjs-plugin-utc": "^0.1.2", + "eslint": "^8.57.0", + "eslint-config-prettier": "^9.1.0", + "glob": "^10.3.10", + "husky": "^9.0.11", + "if-node-version": "^1.1.1", + "jimp": "^0.22.10", + "js-beautify": "^1.15.1", + "json-schema-test": "^2.0.0", + "karma": "^6.4.2", + "karma-chrome-launcher": "^3.2.0", + "karma-mocha": "^2.0.1", + "lint-staged": "^15.2.2", + "mocha": "^10.3.0", + "module-from-string": "^3.3.0", + "node-fetch": "^3.3.2", + "nyc": "^15.1.0", + "prettier": "3.0.3", + "re2": "^1.20.9", + "rollup": "^2.79.1", + "rollup-plugin-terser": "^7.0.2", + "ts-node": "^10.9.2", + "tsify": "^5.0.4", + "typescript": "5.3.3", + "uri-js": "^4.4.1" + }, + "collective": { + "type": "opencollective", + "url": "https://opencollective.com/ajv" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + }, + "prettier": "@ajv-validator/config/prettierrc.json", + "husky": { + "hooks": { + "pre-commit": "lint-staged && npm test" + } + }, + "lint-staged": { + "*.{json,yaml,js,ts}": "prettier --write" + } +} diff --git a/node_modules/body-parser/LICENSE b/node_modules/body-parser/LICENSE new file mode 100644 index 000000000..386b7b694 --- /dev/null +++ b/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-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/body-parser/README.md b/node_modules/body-parser/README.md new file mode 100644 index 000000000..39d320f55 --- /dev/null +++ b/node_modules/body-parser/README.md @@ -0,0 +1,494 @@ +# body-parser + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] + +Node.js body parsing middleware. + +Parse incoming request bodies in a middleware before your handlers, available +under the `req.body` property. + +**Note** As `req.body`'s shape is based on user-controlled input, all +properties and values in this object are untrusted and should be validated +before trusting. For example, `req.body.foo.toString()` may fail in multiple +ways, for example the `foo` property may not be there or may not be a string, +and `toString` may not be a function and instead a string or other user input. + +[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/learn/http/anatomy-of-an-http-transaction). + +_This does not handle multipart bodies_, due to their complex and typically +large nature. For multipart bodies, you may be interested in the following +modules: + + * [busboy](https://www.npmjs.com/package/busboy#readme) and + [connect-busboy](https://www.npmjs.com/package/connect-busboy#readme) + * [multiparty](https://www.npmjs.com/package/multiparty#readme) and + [connect-multiparty](https://www.npmjs.com/package/connect-multiparty#readme) + * [formidable](https://www.npmjs.com/package/formidable#readme) + * [multer](https://www.npmjs.com/package/multer#readme) + +This module provides the following parsers: + + * [JSON body parser](#bodyparserjsonoptions) + * [Raw body parser](#bodyparserrawoptions) + * [Text body parser](#bodyparsertextoptions) + * [URL-encoded form body parser](#bodyparserurlencodedoptions) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.com/package/body#readme) +- [co-body](https://www.npmjs.com/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + +```js +const bodyParser = require('body-parser') +``` + +The `bodyParser` object exposes various factories to create middlewares. All +middlewares will populate the `req.body` property with the parsed body when +the `Content-Type` request header matches the `type` option. + +The various errors returned by this module are described in the +[errors section](#errors). + +### bodyParser.json([options]) + +Returns middleware that only parses `json` and only looks at requests where +the `Content-Type` header matches the `type` option. This parser accepts any +Unicode encoding of the body and supports automatic inflation of `gzip`, +`br` (brotli) and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). + +#### Options + +The `json` function takes an optional `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the json content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### reviver + +The `reviver` option is passed directly to `JSON.parse` as the second +argument. You can find more information on this argument +[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). + +##### strict + +When set to `true`, will only accept arrays and objects; when `false` will +accept anything `JSON.parse` accepts. Defaults to `true`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not a +function, `type` option is passed directly to the +[type-is](https://www.npmjs.com/package/type-is#readme) library and this can +be an extension name (like `json`), a mime type (like `application/json`), or +a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a truthy +value. Defaults to `application/json`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.raw([options]) + +Returns middleware that parses all bodies as a `Buffer` and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate` +encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a `Buffer` object +of the body. + +#### Options + +The `raw` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. +If not a function, `type` option is passed directly to the +[type-is](https://www.npmjs.com/package/type-is#readme) library and this +can be an extension name (like `bin`), a mime type (like +`application/octet-stream`), or a mime type with a wildcard (like `*/*` or +`application/*`). If a function, the `type` option is called as `fn(req)` +and the request is parsed if it returns a truthy value. Defaults to +`application/octet-stream`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text([options]) + +Returns middleware that parses all bodies as a string and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate` +encodings. + +A new `body` string containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a string of the +body. + +#### Options + +The `text` function takes an optional `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the text content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.com/package/type-is#readme) library and this can +be an extension name (like `txt`), a mime type (like `text/plain`), or a mime +type with a wildcard (like `*/*` or `text/*`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a +truthy value. Defaults to `text/plain`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded([options]) + +Returns middleware that only parses `urlencoded` bodies and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser accepts only UTF-8 and ISO-8859-1 encodings of the body and supports +automatic inflation of `gzip`, `br` (brotli) and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This object will contain +key-value pairs, where the value can be a string or array (when `extended` is +`false`), or any type (when `extended` is `true`). + +#### Options + +The `urlencoded` function takes an optional `options` object that may contain +any of the following keys: + +##### extended + +The "extended" syntax allows for rich objects and arrays to be encoded into the +URL-encoded format, allowing for a JSON-like experience with URL-encoded. For +more information, please [see the qs +library](https://www.npmjs.com/package/qs#readme). + +Defaults to `false`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### parameterLimit + +The `parameterLimit` option controls the maximum number of parameters that +are allowed in the URL-encoded data. If a request contains more parameters +than this value, a 413 will be returned to the client. Defaults to `1000`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.com/package/type-is#readme) library and this can +be an extension name (like `urlencoded`), a mime type (like +`application/x-www-form-urlencoded`), or a mime type with a wildcard (like +`*/x-www-form-urlencoded`). If a function, the `type` option is called as +`fn(req)` and the request is parsed if it returns a truthy value. Defaults +to `application/x-www-form-urlencoded`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +##### defaultCharset + +The default charset to parse as, if not specified in content-type. Must be +either `utf-8` or `iso-8859-1`. Defaults to `utf-8`. + +##### charsetSentinel + +Whether to let the value of the `utf8` parameter take precedence as the charset +selector. It requires the form to contain a parameter named `utf8` with a value +of `✓`. Defaults to `false`. + +##### interpretNumericEntities + +Whether to decode numeric entities such as `☺` when parsing an iso-8859-1 +form. Defaults to `false`. + + +##### depth + +The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible. + +## Errors + +The middlewares provided by this module create errors using the +[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors +will typically have a `status`/`statusCode` property that contains the suggested +HTTP response code, an `expose` property to determine if the `message` property +should be displayed to the client, a `type` property to determine the type of +error without matching against the `message`, and a `body` property containing +the read body, if available. + +The following are the common errors created, though any error can come through +for various reasons. + +### content encoding unsupported + +This error will occur when the request had a `Content-Encoding` header that +contained an encoding but the "inflation" option was set to `false`. The +`status` property is set to `415`, the `type` property is set to +`'encoding.unsupported'`, and the `charset` property will be set to the +encoding that is unsupported. + +### entity parse failed + +This error will occur when the request contained an entity that could not be +parsed by the middleware. The `status` property is set to `400`, the `type` +property is set to `'entity.parse.failed'`, and the `body` property is set to +the entity value that failed parsing. + +### entity verify failed + +This error will occur when the request contained an entity that could not be +failed verification by the defined `verify` option. The `status` property is +set to `403`, the `type` property is set to `'entity.verify.failed'`, and the +`body` property is set to the entity value that failed verification. + +### request aborted + +This error will occur when the request is aborted by the client before reading +the body has finished. The `received` property will be set to the number of +bytes received before the request was aborted and the `expected` property is +set to the number of expected bytes. The `status` property is set to `400` +and `type` property is set to `'request.aborted'`. + +### request entity too large + +This error will occur when the request body's size is larger than the "limit" +option. The `limit` property will be set to the byte limit and the `length` +property will be set to the request body's length. The `status` property is +set to `413` and the `type` property is set to `'entity.too.large'`. + +### request size did not match content length + +This error will occur when the request's length did not match the length from +the `Content-Length` header. This typically occurs when the request is malformed, +typically when the `Content-Length` header was calculated based on characters +instead of bytes. The `status` property is set to `400` and the `type` property +is set to `'request.size.invalid'`. + +### stream encoding should not be set + +This error will occur when something called the `req.setEncoding` method prior +to this middleware. This module operates directly on bytes only and you cannot +call `req.setEncoding` when using this module. The `status` property is set to +`500` and the `type` property is set to `'stream.encoding.set'`. + +### stream is not readable + +This error will occur when the request is no longer readable when this middleware +attempts to read it. This typically means something other than a middleware from +this module read the request body already and the middleware was also configured to +read the same request. The `status` property is set to `500` and the `type` +property is set to `'stream.not.readable'`. + +### too many parameters + +This error will occur when the content of the request exceeds the configured +`parameterLimit` for the `urlencoded` parser. The `status` property is set to +`413` and the `type` property is set to `'parameters.too.many'`. + +### unsupported charset "BOGUS" + +This error will occur when the request had a charset parameter in the +`Content-Type` header, but the `iconv-lite` module does not support it OR the +parser does not support it. The charset is contained in the message as well +as in the `charset` property. The `status` property is set to `415`, the +`type` property is set to `'charset.unsupported'`, and the `charset` property +is set to the charset that is unsupported. + +### unsupported content encoding "bogus" + +This error will occur when the request had a `Content-Encoding` header that +contained an unsupported encoding. The encoding is contained in the message +as well as in the `encoding` property. The `status` property is set to `415`, +the `type` property is set to `'encoding.unsupported'`, and the `encoding` +property is set to the encoding that is unsupported. + +### The input exceeded the depth + +This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. When the `depth` option is set to `32` (default value), the error will not be thrown. + +## Examples + +### Express/Connect top-level generic + +This example demonstrates adding a generic JSON and URL-encoded parser as a +top-level middleware, which will parse the bodies of all incoming requests. +This is the simplest setup. + +```js +const express = require('express') +const bodyParser = require('body-parser') + +const app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded()) + +// parse application/json +app.use(bodyParser.json()) + +app.use(function (req, res) { + res.setHeader('Content-Type', 'text/plain') + res.write('you posted:\n') + res.end(String(JSON.stringify(req.body, null, 2))) +}) +``` + +### Express route-specific + +This example demonstrates adding body parsers specifically to the routes that +need them. In general, this is the most recommended way to use body-parser with +Express. + +```js +const express = require('express') +const bodyParser = require('body-parser') + +const app = express() + +// create application/json parser +const jsonParser = bodyParser.json() + +// create application/x-www-form-urlencoded parser +const urlencodedParser = bodyParser.urlencoded() + +// POST /login gets urlencoded bodies +app.post('/login', urlencodedParser, function (req, res) { + if (!req.body || !req.body.username) res.sendStatus(400) + res.send('welcome, ' + req.body.username) +}) + +// POST /api/users gets JSON bodies +app.post('/api/users', jsonParser, function (req, res) { + if (!req.body) res.sendStatus(400) + // create user in req.body +}) +``` + +### Change accepted type for parsers + +All the parsers accept a `type` option which allows you to change the +`Content-Type` that the middleware will parse. + +```js +const express = require('express') +const bodyParser = require('body-parser') + +const app = express() + +// parse various different custom JSON types as JSON +app.use(bodyParser.json({ type: 'application/*+json' })) + +// parse some custom thing into a Buffer +app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) + +// parse an HTML body into a string +app.use(bodyParser.text({ type: 'text/html' })) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://img.shields.io/github/actions/workflow/status/expressjs/body-parser/ci.yml?branch=master&label=ci +[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml +[coveralls-image]: https://img.shields.io/coverallsCoverage/github/expressjs/body-parser?branch=master +[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master +[npm-downloads-image]: https://img.shields.io/npm/dm/body-parser +[npm-url]: https://npmjs.com/package/body-parser +[npm-version-image]: https://img.shields.io/npm/v/body-parser +[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge +[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser diff --git a/node_modules/body-parser/index.js b/node_modules/body-parser/index.js new file mode 100644 index 000000000..013ce5c4e --- /dev/null +++ b/node_modules/body-parser/index.js @@ -0,0 +1,71 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * @typedef {Object} Parsers + * @property {Function} json JSON parser + * @property {Function} raw Raw parser + * @property {Function} text Text parser + * @property {Function} urlencoded URL-encoded parser + */ + +/** + * Module exports. + * @type {Function & Parsers} + */ +exports = module.exports = bodyParser + +/** + * JSON parser. + * @public + */ +Object.defineProperty(exports, 'json', { + configurable: true, + enumerable: true, + get: () => require('./lib/types/json') +}) + +/** + * Raw parser. + * @public + */ +Object.defineProperty(exports, 'raw', { + configurable: true, + enumerable: true, + get: () => require('./lib/types/raw') +}) + +/** + * Text parser. + * @public + */ +Object.defineProperty(exports, 'text', { + configurable: true, + enumerable: true, + get: () => require('./lib/types/text') +}) + +/** + * URL-encoded parser. + * @public + */ +Object.defineProperty(exports, 'urlencoded', { + configurable: true, + enumerable: true, + get: () => require('./lib/types/urlencoded') +}) + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @deprecated + * @public + */ +function bodyParser () { + throw new Error('The bodyParser() generic has been split into individual middleware to use instead.') +} diff --git a/node_modules/body-parser/lib/read.js b/node_modules/body-parser/lib/read.js new file mode 100644 index 000000000..d1f3f4808 --- /dev/null +++ b/node_modules/body-parser/lib/read.js @@ -0,0 +1,247 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var getBody = require('raw-body') +var iconv = require('iconv-lite') +var onFinished = require('on-finished') +var zlib = require('node:zlib') +var hasBody = require('type-is').hasBody +var { getCharset } = require('./utils') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {Object} req + * @param {Object} res + * @param {Function} next + * @param {Function} parse + * @param {Function} debug + * @param {Object} options + * @private + */ +function read (req, res, next, parse, debug, options) { + if (onFinished.isFinished(req)) { + debug('body already parsed') + next() + return + } + + if (!('body' in req)) { + req.body = undefined + } + + // skip requests without bodies + if (!hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!options.shouldParse(req)) { + debug('skip parsing') + next() + return + } + + var encoding = null + if (options?.skipCharset !== true) { + encoding = getCharset(req) || options.defaultCharset + + // validate charset + if (!!options?.isValidCharset && !options.isValidCharset(encoding)) { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding, + type: 'charset.unsupported' + })) + return + } + } + + var length + var opts = options + var stream + + // read options + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error + + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } + + // unpipe from stream and destroy + if (stream !== req) { + req.unpipe() + stream.destroy() + } + + // read off entire request + dump(req, function onfinished () { + next(createError(400, _error)) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } + + // parse + var str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str, encoding) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {Object} req + * @param {Function} debug + * @param {boolean} inflate + * @returns {Object} + * @private + */ +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + if (encoding === 'identity') { + req.length = length + return req + } + + var stream = createDecompressionStream(encoding, debug) + req.pipe(stream) + return stream +} + +/** + * Create a decompression stream for the given encoding. + * @param {string} encoding + * @param {Function} debug + * @returns {Object} + * @private + */ +function createDecompressionStream (encoding, debug) { + switch (encoding) { + case 'deflate': + debug('inflate body') + return zlib.createInflate() + case 'gzip': + debug('gunzip body') + return zlib.createGunzip() + case 'br': + debug('brotli decompress body') + return zlib.createBrotliDecompress() + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } +} + +/** + * Dump the contents of a request. + * + * @param {Object} req + * @param {Function} callback + * @private + */ +function dump (req, callback) { + if (onFinished.isFinished(req)) { + callback(null) + } else { + onFinished(req, callback) + req.resume() + } +} diff --git a/node_modules/body-parser/lib/types/json.js b/node_modules/body-parser/lib/types/json.js new file mode 100644 index 000000000..23c735770 --- /dev/null +++ b/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,158 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('body-parser:json') +var read = require('../read') +var { normalizeOptions } = require('../utils') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex + +var JSON_SYNTAX_CHAR = '#' +var JSON_SYNTAX_REGEXP = /#+/g + +/** + * Create a middleware to parse JSON bodies. + * + * @param {Object} [options] + * @returns {Function} + * @public + */ +function json (options) { + const normalizedOptions = normalizeOptions(options, 'application/json') + + var reviver = options?.reviver + var strict = options?.strict !== false + + function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + if (strict) { + var first = firstchar(body) + + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } + } + + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } + } + + const readOptions = { + ...normalizedOptions, + // assert charset per RFC 7159 sec 8.1 + isValidCharset: (charset) => charset.slice(0, 4) === 'utf-' + } + + return function jsonParser (req, res, next) { + read(req, res, next, parse, debug, readOptions) + } +} + +/** + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @returns {Error} + * @private + */ +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = '' + + if (index !== -1) { + partial = str.substring(0, index) + JSON_SYNTAX_CHAR.repeat(str.length - index) + } + + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) { + return str.substring(index, index + placeholder.length) + }), + stack: e.stack + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @returns {string|undefined} + * @private + */ +function firstchar (str) { + var match = FIRST_CHAR_REGEXP.exec(str) + + return match + ? match[1] + : undefined +} + +/** + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {Object} obj + * @returns {SyntaxError} + * @private + */ +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } + } + + // replace stack before message for Node.js 0.10 and below + error.stack = obj.stack.replace(error.message, obj.message) + error.message = obj.message + + return error +} diff --git a/node_modules/body-parser/lib/types/raw.js b/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 000000000..ad4854dd9 --- /dev/null +++ b/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,42 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var debug = require('debug')('body-parser:raw') +var read = require('../read') +var { normalizeOptions, passthrough } = require('../utils') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {Object} [options] + * @returns {Function} + * @public + */ +function raw (options) { + const normalizedOptions = normalizeOptions(options, 'application/octet-stream') + + const readOptions = { + ...normalizedOptions, + // Skip charset validation and parse the body as is + skipCharset: true + } + + return function rawParser (req, res, next) { + read(req, res, next, passthrough, debug, readOptions) + } +} diff --git a/node_modules/body-parser/lib/types/text.js b/node_modules/body-parser/lib/types/text.js new file mode 100644 index 000000000..9df73be92 --- /dev/null +++ b/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,36 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var debug = require('debug')('body-parser:text') +var read = require('../read') +var { normalizeOptions, passthrough } = require('../utils') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {Object} [options] + * @returns {Function} + * @public + */ +function text (options) { + const normalizedOptions = normalizeOptions(options, 'text/plain') + + return function textParser (req, res, next) { + read(req, res, next, passthrough, debug, normalizedOptions) + } +} diff --git a/node_modules/body-parser/lib/types/urlencoded.js b/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 000000000..4a3227c1e --- /dev/null +++ b/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,142 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('body-parser:urlencoded') +var read = require('../read') +var qs = require('qs') +var { normalizeOptions } = require('../utils') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {Object} [options] + * @returns {Function} + * @public + */ +function urlencoded (options) { + const normalizedOptions = normalizeOptions(options, 'application/x-www-form-urlencoded') + + if (normalizedOptions.defaultCharset !== 'utf-8' && normalizedOptions.defaultCharset !== 'iso-8859-1') { + throw new TypeError('option defaultCharset must be either utf-8 or iso-8859-1') + } + + // create the appropriate query parser + var queryparse = createQueryParser(options) + + function parse (body, encoding) { + return body.length + ? queryparse(body, encoding) + : {} + } + + const readOptions = { + ...normalizedOptions, + // assert charset + isValidCharset: (charset) => charset === 'utf-8' || charset === 'iso-8859-1' + } + + return function urlencodedParser (req, res, next) { + read(req, res, next, parse, debug, readOptions) + } +} + +/** + * Get the extended query parser. + * + * @param {Object} options + * @returns {Function} + * @private + */ +function createQueryParser (options) { + var extended = Boolean(options?.extended) + var parameterLimit = options?.parameterLimit !== undefined + ? options?.parameterLimit + : 1000 + var charsetSentinel = options?.charsetSentinel + var interpretNumericEntities = options?.interpretNumericEntities + var depth = extended ? (options?.depth !== undefined ? options?.depth : 32) : 0 + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isNaN(depth) || depth < 0) { + throw new TypeError('option depth must be a zero or a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body, encoding) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + var arrayLimit = extended ? Math.max(100, paramCount) : paramCount + + debug('parse ' + (extended ? 'extended ' : '') + 'urlencoding') + try { + return qs.parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: depth, + charsetSentinel: charsetSentinel, + interpretNumericEntities: interpretNumericEntities, + charset: encoding, + parameterLimit: parameterLimit, + strictDepth: true + }) + } catch (err) { + if (err instanceof RangeError) { + throw createError(400, 'The input exceeded the depth', { + type: 'querystring.parse.rangeError' + }) + } else { + throw err + } + } + } +} + +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @returns {number|undefined} Returns undefined if limit exceeded + * @private + */ +function parameterCount (body, limit) { + let count = 0 + let index = -1 + do { + count++ + if (count > limit) return undefined // Early exit if limit exceeded + index = body.indexOf('&', index + 1) + } while (index !== -1) + return count +} diff --git a/node_modules/body-parser/lib/utils.js b/node_modules/body-parser/lib/utils.js new file mode 100644 index 000000000..e0bf9741e --- /dev/null +++ b/node_modules/body-parser/lib/utils.js @@ -0,0 +1,98 @@ +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var typeis = require('type-is') + +/** + * Module exports. + */ +module.exports = { + getCharset, + normalizeOptions, + passthrough +} + +/** + * Get the charset of a request. + * + * @param {Object} req + * @returns {string | undefined} + * @private + */ +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string | string[]} type + * @returns {Function} + * @private + */ +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} + +/** + * Normalizes the common options for all parsers. + * + * @param {Object} options options to normalize + * @param {string | string[] | Function} defaultType default content type(s) or a function to determine it + * @returns {Object} + * @private + */ +function normalizeOptions (options, defaultType) { + if (!defaultType) { + // Parsers must define a default content type + throw new TypeError('defaultType must be provided') + } + + var inflate = options?.inflate !== false + var limit = typeof options?.limit !== 'number' + ? bytes.parse(options?.limit || '100kb') + : options?.limit + var type = options?.type || defaultType + var verify = options?.verify || false + var defaultCharset = options?.defaultCharset || 'utf-8' + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + return { + inflate, + limit, + verify, + defaultCharset, + shouldParse + } +} + +/** + * Passthrough function that returns input unchanged. + * Used by parsers that don't need to transform the data. + * + * @param {*} value + * @returns {*} + * @private + */ +function passthrough (value) { + return value +} diff --git a/node_modules/body-parser/package.json b/node_modules/body-parser/package.json new file mode 100644 index 000000000..486878a22 --- /dev/null +++ b/node_modules/body-parser/package.json @@ -0,0 +1,52 @@ +{ + "name": "body-parser", + "description": "Node.js body parsing middleware", + "version": "2.2.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "expressjs/body-parser", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.1", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "devDependencies": { + "eslint": "^8.57.1", + "eslint-config-standard": "^14.1.1", + "eslint-plugin-import": "^2.31.0", + "eslint-plugin-markdown": "^3.0.1", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^6.6.0", + "eslint-plugin-standard": "^4.1.0", + "mocha": "^11.1.0", + "nyc": "^17.1.0", + "supertest": "^7.0.0" + }, + "files": [ + "lib/", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">=18" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/bytes/History.md b/node_modules/bytes/History.md new file mode 100644 index 000000000..d60ce0e6d --- /dev/null +++ b/node_modules/bytes/History.md @@ -0,0 +1,97 @@ +3.1.2 / 2022-01-27 +================== + + * Fix return value for un-parsable strings + +3.1.1 / 2021-11-15 +================== + + * Fix "thousandsSeparator" incorrecting formatting fractional part + +3.1.0 / 2019-01-22 +================== + + * Add petabyte (`pb`) support + +3.0.0 / 2017-08-31 +================== + + * Change "kB" to "KB" in format output + * Remove support for Node.js 0.6 + * Remove support for ComponentJS + +2.5.0 / 2017-03-24 +================== + + * Add option "unit" + +2.4.0 / 2016-06-01 +================== + + * Add option "unitSeparator" + +2.3.0 / 2016-02-15 +================== + + * Drop partial bytes on all parsed units + * Fix non-finite numbers to `.format` to return `null` + * Fix parsing byte string that looks like hex + * perf: hoist regular expressions + +2.2.0 / 2015-11-13 +================== + + * add option "decimalPlaces" + * add option "fixedDecimals" + +2.1.0 / 2015-05-21 +================== + + * add `.format` export + * add `.parse` export + +2.0.2 / 2015-05-20 +================== + + * remove map recreation + * remove unnecessary object construction + +2.0.1 / 2015-05-07 +================== + + * fix browserify require + * remove node.extend dependency + +2.0.0 / 2015-04-12 +================== + + * add option "case" + * add option "thousandsSeparator" + * return "null" on invalid parse input + * support proper round-trip: bytes(bytes(num)) === num + * units no longer case sensitive when parsing + +1.0.0 / 2014-05-05 +================== + + * add negative support. fixes #6 + +0.3.0 / 2014-03-19 +================== + + * added terabyte support + +0.2.1 / 2013-04-01 +================== + + * add .component + +0.2.0 / 2012-10-28 +================== + + * bytes(200).should.eql('200b') + +0.1.0 / 2012-07-04 +================== + + * add bytes to string conversion [yields] diff --git a/node_modules/bytes/LICENSE b/node_modules/bytes/LICENSE new file mode 100644 index 000000000..63e95a963 --- /dev/null +++ b/node_modules/bytes/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015 Jed Watson + +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/bytes/Readme.md b/node_modules/bytes/Readme.md new file mode 100644 index 000000000..5790e23e3 --- /dev/null +++ b/node_modules/bytes/Readme.md @@ -0,0 +1,152 @@ +# Bytes utility + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa. + +## 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): + +```bash +$ npm install bytes +``` + +## Usage + +```js +var bytes = require('bytes'); +``` + +#### bytes(number|string value, [options]): number|string|null + +Default export function. Delegates to either `bytes.format` or `bytes.parse` based on the type of `value`. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number`|`string` | Number value to format or string value to parse | +| options | `Object` | Conversion options for `format` | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`number`|`null` | Return null upon error. Numeric value in bytes, or string value otherwise. | + +**Example** + +```js +bytes(1024); +// output: '1KB' + +bytes('1KB'); +// output: 1024 +``` + +#### bytes.format(number value, [options]): string|null + +Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is + rounded. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number` | Value in bytes | +| options | `Object` | Conversion options | + +**Options** + +| Property | Type | Description | +|-------------------|--------|-----------------------------------------------------------------------------------------| +| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. | +| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` | +| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `'.'`... Default value to `''`. | +| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). | +| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`null` | Return null upon error. String value otherwise. | + +**Example** + +```js +bytes.format(1024); +// output: '1KB' + +bytes.format(1000); +// output: '1000B' + +bytes.format(1000, {thousandsSeparator: ' '}); +// output: '1 000B' + +bytes.format(1024 * 1.7, {decimalPlaces: 0}); +// output: '2KB' + +bytes.format(1024, {unitSeparator: ' '}); +// output: '1 KB' +``` + +#### bytes.parse(string|number value): number|null + +Parse the string value into an integer in bytes. If no unit is given, or `value` +is a number, it is assumed the value is in bytes. + +Supported units and abbreviations are as follows and are case-insensitive: + + * `b` for bytes + * `kb` for kilobytes + * `mb` for megabytes + * `gb` for gigabytes + * `tb` for terabytes + * `pb` for petabytes + +The units are in powers of two, not ten. This means 1kb = 1024b according to this parser. + +**Arguments** + +| Name | Type | Description | +|---------------|--------|--------------------| +| value | `string`|`number` | String to parse, or number in bytes. | + +**Returns** + +| Name | Type | Description | +|---------|-------------|-------------------------| +| results | `number`|`null` | Return null upon error. Value in bytes otherwise. | + +**Example** + +```js +bytes.parse('1KB'); +// output: 1024 + +bytes.parse('1024'); +// output: 1024 + +bytes.parse(1024); +// output: 1024 +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/visionmedia/bytes.js/master?label=ci +[ci-url]: https://github.com/visionmedia/bytes.js/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/visionmedia/bytes.js/master +[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master +[downloads-image]: https://badgen.net/npm/dm/bytes +[downloads-url]: https://npmjs.org/package/bytes +[npm-image]: https://badgen.net/npm/v/bytes +[npm-url]: https://npmjs.org/package/bytes diff --git a/node_modules/bytes/index.js b/node_modules/bytes/index.js new file mode 100644 index 000000000..6f2d0f89e --- /dev/null +++ b/node_modules/bytes/index.js @@ -0,0 +1,170 @@ +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; + +/** + * Module variables. + * @private + */ + +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; + +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; + +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5), +}; + +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; + +/** + * Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ + +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } + + if (typeof value === 'number') { + return format(value, options); + } + + return null; +} + +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public + */ + +function format(value, options) { + if (!Number.isFinite(value)) { + return null; + } + + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; + + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.pb) { + unit = 'PB'; + } else if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; + } + } + + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } + + if (thousandsSeparator) { + str = str.split('.').map(function (s, i) { + return i === 0 + ? s.replace(formatThousandsRegExp, thousandsSeparator) + : s + }).join('.'); + } + + return str + unitSeparator + unit; +} + +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ + +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } + + if (typeof val !== 'string') { + return null; + } + + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; + + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + if (isNaN(floatValue)) { + return null; + } + + return Math.floor(map[unit] * floatValue); +} diff --git a/node_modules/bytes/package.json b/node_modules/bytes/package.json new file mode 100644 index 000000000..f2b6a8b0e --- /dev/null +++ b/node_modules/bytes/package.json @@ -0,0 +1,42 @@ +{ + "name": "bytes", + "description": "Utility to parse a string bytes to bytes and vice-versa", + "version": "3.1.2", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Jed Watson ", + "Théo FIDRY " + ], + "license": "MIT", + "keywords": [ + "byte", + "bytes", + "utility", + "parse", + "parser", + "convert", + "converter" + ], + "repository": "visionmedia/bytes.js", + "devDependencies": { + "eslint": "7.32.0", + "eslint-plugin-markdown": "2.2.1", + "mocha": "9.2.0", + "nyc": "15.1.0" + }, + "files": [ + "History.md", + "LICENSE", + "Readme.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --check-leaks --reporter spec", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/call-bind-apply-helpers/.eslintrc b/node_modules/call-bind-apply-helpers/.eslintrc new file mode 100644 index 000000000..201e859be --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + "no-extra-parens": 0, + "no-magic-numbers": 0, + }, +} diff --git a/node_modules/call-bind-apply-helpers/.github/FUNDING.yml b/node_modules/call-bind-apply-helpers/.github/FUNDING.yml new file mode 100644 index 000000000..0011e9d65 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bind-apply-helpers +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/call-bind-apply-helpers/.nycrc b/node_modules/call-bind-apply-helpers/.nycrc new file mode 100644 index 000000000..bdd626ce9 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/call-bind-apply-helpers/CHANGELOG.md b/node_modules/call-bind-apply-helpers/CHANGELOG.md new file mode 100644 index 000000000..24849428b --- /dev/null +++ b/node_modules/call-bind-apply-helpers/CHANGELOG.md @@ -0,0 +1,30 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.1...v1.0.2) - 2025-02-12 + +### Commits + +- [types] improve inferred types [`e6f9586`](https://github.com/ljharb/call-bind-apply-helpers/commit/e6f95860a3c72879cb861a858cdfb8138fbedec1) +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`e43d540`](https://github.com/ljharb/call-bind-apply-helpers/commit/e43d5409f97543bfbb11f345d47d8ce4e066d8c1) + +## [v1.0.1](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.0...v1.0.1) - 2024-12-08 + +### Commits + +- [types] `reflectApply`: fix types [`4efc396`](https://github.com/ljharb/call-bind-apply-helpers/commit/4efc3965351a4f02cc55e836fa391d3d11ef2ef8) +- [Fix] `reflectApply`: oops, Reflect is not a function [`83cc739`](https://github.com/ljharb/call-bind-apply-helpers/commit/83cc7395de6b79b7730bdf092f1436f0b1263c75) +- [Dev Deps] update `@arethetypeswrong/cli` [`80bd5d3`](https://github.com/ljharb/call-bind-apply-helpers/commit/80bd5d3ae58b4f6b6995ce439dd5a1bcb178a940) + +## v1.0.0 - 2024-12-05 + +### Commits + +- Initial implementation, tests, readme [`7879629`](https://github.com/ljharb/call-bind-apply-helpers/commit/78796290f9b7430c9934d6f33d94ae9bc89fce04) +- Initial commit [`3f1dc16`](https://github.com/ljharb/call-bind-apply-helpers/commit/3f1dc164afc43285631b114a5f9dd9137b2b952f) +- npm init [`081df04`](https://github.com/ljharb/call-bind-apply-helpers/commit/081df048c312fcee400922026f6e97281200a603) +- Only apps should have lockfiles [`5b9ca0f`](https://github.com/ljharb/call-bind-apply-helpers/commit/5b9ca0fe8101ebfaf309c549caac4e0a017ed930) diff --git a/node_modules/call-bind-apply-helpers/LICENSE b/node_modules/call-bind-apply-helpers/LICENSE new file mode 100644 index 000000000..f82f38963 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +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/call-bind-apply-helpers/README.md b/node_modules/call-bind-apply-helpers/README.md new file mode 100644 index 000000000..8fc0dae1b --- /dev/null +++ b/node_modules/call-bind-apply-helpers/README.md @@ -0,0 +1,62 @@ +# call-bind-apply-helpers [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Helper functions around Function call/apply/bind, for use in `call-bind`. + +The only packages that should likely ever use this package directly are `call-bind` and `get-intrinsic`. +Please use `call-bind` unless you have a very good reason not to. + +## Getting started + +```sh +npm install --save call-bind-apply-helpers +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBindBasic = require('call-bind-apply-helpers'); + +function f(a, b) { + assert.equal(this, 1); + assert.equal(a, 2); + assert.equal(b, 3); + assert.equal(arguments.length, 2); +} + +const fBound = callBindBasic([f, 1]); + +delete Function.prototype.call; +delete Function.prototype.bind; + +fBound(2, 3); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/call-bind-apply-helpers +[npm-version-svg]: https://versionbadg.es/ljharb/call-bind-apply-helpers.svg +[deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers.svg +[deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers +[dev-deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bind-apply-helpers.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bind-apply-helpers.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bind-apply-helpers.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bind-apply-helpers +[codecov-image]: https://codecov.io/gh/ljharb/call-bind-apply-helpers/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bind-apply-helpers/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bind-apply-helpers +[actions-url]: https://github.com/ljharb/call-bind-apply-helpers/actions diff --git a/node_modules/call-bind-apply-helpers/actualApply.d.ts b/node_modules/call-bind-apply-helpers/actualApply.d.ts new file mode 100644 index 000000000..b87286a21 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/actualApply.d.ts @@ -0,0 +1 @@ +export = Reflect.apply; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/actualApply.js b/node_modules/call-bind-apply-helpers/actualApply.js new file mode 100644 index 000000000..ffa51355d --- /dev/null +++ b/node_modules/call-bind-apply-helpers/actualApply.js @@ -0,0 +1,10 @@ +'use strict'; + +var bind = require('function-bind'); + +var $apply = require('./functionApply'); +var $call = require('./functionCall'); +var $reflectApply = require('./reflectApply'); + +/** @type {import('./actualApply')} */ +module.exports = $reflectApply || bind.call($call, $apply); diff --git a/node_modules/call-bind-apply-helpers/applyBind.d.ts b/node_modules/call-bind-apply-helpers/applyBind.d.ts new file mode 100644 index 000000000..d176c1ab3 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/applyBind.d.ts @@ -0,0 +1,19 @@ +import actualApply from './actualApply'; + +type TupleSplitHead = T['length'] extends N + ? T + : T extends [...infer R, any] + ? TupleSplitHead + : never + +type TupleSplitTail = O['length'] extends N + ? T + : T extends [infer F, ...infer R] + ? TupleSplitTail<[...R], N, [...O, F]> + : never + +type TupleSplit = [TupleSplitHead, TupleSplitTail] + +declare function applyBind(...args: TupleSplit, 2>[1]): ReturnType; + +export = applyBind; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/applyBind.js b/node_modules/call-bind-apply-helpers/applyBind.js new file mode 100644 index 000000000..d2b772314 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/applyBind.js @@ -0,0 +1,10 @@ +'use strict'; + +var bind = require('function-bind'); +var $apply = require('./functionApply'); +var actualApply = require('./actualApply'); + +/** @type {import('./applyBind')} */ +module.exports = function applyBind() { + return actualApply(bind, $apply, arguments); +}; diff --git a/node_modules/call-bind-apply-helpers/functionApply.d.ts b/node_modules/call-bind-apply-helpers/functionApply.d.ts new file mode 100644 index 000000000..1f6e11b3d --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionApply.d.ts @@ -0,0 +1 @@ +export = Function.prototype.apply; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/functionApply.js b/node_modules/call-bind-apply-helpers/functionApply.js new file mode 100644 index 000000000..c71df9c2b --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionApply.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./functionApply')} */ +module.exports = Function.prototype.apply; diff --git a/node_modules/call-bind-apply-helpers/functionCall.d.ts b/node_modules/call-bind-apply-helpers/functionCall.d.ts new file mode 100644 index 000000000..15e93df35 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionCall.d.ts @@ -0,0 +1 @@ +export = Function.prototype.call; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/functionCall.js b/node_modules/call-bind-apply-helpers/functionCall.js new file mode 100644 index 000000000..7a8d87357 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionCall.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./functionCall')} */ +module.exports = Function.prototype.call; diff --git a/node_modules/call-bind-apply-helpers/index.d.ts b/node_modules/call-bind-apply-helpers/index.d.ts new file mode 100644 index 000000000..541516bd0 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/index.d.ts @@ -0,0 +1,64 @@ +type RemoveFromTuple< + Tuple extends readonly unknown[], + RemoveCount extends number, + Index extends 1[] = [] +> = Index["length"] extends RemoveCount + ? Tuple + : Tuple extends [infer First, ...infer Rest] + ? RemoveFromTuple + : Tuple; + +type ConcatTuples< + Prefix extends readonly unknown[], + Suffix extends readonly unknown[] +> = [...Prefix, ...Suffix]; + +type ExtractFunctionParams = T extends (this: infer TThis, ...args: infer P extends readonly unknown[]) => infer R + ? { thisArg: TThis; params: P; returnType: R } + : never; + +type BindFunction< + T extends (this: any, ...args: any[]) => any, + TThis, + TBoundArgs extends readonly unknown[], + ReceiverBound extends boolean +> = ExtractFunctionParams extends { + thisArg: infer OrigThis; + params: infer P extends readonly unknown[]; + returnType: infer R; +} + ? ReceiverBound extends true + ? (...args: RemoveFromTuple>) => R extends [OrigThis, ...infer Rest] + ? [TThis, ...Rest] // Replace `this` with `thisArg` + : R + : >>( + thisArg: U, + ...args: RemainingArgs + ) => R extends [OrigThis, ...infer Rest] + ? [U, ...ConcatTuples] // Preserve bound args in return type + : R + : never; + +declare function callBind< + const T extends (this: any, ...args: any[]) => any, + Extracted extends ExtractFunctionParams, + const TBoundArgs extends Partial & readonly unknown[], + const TThis extends Extracted["thisArg"] +>( + args: [fn: T, thisArg: TThis, ...boundArgs: TBoundArgs] +): BindFunction; + +declare function callBind< + const T extends (this: any, ...args: any[]) => any, + Extracted extends ExtractFunctionParams, + const TBoundArgs extends Partial & readonly unknown[] +>( + args: [fn: T, ...boundArgs: TBoundArgs] +): BindFunction; + +declare function callBind( + args: [fn: Exclude, ...rest: TArgs] +): never; + +// export as namespace callBind; +export = callBind; diff --git a/node_modules/call-bind-apply-helpers/index.js b/node_modules/call-bind-apply-helpers/index.js new file mode 100644 index 000000000..2f6dab4c1 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/index.js @@ -0,0 +1,15 @@ +'use strict'; + +var bind = require('function-bind'); +var $TypeError = require('es-errors/type'); + +var $call = require('./functionCall'); +var $actualApply = require('./actualApply'); + +/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ +module.exports = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== 'function') { + throw new $TypeError('a function is required'); + } + return $actualApply(bind, $call, args); +}; diff --git a/node_modules/call-bind-apply-helpers/package.json b/node_modules/call-bind-apply-helpers/package.json new file mode 100644 index 000000000..923b8be2f --- /dev/null +++ b/node_modules/call-bind-apply-helpers/package.json @@ -0,0 +1,85 @@ +{ + "name": "call-bind-apply-helpers", + "version": "1.0.2", + "description": "Helper functions around Function call/apply/bind, for use in `call-bind`", + "main": "index.js", + "exports": { + ".": "./index.js", + "./actualApply": "./actualApply.js", + "./applyBind": "./applyBind.js", + "./functionApply": "./functionApply.js", + "./functionCall": "./functionCall.js", + "./reflectApply": "./reflectApply.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bind-apply-helpers.git" + }, + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bind-apply-helpers/issues" + }, + "homepage": "https://github.com/ljharb/call-bind-apply-helpers#readme", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.3", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/for-each": "^0.3.3", + "@types/function-bind": "^1.1.10", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.5", + "has-strict-mode": "^1.1.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/call-bind-apply-helpers/reflectApply.d.ts b/node_modules/call-bind-apply-helpers/reflectApply.d.ts new file mode 100644 index 000000000..6b2ae764c --- /dev/null +++ b/node_modules/call-bind-apply-helpers/reflectApply.d.ts @@ -0,0 +1,3 @@ +declare const reflectApply: false | typeof Reflect.apply; + +export = reflectApply; diff --git a/node_modules/call-bind-apply-helpers/reflectApply.js b/node_modules/call-bind-apply-helpers/reflectApply.js new file mode 100644 index 000000000..3d03caa69 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/reflectApply.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./reflectApply')} */ +module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; diff --git a/node_modules/call-bind-apply-helpers/test/index.js b/node_modules/call-bind-apply-helpers/test/index.js new file mode 100644 index 000000000..1cdc89ed4 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/test/index.js @@ -0,0 +1,63 @@ +'use strict'; + +var callBind = require('../'); +var hasStrictMode = require('has-strict-mode')(); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var v = require('es-value-fixtures'); + +var test = require('tape'); + +test('callBindBasic', function (t) { + forEach(v.nonFunctions, function (nonFunction) { + t['throws']( + // @ts-expect-error + function () { callBind([nonFunction]); }, + TypeError, + inspect(nonFunction) + ' is not a function' + ); + }); + + var sentinel = { sentinel: true }; + /** @type {(this: T, a: A, b: B) => [T | undefined, A, B]} */ + var func = function (a, b) { + // eslint-disable-next-line no-invalid-this + return [!hasStrictMode && this === global ? undefined : this, a, b]; + }; + t.equal(func.length, 2, 'original function length is 2'); + + /** type {(thisArg: unknown, a: number, b: number) => [unknown, number, number]} */ + var bound = callBind([func]); + /** type {((a: number, b: number) => [typeof sentinel, typeof a, typeof b])} */ + var boundR = callBind([func, sentinel]); + /** type {((b: number) => [typeof sentinel, number, typeof b])} */ + var boundArg = callBind([func, sentinel, /** @type {const} */ (1)]); + + // @ts-expect-error + t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with no args'); + + // @ts-expect-error + t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args'); + // @ts-expect-error + t.deepEqual(bound(1, 2), [hasStrictMode ? 1 : Object(1), 2, undefined], 'bound func too few args'); + // @ts-expect-error + t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args'); + // @ts-expect-error + t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args'); + + t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args'); + t.deepEqual(bound(1, 2, 3), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with right args'); + t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args'); + t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg'); + + // @ts-expect-error + t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args'); + // @ts-expect-error + t.deepEqual(bound(1, 2, 3, 4), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with too many args'); + // @ts-expect-error + t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args'); + // @ts-expect-error + t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args'); + + t.end(); +}); diff --git a/node_modules/call-bind-apply-helpers/tsconfig.json b/node_modules/call-bind-apply-helpers/tsconfig.json new file mode 100644 index 000000000..aef999308 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} \ No newline at end of file diff --git a/node_modules/call-bound/.eslintrc b/node_modules/call-bound/.eslintrc new file mode 100644 index 000000000..2612ed8fe --- /dev/null +++ b/node_modules/call-bound/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/call-bound/.github/FUNDING.yml b/node_modules/call-bound/.github/FUNDING.yml new file mode 100644 index 000000000..2a2a13571 --- /dev/null +++ b/node_modules/call-bound/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bound +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/call-bound/.nycrc b/node_modules/call-bound/.nycrc new file mode 100644 index 000000000..bdd626ce9 --- /dev/null +++ b/node_modules/call-bound/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/call-bound/CHANGELOG.md b/node_modules/call-bound/CHANGELOG.md new file mode 100644 index 000000000..8bde4e9a5 --- /dev/null +++ b/node_modules/call-bound/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.4](https://github.com/ljharb/call-bound/compare/v1.0.3...v1.0.4) - 2025-03-03 + +### Commits + +- [types] improve types [`e648922`](https://github.com/ljharb/call-bound/commit/e6489222a9e54f350fbf952ceabe51fd8b6027ff) +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`a42a5eb`](https://github.com/ljharb/call-bound/commit/a42a5ebe6c1b54fcdc7997c7dc64fdca9e936719) +- [Deps] update `call-bind-apply-helpers`, `get-intrinsic` [`f529eac`](https://github.com/ljharb/call-bound/commit/f529eac132404c17156bbc23ab2297a25d0f20b8) + +## [v1.0.3](https://github.com/ljharb/call-bound/compare/v1.0.2...v1.0.3) - 2024-12-15 + +### Commits + +- [Refactor] use `call-bind-apply-helpers` instead of `call-bind` [`5e0b134`](https://github.com/ljharb/call-bound/commit/5e0b13496df14fb7d05dae9412f088da8d3f75be) +- [Deps] update `get-intrinsic` [`41fc967`](https://github.com/ljharb/call-bound/commit/41fc96732a22c7b7e8f381f93ccc54bb6293be2e) +- [readme] fix example [`79a0137`](https://github.com/ljharb/call-bound/commit/79a0137723f7c6d09c9c05452bbf8d5efb5d6e49) +- [meta] add `sideEffects` flag [`08b07be`](https://github.com/ljharb/call-bound/commit/08b07be7f1c03f67dc6f3cdaf0906259771859f7) + +## [v1.0.2](https://github.com/ljharb/call-bound/compare/v1.0.1...v1.0.2) - 2024-12-10 + +### Commits + +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `gopd` [`e6a5ffe`](https://github.com/ljharb/call-bound/commit/e6a5ffe849368fe4f74dfd6cdeca1b9baa39e8d5) +- [Deps] update `call-bind`, `get-intrinsic` [`2aeb5b5`](https://github.com/ljharb/call-bound/commit/2aeb5b521dc2b2683d1345c753ea1161de2d1c14) +- [types] improve return type [`1a0c9fe`](https://github.com/ljharb/call-bound/commit/1a0c9fe3114471e7ca1f57d104e2efe713bb4871) + +## v1.0.1 - 2024-12-05 + +### Commits + +- Initial implementation, tests, readme, types [`6d94121`](https://github.com/ljharb/call-bound/commit/6d94121a9243602e506334069f7a03189fe3363d) +- Initial commit [`0eae867`](https://github.com/ljharb/call-bound/commit/0eae867334ea025c33e6e91cdecfc9df96680cf9) +- npm init [`71b2479`](https://github.com/ljharb/call-bound/commit/71b2479c6723e0b7d91a6b663613067e98b7b275) +- Only apps should have lockfiles [`c3754a9`](https://github.com/ljharb/call-bound/commit/c3754a949b7f9132b47e2d18c1729889736741eb) +- [actions] skip `npm ls` in node < 10 [`74275a5`](https://github.com/ljharb/call-bound/commit/74275a5186b8caf6309b6b97472bdcb0df4683a8) +- [Dev Deps] add missing peer dep [`1354de8`](https://github.com/ljharb/call-bound/commit/1354de8679413e4ae9c523d85f76fa7a5e032d97) diff --git a/node_modules/call-bound/LICENSE b/node_modules/call-bound/LICENSE new file mode 100644 index 000000000..f82f38963 --- /dev/null +++ b/node_modules/call-bound/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +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/call-bound/README.md b/node_modules/call-bound/README.md new file mode 100644 index 000000000..a44e43e56 --- /dev/null +++ b/node_modules/call-bound/README.md @@ -0,0 +1,53 @@ +# call-bound [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Robust call-bound JavaScript intrinsics, using `call-bind` and `get-intrinsic`. + +## Getting started + +```sh +npm install --save call-bound +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBound = require('call-bound'); + +const slice = callBound('Array.prototype.slice'); + +delete Function.prototype.call; +delete Function.prototype.bind; +delete Array.prototype.slice; + +assert.deepEqual(slice([1, 2, 3, 4], 1, -1), [2, 3]); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/call-bound +[npm-version-svg]: https://versionbadg.es/ljharb/call-bound.svg +[deps-svg]: https://david-dm.org/ljharb/call-bound.svg +[deps-url]: https://david-dm.org/ljharb/call-bound +[dev-deps-svg]: https://david-dm.org/ljharb/call-bound/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bound#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bound.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bound.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bound.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bound +[codecov-image]: https://codecov.io/gh/ljharb/call-bound/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bound/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bound +[actions-url]: https://github.com/ljharb/call-bound/actions diff --git a/node_modules/call-bound/index.d.ts b/node_modules/call-bound/index.d.ts new file mode 100644 index 000000000..5562f00ed --- /dev/null +++ b/node_modules/call-bound/index.d.ts @@ -0,0 +1,94 @@ +type Intrinsic = typeof globalThis; + +type IntrinsicName = keyof Intrinsic | `%${keyof Intrinsic}%`; + +type IntrinsicPath = IntrinsicName | `${StripPercents}.${string}` | `%${StripPercents}.${string}%`; + +type AllowMissing = boolean; + +type StripPercents = T extends `%${infer U}%` ? U : T; + +type BindMethodPrecise = + F extends (this: infer This, ...args: infer Args) => infer R + ? (obj: This, ...args: Args) => R + : F extends { + (this: infer This1, ...args: infer Args1): infer R1; + (this: infer This2, ...args: infer Args2): infer R2 + } + ? { + (obj: This1, ...args: Args1): R1; + (obj: This2, ...args: Args2): R2 + } + : never + +// Extract method type from a prototype +type GetPrototypeMethod = + (typeof globalThis)[T] extends { prototype: any } + ? M extends keyof (typeof globalThis)[T]['prototype'] + ? (typeof globalThis)[T]['prototype'][M] + : never + : never + +// Get static property/method +type GetStaticMember = + P extends keyof (typeof globalThis)[T] ? (typeof globalThis)[T][P] : never + +// Type that maps string path to actual bound function or value with better precision +type BoundIntrinsic = + S extends `${infer Obj}.prototype.${infer Method}` + ? Obj extends keyof typeof globalThis + ? BindMethodPrecise> + : unknown + : S extends `${infer Obj}.${infer Prop}` + ? Obj extends keyof typeof globalThis + ? GetStaticMember + : unknown + : unknown + +declare function arraySlice(array: readonly T[], start?: number, end?: number): T[]; +declare function arraySlice(array: ArrayLike, start?: number, end?: number): T[]; +declare function arraySlice(array: IArguments, start?: number, end?: number): T[]; + +// Special cases for methods that need explicit typing +interface SpecialCases { + '%Object.prototype.isPrototypeOf%': (thisArg: {}, obj: unknown) => boolean; + '%String.prototype.replace%': { + (str: string, searchValue: string | RegExp, replaceValue: string): string; + (str: string, searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string + }; + '%Object.prototype.toString%': (obj: {}) => string; + '%Object.prototype.hasOwnProperty%': (obj: {}, v: PropertyKey) => boolean; + '%Array.prototype.slice%': typeof arraySlice; + '%Array.prototype.map%': (array: readonly T[], callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any) => U[]; + '%Array.prototype.filter%': (array: readonly T[], predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any) => T[]; + '%Array.prototype.indexOf%': (array: readonly T[], searchElement: T, fromIndex?: number) => number; + '%Function.prototype.apply%': (fn: (...args: A) => R, thisArg: any, args: A) => R; + '%Function.prototype.call%': (fn: (...args: A) => R, thisArg: any, ...args: A) => R; + '%Function.prototype.bind%': (fn: (...args: A) => R, thisArg: any, ...args: A) => (...remainingArgs: A) => R; + '%Promise.prototype.then%': { + (promise: Promise, onfulfilled: (value: T) => R | PromiseLike): Promise; + (promise: Promise, onfulfilled: ((value: T) => R | PromiseLike) | undefined | null, onrejected: (reason: any) => R | PromiseLike): Promise; + }; + '%RegExp.prototype.test%': (regexp: RegExp, str: string) => boolean; + '%RegExp.prototype.exec%': (regexp: RegExp, str: string) => RegExpExecArray | null; + '%Error.prototype.toString%': (error: Error) => string; + '%TypeError.prototype.toString%': (error: TypeError) => string; + '%String.prototype.split%': ( + obj: unknown, + splitter: string | RegExp | { + [Symbol.split](string: string, limit?: number): string[]; + }, + limit?: number | undefined + ) => string[]; +} + +/** + * Returns a bound function for a prototype method, or a value for a static property. + * + * @param name - The name of the intrinsic (e.g. 'Array.prototype.slice') + * @param {AllowMissing} [allowMissing] - Whether to allow missing intrinsics (default: false) + */ +declare function callBound, S extends IntrinsicPath>(name: K, allowMissing?: AllowMissing): SpecialCases[`%${StripPercents}%`]; +declare function callBound, S extends IntrinsicPath>(name: S, allowMissing?: AllowMissing): BoundIntrinsic; + +export = callBound; diff --git a/node_modules/call-bound/index.js b/node_modules/call-bound/index.js new file mode 100644 index 000000000..e9ade749d --- /dev/null +++ b/node_modules/call-bound/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBindBasic = require('call-bind-apply-helpers'); + +/** @type {(thisArg: string, searchString: string, position?: number) => number} */ +var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); + +/** @type {import('.')} */ +module.exports = function callBoundIntrinsic(name, allowMissing) { + /* eslint no-extra-parens: 0 */ + + var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing)); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBindBasic(/** @type {const} */ ([intrinsic])); + } + return intrinsic; +}; diff --git a/node_modules/call-bound/package.json b/node_modules/call-bound/package.json new file mode 100644 index 000000000..d542db430 --- /dev/null +++ b/node_modules/call-bound/package.json @@ -0,0 +1,99 @@ +{ + "name": "call-bound", + "version": "1.0.4", + "description": "Robust call-bound JavaScript intrinsics, using `call-bind` and `get-intrinsic`.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bound.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "callbind", + "callbound", + "call", + "bind", + "bound", + "call-bind", + "call-bound", + "function", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bound/issues" + }, + "homepage": "https://github.com/ljharb/call-bound#readme", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.4", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.3.0", + "@types/call-bind": "^1.0.5", + "@types/get-intrinsic": "^1.2.3", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.5", + "gopd": "^1.2.0", + "has-strict-mode": "^1.1.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/call-bound/test/index.js b/node_modules/call-bound/test/index.js new file mode 100644 index 000000000..a2fc9f0f2 --- /dev/null +++ b/node_modules/call-bound/test/index.js @@ -0,0 +1,61 @@ +'use strict'; + +var test = require('tape'); + +var callBound = require('../'); + +/** @template {true} T @template U @typedef {T extends U ? T : never} AssertType */ + +test('callBound', function (t) { + // static primitive + t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself'); + t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself'); + + // static non-function object + t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself'); + t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself'); + t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself'); + t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself'); + + // static function + t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself'); + t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself'); + + // prototype primitive + t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself'); + t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself'); + + var x = callBound('Object.prototype.toString'); + var y = callBound('%Object.prototype.toString%'); + + // prototype function + t.notEqual(x, Object.prototype.toString, 'Object.prototype.toString does not yield itself'); + t.notEqual(y, Object.prototype.toString, '%Object.prototype.toString% does not yield itself'); + t.equal(x(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original'); + t.equal(y(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original'); + + t['throws']( + // @ts-expect-error + function () { callBound('does not exist'); }, + SyntaxError, + 'nonexistent intrinsic throws' + ); + t['throws']( + // @ts-expect-error + function () { callBound('does not exist', true); }, + SyntaxError, + 'allowMissing arg still throws for unknown intrinsic' + ); + + t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) { + st['throws']( + function () { callBound('WeakRef'); }, + TypeError, + 'real but absent intrinsic throws' + ); + st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception'); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/call-bound/tsconfig.json b/node_modules/call-bound/tsconfig.json new file mode 100644 index 000000000..8976d98b8 --- /dev/null +++ b/node_modules/call-bound/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "ESNext", + "lib": ["es2024"], + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/commander/LICENSE b/node_modules/commander/LICENSE new file mode 100644 index 000000000..10f997ab1 --- /dev/null +++ b/node_modules/commander/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk + +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/commander/Readme.md b/node_modules/commander/Readme.md new file mode 100644 index 000000000..1f10fb5a6 --- /dev/null +++ b/node_modules/commander/Readme.md @@ -0,0 +1,1159 @@ +# Commander.js + +[![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22) +[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander) +[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true) +[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander) + +The complete solution for [node.js](http://nodejs.org) command-line interfaces. + +Read this in other languages: English | [简体中文](./Readme_zh-CN.md) + +- [Commander.js](#commanderjs) + - [Installation](#installation) + - [Quick Start](#quick-start) + - [Declaring _program_ variable](#declaring-program-variable) + - [Options](#options) + - [Common option types, boolean and value](#common-option-types-boolean-and-value) + - [Default option value](#default-option-value) + - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue) + - [Required option](#required-option) + - [Variadic option](#variadic-option) + - [Version option](#version-option) + - [More configuration](#more-configuration) + - [Custom option processing](#custom-option-processing) + - [Commands](#commands) + - [Command-arguments](#command-arguments) + - [More configuration](#more-configuration-1) + - [Custom argument processing](#custom-argument-processing) + - [Action handler](#action-handler) + - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands) + - [Life cycle hooks](#life-cycle-hooks) + - [Automated help](#automated-help) + - [Custom help](#custom-help) + - [Display help after errors](#display-help-after-errors) + - [Display help from code](#display-help-from-code) + - [.name](#name) + - [.usage](#usage) + - [.description and .summary](#description-and-summary) + - [.helpOption(flags, description)](#helpoptionflags-description) + - [.helpCommand()](#helpcommand) + - [Help Groups](#help-groups) + - [More configuration](#more-configuration-2) + - [Custom event listeners](#custom-event-listeners) + - [Bits and pieces](#bits-and-pieces) + - [.parse() and .parseAsync()](#parse-and-parseasync) + - [Parsing Configuration](#parsing-configuration) + - [Legacy options as properties](#legacy-options-as-properties) + - [TypeScript](#typescript) + - [createCommand()](#createcommand) + - [Node options such as `--harmony`](#node-options-such-as---harmony) + - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands) + - [npm run-script](#npm-run-script) + - [Display error](#display-error) + - [Override exit and output handling](#override-exit-and-output-handling) + - [Additional documentation](#additional-documentation) + - [Support](#support) + - [Commander for enterprise](#commander-for-enterprise) + +For information about terms used in this document see: [terminology](./docs/terminology.md) + +## Installation + +```sh +npm install commander +``` + +## Quick Start + +You write code to describe your command line interface. +Commander looks after parsing the arguments into options and command-arguments, +displays usage errors for problems, and implements a help system. + +Commander is strict and displays an error for unrecognised options. +The two most used option types are a boolean option, and an option which takes its value from the following argument. + +Example file: [split.js](./examples/split.js) + +```js +const { program } = require('commander'); + +program + .option('--first') + .option('-s, --separator ') + .argument(''); + +program.parse(); + +const options = program.opts(); +const limit = options.first ? 1 : undefined; +console.log(program.args[0].split(options.separator, limit)); +``` + +```console +$ node split.js -s / --fits a/b/c +error: unknown option '--fits' +(Did you mean --first?) +$ node split.js -s / --first a/b/c +[ 'a' ] +``` + +Here is a more complete program using a subcommand and with descriptions for the help. In a multi-command program, you have an action handler for each command (or stand-alone executables for the commands). + +Example file: [string-util.js](./examples/string-util.js) + +```js +const { Command } = require('commander'); +const program = new Command(); + +program + .name('string-util') + .description('CLI to some JavaScript string utilities') + .version('0.8.0'); + +program.command('split') + .description('Split a string into substrings and display as an array') + .argument('', 'string to split') + .option('--first', 'display just the first substring') + .option('-s, --separator ', 'separator character', ',') + .action((str, options) => { + const limit = options.first ? 1 : undefined; + console.log(str.split(options.separator, limit)); + }); + +program.parse(); +``` + +```console +$ node string-util.js help split +Usage: string-util split [options] + +Split a string into substrings and display as an array. + +Arguments: + string string to split + +Options: + --first display just the first substring + -s, --separator separator character (default: ",") + -h, --help display help for command + +$ node string-util.js split --separator=/ a/b/c +[ 'a', 'b', 'c' ] +``` + +More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory. + +## Declaring _program_ variable + +Commander exports a global object which is convenient for quick programs. +This is used in the examples in this README for brevity. + +```js +// CommonJS (.cjs) +const { program } = require('commander'); +``` + +For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use. + +```js +// CommonJS (.cjs) +const { Command } = require('commander'); +const program = new Command(); +``` + +```js +// ECMAScript (.mjs) +import { Command } from 'commander'; +const program = new Command(); +``` + +```ts +// TypeScript (.ts) +import { Command } from 'commander'; +const program = new Command(); +``` + +## Options + +Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|'). To allow a wider range of short-ish flags than just +single characters, you may also have two long options. Examples: + +```js +program + .option('-p, --port ', 'server port number') + .option('--trace', 'add extra debugging output') + .option('--ws, --workspace ', 'use a custom workspace') +``` + +The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler. + +Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc. + +An option and its option-argument can be separated by a space, or combined into the same argument. The option-argument can follow the short option directly or follow an `=` for a long option. + +```sh +serve -p 80 +serve -p80 +serve --port 80 +serve --port=80 +``` + +You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted. + +By default, options on the command line are not positional, and can be specified before or after other arguments. + +There are additional related routines for when `.opts()` is not enough: + +- `.optsWithGlobals()` returns merged local and global option values +- `.getOptionValue()` and `.setOptionValue()` work with a single option value +- `.getOptionValueSource()` and `.setOptionValueWithSource()` include where the option value came from + +### Common option types, boolean and value + +The two most used option types are a boolean option, and an option which takes its value +from the following argument (declared with angle brackets like `--expect `). Both are `undefined` unless specified on command line. + +Example file: [options-common.js](./examples/options-common.js) + +```js +program + .option('-d, --debug', 'output extra debugging') + .option('-s, --small', 'small pizza size') + .option('-p, --pizza-type ', 'flavour of pizza'); + +program.parse(process.argv); + +const options = program.opts(); +if (options.debug) console.log(options); +console.log('pizza details:'); +if (options.small) console.log('- small pizza size'); +if (options.pizzaType) console.log(`- ${options.pizzaType}`); +``` + +```console +$ pizza-options -p +error: option '-p, --pizza-type ' argument missing +$ pizza-options -d -s -p vegetarian +{ debug: true, small: true, pizzaType: 'vegetarian' } +pizza details: +- small pizza size +- vegetarian +$ pizza-options --pizza-type=cheese +pizza details: +- cheese +``` + +Multiple boolean short options may be combined following the dash, and may be followed by a single short option taking a value. +For example `-d -s -p cheese` may be written as `-ds -p cheese` or even `-dsp cheese`. + +Options with an expected option-argument are greedy and will consume the following argument whatever the value. +So `--id -xyz` reads `-xyz` as the option-argument. + +`program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array. The parameter is optional and defaults to `process.argv`. + +### Default option value + +You can specify a default value for an option. + +Example file: [options-defaults.js](./examples/options-defaults.js) + +```js +program + .option('-c, --cheese ', 'add the specified type of cheese', 'blue'); + +program.parse(); + +console.log(`cheese: ${program.opts().cheese}`); +``` + +```console +$ pizza-options +cheese: blue +$ pizza-options --cheese stilton +cheese: stilton +``` + +### Other option types, negatable boolean and boolean|value + +You can define a boolean option long name with a leading `no-` to set the option value to false when used. +Defined alone this also makes the option true by default. + +If you define `--foo` first, adding `--no-foo` does not change the default value from what it would +otherwise be. + +Example file: [options-negatable.js](./examples/options-negatable.js) + +```js +program + .option('--no-sauce', 'Remove sauce') + .option('--cheese ', 'cheese flavour', 'mozzarella') + .option('--no-cheese', 'plain with no cheese') + .parse(); + +const options = program.opts(); +const sauceStr = options.sauce ? 'sauce' : 'no sauce'; +const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`; +console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`); +``` + +```console +$ pizza-options +You ordered a pizza with sauce and mozzarella cheese +$ pizza-options --sauce +error: unknown option '--sauce' +$ pizza-options --cheese=blue +You ordered a pizza with sauce and blue cheese +$ pizza-options --no-sauce --no-cheese +You ordered a pizza with no sauce and no cheese +``` + +You can specify an option which may be used as a boolean option but may optionally take an option-argument +(declared with square brackets like `--optional [value]`). + +Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js) + +```js +program + .option('-c, --cheese [type]', 'Add cheese with optional type'); + +program.parse(process.argv); + +const options = program.opts(); +if (options.cheese === undefined) console.log('no cheese'); +else if (options.cheese === true) console.log('add cheese'); +else console.log(`add cheese type ${options.cheese}`); +``` + +```console +$ pizza-options +no cheese +$ pizza-options --cheese +add cheese +$ pizza-options --cheese mozzarella +add cheese type mozzarella +``` + +Options with an optional option-argument are not greedy and will ignore arguments starting with a dash. +So `id` behaves as a boolean option for `--id -ABCD`, but you can use a combined form if needed like `--id=-ABCD`. +Negative numbers are special and are accepted as an option-argument. + +For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md). + +### Required option + +You may specify a required (mandatory) option using `.requiredOption()`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (say from environment). The method is otherwise the same as `.option()` in format, taking flags and description, and optional default value or custom processing. + +Example file: [options-required.js](./examples/options-required.js) + +```js +program + .requiredOption('-c, --cheese ', 'pizza must have cheese'); + +program.parse(); +``` + +```console +$ pizza +error: required option '-c, --cheese ' not specified +``` + +### Variadic option + +You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you +can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments +are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value +is specified in the same argument as the option then no further values are read. + +Example file: [options-variadic.js](./examples/options-variadic.js) + +```js +program + .option('-n, --number ', 'specify numbers') + .option('-l, --letter [letters...]', 'specify letters'); + +program.parse(); + +console.log('Options: ', program.opts()); +console.log('Remaining arguments: ', program.args); +``` + +```console +$ collect -n 1 2 3 --letter a b c +Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] } +Remaining arguments: [] +$ collect --letter=A -n80 operand +Options: { number: [ '80' ], letter: [ 'A' ] } +Remaining arguments: [ 'operand' ] +$ collect --letter -n 1 -n 2 3 -- operand +Options: { number: [ '1', '2', '3' ], letter: true } +Remaining arguments: [ 'operand' ] +``` + +For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md). + +### Version option + +The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits. + +```js +program.version('0.0.1'); +``` + +```console +$ ./examples/pizza -V +0.0.1 +``` + +You may change the flags and description by passing additional parameters to the `version` method, using +the same syntax for flags as the `option` method. + +```js +program.version('0.0.1', '-v, --vers', 'output the current version'); +``` + +### More configuration + +You can add most options using the `.option()` method, but there are some additional features available +by constructing an `Option` explicitly for less common cases. + +Example files: [options-extra.js](./examples/options-extra.js), [options-env.js](./examples/options-env.js), [options-conflicts.js](./examples/options-conflicts.js), [options-implies.js](./examples/options-implies.js) + +```js +program + .addOption(new Option('-s, --secret').hideHelp()) + .addOption(new Option('-t, --timeout ', 'timeout in seconds').default(60, 'one minute')) + .addOption(new Option('-d, --drink ', 'drink size').choices(['small', 'medium', 'large'])) + .addOption(new Option('-p, --port ', 'port number').env('PORT')) + .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat)) + .addOption(new Option('--disable-server', 'disables the server').conflicts('port')) + .addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' })); +``` + +```console +$ extra --help +Usage: help [options] + +Options: + -t, --timeout timeout in seconds (default: one minute) + -d, --drink drink cup size (choices: "small", "medium", "large") + -p, --port port number (env: PORT) + --donate [amount] optional donation in dollars (preset: "20") + --disable-server disables the server + --free-drink small drink included free + -h, --help display help for command + +$ extra --drink huge +error: option '-d, --drink ' argument 'huge' is invalid. Allowed choices are small, medium, large. + +$ PORT=80 extra --donate --free-drink +Options: { timeout: 60, donate: 20, port: '80', freeDrink: true, drink: 'small' } + +$ extra --disable-server --port 8000 +error: option '--disable-server' cannot be used with option '-p, --port ' +``` + +Specify a required (mandatory) option using the `Option` method `.makeOptionMandatory()`. This matches the `Command` method [.requiredOption()](#required-option). + +### Custom option processing + +You may specify a function to do custom processing of option-arguments. The callback function receives two parameters, +the user specified option-argument and the previous value for the option. It returns the new value for the option. + +This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing. + +You can optionally specify the default/starting value for the option after the function parameter. + +Example file: [options-custom-processing.js](./examples/options-custom-processing.js) + +```js +function myParseInt(value, dummyPrevious) { + // parseInt takes a string and a radix + const parsedValue = parseInt(value, 10); + if (isNaN(parsedValue)) { + throw new commander.InvalidArgumentError('Not a number.'); + } + return parsedValue; +} + +function increaseVerbosity(dummyValue, previous) { + return previous + 1; +} + +function collect(value, previous) { + return previous.concat([value]); +} + +function commaSeparatedList(value, dummyPrevious) { + return value.split(','); +} + +program + .option('-f, --float ', 'float argument', parseFloat) + .option('-i, --integer ', 'integer argument', myParseInt) + .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0) + .option('-c, --collect ', 'repeatable value', collect, []) + .option('-l, --list ', 'comma separated list', commaSeparatedList) +; + +program.parse(); + +const options = program.opts(); +if (options.float !== undefined) console.log(`float: ${options.float}`); +if (options.integer !== undefined) console.log(`integer: ${options.integer}`); +if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`); +if (options.collect.length > 0) console.log(options.collect); +if (options.list !== undefined) console.log(options.list); +``` + +```console +$ custom -f 1e2 +float: 100 +$ custom --integer 2 +integer: 2 +$ custom -v -v -v +verbose: 3 +$ custom -c a -c b -c c +[ 'a', 'b', 'c' ] +$ custom --list x,y,z +[ 'x', 'y', 'z' ] +``` + +## Commands + +You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)). + +In the first parameter to `.command()` you specify the command name. You may append the command-arguments after the command name, or specify them separately using `.argument()`. The arguments may be `` or `[optional]`, and the last argument may also be `variadic...`. + +You can use `.addCommand()` to add an already configured subcommand to the program. + +For example: + +```js +// Command implemented using action handler (description is supplied separately to `.command`) +// Returns new command for configuring. +program + .command('clone [destination]') + .description('clone a repository into a newly created directory') + .action((source, destination) => { + console.log('clone command called'); + }); + +// Command implemented using stand-alone executable file, indicated by adding description as second parameter to `.command`. +// Returns `this` for adding more commands. +program + .command('start ', 'start named service') + .command('stop [service]', 'stop named service, or all if no name supplied'); + +// Command prepared separately. +// Returns `this` for adding more commands. +program + .addCommand(build.makeBuildCommand()); +``` + +Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will +remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other +subcommand is specified ([example](./examples/defaultCommand.js)). + +You can add alternative names for a command with `.alias()`. ([example](./examples/alias.js)) + +`.command()` automatically copies the inherited settings from the parent command to the newly created subcommand. This is only done during creation, any later setting changes to the parent are not inherited. + +For safety, `.addCommand()` does not automatically copy the inherited settings from the parent command. There is a helper routine `.copyInheritedSettings()` for copying the settings when they are wanted. + +### Command-arguments + +For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This +is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands +you can instead use the following method. + +To configure a command, you can use `.argument()` to specify each expected command-argument. +You supply the argument name and an optional description. The argument may be `` or `[optional]`. +You can specify a default value for an optional command-argument. + +Example file: [argument.js](./examples/argument.js) + +```js +program + .version('0.1.0') + .argument('', 'user to login') + .argument('[password]', 'password for user, if required', 'no password given') + .action((username, password) => { + console.log('username:', username); + console.log('password:', password); + }); +``` + + The last argument of a command can be variadic, and only the last argument. To make an argument variadic you + append `...` to the argument name. A variadic argument is passed to the action handler as an array. For example: + +```js +program + .version('0.1.0') + .command('rmdir') + .argument('') + .action(function (dirs) { + dirs.forEach((dir) => { + console.log('rmdir %s', dir); + }); + }); +``` + +There is a convenience method to add multiple arguments at once, but without descriptions: + +```js +program + .arguments(' '); +``` + +#### More configuration + +There are some additional features available by constructing an `Argument` explicitly for less common cases. + +Example file: [arguments-extra.js](./examples/arguments-extra.js) + +```js +program + .addArgument(new commander.Argument('', 'drink cup size').choices(['small', 'medium', 'large'])) + .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute')) +``` + +#### Custom argument processing + +You may specify a function to do custom processing of command-arguments (like for option-arguments). +The callback function receives two parameters, the user specified command-argument and the previous value for the argument. +It returns the new value for the argument. + +The processed argument values are passed to the action handler, and saved as `.processedArgs`. + +You can optionally specify the default/starting value for the argument after the function parameter. + +Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js) + +```js +program + .command('add') + .argument('', 'integer argument', myParseInt) + .argument('[second]', 'integer argument', myParseInt, 1000) + .action((first, second) => { + console.log(`${first} + ${second} = ${first + second}`); + }) +; +``` + +### Action handler + +The action handler gets passed a parameter for each command-argument you declared, and two additional parameters +which are the parsed options and the command object itself. + +Example file: [thank.js](./examples/thank.js) + +```js +program + .argument('') + .option('-t, --title ', 'title to use before name') + .option('-d, --debug', 'display some debugging') + .action((name, options, command) => { + if (options.debug) { + console.error('Called %s with options %o', command.name(), options); + } + const title = options.title ? `${options.title} ` : ''; + console.log(`Thank-you ${title}${name}`); + }); +``` + +If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. The `this` keyword is set to the running command and can be used from a function expression (but not from an arrow function). + +Example file: [action-this.js](./examples/action-this.js) + +```js +program + .command('serve') + .argument('`; + if (buffer) { + buffer[0] = `${appendStyleScript}${buffer[0]}`; + return; + } + return Promise.resolve(appendStyleScript); + }; + const addClassNameToContext = ({ context }) => { + if (!contextMap.has(context)) { + contextMap.set(context, [{}, {}]); + } + const [toAdd, added] = contextMap.get(context); + let allAdded = true; + if (!added[cssClassName[import_common.SELECTOR]]) { + allAdded = false; + toAdd[cssClassName[import_common.SELECTOR]] = cssClassName[import_common.STYLE_STRING]; + } + cssClassName[import_common.SELECTORS].forEach( + ({ [import_common.CLASS_NAME]: className2, [import_common.STYLE_STRING]: styleString }) => { + if (!added[className2]) { + allAdded = false; + toAdd[className2] = styleString; + } + } + ); + if (allAdded) { + return; + } + return Promise.resolve((0, import_html.raw)("", [appendStyle])); + }; + const className = new String(cssClassName[import_common.CLASS_NAME]); + Object.assign(className, cssClassName); + className.isEscaped = true; + className.callbacks = [addClassNameToContext]; + const promise = Promise.resolve(className); + Object.assign(promise, cssClassName); + promise.toString = cssJsxDomObject.toString; + return promise; + }; + const css2 = (strings, ...values) => { + return newCssClassNameObject((0, import_common.cssCommon)(strings, values)); + }; + const cx2 = (...args) => { + args = (0, import_common.cxCommon)(args); + return css2(Array(args.length).fill(""), ...args); + }; + const keyframes2 = import_common.keyframesCommon; + const viewTransition2 = ((strings, ...values) => { + return newCssClassNameObject((0, import_common.viewTransitionCommon)(strings, values)); + }); + const Style2 = ({ children, nonce } = {}) => (0, import_html.raw)( + ``, + [ + ({ context }) => { + nonceMap.set(context, nonce); + return void 0; + } + ] + ); + Style2[import_constants.DOM_RENDERER] = StyleRenderToDom; + return { + css: css2, + cx: cx2, + keyframes: keyframes2, + viewTransition: viewTransition2, + Style: Style2 + }; +}; +const defaultContext = createCssContext({ + id: import_common.DEFAULT_STYLE_ID +}); +const css = defaultContext.css; +const cx = defaultContext.cx; +const keyframes = defaultContext.keyframes; +const viewTransition = defaultContext.viewTransition; +const Style = defaultContext.Style; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Style, + createCssContext, + css, + cx, + keyframes, + rawCssString, + viewTransition +}); diff --git a/node_modules/hono/dist/cjs/helper/dev/index.js b/node_modules/hono/dist/cjs/helper/dev/index.js new file mode 100644 index 000000000..4e22ded3d --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/dev/index.js @@ -0,0 +1,80 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var dev_exports = {}; +__export(dev_exports, { + getRouterName: () => getRouterName, + inspectRoutes: () => inspectRoutes, + showRoutes: () => showRoutes +}); +module.exports = __toCommonJS(dev_exports); +var import_color = require("../../utils/color"); +var import_handler = require("../../utils/handler"); +const handlerName = (handler) => { + return handler.name || ((0, import_handler.isMiddleware)(handler) ? "[middleware]" : "[handler]"); +}; +const inspectRoutes = (hono) => { + return hono.routes.map(({ path, method, handler }) => { + const targetHandler = (0, import_handler.findTargetHandler)(handler); + return { + path, + method, + name: handlerName(targetHandler), + isMiddleware: (0, import_handler.isMiddleware)(targetHandler) + }; + }); +}; +const showRoutes = (hono, opts) => { + const colorEnabled = opts?.colorize ?? (0, import_color.getColorEnabled)(); + const routeData = {}; + let maxMethodLength = 0; + let maxPathLength = 0; + inspectRoutes(hono).filter(({ isMiddleware: isMiddleware2 }) => opts?.verbose || !isMiddleware2).map((route) => { + const key = `${route.method}-${route.path}`; + (routeData[key] ||= []).push(route); + if (routeData[key].length > 1) { + return; + } + maxMethodLength = Math.max(maxMethodLength, route.method.length); + maxPathLength = Math.max(maxPathLength, route.path.length); + return { method: route.method, path: route.path, routes: routeData[key] }; + }).forEach((data) => { + if (!data) { + return; + } + const { method, path, routes } = data; + const methodStr = colorEnabled ? `\x1B[32m${method}\x1B[0m` : method; + console.log(`${methodStr} ${" ".repeat(maxMethodLength - method.length)} ${path}`); + if (!opts?.verbose) { + return; + } + routes.forEach(({ name }) => { + console.log(`${" ".repeat(maxMethodLength + 3)} ${name}`); + }); + }); +}; +const getRouterName = (app) => { + app.router.match("GET", "/"); + return app.router.name; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + getRouterName, + inspectRoutes, + showRoutes +}); diff --git a/node_modules/hono/dist/cjs/helper/factory/index.js b/node_modules/hono/dist/cjs/helper/factory/index.js new file mode 100644 index 000000000..0e1463571 --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/factory/index.js @@ -0,0 +1,55 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var factory_exports = {}; +__export(factory_exports, { + Factory: () => Factory, + createFactory: () => createFactory, + createMiddleware: () => createMiddleware +}); +module.exports = __toCommonJS(factory_exports); +var import_hono = require("../../hono"); +class Factory { + initApp; + #defaultAppOptions; + constructor(init) { + this.initApp = init?.initApp; + this.#defaultAppOptions = init?.defaultAppOptions; + } + createApp = (options) => { + const app = new import_hono.Hono( + options && this.#defaultAppOptions ? { ...this.#defaultAppOptions, ...options } : options ?? this.#defaultAppOptions + ); + if (this.initApp) { + this.initApp(app); + } + return app; + }; + createMiddleware = (middleware) => middleware; + createHandlers = (...handlers) => { + return handlers.filter((handler) => handler !== void 0); + }; +} +const createFactory = (init) => new Factory(init); +const createMiddleware = (middleware) => middleware; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Factory, + createFactory, + createMiddleware +}); diff --git a/node_modules/hono/dist/cjs/helper/html/index.js b/node_modules/hono/dist/cjs/helper/html/index.js new file mode 100644 index 000000000..faa3baa27 --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/html/index.js @@ -0,0 +1,65 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var html_exports = {}; +__export(html_exports, { + html: () => html, + raw: () => import_html.raw +}); +module.exports = __toCommonJS(html_exports); +var import_html = require("../../utils/html"); +const html = (strings, ...values) => { + const buffer = [""]; + for (let i = 0, len = strings.length - 1; i < len; i++) { + buffer[0] += strings[i]; + const children = Array.isArray(values[i]) ? values[i].flat(Infinity) : [values[i]]; + for (let i2 = 0, len2 = children.length; i2 < len2; i2++) { + const child = children[i2]; + if (typeof child === "string") { + (0, import_html.escapeToBuffer)(child, buffer); + } else if (typeof child === "number") { + ; + buffer[0] += child; + } else if (typeof child === "boolean" || child === null || child === void 0) { + continue; + } else if (typeof child === "object" && child.isEscaped) { + if (child.callbacks) { + buffer.unshift("", child); + } else { + const tmp = child.toString(); + if (tmp instanceof Promise) { + buffer.unshift("", tmp); + } else { + buffer[0] += tmp; + } + } + } else if (child instanceof Promise) { + buffer.unshift("", child); + } else { + (0, import_html.escapeToBuffer)(child.toString(), buffer); + } + } + } + buffer[0] += strings.at(-1); + return buffer.length === 1 ? "callbacks" in buffer ? (0, import_html.raw)((0, import_html.resolveCallbackSync)((0, import_html.raw)(buffer[0], buffer.callbacks))) : (0, import_html.raw)(buffer[0]) : (0, import_html.stringBufferToString)(buffer, buffer.callbacks); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + html, + raw +}); diff --git a/node_modules/hono/dist/cjs/helper/proxy/index.js b/node_modules/hono/dist/cjs/helper/proxy/index.js new file mode 100644 index 000000000..2c74f1736 --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/proxy/index.js @@ -0,0 +1,112 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var proxy_exports = {}; +__export(proxy_exports, { + proxy: () => proxy +}); +module.exports = __toCommonJS(proxy_exports); +var import_http_exception = require("../../http-exception"); +const hopByHopHeaders = [ + "connection", + "keep-alive", + "proxy-authenticate", + "proxy-authorization", + "te", + "trailer", + "transfer-encoding", + "upgrade" +]; +const ALLOWED_TOKEN_PATTERN = /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/; +const buildRequestInitFromRequest = (request, strictConnectionProcessing) => { + if (!request) { + return {}; + } + const headers = new Headers(request.headers); + if (strictConnectionProcessing) { + const connectionValue = headers.get("connection"); + if (connectionValue) { + const headerNames = connectionValue.split(",").map((h) => h.trim()); + const invalidHeaders = headerNames.filter((h) => !ALLOWED_TOKEN_PATTERN.test(h)); + if (invalidHeaders.length > 0) { + throw new import_http_exception.HTTPException(400, { + message: `Invalid Connection header value: ${invalidHeaders.join(", ")}` + }); + } + headerNames.forEach((headerName) => { + headers.delete(headerName); + }); + } + } + hopByHopHeaders.forEach((header) => { + headers.delete(header); + }); + return { + method: request.method, + body: request.body, + duplex: request.body ? "half" : void 0, + headers, + signal: request.signal + }; +}; +const preprocessRequestInit = (requestInit) => { + if (!requestInit.headers || Array.isArray(requestInit.headers) || requestInit.headers instanceof Headers) { + return requestInit; + } + const headers = new Headers(); + for (const [key, value] of Object.entries(requestInit.headers)) { + if (value == null) { + headers.delete(key); + } else { + headers.set(key, value); + } + } + requestInit.headers = headers; + return requestInit; +}; +const proxy = async (input, proxyInit) => { + const { + raw, + customFetch, + strictConnectionProcessing = false, + ...requestInit + } = proxyInit instanceof Request ? { raw: proxyInit } : proxyInit ?? {}; + const req = new Request(input, { + ...buildRequestInitFromRequest(raw, strictConnectionProcessing), + ...preprocessRequestInit(requestInit) + }); + req.headers.delete("accept-encoding"); + const res = await (customFetch || fetch)(req); + const resHeaders = new Headers(res.headers); + hopByHopHeaders.forEach((header) => { + resHeaders.delete(header); + }); + if (resHeaders.has("content-encoding")) { + resHeaders.delete("content-encoding"); + resHeaders.delete("content-length"); + } + return new Response(res.body, { + status: res.status, + statusText: res.statusText, + headers: resHeaders + }); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + proxy +}); diff --git a/node_modules/hono/dist/cjs/helper/route/index.js b/node_modules/hono/dist/cjs/helper/route/index.js new file mode 100644 index 000000000..95769dbfd --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/route/index.js @@ -0,0 +1,72 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var route_exports = {}; +__export(route_exports, { + basePath: () => basePath, + baseRoutePath: () => baseRoutePath, + matchedRoutes: () => matchedRoutes, + routePath: () => routePath +}); +module.exports = __toCommonJS(route_exports); +var import_constants = require("../../request/constants"); +var import_url = require("../../utils/url"); +const matchedRoutes = (c) => ( + // @ts-expect-error c.req[GET_MATCH_RESULT] is not typed + c.req[import_constants.GET_MATCH_RESULT][0].map(([[, route]]) => route) +); +const routePath = (c, index) => matchedRoutes(c).at(index ?? c.req.routeIndex)?.path ?? ""; +const baseRoutePath = (c, index) => matchedRoutes(c).at(index ?? c.req.routeIndex)?.basePath ?? ""; +const basePathCacheMap = /* @__PURE__ */ new WeakMap(); +const basePath = (c, index) => { + index ??= c.req.routeIndex; + const cache = basePathCacheMap.get(c) || []; + if (typeof cache[index] === "string") { + return cache[index]; + } + let result; + const rp = baseRoutePath(c, index); + if (!/[:*]/.test(rp)) { + result = rp; + } else { + const paths = (0, import_url.splitRoutingPath)(rp); + const reqPath = c.req.path; + let basePathLength = 0; + for (let i = 0, len = paths.length; i < len; i++) { + const pattern = (0, import_url.getPattern)(paths[i], paths[i + 1]); + if (pattern) { + const re = pattern[2] === true || pattern === "*" ? /[^\/]+/ : pattern[2]; + basePathLength += reqPath.substring(basePathLength + 1).match(re)?.[0].length || 0; + } else { + basePathLength += paths[i].length; + } + basePathLength += 1; + } + result = reqPath.substring(0, basePathLength); + } + cache[index] = result; + basePathCacheMap.set(c, cache); + return result; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + basePath, + baseRoutePath, + matchedRoutes, + routePath +}); diff --git a/node_modules/hono/dist/cjs/helper/ssg/index.js b/node_modules/hono/dist/cjs/helper/ssg/index.js new file mode 100644 index 000000000..4969d061c --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/ssg/index.js @@ -0,0 +1,39 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var ssg_exports = {}; +__export(ssg_exports, { + X_HONO_DISABLE_SSG_HEADER_KEY: () => import_middleware.X_HONO_DISABLE_SSG_HEADER_KEY, + disableSSG: () => import_middleware.disableSSG, + isSSGContext: () => import_middleware.isSSGContext, + onlySSG: () => import_middleware.onlySSG, + ssgParams: () => import_middleware.ssgParams +}); +module.exports = __toCommonJS(ssg_exports); +__reExport(ssg_exports, require("./ssg"), module.exports); +var import_middleware = require("./middleware"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + X_HONO_DISABLE_SSG_HEADER_KEY, + disableSSG, + isSSGContext, + onlySSG, + ssgParams, + ...require("./ssg") +}); diff --git a/node_modules/hono/dist/cjs/helper/ssg/middleware.js b/node_modules/hono/dist/cjs/helper/ssg/middleware.js new file mode 100644 index 000000000..fcab0319f --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/ssg/middleware.js @@ -0,0 +1,74 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var middleware_exports = {}; +__export(middleware_exports, { + SSG_CONTEXT: () => SSG_CONTEXT, + SSG_DISABLED_RESPONSE: () => SSG_DISABLED_RESPONSE, + X_HONO_DISABLE_SSG_HEADER_KEY: () => X_HONO_DISABLE_SSG_HEADER_KEY, + disableSSG: () => disableSSG, + isSSGContext: () => isSSGContext, + onlySSG: () => onlySSG, + ssgParams: () => ssgParams +}); +module.exports = __toCommonJS(middleware_exports); +var import_utils = require("./utils"); +const SSG_CONTEXT = "HONO_SSG_CONTEXT"; +const X_HONO_DISABLE_SSG_HEADER_KEY = "x-hono-disable-ssg"; +const SSG_DISABLED_RESPONSE = (() => { + try { + return new Response("SSG is disabled", { + status: 404, + headers: { [X_HONO_DISABLE_SSG_HEADER_KEY]: "true" } + }); + } catch { + return null; + } +})(); +const ssgParams = (params) => async (c, next) => { + if ((0, import_utils.isDynamicRoute)(c.req.path)) { + ; + c.req.raw.ssgParams = Array.isArray(params) ? params : await params(c); + return c.notFound(); + } + await next(); +}; +const isSSGContext = (c) => !!c.env?.[SSG_CONTEXT]; +const disableSSG = () => async function disableSSG2(c, next) { + if (isSSGContext(c)) { + c.header(X_HONO_DISABLE_SSG_HEADER_KEY, "true"); + return c.notFound(); + } + await next(); +}; +const onlySSG = () => async function onlySSG2(c, next) { + if (!isSSGContext(c)) { + return c.notFound(); + } + await next(); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + SSG_CONTEXT, + SSG_DISABLED_RESPONSE, + X_HONO_DISABLE_SSG_HEADER_KEY, + disableSSG, + isSSGContext, + onlySSG, + ssgParams +}); diff --git a/node_modules/hono/dist/cjs/helper/ssg/ssg.js b/node_modules/hono/dist/cjs/helper/ssg/ssg.js new file mode 100644 index 000000000..0a4493a92 --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/ssg/ssg.js @@ -0,0 +1,326 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var ssg_exports = {}; +__export(ssg_exports, { + DEFAULT_OUTPUT_DIR: () => DEFAULT_OUTPUT_DIR, + combineAfterGenerateHooks: () => combineAfterGenerateHooks, + combineAfterResponseHooks: () => combineAfterResponseHooks, + combineBeforeRequestHooks: () => combineBeforeRequestHooks, + defaultExtensionMap: () => defaultExtensionMap, + defaultPlugin: () => defaultPlugin, + fetchRoutesContent: () => fetchRoutesContent, + saveContentToFile: () => saveContentToFile, + toSSG: () => toSSG +}); +module.exports = __toCommonJS(ssg_exports); +var import_utils = require("../../client/utils"); +var import_concurrent = require("../../utils/concurrent"); +var import_mime = require("../../utils/mime"); +var import_middleware = require("./middleware"); +var import_utils2 = require("./utils"); +const DEFAULT_CONCURRENCY = 2; +const DEFAULT_CONTENT_TYPE = "text/plain"; +const DEFAULT_OUTPUT_DIR = "./static"; +const generateFilePath = (routePath, outDir, mimeType, extensionMap) => { + const extension = determineExtension(mimeType, extensionMap); + if (routePath.endsWith(`.${extension}`)) { + return (0, import_utils2.joinPaths)(outDir, routePath); + } + if (routePath === "/") { + return (0, import_utils2.joinPaths)(outDir, `index.${extension}`); + } + if (routePath.endsWith("/")) { + return (0, import_utils2.joinPaths)(outDir, routePath, `index.${extension}`); + } + return (0, import_utils2.joinPaths)(outDir, `${routePath}.${extension}`); +}; +const parseResponseContent = async (response) => { + const contentType = response.headers.get("Content-Type"); + try { + if (contentType?.includes("text") || contentType?.includes("json")) { + return await response.text(); + } else { + return await response.arrayBuffer(); + } + } catch (error) { + throw new Error( + `Error processing response: ${error instanceof Error ? error.message : "Unknown error"}` + ); + } +}; +const defaultExtensionMap = { + "text/html": "html", + "text/xml": "xml", + "application/xml": "xml", + "application/yaml": "yaml" +}; +const determineExtension = (mimeType, userExtensionMap) => { + const extensionMap = userExtensionMap || defaultExtensionMap; + if (mimeType in extensionMap) { + return extensionMap[mimeType]; + } + return (0, import_mime.getExtension)(mimeType) || "html"; +}; +const combineBeforeRequestHooks = (hooks) => { + if (!Array.isArray(hooks)) { + return hooks; + } + return async (req) => { + let currentReq = req; + for (const hook of hooks) { + const result = await hook(currentReq); + if (result === false) { + return false; + } + if (result instanceof Request) { + currentReq = result; + } + } + return currentReq; + }; +}; +const combineAfterResponseHooks = (hooks) => { + if (!Array.isArray(hooks)) { + return hooks; + } + return async (res) => { + let currentRes = res; + for (const hook of hooks) { + const result = await hook(currentRes); + if (result === false) { + return false; + } + if (result instanceof Response) { + currentRes = result; + } + } + return currentRes; + }; +}; +const combineAfterGenerateHooks = (hooks, fsModule, options) => { + if (!Array.isArray(hooks)) { + return hooks; + } + return async (result) => { + for (const hook of hooks) { + await hook(result, fsModule, options); + } + }; +}; +const fetchRoutesContent = function* (app, beforeRequestHook, afterResponseHook, concurrency) { + const baseURL = "http://localhost"; + const pool = (0, import_concurrent.createPool)({ concurrency }); + for (const route of (0, import_utils2.filterStaticGenerateRoutes)(app)) { + const thisRouteBaseURL = new URL(route.path, baseURL).toString(); + let forGetInfoURLRequest = new Request(thisRouteBaseURL); + yield new Promise(async (resolveGetInfo, rejectGetInfo) => { + try { + if (beforeRequestHook) { + const maybeRequest = await beforeRequestHook(forGetInfoURLRequest); + if (!maybeRequest) { + resolveGetInfo(void 0); + return; + } + forGetInfoURLRequest = maybeRequest; + } + await pool.run(() => app.fetch(forGetInfoURLRequest)); + if (!forGetInfoURLRequest.ssgParams) { + if ((0, import_utils2.isDynamicRoute)(route.path)) { + resolveGetInfo(void 0); + return; + } + forGetInfoURLRequest.ssgParams = [{}]; + } + const requestInit = { + method: forGetInfoURLRequest.method, + headers: forGetInfoURLRequest.headers + }; + resolveGetInfo( + (function* () { + for (const param of forGetInfoURLRequest.ssgParams) { + yield new Promise(async (resolveReq, rejectReq) => { + try { + const replacedUrlParam = (0, import_utils.replaceUrlParam)(route.path, param); + let response = await pool.run( + () => app.request(replacedUrlParam, requestInit, { + [import_middleware.SSG_CONTEXT]: true + }) + ); + if (response.headers.get(import_middleware.X_HONO_DISABLE_SSG_HEADER_KEY)) { + resolveReq(void 0); + return; + } + if (afterResponseHook) { + const maybeResponse = await afterResponseHook(response); + if (!maybeResponse) { + resolveReq(void 0); + return; + } + response = maybeResponse; + } + const mimeType = response.headers.get("Content-Type")?.split(";")[0] || DEFAULT_CONTENT_TYPE; + const content = await parseResponseContent(response); + resolveReq({ + routePath: replacedUrlParam, + mimeType, + content + }); + } catch (error) { + rejectReq(error); + } + }); + } + })() + ); + } catch (error) { + rejectGetInfo(error); + } + }); + } +}; +const createdDirs = /* @__PURE__ */ new Set(); +const saveContentToFile = async (data, fsModule, outDir, extensionMap) => { + const awaitedData = await data; + if (!awaitedData) { + return; + } + const { routePath, content, mimeType } = awaitedData; + const filePath = generateFilePath(routePath, outDir, mimeType, extensionMap); + const dirPath = (0, import_utils2.dirname)(filePath); + if (!createdDirs.has(dirPath)) { + await fsModule.mkdir(dirPath, { recursive: true }); + createdDirs.add(dirPath); + } + if (typeof content === "string") { + await fsModule.writeFile(filePath, content); + } else if (content instanceof ArrayBuffer) { + await fsModule.writeFile(filePath, new Uint8Array(content)); + } + return filePath; +}; +const defaultPlugin = { + afterResponseHook: (res) => { + if (res.status !== 200) { + return false; + } + return res; + } +}; +const toSSG = async (app, fs, options) => { + let result; + const getInfoPromises = []; + const savePromises = []; + const plugins = options?.plugins || [defaultPlugin]; + const beforeRequestHooks = []; + const afterResponseHooks = []; + const afterGenerateHooks = []; + if (options?.beforeRequestHook) { + beforeRequestHooks.push( + ...Array.isArray(options.beforeRequestHook) ? options.beforeRequestHook : [options.beforeRequestHook] + ); + } + if (options?.afterResponseHook) { + afterResponseHooks.push( + ...Array.isArray(options.afterResponseHook) ? options.afterResponseHook : [options.afterResponseHook] + ); + } + if (options?.afterGenerateHook) { + afterGenerateHooks.push( + ...Array.isArray(options.afterGenerateHook) ? options.afterGenerateHook : [options.afterGenerateHook] + ); + } + for (const plugin of plugins) { + if (plugin.beforeRequestHook) { + beforeRequestHooks.push( + ...Array.isArray(plugin.beforeRequestHook) ? plugin.beforeRequestHook : [plugin.beforeRequestHook] + ); + } + if (plugin.afterResponseHook) { + afterResponseHooks.push( + ...Array.isArray(plugin.afterResponseHook) ? plugin.afterResponseHook : [plugin.afterResponseHook] + ); + } + if (plugin.afterGenerateHook) { + afterGenerateHooks.push( + ...Array.isArray(plugin.afterGenerateHook) ? plugin.afterGenerateHook : [plugin.afterGenerateHook] + ); + } + } + try { + const outputDir = options?.dir ?? DEFAULT_OUTPUT_DIR; + const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY; + const combinedBeforeRequestHook = combineBeforeRequestHooks( + beforeRequestHooks.length > 0 ? beforeRequestHooks : [(req) => req] + ); + const combinedAfterResponseHook = combineAfterResponseHooks( + afterResponseHooks.length > 0 ? afterResponseHooks : [(req) => req] + ); + const getInfoGen = fetchRoutesContent( + app, + combinedBeforeRequestHook, + combinedAfterResponseHook, + concurrency + ); + for (const getInfo of getInfoGen) { + getInfoPromises.push( + getInfo.then((getContentGen) => { + if (!getContentGen) { + return; + } + for (const content of getContentGen) { + savePromises.push( + saveContentToFile(content, fs, outputDir, options?.extensionMap).catch((e) => e) + ); + } + }) + ); + } + await Promise.all(getInfoPromises); + const files = []; + for (const savePromise of savePromises) { + const fileOrError = await savePromise; + if (typeof fileOrError === "string") { + files.push(fileOrError); + } else if (fileOrError) { + throw fileOrError; + } + } + result = { success: true, files }; + } catch (error) { + const errorObj = error instanceof Error ? error : new Error(String(error)); + result = { success: false, files: [], error: errorObj }; + } + if (afterGenerateHooks.length > 0) { + const combinedAfterGenerateHooks = combineAfterGenerateHooks(afterGenerateHooks, fs, options); + await combinedAfterGenerateHooks(result, fs, options); + } + return result; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + DEFAULT_OUTPUT_DIR, + combineAfterGenerateHooks, + combineAfterResponseHooks, + combineBeforeRequestHooks, + defaultExtensionMap, + defaultPlugin, + fetchRoutesContent, + saveContentToFile, + toSSG +}); diff --git a/node_modules/hono/dist/cjs/helper/ssg/utils.js b/node_modules/hono/dist/cjs/helper/ssg/utils.js new file mode 100644 index 000000000..8cb13afda --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/ssg/utils.js @@ -0,0 +1,85 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var utils_exports = {}; +__export(utils_exports, { + dirname: () => dirname, + filterStaticGenerateRoutes: () => filterStaticGenerateRoutes, + isDynamicRoute: () => isDynamicRoute, + joinPaths: () => joinPaths +}); +module.exports = __toCommonJS(utils_exports); +var import_router = require("../../router"); +var import_handler = require("../../utils/handler"); +const dirname = (path) => { + const separatedPath = path.split(/[\/\\]/); + return separatedPath.slice(0, -1).join("/"); +}; +const normalizePath = (path) => { + return path.replace(/(\\)/g, "/").replace(/\/$/g, ""); +}; +const handleParent = (resultPaths, beforeParentFlag) => { + if (resultPaths.length === 0 || beforeParentFlag) { + resultPaths.push(".."); + } else { + resultPaths.pop(); + } +}; +const handleNonDot = (path, resultPaths) => { + path = path.replace(/^\.(?!.)/, ""); + if (path !== "") { + resultPaths.push(path); + } +}; +const handleSegments = (paths, resultPaths) => { + let beforeParentFlag = false; + for (const path of paths) { + if (path === "..") { + handleParent(resultPaths, beforeParentFlag); + beforeParentFlag = true; + } else { + handleNonDot(path, resultPaths); + beforeParentFlag = false; + } + } +}; +const joinPaths = (...paths) => { + paths = paths.map(normalizePath); + const resultPaths = []; + handleSegments(paths.join("/").split("/"), resultPaths); + return (paths[0][0] === "/" ? "/" : "") + resultPaths.join("/"); +}; +const filterStaticGenerateRoutes = (hono) => { + return hono.routes.reduce((acc, { method, handler, path }) => { + const targetHandler = (0, import_handler.findTargetHandler)(handler); + if (["GET", import_router.METHOD_NAME_ALL].includes(method) && !(0, import_handler.isMiddleware)(targetHandler)) { + acc.push({ path }); + } + return acc; + }, []); +}; +const isDynamicRoute = (path) => { + return path.split("/").some((segment) => segment.startsWith(":") || segment.includes("*")); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + dirname, + filterStaticGenerateRoutes, + isDynamicRoute, + joinPaths +}); diff --git a/node_modules/hono/dist/cjs/helper/streaming/index.js b/node_modules/hono/dist/cjs/helper/streaming/index.js new file mode 100644 index 000000000..b343d994d --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/streaming/index.js @@ -0,0 +1,36 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var streaming_exports = {}; +__export(streaming_exports, { + SSEStreamingApi: () => import_sse.SSEStreamingApi, + stream: () => import_stream.stream, + streamSSE: () => import_sse.streamSSE, + streamText: () => import_text.streamText +}); +module.exports = __toCommonJS(streaming_exports); +var import_stream = require("./stream"); +var import_sse = require("./sse"); +var import_text = require("./text"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + SSEStreamingApi, + stream, + streamSSE, + streamText +}); diff --git a/node_modules/hono/dist/cjs/helper/streaming/sse.js b/node_modules/hono/dist/cjs/helper/streaming/sse.js new file mode 100644 index 000000000..95a780640 --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/streaming/sse.js @@ -0,0 +1,86 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var sse_exports = {}; +__export(sse_exports, { + SSEStreamingApi: () => SSEStreamingApi, + streamSSE: () => streamSSE +}); +module.exports = __toCommonJS(sse_exports); +var import_html = require("../../utils/html"); +var import_stream = require("../../utils/stream"); +var import_utils = require("./utils"); +class SSEStreamingApi extends import_stream.StreamingApi { + constructor(writable, readable) { + super(writable, readable); + } + async writeSSE(message) { + const data = await (0, import_html.resolveCallback)(message.data, import_html.HtmlEscapedCallbackPhase.Stringify, false, {}); + const dataLines = data.split("\n").map((line) => { + return `data: ${line}`; + }).join("\n"); + const sseData = [ + message.event && `event: ${message.event}`, + dataLines, + message.id && `id: ${message.id}`, + message.retry && `retry: ${message.retry}` + ].filter(Boolean).join("\n") + "\n\n"; + await this.write(sseData); + } +} +const run = async (stream, cb, onError) => { + try { + await cb(stream); + } catch (e) { + if (e instanceof Error && onError) { + await onError(e, stream); + await stream.writeSSE({ + event: "error", + data: e.message + }); + } else { + console.error(e); + } + } finally { + stream.close(); + } +}; +const contextStash = /* @__PURE__ */ new WeakMap(); +const streamSSE = (c, cb, onError) => { + const { readable, writable } = new TransformStream(); + const stream = new SSEStreamingApi(writable, readable); + if ((0, import_utils.isOldBunVersion)()) { + c.req.raw.signal.addEventListener("abort", () => { + if (!stream.closed) { + stream.abort(); + } + }); + } + contextStash.set(stream.responseReadable, c); + c.header("Transfer-Encoding", "chunked"); + c.header("Content-Type", "text/event-stream"); + c.header("Cache-Control", "no-cache"); + c.header("Connection", "keep-alive"); + run(stream, cb, onError); + return c.newResponse(stream.responseReadable); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + SSEStreamingApi, + streamSSE +}); diff --git a/node_modules/hono/dist/cjs/helper/streaming/stream.js b/node_modules/hono/dist/cjs/helper/streaming/stream.js new file mode 100644 index 000000000..29d3dd896 --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/streaming/stream.js @@ -0,0 +1,57 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var stream_exports = {}; +__export(stream_exports, { + stream: () => stream +}); +module.exports = __toCommonJS(stream_exports); +var import_stream = require("../../utils/stream"); +var import_utils = require("./utils"); +const contextStash = /* @__PURE__ */ new WeakMap(); +const stream = (c, cb, onError) => { + const { readable, writable } = new TransformStream(); + const stream2 = new import_stream.StreamingApi(writable, readable); + if ((0, import_utils.isOldBunVersion)()) { + c.req.raw.signal.addEventListener("abort", () => { + if (!stream2.closed) { + stream2.abort(); + } + }); + } + contextStash.set(stream2.responseReadable, c); + (async () => { + try { + await cb(stream2); + } catch (e) { + if (e === void 0) { + } else if (e instanceof Error && onError) { + await onError(e, stream2); + } else { + console.error(e); + } + } finally { + stream2.close(); + } + })(); + return c.newResponse(stream2.responseReadable); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + stream +}); diff --git a/node_modules/hono/dist/cjs/helper/streaming/text.js b/node_modules/hono/dist/cjs/helper/streaming/text.js new file mode 100644 index 000000000..c4fba1df2 --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/streaming/text.js @@ -0,0 +1,35 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var text_exports = {}; +__export(text_exports, { + streamText: () => streamText +}); +module.exports = __toCommonJS(text_exports); +var import_context = require("../../context"); +var import__ = require("./"); +const streamText = (c, cb, onError) => { + c.header("Content-Type", import_context.TEXT_PLAIN); + c.header("X-Content-Type-Options", "nosniff"); + c.header("Transfer-Encoding", "chunked"); + return (0, import__.stream)(c, cb, onError); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + streamText +}); diff --git a/node_modules/hono/dist/cjs/helper/streaming/utils.js b/node_modules/hono/dist/cjs/helper/streaming/utils.js new file mode 100644 index 000000000..ff818c1f7 --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/streaming/utils.js @@ -0,0 +1,36 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var utils_exports = {}; +__export(utils_exports, { + isOldBunVersion: () => isOldBunVersion +}); +module.exports = __toCommonJS(utils_exports); +let isOldBunVersion = () => { + const version = typeof Bun !== "undefined" ? Bun.version : void 0; + if (version === void 0) { + return false; + } + const result = version.startsWith("1.1") || version.startsWith("1.0") || version.startsWith("0."); + isOldBunVersion = () => result; + return result; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + isOldBunVersion +}); diff --git a/node_modules/hono/dist/cjs/helper/testing/index.js b/node_modules/hono/dist/cjs/helper/testing/index.js new file mode 100644 index 000000000..6e9e432a5 --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/testing/index.js @@ -0,0 +1,34 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var testing_exports = {}; +__export(testing_exports, { + testClient: () => testClient +}); +module.exports = __toCommonJS(testing_exports); +var import_client = require("../../client"); +const testClient = (app, Env, executionCtx, options) => { + const customFetch = (input, init) => { + return app.request(input, init, Env, executionCtx); + }; + return (0, import_client.hc)("http://localhost", { ...options, fetch: customFetch }); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + testClient +}); diff --git a/node_modules/hono/dist/cjs/helper/websocket/index.js b/node_modules/hono/dist/cjs/helper/websocket/index.js new file mode 100644 index 000000000..ee33b6549 --- /dev/null +++ b/node_modules/hono/dist/cjs/helper/websocket/index.js @@ -0,0 +1,82 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var websocket_exports = {}; +__export(websocket_exports, { + WSContext: () => WSContext, + createWSMessageEvent: () => createWSMessageEvent, + defineWebSocketHelper: () => defineWebSocketHelper +}); +module.exports = __toCommonJS(websocket_exports); +class WSContext { + #init; + constructor(init) { + this.#init = init; + this.raw = init.raw; + this.url = init.url ? new URL(init.url) : null; + this.protocol = init.protocol ?? null; + } + send(source, options) { + this.#init.send(source, options ?? {}); + } + raw; + binaryType = "arraybuffer"; + get readyState() { + return this.#init.readyState; + } + url; + protocol; + close(code, reason) { + this.#init.close(code, reason); + } +} +const createWSMessageEvent = (source) => { + return new MessageEvent("message", { + data: source + }); +}; +const defineWebSocketHelper = (handler) => { + return ((...args) => { + if (typeof args[0] === "function") { + const [createEvents, options] = args; + return async function upgradeWebSocket(c, next) { + const events = await createEvents(c); + const result = await handler(c, events, options); + if (result) { + return result; + } + await next(); + }; + } else { + const [c, events, options] = args; + return (async () => { + const upgraded = await handler(c, events, options); + if (!upgraded) { + throw new Error("Failed to upgrade WebSocket"); + } + return upgraded; + })(); + } + }); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + WSContext, + createWSMessageEvent, + defineWebSocketHelper +}); diff --git a/node_modules/hono/dist/cjs/hono-base.js b/node_modules/hono/dist/cjs/hono-base.js new file mode 100644 index 000000000..63eebce29 --- /dev/null +++ b/node_modules/hono/dist/cjs/hono-base.js @@ -0,0 +1,401 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var hono_base_exports = {}; +__export(hono_base_exports, { + HonoBase: () => Hono +}); +module.exports = __toCommonJS(hono_base_exports); +var import_compose = require("./compose"); +var import_context = require("./context"); +var import_router = require("./router"); +var import_constants = require("./utils/constants"); +var import_url = require("./utils/url"); +const notFoundHandler = (c) => { + return c.text("404 Not Found", 404); +}; +const errorHandler = (err, c) => { + if ("getResponse" in err) { + const res = err.getResponse(); + return c.newResponse(res.body, res); + } + console.error(err); + return c.text("Internal Server Error", 500); +}; +class Hono { + get; + post; + put; + delete; + options; + patch; + all; + on; + use; + /* + This class is like an abstract class and does not have a router. + To use it, inherit the class and implement router in the constructor. + */ + router; + getPath; + // Cannot use `#` because it requires visibility at JavaScript runtime. + _basePath = "/"; + #path = "/"; + routes = []; + constructor(options = {}) { + const allMethods = [...import_router.METHODS, import_router.METHOD_NAME_ALL_LOWERCASE]; + allMethods.forEach((method) => { + this[method] = (args1, ...args) => { + if (typeof args1 === "string") { + this.#path = args1; + } else { + this.#addRoute(method, this.#path, args1); + } + args.forEach((handler) => { + this.#addRoute(method, this.#path, handler); + }); + return this; + }; + }); + this.on = (method, path, ...handlers) => { + for (const p of [path].flat()) { + this.#path = p; + for (const m of [method].flat()) { + handlers.map((handler) => { + this.#addRoute(m.toUpperCase(), this.#path, handler); + }); + } + } + return this; + }; + this.use = (arg1, ...handlers) => { + if (typeof arg1 === "string") { + this.#path = arg1; + } else { + this.#path = "*"; + handlers.unshift(arg1); + } + handlers.forEach((handler) => { + this.#addRoute(import_router.METHOD_NAME_ALL, this.#path, handler); + }); + return this; + }; + const { strict, ...optionsWithoutStrict } = options; + Object.assign(this, optionsWithoutStrict); + this.getPath = strict ?? true ? options.getPath ?? import_url.getPath : import_url.getPathNoStrict; + } + #clone() { + const clone = new Hono({ + router: this.router, + getPath: this.getPath + }); + clone.errorHandler = this.errorHandler; + clone.#notFoundHandler = this.#notFoundHandler; + clone.routes = this.routes; + return clone; + } + #notFoundHandler = notFoundHandler; + // Cannot use `#` because it requires visibility at JavaScript runtime. + errorHandler = errorHandler; + /** + * `.route()` allows grouping other Hono instance in routes. + * + * @see {@link https://hono.dev/docs/api/routing#grouping} + * + * @param {string} path - base Path + * @param {Hono} app - other Hono instance + * @returns {Hono} routed Hono instance + * + * @example + * ```ts + * const app = new Hono() + * const app2 = new Hono() + * + * app2.get("/user", (c) => c.text("user")) + * app.route("/api", app2) // GET /api/user + * ``` + */ + route(path, app) { + const subApp = this.basePath(path); + app.routes.map((r) => { + let handler; + if (app.errorHandler === errorHandler) { + handler = r.handler; + } else { + handler = async (c, next) => (await (0, import_compose.compose)([], app.errorHandler)(c, () => r.handler(c, next))).res; + handler[import_constants.COMPOSED_HANDLER] = r.handler; + } + subApp.#addRoute(r.method, r.path, handler); + }); + return this; + } + /** + * `.basePath()` allows base paths to be specified. + * + * @see {@link https://hono.dev/docs/api/routing#base-path} + * + * @param {string} path - base Path + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * const api = new Hono().basePath('/api') + * ``` + */ + basePath(path) { + const subApp = this.#clone(); + subApp._basePath = (0, import_url.mergePath)(this._basePath, path); + return subApp; + } + /** + * `.onError()` handles an error and returns a customized Response. + * + * @see {@link https://hono.dev/docs/api/hono#error-handling} + * + * @param {ErrorHandler} handler - request Handler for error + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * app.onError((err, c) => { + * console.error(`${err}`) + * return c.text('Custom Error Message', 500) + * }) + * ``` + */ + onError = (handler) => { + this.errorHandler = handler; + return this; + }; + /** + * `.notFound()` allows you to customize a Not Found Response. + * + * @see {@link https://hono.dev/docs/api/hono#not-found} + * + * @param {NotFoundHandler} handler - request handler for not-found + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * app.notFound((c) => { + * return c.text('Custom 404 Message', 404) + * }) + * ``` + */ + notFound = (handler) => { + this.#notFoundHandler = handler; + return this; + }; + /** + * `.mount()` allows you to mount applications built with other frameworks into your Hono application. + * + * @see {@link https://hono.dev/docs/api/hono#mount} + * + * @param {string} path - base Path + * @param {Function} applicationHandler - other Request Handler + * @param {MountOptions} [options] - options of `.mount()` + * @returns {Hono} mounted Hono instance + * + * @example + * ```ts + * import { Router as IttyRouter } from 'itty-router' + * import { Hono } from 'hono' + * // Create itty-router application + * const ittyRouter = IttyRouter() + * // GET /itty-router/hello + * ittyRouter.get('/hello', () => new Response('Hello from itty-router')) + * + * const app = new Hono() + * app.mount('/itty-router', ittyRouter.handle) + * ``` + * + * @example + * ```ts + * const app = new Hono() + * // Send the request to another application without modification. + * app.mount('/app', anotherApp, { + * replaceRequest: (req) => req, + * }) + * ``` + */ + mount(path, applicationHandler, options) { + let replaceRequest; + let optionHandler; + if (options) { + if (typeof options === "function") { + optionHandler = options; + } else { + optionHandler = options.optionHandler; + if (options.replaceRequest === false) { + replaceRequest = (request) => request; + } else { + replaceRequest = options.replaceRequest; + } + } + } + const getOptions = optionHandler ? (c) => { + const options2 = optionHandler(c); + return Array.isArray(options2) ? options2 : [options2]; + } : (c) => { + let executionContext = void 0; + try { + executionContext = c.executionCtx; + } catch { + } + return [c.env, executionContext]; + }; + replaceRequest ||= (() => { + const mergedPath = (0, import_url.mergePath)(this._basePath, path); + const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length; + return (request) => { + const url = new URL(request.url); + url.pathname = url.pathname.slice(pathPrefixLength) || "/"; + return new Request(url, request); + }; + })(); + const handler = async (c, next) => { + const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c)); + if (res) { + return res; + } + await next(); + }; + this.#addRoute(import_router.METHOD_NAME_ALL, (0, import_url.mergePath)(path, "*"), handler); + return this; + } + #addRoute(method, path, handler) { + method = method.toUpperCase(); + path = (0, import_url.mergePath)(this._basePath, path); + const r = { basePath: this._basePath, path, method, handler }; + this.router.add(method, path, [handler, r]); + this.routes.push(r); + } + #handleError(err, c) { + if (err instanceof Error) { + return this.errorHandler(err, c); + } + throw err; + } + #dispatch(request, executionCtx, env, method) { + if (method === "HEAD") { + return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))(); + } + const path = this.getPath(request, { env }); + const matchResult = this.router.match(method, path); + const c = new import_context.Context(request, { + path, + matchResult, + env, + executionCtx, + notFoundHandler: this.#notFoundHandler + }); + if (matchResult[0].length === 1) { + let res; + try { + res = matchResult[0][0][0][0](c, async () => { + c.res = await this.#notFoundHandler(c); + }); + } catch (err) { + return this.#handleError(err, c); + } + return res instanceof Promise ? res.then( + (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c)) + ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c); + } + const composed = (0, import_compose.compose)(matchResult[0], this.errorHandler, this.#notFoundHandler); + return (async () => { + try { + const context = await composed(c); + if (!context.finalized) { + throw new Error( + "Context is not finalized. Did you forget to return a Response object or `await next()`?" + ); + } + return context.res; + } catch (err) { + return this.#handleError(err, c); + } + })(); + } + /** + * `.fetch()` will be entry point of your app. + * + * @see {@link https://hono.dev/docs/api/hono#fetch} + * + * @param {Request} request - request Object of request + * @param {Env} Env - env Object + * @param {ExecutionContext} - context of execution + * @returns {Response | Promise} response of request + * + */ + fetch = (request, ...rest) => { + return this.#dispatch(request, rest[1], rest[0], request.method); + }; + /** + * `.request()` is a useful method for testing. + * You can pass a URL or pathname to send a GET request. + * app will return a Response object. + * ```ts + * test('GET /hello is ok', async () => { + * const res = await app.request('/hello') + * expect(res.status).toBe(200) + * }) + * ``` + * @see https://hono.dev/docs/api/hono#request + */ + request = (input, requestInit, Env, executionCtx) => { + if (input instanceof Request) { + return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx); + } + input = input.toString(); + return this.fetch( + new Request( + /^https?:\/\//.test(input) ? input : `http://localhost${(0, import_url.mergePath)("/", input)}`, + requestInit + ), + Env, + executionCtx + ); + }; + /** + * `.fire()` automatically adds a global fetch event listener. + * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers. + * @deprecated + * Use `fire` from `hono/service-worker` instead. + * ```ts + * import { Hono } from 'hono' + * import { fire } from 'hono/service-worker' + * + * const app = new Hono() + * // ... + * fire(app) + * ``` + * @see https://hono.dev/docs/api/hono#fire + * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API + * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/ + */ + fire = () => { + addEventListener("fetch", (event) => { + event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method)); + }); + }; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + HonoBase +}); diff --git a/node_modules/hono/dist/cjs/hono.js b/node_modules/hono/dist/cjs/hono.js new file mode 100644 index 000000000..06d59a2b5 --- /dev/null +++ b/node_modules/hono/dist/cjs/hono.js @@ -0,0 +1,44 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var hono_exports = {}; +__export(hono_exports, { + Hono: () => Hono +}); +module.exports = __toCommonJS(hono_exports); +var import_hono_base = require("./hono-base"); +var import_reg_exp_router = require("./router/reg-exp-router"); +var import_smart_router = require("./router/smart-router"); +var import_trie_router = require("./router/trie-router"); +class Hono extends import_hono_base.HonoBase { + /** + * Creates an instance of the Hono class. + * + * @param options - Optional configuration options for the Hono instance. + */ + constructor(options = {}) { + super(options); + this.router = options.router ?? new import_smart_router.SmartRouter({ + routers: [new import_reg_exp_router.RegExpRouter(), new import_trie_router.TrieRouter()] + }); + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Hono +}); diff --git a/node_modules/hono/dist/cjs/http-exception.js b/node_modules/hono/dist/cjs/http-exception.js new file mode 100644 index 000000000..3ad00c5d0 --- /dev/null +++ b/node_modules/hono/dist/cjs/http-exception.js @@ -0,0 +1,58 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var http_exception_exports = {}; +__export(http_exception_exports, { + HTTPException: () => HTTPException +}); +module.exports = __toCommonJS(http_exception_exports); +class HTTPException extends Error { + res; + status; + /** + * Creates an instance of `HTTPException`. + * @param status - HTTP status code for the exception. Defaults to 500. + * @param options - Additional options for the exception. + */ + constructor(status = 500, options) { + super(options?.message, { cause: options?.cause }); + this.res = options?.res; + this.status = status; + } + /** + * Returns the response object associated with the exception. + * If a response object is not provided, a new response is created with the error message and status code. + * @returns The response object. + */ + getResponse() { + if (this.res) { + const newResponse = new Response(this.res.body, { + status: this.status, + headers: this.res.headers + }); + return newResponse; + } + return new Response(this.message, { + status: this.status + }); + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + HTTPException +}); diff --git a/node_modules/hono/dist/cjs/index.js b/node_modules/hono/dist/cjs/index.js new file mode 100644 index 000000000..256c73895 --- /dev/null +++ b/node_modules/hono/dist/cjs/index.js @@ -0,0 +1,28 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var index_exports = {}; +__export(index_exports, { + Hono: () => import_hono.Hono +}); +module.exports = __toCommonJS(index_exports); +var import_hono = require("./hono"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Hono +}); diff --git a/node_modules/hono/dist/cjs/jsx/base.js b/node_modules/hono/dist/cjs/jsx/base.js new file mode 100644 index 000000000..48578a14a --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/base.js @@ -0,0 +1,375 @@ +"use strict"; +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 __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 __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 +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var base_exports = {}; +__export(base_exports, { + Fragment: () => Fragment, + JSXFragmentNode: () => JSXFragmentNode, + JSXNode: () => JSXNode, + booleanAttributes: () => booleanAttributes, + cloneElement: () => cloneElement, + getNameSpaceContext: () => getNameSpaceContext, + isValidElement: () => isValidElement, + jsx: () => jsx, + jsxFn: () => jsxFn, + memo: () => memo, + reactAPICompatVersion: () => reactAPICompatVersion, + shallowEqual: () => shallowEqual +}); +module.exports = __toCommonJS(base_exports); +var import_html = require("../helper/html"); +var import_html2 = require("../utils/html"); +var import_constants = require("./constants"); +var import_context = require("./context"); +var import_common = require("./intrinsic-element/common"); +var intrinsicElementTags = __toESM(require("./intrinsic-element/components"), 1); +var import_utils = require("./utils"); +let nameSpaceContext = void 0; +const getNameSpaceContext = () => nameSpaceContext; +const toSVGAttributeName = (key) => /[A-Z]/.test(key) && // Presentation attributes are findable in style object. "clip-path", "font-size", "stroke-width", etc. +// Or other un-deprecated kebab-case attributes. "overline-position", "paint-order", "strikethrough-position", etc. +key.match( + /^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/ +) ? key.replace(/([A-Z])/g, "-$1").toLowerCase() : key; +const emptyTags = [ + "area", + "base", + "br", + "col", + "embed", + "hr", + "img", + "input", + "keygen", + "link", + "meta", + "param", + "source", + "track", + "wbr" +]; +const booleanAttributes = [ + "allowfullscreen", + "async", + "autofocus", + "autoplay", + "checked", + "controls", + "default", + "defer", + "disabled", + "download", + "formnovalidate", + "hidden", + "inert", + "ismap", + "itemscope", + "loop", + "multiple", + "muted", + "nomodule", + "novalidate", + "open", + "playsinline", + "readonly", + "required", + "reversed", + "selected" +]; +const childrenToStringToBuffer = (children, buffer) => { + for (let i = 0, len = children.length; i < len; i++) { + const child = children[i]; + if (typeof child === "string") { + (0, import_html2.escapeToBuffer)(child, buffer); + } else if (typeof child === "boolean" || child === null || child === void 0) { + continue; + } else if (child instanceof JSXNode) { + child.toStringToBuffer(buffer); + } else if (typeof child === "number" || child.isEscaped) { + ; + buffer[0] += child; + } else if (child instanceof Promise) { + buffer.unshift("", child); + } else { + childrenToStringToBuffer(child, buffer); + } + } +}; +class JSXNode { + tag; + props; + key; + children; + isEscaped = true; + localContexts; + constructor(tag, props, children) { + this.tag = tag; + this.props = props; + this.children = children; + } + get type() { + return this.tag; + } + // Added for compatibility with libraries that rely on React's internal structure + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get ref() { + return this.props.ref || null; + } + toString() { + const buffer = [""]; + this.localContexts?.forEach(([context, value]) => { + context.values.push(value); + }); + try { + this.toStringToBuffer(buffer); + } finally { + this.localContexts?.forEach(([context]) => { + context.values.pop(); + }); + } + return buffer.length === 1 ? "callbacks" in buffer ? (0, import_html2.resolveCallbackSync)((0, import_html.raw)(buffer[0], buffer.callbacks)).toString() : buffer[0] : (0, import_html2.stringBufferToString)(buffer, buffer.callbacks); + } + toStringToBuffer(buffer) { + const tag = this.tag; + const props = this.props; + let { children } = this; + buffer[0] += `<${tag}`; + const normalizeKey = nameSpaceContext && (0, import_context.useContext)(nameSpaceContext) === "svg" ? (key) => toSVGAttributeName((0, import_utils.normalizeIntrinsicElementKey)(key)) : (key) => (0, import_utils.normalizeIntrinsicElementKey)(key); + for (let [key, v] of Object.entries(props)) { + key = normalizeKey(key); + if (key === "children") { + } else if (key === "style" && typeof v === "object") { + let styleStr = ""; + (0, import_utils.styleObjectForEach)(v, (property, value) => { + if (value != null) { + styleStr += `${styleStr ? ";" : ""}${property}:${value}`; + } + }); + buffer[0] += ' style="'; + (0, import_html2.escapeToBuffer)(styleStr, buffer); + buffer[0] += '"'; + } else if (typeof v === "string") { + buffer[0] += ` ${key}="`; + (0, import_html2.escapeToBuffer)(v, buffer); + buffer[0] += '"'; + } else if (v === null || v === void 0) { + } else if (typeof v === "number" || v.isEscaped) { + buffer[0] += ` ${key}="${v}"`; + } else if (typeof v === "boolean" && booleanAttributes.includes(key)) { + if (v) { + buffer[0] += ` ${key}=""`; + } + } else if (key === "dangerouslySetInnerHTML") { + if (children.length > 0) { + throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`."); + } + children = [(0, import_html.raw)(v.__html)]; + } else if (v instanceof Promise) { + buffer[0] += ` ${key}="`; + buffer.unshift('"', v); + } else if (typeof v === "function") { + if (!key.startsWith("on") && key !== "ref") { + throw new Error(`Invalid prop '${key}' of type 'function' supplied to '${tag}'.`); + } + } else { + buffer[0] += ` ${key}="`; + (0, import_html2.escapeToBuffer)(v.toString(), buffer); + buffer[0] += '"'; + } + } + if (emptyTags.includes(tag) && children.length === 0) { + buffer[0] += "/>"; + return; + } + buffer[0] += ">"; + childrenToStringToBuffer(children, buffer); + buffer[0] += ``; + } +} +class JSXFunctionNode extends JSXNode { + toStringToBuffer(buffer) { + const { children } = this; + const props = { ...this.props }; + if (children.length) { + props.children = children.length === 1 ? children[0] : children; + } + const res = this.tag.call(null, props); + if (typeof res === "boolean" || res == null) { + return; + } else if (res instanceof Promise) { + if (import_context.globalContexts.length === 0) { + buffer.unshift("", res); + } else { + const currentContexts = import_context.globalContexts.map((c) => [c, c.values.at(-1)]); + buffer.unshift( + "", + res.then((childRes) => { + if (childRes instanceof JSXNode) { + childRes.localContexts = currentContexts; + } + return childRes; + }) + ); + } + } else if (res instanceof JSXNode) { + res.toStringToBuffer(buffer); + } else if (typeof res === "number" || res.isEscaped) { + buffer[0] += res; + if (res.callbacks) { + buffer.callbacks ||= []; + buffer.callbacks.push(...res.callbacks); + } + } else { + (0, import_html2.escapeToBuffer)(res, buffer); + } + } +} +class JSXFragmentNode extends JSXNode { + toStringToBuffer(buffer) { + childrenToStringToBuffer(this.children, buffer); + } +} +const jsx = (tag, props, ...children) => { + props ??= {}; + if (children.length) { + props.children = children.length === 1 ? children[0] : children; + } + const key = props.key; + delete props["key"]; + const node = jsxFn(tag, props, children); + node.key = key; + return node; +}; +let initDomRenderer = false; +const jsxFn = (tag, props, children) => { + if (!initDomRenderer) { + for (const k in import_common.domRenderers) { + ; + intrinsicElementTags[k][import_constants.DOM_RENDERER] = import_common.domRenderers[k]; + } + initDomRenderer = true; + } + if (typeof tag === "function") { + return new JSXFunctionNode(tag, props, children); + } else if (intrinsicElementTags[tag]) { + return new JSXFunctionNode( + intrinsicElementTags[tag], + props, + children + ); + } else if (tag === "svg" || tag === "head") { + nameSpaceContext ||= (0, import_context.createContext)(""); + return new JSXNode(tag, props, [ + new JSXFunctionNode( + nameSpaceContext, + { + value: tag + }, + children + ) + ]); + } else { + return new JSXNode(tag, props, children); + } +}; +const shallowEqual = (a, b) => { + if (a === b) { + return true; + } + const aKeys = Object.keys(a).sort(); + const bKeys = Object.keys(b).sort(); + if (aKeys.length !== bKeys.length) { + return false; + } + for (let i = 0, len = aKeys.length; i < len; i++) { + if (aKeys[i] === "children" && bKeys[i] === "children" && !a.children?.length && !b.children?.length) { + continue; + } else if (a[aKeys[i]] !== b[aKeys[i]]) { + return false; + } + } + return true; +}; +const memo = (component, propsAreEqual = shallowEqual) => { + let computed = null; + let prevProps = void 0; + const wrapper = ((props) => { + if (prevProps && !propsAreEqual(prevProps, props)) { + computed = null; + } + prevProps = props; + return computed ||= component(props); + }); + wrapper[import_constants.DOM_MEMO] = propsAreEqual; + wrapper[import_constants.DOM_RENDERER] = component; + return wrapper; +}; +const Fragment = ({ + children +}) => { + return new JSXFragmentNode( + "", + { + children + }, + Array.isArray(children) ? children : children ? [children] : [] + ); +}; +const isValidElement = (element) => { + return !!(element && typeof element === "object" && "tag" in element && "props" in element); +}; +const cloneElement = (element, props, ...children) => { + let childrenToClone; + if (children.length > 0) { + childrenToClone = children; + } else { + const c = element.props.children; + childrenToClone = Array.isArray(c) ? c : [c]; + } + return jsx( + element.tag, + { ...element.props, ...props }, + ...childrenToClone + ); +}; +const reactAPICompatVersion = "19.0.0-hono-jsx"; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Fragment, + JSXFragmentNode, + JSXNode, + booleanAttributes, + cloneElement, + getNameSpaceContext, + isValidElement, + jsx, + jsxFn, + memo, + reactAPICompatVersion, + shallowEqual +}); diff --git a/node_modules/hono/dist/cjs/jsx/children.js b/node_modules/hono/dist/cjs/jsx/children.js new file mode 100644 index 000000000..0820d846a --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/children.js @@ -0,0 +1,45 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var children_exports = {}; +__export(children_exports, { + Children: () => Children, + toArray: () => toArray +}); +module.exports = __toCommonJS(children_exports); +const toArray = (children) => Array.isArray(children) ? children : [children]; +const Children = { + map: (children, fn) => toArray(children).map(fn), + forEach: (children, fn) => { + toArray(children).forEach(fn); + }, + count: (children) => toArray(children).length, + only: (_children) => { + const children = toArray(_children); + if (children.length !== 1) { + throw new Error("Children.only() expects only one child"); + } + return children[0]; + }, + toArray +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Children, + toArray +}); diff --git a/node_modules/hono/dist/cjs/jsx/components.js b/node_modules/hono/dist/cjs/jsx/components.js new file mode 100644 index 000000000..9102aa820 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/components.js @@ -0,0 +1,176 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var components_exports = {}; +__export(components_exports, { + ErrorBoundary: () => ErrorBoundary, + childrenToString: () => childrenToString +}); +module.exports = __toCommonJS(components_exports); +var import_html = require("../helper/html"); +var import_html2 = require("../utils/html"); +var import_constants = require("./constants"); +var import_context = require("./context"); +var import_components = require("./dom/components"); +var import_streaming = require("./streaming"); +let errorBoundaryCounter = 0; +const childrenToString = async (children) => { + try { + return children.flat().map((c) => c == null || typeof c === "boolean" ? "" : c.toString()); + } catch (e) { + if (e instanceof Promise) { + await e; + return childrenToString(children); + } else { + throw e; + } + } +}; +const ErrorBoundary = async ({ children, fallback, fallbackRender, onError }) => { + if (!children) { + return (0, import_html.raw)(""); + } + if (!Array.isArray(children)) { + children = [children]; + } + const nonce = (0, import_context.useContext)(import_streaming.StreamingContext)?.scriptNonce; + let fallbackStr; + const fallbackRes = (error) => { + onError?.(error); + return (fallbackStr || fallbackRender?.(error) || "").toString(); + }; + let resArray = []; + try { + resArray = children.map( + (c) => c == null || typeof c === "boolean" ? "" : c.toString() + ); + } catch (e) { + fallbackStr = await fallback?.toString(); + if (e instanceof Promise) { + resArray = [ + e.then(() => childrenToString(children)).catch((e2) => fallbackRes(e2)) + ]; + } else { + resArray = [fallbackRes(e)]; + } + } + if (resArray.some((res) => res instanceof Promise)) { + fallbackStr ||= await fallback?.toString(); + const index = errorBoundaryCounter++; + const replaceRe = RegExp(`(.*?)(.*?)()`); + const caught = false; + const catchCallback = ({ error: error2, buffer }) => { + if (caught) { + return ""; + } + const fallbackResString = fallbackRes(error2); + if (buffer) { + buffer[0] = buffer[0].replace(replaceRe, fallbackResString); + } + return buffer ? "" : ``; + }; + let error; + const promiseAll = Promise.all(resArray).catch((e) => error = e); + return (0, import_html.raw)(``, [ + ({ phase, buffer, context }) => { + if (phase === import_html2.HtmlEscapedCallbackPhase.BeforeStream) { + return; + } + return promiseAll.then(async (htmlArray) => { + if (error) { + throw error; + } + htmlArray = htmlArray.flat(); + const content = htmlArray.join(""); + let html = buffer ? "" : ` +((d,c) => { +c=d.currentScript.previousSibling +d=d.getElementById('E:${index}') +if(!d)return +d.parentElement.insertBefore(c.content,d.nextSibling) +})(document) +`; + if (htmlArray.every((html2) => !html2.callbacks?.length)) { + if (buffer) { + buffer[0] = buffer[0].replace(replaceRe, content); + } + return html; + } + if (buffer) { + buffer[0] = buffer[0].replace( + replaceRe, + (_all, pre, _, post) => `${pre}${content}${post}` + ); + } + const callbacks = htmlArray.map((html2) => html2.callbacks || []).flat(); + if (phase === import_html2.HtmlEscapedCallbackPhase.Stream) { + html = await (0, import_html2.resolveCallback)( + html, + import_html2.HtmlEscapedCallbackPhase.BeforeStream, + true, + context + ); + } + let resolvedCount = 0; + const promises = callbacks.map( + (c) => (...args) => c(...args)?.then((content2) => { + resolvedCount++; + if (buffer) { + if (resolvedCount === callbacks.length) { + buffer[0] = buffer[0].replace(replaceRe, (_all, _pre, content3) => content3); + } + buffer[0] += content2; + return (0, import_html.raw)("", content2.callbacks); + } + return (0, import_html.raw)( + content2 + (resolvedCount !== callbacks.length ? "" : ``), + content2.callbacks + ); + }).catch((error2) => catchCallback({ error: error2, buffer })) + ); + return (0, import_html.raw)(html, promises); + }).catch((error2) => catchCallback({ error: error2, buffer })); + } + ]); + } else { + return (0, import_html.raw)(resArray.join("")); + } +}; +ErrorBoundary[import_constants.DOM_RENDERER] = import_components.ErrorBoundary; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + ErrorBoundary, + childrenToString +}); diff --git a/node_modules/hono/dist/cjs/jsx/constants.js b/node_modules/hono/dist/cjs/jsx/constants.js new file mode 100644 index 000000000..35e4eaefd --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/constants.js @@ -0,0 +1,43 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var constants_exports = {}; +__export(constants_exports, { + DOM_ERROR_HANDLER: () => DOM_ERROR_HANDLER, + DOM_INTERNAL_TAG: () => DOM_INTERNAL_TAG, + DOM_MEMO: () => DOM_MEMO, + DOM_RENDERER: () => DOM_RENDERER, + DOM_STASH: () => DOM_STASH, + PERMALINK: () => PERMALINK +}); +module.exports = __toCommonJS(constants_exports); +const DOM_RENDERER = /* @__PURE__ */ Symbol("RENDERER"); +const DOM_ERROR_HANDLER = /* @__PURE__ */ Symbol("ERROR_HANDLER"); +const DOM_STASH = /* @__PURE__ */ Symbol("STASH"); +const DOM_INTERNAL_TAG = /* @__PURE__ */ Symbol("INTERNAL"); +const DOM_MEMO = /* @__PURE__ */ Symbol("MEMO"); +const PERMALINK = /* @__PURE__ */ Symbol("PERMALINK"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + DOM_ERROR_HANDLER, + DOM_INTERNAL_TAG, + DOM_MEMO, + DOM_RENDERER, + DOM_STASH, + PERMALINK +}); diff --git a/node_modules/hono/dist/cjs/jsx/context.js b/node_modules/hono/dist/cjs/jsx/context.js new file mode 100644 index 000000000..5204e4d0c --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/context.js @@ -0,0 +1,61 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var context_exports = {}; +__export(context_exports, { + createContext: () => createContext, + globalContexts: () => globalContexts, + useContext: () => useContext +}); +module.exports = __toCommonJS(context_exports); +var import_html = require("../helper/html"); +var import_base = require("./base"); +var import_constants = require("./constants"); +var import_context = require("./dom/context"); +const globalContexts = []; +const createContext = (defaultValue) => { + const values = [defaultValue]; + const context = ((props) => { + values.push(props.value); + let string; + try { + string = props.children ? (Array.isArray(props.children) ? new import_base.JSXFragmentNode("", {}, props.children) : props.children).toString() : ""; + } finally { + values.pop(); + } + if (string instanceof Promise) { + return string.then((resString) => (0, import_html.raw)(resString, resString.callbacks)); + } else { + return (0, import_html.raw)(string); + } + }); + context.values = values; + context.Provider = context; + context[import_constants.DOM_RENDERER] = (0, import_context.createContextProviderFunction)(values); + globalContexts.push(context); + return context; +}; +const useContext = (context) => { + return context.values.at(-1); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + createContext, + globalContexts, + useContext +}); diff --git a/node_modules/hono/dist/cjs/jsx/dom/client.js b/node_modules/hono/dist/cjs/jsx/dom/client.js new file mode 100644 index 000000000..d48651dd0 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/dom/client.js @@ -0,0 +1,77 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var client_exports = {}; +__export(client_exports, { + createRoot: () => createRoot, + default: () => client_default, + hydrateRoot: () => hydrateRoot +}); +module.exports = __toCommonJS(client_exports); +var import_hooks = require("../hooks"); +var import_render = require("./render"); +const createRoot = (element, options = {}) => { + let setJsxNode = ( + // unmounted + void 0 + ); + if (Object.keys(options).length > 0) { + console.warn("createRoot options are not supported yet"); + } + return { + render(jsxNode) { + if (setJsxNode === null) { + throw new Error("Cannot update an unmounted root"); + } + if (setJsxNode) { + setJsxNode(jsxNode); + } else { + (0, import_render.renderNode)( + (0, import_render.buildNode)({ + tag: () => { + const [_jsxNode, _setJsxNode] = (0, import_hooks.useState)(jsxNode); + setJsxNode = _setJsxNode; + return _jsxNode; + }, + props: {} + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }), + element + ); + } + }, + unmount() { + setJsxNode?.(null); + setJsxNode = null; + } + }; +}; +const hydrateRoot = (element, reactNode, options = {}) => { + const root = createRoot(element, options); + root.render(reactNode); + return root; +}; +var client_default = { + createRoot, + hydrateRoot +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + createRoot, + hydrateRoot +}); diff --git a/node_modules/hono/dist/cjs/jsx/dom/components.js b/node_modules/hono/dist/cjs/jsx/dom/components.js new file mode 100644 index 000000000..e5afb7fad --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/dom/components.js @@ -0,0 +1,56 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var components_exports = {}; +__export(components_exports, { + ErrorBoundary: () => ErrorBoundary, + Suspense: () => Suspense +}); +module.exports = __toCommonJS(components_exports); +var import_constants = require("../constants"); +var import_jsx_runtime = require("./jsx-runtime"); +const ErrorBoundary = (({ children, fallback, fallbackRender, onError }) => { + const res = (0, import_jsx_runtime.Fragment)({ children }); + res[import_constants.DOM_ERROR_HANDLER] = (err) => { + if (err instanceof Promise) { + throw err; + } + onError?.(err); + return fallbackRender?.(err) || fallback; + }; + return res; +}); +const Suspense = (({ + children, + fallback +}) => { + const res = (0, import_jsx_runtime.Fragment)({ children }); + res[import_constants.DOM_ERROR_HANDLER] = (err, retry) => { + if (!(err instanceof Promise)) { + throw err; + } + err.finally(retry); + return fallback; + }; + return res; +}); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + ErrorBoundary, + Suspense +}); diff --git a/node_modules/hono/dist/cjs/jsx/dom/context.js b/node_modules/hono/dist/cjs/jsx/dom/context.js new file mode 100644 index 000000000..547f03366 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/dom/context.js @@ -0,0 +1,72 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var context_exports = {}; +__export(context_exports, { + createContext: () => createContext, + createContextProviderFunction: () => createContextProviderFunction +}); +module.exports = __toCommonJS(context_exports); +var import_constants = require("../constants"); +var import_context = require("../context"); +var import_utils = require("./utils"); +const createContextProviderFunction = (values) => ({ value, children }) => { + if (!children) { + return void 0; + } + const props = { + children: [ + { + tag: (0, import_utils.setInternalTagFlag)(() => { + values.push(value); + }), + props: {} + } + ] + }; + if (Array.isArray(children)) { + props.children.push(...children.flat()); + } else { + props.children.push(children); + } + props.children.push({ + tag: (0, import_utils.setInternalTagFlag)(() => { + values.pop(); + }), + props: {} + }); + const res = { tag: "", props, type: "" }; + res[import_constants.DOM_ERROR_HANDLER] = (err) => { + values.pop(); + throw err; + }; + return res; +}; +const createContext = (defaultValue) => { + const values = [defaultValue]; + const context = createContextProviderFunction(values); + context.values = values; + context.Provider = context; + import_context.globalContexts.push(context); + return context; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + createContext, + createContextProviderFunction +}); diff --git a/node_modules/hono/dist/cjs/jsx/dom/css.js b/node_modules/hono/dist/cjs/jsx/dom/css.js new file mode 100644 index 000000000..f0042915c --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/dom/css.js @@ -0,0 +1,162 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var css_exports = {}; +__export(css_exports, { + Style: () => Style, + createCssContext: () => createCssContext, + createCssJsxDomObjects: () => createCssJsxDomObjects, + css: () => css, + cx: () => cx, + keyframes: () => keyframes, + rawCssString: () => import_common2.rawCssString, + viewTransition: () => viewTransition +}); +module.exports = __toCommonJS(css_exports); +var import_common = require("../../helper/css/common"); +var import_common2 = require("../../helper/css/common"); +const splitRule = (rule) => { + const result = []; + let startPos = 0; + let depth = 0; + for (let i = 0, len = rule.length; i < len; i++) { + const char = rule[i]; + if (char === "'" || char === '"') { + const quote = char; + i++; + for (; i < len; i++) { + if (rule[i] === "\\") { + i++; + continue; + } + if (rule[i] === quote) { + break; + } + } + continue; + } + if (char === "{") { + depth++; + continue; + } + if (char === "}") { + depth--; + if (depth === 0) { + result.push(rule.slice(startPos, i + 1)); + startPos = i + 1; + } + continue; + } + } + return result; +}; +const createCssJsxDomObjects = ({ id }) => { + let styleSheet = void 0; + const findStyleSheet = () => { + if (!styleSheet) { + styleSheet = document.querySelector(`style#${id}`)?.sheet; + if (styleSheet) { + ; + styleSheet.addedStyles = /* @__PURE__ */ new Set(); + } + } + return styleSheet ? [styleSheet, styleSheet.addedStyles] : []; + }; + const insertRule = (className, styleString) => { + const [sheet, addedStyles] = findStyleSheet(); + if (!sheet || !addedStyles) { + Promise.resolve().then(() => { + if (!findStyleSheet()[0]) { + throw new Error("style sheet not found"); + } + insertRule(className, styleString); + }); + return; + } + if (!addedStyles.has(className)) { + addedStyles.add(className); + (className.startsWith(import_common.PSEUDO_GLOBAL_SELECTOR) ? splitRule(styleString) : [`${className[0] === "@" ? "" : "."}${className}{${styleString}}`]).forEach((rule) => { + sheet.insertRule(rule, sheet.cssRules.length); + }); + } + }; + const cssObject = { + toString() { + const selector = this[import_common.SELECTOR]; + insertRule(selector, this[import_common.STYLE_STRING]); + this[import_common.SELECTORS].forEach(({ [import_common.CLASS_NAME]: className, [import_common.STYLE_STRING]: styleString }) => { + insertRule(className, styleString); + }); + return this[import_common.CLASS_NAME]; + } + }; + const Style2 = ({ children, nonce }) => ({ + tag: "style", + props: { + id, + nonce, + children: children && (Array.isArray(children) ? children : [children]).map( + (c) => c[import_common.STYLE_STRING] + ) + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }); + return [cssObject, Style2]; +}; +const createCssContext = ({ id }) => { + const [cssObject, Style2] = createCssJsxDomObjects({ id }); + const newCssClassNameObject = (cssClassName) => { + cssClassName.toString = cssObject.toString; + return cssClassName; + }; + const css2 = (strings, ...values) => { + return newCssClassNameObject((0, import_common.cssCommon)(strings, values)); + }; + const cx2 = (...args) => { + args = (0, import_common.cxCommon)(args); + return css2(Array(args.length).fill(""), ...args); + }; + const keyframes2 = import_common.keyframesCommon; + const viewTransition2 = ((strings, ...values) => { + return newCssClassNameObject((0, import_common.viewTransitionCommon)(strings, values)); + }); + return { + css: css2, + cx: cx2, + keyframes: keyframes2, + viewTransition: viewTransition2, + Style: Style2 + }; +}; +const defaultContext = createCssContext({ id: import_common.DEFAULT_STYLE_ID }); +const css = defaultContext.css; +const cx = defaultContext.cx; +const keyframes = defaultContext.keyframes; +const viewTransition = defaultContext.viewTransition; +const Style = defaultContext.Style; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Style, + createCssContext, + createCssJsxDomObjects, + css, + cx, + keyframes, + rawCssString, + viewTransition +}); diff --git a/node_modules/hono/dist/cjs/jsx/dom/hooks/index.js b/node_modules/hono/dist/cjs/jsx/dom/hooks/index.js new file mode 100644 index 000000000..1ce3b779b --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/dom/hooks/index.js @@ -0,0 +1,75 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var hooks_exports = {}; +__export(hooks_exports, { + FormContext: () => FormContext, + registerAction: () => registerAction, + useActionState: () => useActionState, + useFormStatus: () => useFormStatus, + useOptimistic: () => useOptimistic +}); +module.exports = __toCommonJS(hooks_exports); +var import_constants = require("../../constants"); +var import_context = require("../../context"); +var import_hooks = require("../../hooks"); +var import_context2 = require("../context"); +const FormContext = (0, import_context2.createContext)({ + pending: false, + data: null, + method: null, + action: null +}); +const actions = /* @__PURE__ */ new Set(); +const registerAction = (action) => { + actions.add(action); + action.finally(() => actions.delete(action)); +}; +const useFormStatus = () => { + return (0, import_context.useContext)(FormContext); +}; +const useOptimistic = (state, updateState) => { + const [optimisticState, setOptimisticState] = (0, import_hooks.useState)(state); + if (actions.size > 0) { + Promise.all(actions).finally(() => { + setOptimisticState(state); + }); + } else { + setOptimisticState(state); + } + const cb = (0, import_hooks.useCallback)((newData) => { + setOptimisticState((currentState) => updateState(currentState, newData)); + }, []); + return [optimisticState, cb]; +}; +const useActionState = (fn, initialState, permalink) => { + const [state, setState] = (0, import_hooks.useState)(initialState); + const actionState = async (data) => { + setState(await fn(state, data)); + }; + actionState[import_constants.PERMALINK] = permalink; + return [state, actionState]; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + FormContext, + registerAction, + useActionState, + useFormStatus, + useOptimistic +}); diff --git a/node_modules/hono/dist/cjs/jsx/dom/index.js b/node_modules/hono/dist/cjs/jsx/dom/index.js new file mode 100644 index 000000000..d01dd10d1 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/dom/index.js @@ -0,0 +1,182 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var dom_exports = {}; +__export(dom_exports, { + Children: () => import_children.Children, + ErrorBoundary: () => import_components.ErrorBoundary, + Fragment: () => import_jsx_runtime.Fragment, + StrictMode: () => import_jsx_runtime.Fragment, + Suspense: () => import_components.Suspense, + cloneElement: () => cloneElement, + createContext: () => import_context2.createContext, + createElement: () => createElement, + createPortal: () => import_render.createPortal, + createRef: () => import_hooks.createRef, + default: () => dom_default, + flushSync: () => import_render.flushSync, + forwardRef: () => import_hooks.forwardRef, + isValidElement: () => import_base.isValidElement, + jsx: () => createElement, + memo: () => memo, + render: () => import_render2.render, + startTransition: () => import_hooks.startTransition, + startViewTransition: () => import_hooks.startViewTransition, + use: () => import_hooks.use, + useActionState: () => import_hooks2.useActionState, + useCallback: () => import_hooks.useCallback, + useContext: () => import_context.useContext, + useDebugValue: () => import_hooks.useDebugValue, + useDeferredValue: () => import_hooks.useDeferredValue, + useEffect: () => import_hooks.useEffect, + useFormStatus: () => import_hooks2.useFormStatus, + useId: () => import_hooks.useId, + useImperativeHandle: () => import_hooks.useImperativeHandle, + useInsertionEffect: () => import_hooks.useInsertionEffect, + useLayoutEffect: () => import_hooks.useLayoutEffect, + useMemo: () => import_hooks.useMemo, + useOptimistic: () => import_hooks2.useOptimistic, + useReducer: () => import_hooks.useReducer, + useRef: () => import_hooks.useRef, + useState: () => import_hooks.useState, + useSyncExternalStore: () => import_hooks.useSyncExternalStore, + useTransition: () => import_hooks.useTransition, + useViewTransition: () => import_hooks.useViewTransition, + version: () => import_base.reactAPICompatVersion +}); +module.exports = __toCommonJS(dom_exports); +var import_base = require("../base"); +var import_children = require("../children"); +var import_constants = require("../constants"); +var import_context = require("../context"); +var import_hooks = require("../hooks"); +var import_components = require("./components"); +var import_context2 = require("./context"); +var import_hooks2 = require("./hooks"); +var import_jsx_runtime = require("./jsx-runtime"); +var import_render = require("./render"); +var import_render2 = require("./render"); +const createElement = (tag, props, ...children) => { + const jsxProps = props ? { ...props } : {}; + if (children.length) { + jsxProps.children = children.length === 1 ? children[0] : children; + } + let key = void 0; + if ("key" in jsxProps) { + key = jsxProps.key; + delete jsxProps.key; + } + return (0, import_jsx_runtime.jsx)(tag, jsxProps, key); +}; +const cloneElement = (element, props, ...children) => { + return (0, import_jsx_runtime.jsx)( + element.tag, + { + ...element.props, + ...props, + children: children.length ? children : element.props.children + }, + element.key + ); +}; +const memo = (component, propsAreEqual = import_base.shallowEqual) => { + const wrapper = ((props) => component(props)); + wrapper[import_constants.DOM_MEMO] = propsAreEqual; + return wrapper; +}; +var dom_default = { + version: import_base.reactAPICompatVersion, + useState: import_hooks.useState, + useEffect: import_hooks.useEffect, + useRef: import_hooks.useRef, + useCallback: import_hooks.useCallback, + use: import_hooks.use, + startTransition: import_hooks.startTransition, + useTransition: import_hooks.useTransition, + useDeferredValue: import_hooks.useDeferredValue, + startViewTransition: import_hooks.startViewTransition, + useViewTransition: import_hooks.useViewTransition, + useMemo: import_hooks.useMemo, + useLayoutEffect: import_hooks.useLayoutEffect, + useInsertionEffect: import_hooks.useInsertionEffect, + useReducer: import_hooks.useReducer, + useId: import_hooks.useId, + useDebugValue: import_hooks.useDebugValue, + createRef: import_hooks.createRef, + forwardRef: import_hooks.forwardRef, + useImperativeHandle: import_hooks.useImperativeHandle, + useSyncExternalStore: import_hooks.useSyncExternalStore, + useFormStatus: import_hooks2.useFormStatus, + useActionState: import_hooks2.useActionState, + useOptimistic: import_hooks2.useOptimistic, + Suspense: import_components.Suspense, + ErrorBoundary: import_components.ErrorBoundary, + createContext: import_context2.createContext, + useContext: import_context.useContext, + memo, + isValidElement: import_base.isValidElement, + createElement, + cloneElement, + Children: import_children.Children, + Fragment: import_jsx_runtime.Fragment, + StrictMode: import_jsx_runtime.Fragment, + flushSync: import_render.flushSync, + createPortal: import_render.createPortal +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Children, + ErrorBoundary, + Fragment, + StrictMode, + Suspense, + cloneElement, + createContext, + createElement, + createPortal, + createRef, + flushSync, + forwardRef, + isValidElement, + jsx, + memo, + render, + startTransition, + startViewTransition, + use, + useActionState, + useCallback, + useContext, + useDebugValue, + useDeferredValue, + useEffect, + useFormStatus, + useId, + useImperativeHandle, + useInsertionEffect, + useLayoutEffect, + useMemo, + useOptimistic, + useReducer, + useRef, + useState, + useSyncExternalStore, + useTransition, + useViewTransition, + version +}); diff --git a/node_modules/hono/dist/cjs/jsx/dom/intrinsic-element/components.js b/node_modules/hono/dist/cjs/jsx/dom/intrinsic-element/components.js new file mode 100644 index 000000000..d35539551 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/dom/intrinsic-element/components.js @@ -0,0 +1,369 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var components_exports = {}; +__export(components_exports, { + button: () => button, + clearCache: () => clearCache, + composeRef: () => composeRef, + form: () => form, + input: () => input, + link: () => link, + meta: () => meta, + script: () => script, + style: () => style, + title: () => title +}); +module.exports = __toCommonJS(components_exports); +var import_context = require("../../context"); +var import_hooks = require("../../hooks"); +var import_common = require("../../intrinsic-element/common"); +var import_hooks2 = require("../hooks"); +var import_render = require("../render"); +const clearCache = () => { + blockingPromiseMap = /* @__PURE__ */ Object.create(null); + createdElements = /* @__PURE__ */ Object.create(null); +}; +const composeRef = (ref, cb) => { + return (0, import_hooks.useMemo)( + () => (e) => { + let refCleanup; + if (ref) { + if (typeof ref === "function") { + refCleanup = ref(e) || (() => { + ref(null); + }); + } else if (ref && "current" in ref) { + ref.current = e; + refCleanup = () => { + ref.current = null; + }; + } + } + const cbCleanup = cb(e); + return () => { + cbCleanup?.(); + refCleanup?.(); + }; + }, + [ref] + ); +}; +let blockingPromiseMap = /* @__PURE__ */ Object.create(null); +let createdElements = /* @__PURE__ */ Object.create(null); +const documentMetadataTag = (tag, props, preserveNodeType, supportSort, supportBlocking) => { + if (props?.itemProp) { + return { + tag, + props, + type: tag, + ref: props.ref + }; + } + const head = document.head; + let { onLoad, onError, precedence, blocking, ...restProps } = props; + let element = null; + let created = false; + const deDupeKeys = import_common.deDupeKeyMap[tag]; + let existingElements = void 0; + if (deDupeKeys.length > 0) { + const tags = head.querySelectorAll(tag); + LOOP: for (const e of tags) { + for (const key of import_common.deDupeKeyMap[tag]) { + if (e.getAttribute(key) === props[key]) { + element = e; + break LOOP; + } + } + } + if (!element) { + const cacheKey = deDupeKeys.reduce( + (acc, key) => props[key] === void 0 ? acc : `${acc}-${key}-${props[key]}`, + tag + ); + created = !createdElements[cacheKey]; + element = createdElements[cacheKey] ||= (() => { + const e = document.createElement(tag); + for (const key of deDupeKeys) { + if (props[key] !== void 0) { + e.setAttribute(key, props[key]); + } + if (props.rel) { + e.setAttribute("rel", props.rel); + } + } + return e; + })(); + } + } else { + existingElements = head.querySelectorAll(tag); + } + precedence = supportSort ? precedence ?? "" : void 0; + if (supportSort) { + restProps[import_common.dataPrecedenceAttr] = precedence; + } + const insert = (0, import_hooks.useCallback)( + (e) => { + if (deDupeKeys.length > 0) { + let found = false; + for (const existingElement of head.querySelectorAll(tag)) { + if (found && existingElement.getAttribute(import_common.dataPrecedenceAttr) !== precedence) { + head.insertBefore(e, existingElement); + return; + } + if (existingElement.getAttribute(import_common.dataPrecedenceAttr) === precedence) { + found = true; + } + } + head.appendChild(e); + } else if (existingElements) { + let found = false; + for (const existingElement of existingElements) { + if (existingElement === e) { + found = true; + break; + } + } + if (!found) { + head.insertBefore( + e, + head.contains(existingElements[0]) ? existingElements[0] : head.querySelector(tag) + ); + } + existingElements = void 0; + } + }, + [precedence] + ); + const ref = composeRef(props.ref, (e) => { + const key = deDupeKeys[0]; + if (preserveNodeType === 2) { + e.innerHTML = ""; + } + if (created || existingElements) { + insert(e); + } + if (!onError && !onLoad) { + return; + } + let promise = blockingPromiseMap[e.getAttribute(key)] ||= new Promise( + (resolve, reject) => { + e.addEventListener("load", resolve); + e.addEventListener("error", reject); + } + ); + if (onLoad) { + promise = promise.then(onLoad); + } + if (onError) { + promise = promise.catch(onError); + } + promise.catch(() => { + }); + }); + if (supportBlocking && blocking === "render") { + const key = import_common.deDupeKeyMap[tag][0]; + if (props[key]) { + const value = props[key]; + const promise = blockingPromiseMap[value] ||= new Promise((resolve, reject) => { + insert(element); + element.addEventListener("load", resolve); + element.addEventListener("error", reject); + }); + (0, import_hooks.use)(promise); + } + } + const jsxNode = { + tag, + type: tag, + props: { + ...restProps, + ref + }, + ref + }; + jsxNode.p = preserveNodeType; + if (element) { + jsxNode.e = element; + } + return (0, import_render.createPortal)( + jsxNode, + head + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ); +}; +const title = (props) => { + const nameSpaceContext = (0, import_render.getNameSpaceContext)(); + const ns = nameSpaceContext && (0, import_context.useContext)(nameSpaceContext); + if (ns?.endsWith("svg")) { + return { + tag: "title", + props, + type: "title", + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ref: props.ref + }; + } + return documentMetadataTag("title", props, void 0, false, false); +}; +const script = (props) => { + if (!props || ["src", "async"].some((k) => !props[k])) { + return { + tag: "script", + props, + type: "script", + ref: props.ref + }; + } + return documentMetadataTag("script", props, 1, false, true); +}; +const style = (props) => { + if (!props || !["href", "precedence"].every((k) => k in props)) { + return { + tag: "style", + props, + type: "style", + ref: props.ref + }; + } + props["data-href"] = props.href; + delete props.href; + return documentMetadataTag("style", props, 2, true, true); +}; +const link = (props) => { + if (!props || ["onLoad", "onError"].some((k) => k in props) || props.rel === "stylesheet" && (!("precedence" in props) || "disabled" in props)) { + return { + tag: "link", + props, + type: "link", + ref: props.ref + }; + } + return documentMetadataTag("link", props, 1, "precedence" in props, true); +}; +const meta = (props) => { + return documentMetadataTag("meta", props, void 0, false, false); +}; +const customEventFormAction = /* @__PURE__ */ Symbol(); +const form = (props) => { + const { action, ...restProps } = props; + if (typeof action !== "function") { + ; + restProps.action = action; + } + const [state, setState] = (0, import_hooks.useState)([null, false]); + const onSubmit = (0, import_hooks.useCallback)( + async (ev) => { + const currentAction = ev.isTrusted ? action : ev.detail[customEventFormAction]; + if (typeof currentAction !== "function") { + return; + } + ev.preventDefault(); + const formData = new FormData(ev.target); + setState([formData, true]); + const actionRes = currentAction(formData); + if (actionRes instanceof Promise) { + (0, import_hooks2.registerAction)(actionRes); + await actionRes; + } + setState([null, true]); + }, + [] + ); + const ref = composeRef(props.ref, (el) => { + el.addEventListener("submit", onSubmit); + return () => { + el.removeEventListener("submit", onSubmit); + }; + }); + const [data, isDirty] = state; + state[1] = false; + return { + tag: import_hooks2.FormContext, + props: { + value: { + pending: data !== null, + data, + method: data ? "post" : null, + action: data ? action : null + }, + children: { + tag: "form", + props: { + ...restProps, + ref + }, + type: "form", + ref + } + }, + f: isDirty + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; +}; +const formActionableElement = (tag, { + formAction, + ...props +}) => { + if (typeof formAction === "function") { + const onClick = (0, import_hooks.useCallback)((ev) => { + ev.preventDefault(); + ev.currentTarget.form.dispatchEvent( + new CustomEvent("submit", { detail: { [customEventFormAction]: formAction } }) + ); + }, []); + props.ref = composeRef(props.ref, (el) => { + el.addEventListener("click", onClick); + return () => { + el.removeEventListener("click", onClick); + }; + }); + } + return { + tag, + props, + type: tag, + ref: props.ref + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; +}; +const input = (props) => formActionableElement("input", props); +const button = (props) => formActionableElement("button", props); +Object.assign(import_common.domRenderers, { + title, + script, + style, + link, + meta, + form, + input, + button +}); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + button, + clearCache, + composeRef, + form, + input, + link, + meta, + script, + style, + title +}); diff --git a/node_modules/hono/dist/cjs/jsx/dom/jsx-dev-runtime.js b/node_modules/hono/dist/cjs/jsx/dom/jsx-dev-runtime.js new file mode 100644 index 000000000..24faf6ccc --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/dom/jsx-dev-runtime.js @@ -0,0 +1,53 @@ +"use strict"; +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 __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 __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 +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jsx_dev_runtime_exports = {}; +__export(jsx_dev_runtime_exports, { + Fragment: () => Fragment, + jsxDEV: () => jsxDEV +}); +module.exports = __toCommonJS(jsx_dev_runtime_exports); +var intrinsicElementTags = __toESM(require("./intrinsic-element/components"), 1); +const jsxDEV = (tag, props, key) => { + if (typeof tag === "string" && intrinsicElementTags[tag]) { + tag = intrinsicElementTags[tag]; + } + return { + tag, + type: tag, + props, + key, + ref: props.ref + }; +}; +const Fragment = (props) => jsxDEV("", props, void 0); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Fragment, + jsxDEV +}); diff --git a/node_modules/hono/dist/cjs/jsx/dom/jsx-runtime.js b/node_modules/hono/dist/cjs/jsx/dom/jsx-runtime.js new file mode 100644 index 000000000..be6fe82dc --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/dom/jsx-runtime.js @@ -0,0 +1,33 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jsx_runtime_exports = {}; +__export(jsx_runtime_exports, { + Fragment: () => import_jsx_dev_runtime.Fragment, + jsx: () => import_jsx_dev_runtime.jsxDEV, + jsxs: () => import_jsx_dev_runtime2.jsxDEV +}); +module.exports = __toCommonJS(jsx_runtime_exports); +var import_jsx_dev_runtime = require("./jsx-dev-runtime"); +var import_jsx_dev_runtime2 = require("./jsx-dev-runtime"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Fragment, + jsx, + jsxs +}); diff --git a/node_modules/hono/dist/cjs/jsx/dom/render.js b/node_modules/hono/dist/cjs/jsx/dom/render.js new file mode 100644 index 000000000..45291c4e5 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/dom/render.js @@ -0,0 +1,622 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var render_exports = {}; +__export(render_exports, { + build: () => build, + buildDataStack: () => buildDataStack, + buildNode: () => buildNode, + createPortal: () => createPortal, + flushSync: () => flushSync, + getNameSpaceContext: () => getNameSpaceContext, + render: () => render, + renderNode: () => renderNode, + update: () => update +}); +module.exports = __toCommonJS(render_exports); +var import_children = require("../children"); +var import_constants = require("../constants"); +var import_context = require("../context"); +var import_hooks = require("../hooks"); +var import_utils = require("../utils"); +var import_context2 = require("./context"); +const HONO_PORTAL_ELEMENT = "_hp"; +const eventAliasMap = { + Change: "Input", + DoubleClick: "DblClick" +}; +const nameSpaceMap = { + svg: "2000/svg", + math: "1998/Math/MathML" +}; +const buildDataStack = []; +const refCleanupMap = /* @__PURE__ */ new WeakMap(); +let nameSpaceContext = void 0; +const getNameSpaceContext = () => nameSpaceContext; +const isNodeString = (node) => "t" in node; +const eventCache = { + // pre-define events that are used very frequently + onClick: ["click", false] +}; +const getEventSpec = (key) => { + if (!key.startsWith("on")) { + return void 0; + } + if (eventCache[key]) { + return eventCache[key]; + } + const match = key.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/); + if (match) { + const [, eventName, capture] = match; + return eventCache[key] = [(eventAliasMap[eventName] || eventName).toLowerCase(), !!capture]; + } + return void 0; +}; +const toAttributeName = (element, key) => nameSpaceContext && element instanceof SVGElement && /[A-Z]/.test(key) && (key in element.style || // Presentation attributes are findable in style object. "clip-path", "font-size", "stroke-width", etc. +key.match(/^(?:o|pai|str|u|ve)/)) ? key.replace(/([A-Z])/g, "-$1").toLowerCase() : key; +const applyProps = (container, attributes, oldAttributes) => { + attributes ||= {}; + for (let key in attributes) { + const value = attributes[key]; + if (key !== "children" && (!oldAttributes || oldAttributes[key] !== value)) { + key = (0, import_utils.normalizeIntrinsicElementKey)(key); + const eventSpec = getEventSpec(key); + if (eventSpec) { + if (oldAttributes?.[key] !== value) { + if (oldAttributes) { + container.removeEventListener(eventSpec[0], oldAttributes[key], eventSpec[1]); + } + if (value != null) { + if (typeof value !== "function") { + throw new Error(`Event handler for "${key}" is not a function`); + } + container.addEventListener(eventSpec[0], value, eventSpec[1]); + } + } + } else if (key === "dangerouslySetInnerHTML" && value) { + container.innerHTML = value.__html; + } else if (key === "ref") { + let cleanup; + if (typeof value === "function") { + cleanup = value(container) || (() => value(null)); + } else if (value && "current" in value) { + value.current = container; + cleanup = () => value.current = null; + } + refCleanupMap.set(container, cleanup); + } else if (key === "style") { + const style = container.style; + if (typeof value === "string") { + style.cssText = value; + } else { + style.cssText = ""; + if (value != null) { + (0, import_utils.styleObjectForEach)(value, style.setProperty.bind(style)); + } + } + } else { + if (key === "value") { + const nodeName = container.nodeName; + if (nodeName === "INPUT" || nodeName === "TEXTAREA" || nodeName === "SELECT") { + ; + container.value = value === null || value === void 0 || value === false ? null : value; + if (nodeName === "TEXTAREA") { + container.textContent = value; + continue; + } else if (nodeName === "SELECT") { + if (container.selectedIndex === -1) { + ; + container.selectedIndex = 0; + } + continue; + } + } + } else if (key === "checked" && container.nodeName === "INPUT" || key === "selected" && container.nodeName === "OPTION") { + ; + container[key] = value; + } + const k = toAttributeName(container, key); + if (value === null || value === void 0 || value === false) { + container.removeAttribute(k); + } else if (value === true) { + container.setAttribute(k, ""); + } else if (typeof value === "string" || typeof value === "number") { + container.setAttribute(k, value); + } else { + container.setAttribute(k, value.toString()); + } + } + } + } + if (oldAttributes) { + for (let key in oldAttributes) { + const value = oldAttributes[key]; + if (key !== "children" && !(key in attributes)) { + key = (0, import_utils.normalizeIntrinsicElementKey)(key); + const eventSpec = getEventSpec(key); + if (eventSpec) { + container.removeEventListener(eventSpec[0], value, eventSpec[1]); + } else if (key === "ref") { + refCleanupMap.get(container)?.(); + } else { + container.removeAttribute(toAttributeName(container, key)); + } + } + } + } +}; +const invokeTag = (context, node) => { + node[import_constants.DOM_STASH][0] = 0; + buildDataStack.push([context, node]); + const func = node.tag[import_constants.DOM_RENDERER] || node.tag; + const props = func.defaultProps ? { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ...func.defaultProps, + ...node.props + } : node.props; + try { + return [func.call(null, props)]; + } finally { + buildDataStack.pop(); + } +}; +const getNextChildren = (node, container, nextChildren, childrenToRemove, callbacks) => { + if (node.vR?.length) { + childrenToRemove.push(...node.vR); + delete node.vR; + } + if (typeof node.tag === "function") { + node[import_constants.DOM_STASH][1][import_hooks.STASH_EFFECT]?.forEach((data) => callbacks.push(data)); + } + node.vC.forEach((child) => { + if (isNodeString(child)) { + nextChildren.push(child); + } else { + if (typeof child.tag === "function" || child.tag === "") { + child.c = container; + const currentNextChildrenIndex = nextChildren.length; + getNextChildren(child, container, nextChildren, childrenToRemove, callbacks); + if (child.s) { + for (let i = currentNextChildrenIndex; i < nextChildren.length; i++) { + nextChildren[i].s = true; + } + child.s = false; + } + } else { + nextChildren.push(child); + if (child.vR?.length) { + childrenToRemove.push(...child.vR); + delete child.vR; + } + } + } + }); +}; +const findInsertBefore = (node) => { + for (; ; node = node.tag === HONO_PORTAL_ELEMENT || !node.vC || !node.pP ? node.nN : node.vC[0]) { + if (!node) { + return null; + } + if (node.tag !== HONO_PORTAL_ELEMENT && node.e) { + return node.e; + } + } +}; +const removeNode = (node) => { + if (!isNodeString(node)) { + node[import_constants.DOM_STASH]?.[1][import_hooks.STASH_EFFECT]?.forEach((data) => data[2]?.()); + refCleanupMap.get(node.e)?.(); + if (node.p === 2) { + node.vC?.forEach((n) => n.p = 2); + } + node.vC?.forEach(removeNode); + } + if (!node.p) { + node.e?.remove(); + delete node.e; + } + if (typeof node.tag === "function") { + updateMap.delete(node); + fallbackUpdateFnArrayMap.delete(node); + delete node[import_constants.DOM_STASH][3]; + node.a = true; + } +}; +const apply = (node, container, isNew) => { + node.c = container; + applyNodeObject(node, container, isNew); +}; +const findChildNodeIndex = (childNodes, child) => { + if (!child) { + return; + } + for (let i = 0, len = childNodes.length; i < len; i++) { + if (childNodes[i] === child) { + return i; + } + } + return; +}; +const cancelBuild = /* @__PURE__ */ Symbol(); +const applyNodeObject = (node, container, isNew) => { + const next = []; + const remove = []; + const callbacks = []; + getNextChildren(node, container, next, remove, callbacks); + remove.forEach(removeNode); + const childNodes = isNew ? void 0 : container.childNodes; + let offset; + let insertBeforeNode = null; + if (isNew) { + offset = -1; + } else if (!childNodes.length) { + offset = 0; + } else { + const offsetByNextNode = findChildNodeIndex(childNodes, findInsertBefore(node.nN)); + if (offsetByNextNode !== void 0) { + insertBeforeNode = childNodes[offsetByNextNode]; + offset = offsetByNextNode; + } else { + offset = findChildNodeIndex(childNodes, next.find((n) => n.tag !== HONO_PORTAL_ELEMENT && n.e)?.e) ?? -1; + } + if (offset === -1) { + isNew = true; + } + } + for (let i = 0, len = next.length; i < len; i++, offset++) { + const child = next[i]; + let el; + if (child.s && child.e) { + el = child.e; + child.s = false; + } else { + const isNewLocal = isNew || !child.e; + if (isNodeString(child)) { + if (child.e && child.d) { + child.e.textContent = child.t; + } + child.d = false; + el = child.e ||= document.createTextNode(child.t); + } else { + el = child.e ||= child.n ? document.createElementNS(child.n, child.tag) : document.createElement(child.tag); + applyProps(el, child.props, child.pP); + applyNodeObject(child, el, isNewLocal); + } + } + if (child.tag === HONO_PORTAL_ELEMENT) { + offset--; + } else if (isNew) { + if (!el.parentNode) { + container.appendChild(el); + } + } else if (childNodes[offset] !== el && childNodes[offset - 1] !== el) { + if (childNodes[offset + 1] === el) { + container.appendChild(childNodes[offset]); + } else { + container.insertBefore(el, insertBeforeNode || childNodes[offset] || null); + } + } + } + if (node.pP) { + delete node.pP; + } + if (callbacks.length) { + const useLayoutEffectCbs = []; + const useEffectCbs = []; + callbacks.forEach(([, useLayoutEffectCb, , useEffectCb, useInsertionEffectCb]) => { + if (useLayoutEffectCb) { + useLayoutEffectCbs.push(useLayoutEffectCb); + } + if (useEffectCb) { + useEffectCbs.push(useEffectCb); + } + useInsertionEffectCb?.(); + }); + useLayoutEffectCbs.forEach((cb) => cb()); + if (useEffectCbs.length) { + requestAnimationFrame(() => { + useEffectCbs.forEach((cb) => cb()); + }); + } + } +}; +const isSameContext = (oldContexts, newContexts) => !!(oldContexts && oldContexts.length === newContexts.length && oldContexts.every((ctx, i) => ctx[1] === newContexts[i][1])); +const fallbackUpdateFnArrayMap = /* @__PURE__ */ new WeakMap(); +const build = (context, node, children) => { + const buildWithPreviousChildren = !children && node.pC; + if (children) { + node.pC ||= node.vC; + } + let foundErrorHandler; + try { + children ||= typeof node.tag == "function" ? invokeTag(context, node) : (0, import_children.toArray)(node.props.children); + if (children[0]?.tag === "" && children[0][import_constants.DOM_ERROR_HANDLER]) { + foundErrorHandler = children[0][import_constants.DOM_ERROR_HANDLER]; + context[5].push([context, foundErrorHandler, node]); + } + const oldVChildren = buildWithPreviousChildren ? [...node.pC] : node.vC ? [...node.vC] : void 0; + const vChildren = []; + let prevNode; + for (let i = 0; i < children.length; i++) { + if (Array.isArray(children[i])) { + children.splice(i, 1, ...children[i].flat()); + } + let child = buildNode(children[i]); + if (child) { + if (typeof child.tag === "function" && // eslint-disable-next-line @typescript-eslint/no-explicit-any + !child.tag[import_constants.DOM_INTERNAL_TAG]) { + if (import_context.globalContexts.length > 0) { + child[import_constants.DOM_STASH][2] = import_context.globalContexts.map((c) => [c, c.values.at(-1)]); + } + if (context[5]?.length) { + child[import_constants.DOM_STASH][3] = context[5].at(-1); + } + } + let oldChild; + if (oldVChildren && oldVChildren.length) { + const i2 = oldVChildren.findIndex( + isNodeString(child) ? (c) => isNodeString(c) : child.key !== void 0 ? (c) => c.key === child.key && c.tag === child.tag : (c) => c.tag === child.tag + ); + if (i2 !== -1) { + oldChild = oldVChildren[i2]; + oldVChildren.splice(i2, 1); + } + } + if (oldChild) { + if (isNodeString(child)) { + if (oldChild.t !== child.t) { + ; + oldChild.t = child.t; + oldChild.d = true; + } + child = oldChild; + } else { + const pP = oldChild.pP = oldChild.props; + oldChild.props = child.props; + oldChild.f ||= child.f || node.f; + if (typeof child.tag === "function") { + const oldContexts = oldChild[import_constants.DOM_STASH][2]; + oldChild[import_constants.DOM_STASH][2] = child[import_constants.DOM_STASH][2] || []; + oldChild[import_constants.DOM_STASH][3] = child[import_constants.DOM_STASH][3]; + if (!oldChild.f && ((oldChild.o || oldChild) === child.o || // The code generated by the react compiler is memoized under this condition. + oldChild.tag[import_constants.DOM_MEMO]?.(pP, oldChild.props)) && // The `memo` function is memoized under this condition. + isSameContext(oldContexts, oldChild[import_constants.DOM_STASH][2])) { + oldChild.s = true; + } + } + child = oldChild; + } + } else if (!isNodeString(child) && nameSpaceContext) { + const ns = (0, import_context.useContext)(nameSpaceContext); + if (ns) { + child.n = ns; + } + } + if (!isNodeString(child) && !child.s) { + build(context, child); + delete child.f; + } + vChildren.push(child); + if (prevNode && !prevNode.s && !child.s) { + for (let p = prevNode; p && !isNodeString(p); p = p.vC?.at(-1)) { + p.nN = child; + } + } + prevNode = child; + } + } + node.vR = buildWithPreviousChildren ? [...node.vC, ...oldVChildren || []] : oldVChildren || []; + node.vC = vChildren; + if (buildWithPreviousChildren) { + delete node.pC; + } + } catch (e) { + node.f = true; + if (e === cancelBuild) { + if (foundErrorHandler) { + return; + } else { + throw e; + } + } + const [errorHandlerContext, errorHandler, errorHandlerNode] = node[import_constants.DOM_STASH]?.[3] || []; + if (errorHandler) { + const fallbackUpdateFn = () => update([0, false, context[2]], errorHandlerNode); + const fallbackUpdateFnArray = fallbackUpdateFnArrayMap.get(errorHandlerNode) || []; + fallbackUpdateFnArray.push(fallbackUpdateFn); + fallbackUpdateFnArrayMap.set(errorHandlerNode, fallbackUpdateFnArray); + const fallback = errorHandler(e, () => { + const fnArray = fallbackUpdateFnArrayMap.get(errorHandlerNode); + if (fnArray) { + const i = fnArray.indexOf(fallbackUpdateFn); + if (i !== -1) { + fnArray.splice(i, 1); + return fallbackUpdateFn(); + } + } + }); + if (fallback) { + if (context[0] === 1) { + context[1] = true; + } else { + build(context, errorHandlerNode, [fallback]); + if ((errorHandler.length === 1 || context !== errorHandlerContext) && errorHandlerNode.c) { + apply(errorHandlerNode, errorHandlerNode.c, false); + return; + } + } + throw cancelBuild; + } + } + throw e; + } finally { + if (foundErrorHandler) { + context[5].pop(); + } + } +}; +const buildNode = (node) => { + if (node === void 0 || node === null || typeof node === "boolean") { + return void 0; + } else if (typeof node === "string" || typeof node === "number") { + return { t: node.toString(), d: true }; + } else { + if ("vR" in node) { + node = { + tag: node.tag, + props: node.props, + key: node.key, + f: node.f, + type: node.tag, + ref: node.props.ref, + o: node.o || node + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; + } + if (typeof node.tag === "function") { + ; + node[import_constants.DOM_STASH] = [0, []]; + } else { + const ns = nameSpaceMap[node.tag]; + if (ns) { + nameSpaceContext ||= (0, import_context2.createContext)(""); + node.props.children = [ + { + tag: nameSpaceContext, + props: { + value: node.n = `http://www.w3.org/${ns}`, + children: node.props.children + } + } + ]; + } + } + return node; + } +}; +const replaceContainer = (node, from, to) => { + if (node.c === from) { + node.c = to; + node.vC.forEach((child) => replaceContainer(child, from, to)); + } +}; +const updateSync = (context, node) => { + node[import_constants.DOM_STASH][2]?.forEach(([c, v]) => { + c.values.push(v); + }); + try { + build(context, node, void 0); + } catch { + return; + } + if (node.a) { + delete node.a; + return; + } + node[import_constants.DOM_STASH][2]?.forEach(([c]) => { + c.values.pop(); + }); + if (context[0] !== 1 || !context[1]) { + apply(node, node.c, false); + } +}; +const updateMap = /* @__PURE__ */ new WeakMap(); +const currentUpdateSets = []; +const update = async (context, node) => { + context[5] ||= []; + const existing = updateMap.get(node); + if (existing) { + existing[0](void 0); + } + let resolve; + const promise = new Promise((r) => resolve = r); + updateMap.set(node, [ + resolve, + () => { + if (context[2]) { + context[2](context, node, (context2) => { + updateSync(context2, node); + }).then(() => resolve(node)); + } else { + updateSync(context, node); + resolve(node); + } + } + ]); + if (currentUpdateSets.length) { + ; + currentUpdateSets.at(-1).add(node); + } else { + await Promise.resolve(); + const latest = updateMap.get(node); + if (latest) { + updateMap.delete(node); + latest[1](); + } + } + return promise; +}; +const renderNode = (node, container) => { + const context = []; + context[5] = []; + context[4] = true; + build(context, node, void 0); + context[4] = false; + const fragment = document.createDocumentFragment(); + apply(node, fragment, true); + replaceContainer(node, fragment, container); + container.replaceChildren(fragment); +}; +const render = (jsxNode, container) => { + renderNode(buildNode({ tag: "", props: { children: jsxNode } }), container); +}; +const flushSync = (callback) => { + const set = /* @__PURE__ */ new Set(); + currentUpdateSets.push(set); + callback(); + set.forEach((node) => { + const latest = updateMap.get(node); + if (latest) { + updateMap.delete(node); + latest[1](); + } + }); + currentUpdateSets.pop(); +}; +const createPortal = (children, container, key) => ({ + tag: HONO_PORTAL_ELEMENT, + props: { + children + }, + key, + e: container, + p: 1 + // eslint-disable-next-line @typescript-eslint/no-explicit-any +}); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + build, + buildDataStack, + buildNode, + createPortal, + flushSync, + getNameSpaceContext, + render, + renderNode, + update +}); diff --git a/node_modules/hono/dist/cjs/jsx/dom/server.js b/node_modules/hono/dist/cjs/jsx/dom/server.js new file mode 100644 index 000000000..58f12ed29 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/dom/server.js @@ -0,0 +1,68 @@ +"use strict"; +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 __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 __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 +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var server_exports = {}; +__export(server_exports, { + default: () => server_default, + renderToReadableStream: () => renderToReadableStream, + renderToString: () => renderToString, + version: () => import__.default +}); +module.exports = __toCommonJS(server_exports); +var import_streaming = require("../streaming"); +var import__ = __toESM(require("./"), 1); +const renderToString = (element, options = {}) => { + if (Object.keys(options).length > 0) { + console.warn("options are not supported yet"); + } + const res = element?.toString() ?? ""; + if (typeof res !== "string") { + throw new Error("Async component is not supported in renderToString"); + } + return res; +}; +const renderToReadableStream = async (element, options = {}) => { + if (Object.keys(options).some((key) => key !== "onError")) { + console.warn("options are not supported yet, except onError"); + } + if (!element || typeof element !== "object") { + element = element?.toString() ?? ""; + } + return (0, import_streaming.renderToReadableStream)(element, options.onError); +}; +var server_default = { + renderToString, + renderToReadableStream, + version: import__.default +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + renderToReadableStream, + renderToString, + version +}); diff --git a/node_modules/hono/dist/cjs/jsx/dom/utils.js b/node_modules/hono/dist/cjs/jsx/dom/utils.js new file mode 100644 index 000000000..47d6fb666 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/dom/utils.js @@ -0,0 +1,33 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var utils_exports = {}; +__export(utils_exports, { + setInternalTagFlag: () => setInternalTagFlag +}); +module.exports = __toCommonJS(utils_exports); +var import_constants = require("../constants"); +const setInternalTagFlag = (fn) => { + ; + fn[import_constants.DOM_INTERNAL_TAG] = true; + return fn; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + setInternalTagFlag +}); diff --git a/node_modules/hono/dist/cjs/jsx/hooks/index.js b/node_modules/hono/dist/cjs/jsx/hooks/index.js new file mode 100644 index 000000000..948bd7598 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/hooks/index.js @@ -0,0 +1,371 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var hooks_exports = {}; +__export(hooks_exports, { + STASH_EFFECT: () => STASH_EFFECT, + createRef: () => createRef, + forwardRef: () => forwardRef, + startTransition: () => startTransition, + startViewTransition: () => startViewTransition, + use: () => use, + useCallback: () => useCallback, + useDebugValue: () => useDebugValue, + useDeferredValue: () => useDeferredValue, + useEffect: () => useEffect, + useId: () => useId, + useImperativeHandle: () => useImperativeHandle, + useInsertionEffect: () => useInsertionEffect, + useLayoutEffect: () => useLayoutEffect, + useMemo: () => useMemo, + useReducer: () => useReducer, + useRef: () => useRef, + useState: () => useState, + useSyncExternalStore: () => useSyncExternalStore, + useTransition: () => useTransition, + useViewTransition: () => useViewTransition +}); +module.exports = __toCommonJS(hooks_exports); +var import_constants = require("../constants"); +var import_render = require("../dom/render"); +const STASH_SATE = 0; +const STASH_EFFECT = 1; +const STASH_CALLBACK = 2; +const STASH_MEMO = 3; +const STASH_REF = 4; +const resolvedPromiseValueMap = /* @__PURE__ */ new WeakMap(); +const isDepsChanged = (prevDeps, deps) => !prevDeps || !deps || prevDeps.length !== deps.length || deps.some((dep, i) => dep !== prevDeps[i]); +let viewTransitionState = void 0; +const documentStartViewTransition = (cb) => { + if (document?.startViewTransition) { + return document.startViewTransition(cb); + } else { + cb(); + return { finished: Promise.resolve() }; + } +}; +let updateHook = void 0; +const viewTransitionHook = (context, node, cb) => { + const state = [true, false]; + let lastVC = node.vC; + return documentStartViewTransition(() => { + if (lastVC === node.vC) { + viewTransitionState = state; + cb(context); + viewTransitionState = void 0; + lastVC = node.vC; + } + }).finished.then(() => { + if (state[1] && lastVC === node.vC) { + state[0] = false; + viewTransitionState = state; + cb(context); + viewTransitionState = void 0; + } + }); +}; +const startViewTransition = (callback) => { + updateHook = viewTransitionHook; + try { + callback(); + } finally { + updateHook = void 0; + } +}; +const useViewTransition = () => { + const buildData = import_render.buildDataStack.at(-1); + if (!buildData) { + return [false, () => { + }]; + } + if (viewTransitionState) { + viewTransitionState[1] = true; + } + return [!!viewTransitionState?.[0], startViewTransition]; +}; +const pendingStack = []; +const runCallback = (type, callback) => { + let resolve; + const promise = new Promise((r) => resolve = r); + pendingStack.push([type, promise]); + try { + const res = callback(); + if (res instanceof Promise) { + res.then(resolve, resolve); + } else { + resolve(); + } + } finally { + pendingStack.pop(); + } +}; +const startTransition = (callback) => { + runCallback(1, callback); +}; +const startTransitionHook = (callback) => { + runCallback(2, callback); +}; +const useTransition = () => { + const buildData = import_render.buildDataStack.at(-1); + if (!buildData) { + return [false, () => { + }]; + } + const [error, setError] = useState(); + const [state, updateState] = useState(); + if (error) { + throw error[0]; + } + const startTransitionLocalHook = useCallback( + (callback) => { + startTransitionHook(() => { + updateState((state2) => !state2); + let res = callback(); + if (res instanceof Promise) { + res = res.catch((e) => { + setError([e]); + }); + } + return res; + }); + }, + [state] + ); + const [context] = buildData; + return [context[0] === 2, startTransitionLocalHook]; +}; +const useDeferredValue = (value, ...rest) => { + const [values, setValues] = useState( + rest.length ? [rest[0], rest[0]] : [value, value] + ); + if (Object.is(values[1], value)) { + return values[1]; + } + pendingStack.push([3, Promise.resolve()]); + updateHook = async (context, _, cb) => { + cb(context); + values[0] = value; + }; + setValues([values[0], value]); + updateHook = void 0; + pendingStack.pop(); + return values[0]; +}; +const useState = (initialState) => { + const resolveInitialState = () => typeof initialState === "function" ? initialState() : initialState; + const buildData = import_render.buildDataStack.at(-1); + if (!buildData) { + return [resolveInitialState(), () => { + }]; + } + const [, node] = buildData; + const stateArray = node[import_constants.DOM_STASH][1][STASH_SATE] ||= []; + const hookIndex = node[import_constants.DOM_STASH][0]++; + return stateArray[hookIndex] ||= [ + resolveInitialState(), + (newState) => { + const localUpdateHook = updateHook; + const stateData = stateArray[hookIndex]; + if (typeof newState === "function") { + newState = newState(stateData[0]); + } + if (!Object.is(newState, stateData[0])) { + stateData[0] = newState; + if (pendingStack.length) { + const [pendingType, pendingPromise] = pendingStack.at(-1); + Promise.all([ + pendingType === 3 ? node : (0, import_render.update)([pendingType, false, localUpdateHook], node), + pendingPromise + ]).then(([node2]) => { + if (!node2 || !(pendingType === 2 || pendingType === 3)) { + return; + } + const lastVC = node2.vC; + const addUpdateTask = () => { + setTimeout(() => { + if (lastVC !== node2.vC) { + return; + } + (0, import_render.update)([pendingType === 3 ? 1 : 0, false, localUpdateHook], node2); + }); + }; + requestAnimationFrame(addUpdateTask); + }); + } else { + (0, import_render.update)([0, false, localUpdateHook], node); + } + } + } + ]; +}; +const useReducer = (reducer, initialArg, init) => { + const handler = useCallback( + (action) => { + setState((state2) => reducer(state2, action)); + }, + [reducer] + ); + const [state, setState] = useState(() => init ? init(initialArg) : initialArg); + return [state, handler]; +}; +const useEffectCommon = (index, effect, deps) => { + const buildData = import_render.buildDataStack.at(-1); + if (!buildData) { + return; + } + const [, node] = buildData; + const effectDepsArray = node[import_constants.DOM_STASH][1][STASH_EFFECT] ||= []; + const hookIndex = node[import_constants.DOM_STASH][0]++; + const [prevDeps, , prevCleanup] = effectDepsArray[hookIndex] ||= []; + if (isDepsChanged(prevDeps, deps)) { + if (prevCleanup) { + prevCleanup(); + } + const runner = () => { + data[index] = void 0; + data[2] = effect(); + }; + const data = [deps, void 0, void 0, void 0, void 0]; + data[index] = runner; + effectDepsArray[hookIndex] = data; + } +}; +const useEffect = (effect, deps) => useEffectCommon(3, effect, deps); +const useLayoutEffect = (effect, deps) => useEffectCommon(1, effect, deps); +const useInsertionEffect = (effect, deps) => useEffectCommon(4, effect, deps); +const useCallback = (callback, deps) => { + const buildData = import_render.buildDataStack.at(-1); + if (!buildData) { + return callback; + } + const [, node] = buildData; + const callbackArray = node[import_constants.DOM_STASH][1][STASH_CALLBACK] ||= []; + const hookIndex = node[import_constants.DOM_STASH][0]++; + const prevDeps = callbackArray[hookIndex]; + if (isDepsChanged(prevDeps?.[1], deps)) { + callbackArray[hookIndex] = [callback, deps]; + } else { + callback = callbackArray[hookIndex][0]; + } + return callback; +}; +const useRef = (initialValue) => { + const buildData = import_render.buildDataStack.at(-1); + if (!buildData) { + return { current: initialValue }; + } + const [, node] = buildData; + const refArray = node[import_constants.DOM_STASH][1][STASH_REF] ||= []; + const hookIndex = node[import_constants.DOM_STASH][0]++; + return refArray[hookIndex] ||= { current: initialValue }; +}; +const use = (promise) => { + const cachedRes = resolvedPromiseValueMap.get(promise); + if (cachedRes) { + if (cachedRes.length === 2) { + throw cachedRes[1]; + } + return cachedRes[0]; + } + promise.then( + (res) => resolvedPromiseValueMap.set(promise, [res]), + (e) => resolvedPromiseValueMap.set(promise, [void 0, e]) + ); + throw promise; +}; +const useMemo = (factory, deps) => { + const buildData = import_render.buildDataStack.at(-1); + if (!buildData) { + return factory(); + } + const [, node] = buildData; + const memoArray = node[import_constants.DOM_STASH][1][STASH_MEMO] ||= []; + const hookIndex = node[import_constants.DOM_STASH][0]++; + const prevDeps = memoArray[hookIndex]; + if (isDepsChanged(prevDeps?.[1], deps)) { + memoArray[hookIndex] = [factory(), deps]; + } + return memoArray[hookIndex][0]; +}; +let idCounter = 0; +const useId = () => useMemo(() => `:r${(idCounter++).toString(32)}:`, []); +const useDebugValue = (_value, _formatter) => { +}; +const createRef = () => { + return { current: null }; +}; +const forwardRef = (Component) => { + return (props) => { + const { ref, ...rest } = props; + return Component(rest, ref); + }; +}; +const useImperativeHandle = (ref, createHandle, deps) => { + useEffect(() => { + ref.current = createHandle(); + return () => { + ref.current = null; + }; + }, deps); +}; +const useSyncExternalStore = (subscribe, getSnapshot, getServerSnapshot) => { + const buildData = import_render.buildDataStack.at(-1); + if (!buildData) { + if (!getServerSnapshot) { + throw new Error("getServerSnapshot is required for server side rendering"); + } + return getServerSnapshot(); + } + const [serverSnapshotIsUsed] = useState(!!(buildData[0][4] && getServerSnapshot)); + const [state, setState] = useState( + () => serverSnapshotIsUsed ? getServerSnapshot() : getSnapshot() + ); + useEffect(() => { + if (serverSnapshotIsUsed) { + setState(getSnapshot()); + } + return subscribe(() => { + setState(getSnapshot()); + }); + }, []); + return state; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + STASH_EFFECT, + createRef, + forwardRef, + startTransition, + startViewTransition, + use, + useCallback, + useDebugValue, + useDeferredValue, + useEffect, + useId, + useImperativeHandle, + useInsertionEffect, + useLayoutEffect, + useMemo, + useReducer, + useRef, + useState, + useSyncExternalStore, + useTransition, + useViewTransition +}); diff --git a/node_modules/hono/dist/cjs/jsx/index.js b/node_modules/hono/dist/cjs/jsx/index.js new file mode 100644 index 000000000..d750bb076 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/index.js @@ -0,0 +1,139 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jsx_exports = {}; +__export(jsx_exports, { + Children: () => import_children.Children, + ErrorBoundary: () => import_components.ErrorBoundary, + Fragment: () => import_base.Fragment, + StrictMode: () => import_base.Fragment, + Suspense: () => import_streaming.Suspense, + cloneElement: () => import_base.cloneElement, + createContext: () => import_context.createContext, + createElement: () => import_base.jsx, + createRef: () => import_hooks2.createRef, + default: () => jsx_default, + forwardRef: () => import_hooks2.forwardRef, + isValidElement: () => import_base.isValidElement, + jsx: () => import_base.jsx, + memo: () => import_base.memo, + startTransition: () => import_hooks2.startTransition, + startViewTransition: () => import_hooks2.startViewTransition, + use: () => import_hooks2.use, + useActionState: () => import_hooks.useActionState, + useCallback: () => import_hooks2.useCallback, + useContext: () => import_context.useContext, + useDebugValue: () => import_hooks2.useDebugValue, + useDeferredValue: () => import_hooks2.useDeferredValue, + useEffect: () => import_hooks2.useEffect, + useId: () => import_hooks2.useId, + useImperativeHandle: () => import_hooks2.useImperativeHandle, + useInsertionEffect: () => import_hooks2.useInsertionEffect, + useLayoutEffect: () => import_hooks2.useLayoutEffect, + useMemo: () => import_hooks2.useMemo, + useOptimistic: () => import_hooks.useOptimistic, + useReducer: () => import_hooks2.useReducer, + useRef: () => import_hooks2.useRef, + useState: () => import_hooks2.useState, + useSyncExternalStore: () => import_hooks2.useSyncExternalStore, + useTransition: () => import_hooks2.useTransition, + useViewTransition: () => import_hooks2.useViewTransition, + version: () => import_base.reactAPICompatVersion +}); +module.exports = __toCommonJS(jsx_exports); +var import_base = require("./base"); +var import_children = require("./children"); +var import_components = require("./components"); +var import_context = require("./context"); +var import_hooks = require("./dom/hooks"); +var import_hooks2 = require("./hooks"); +var import_streaming = require("./streaming"); +var jsx_default = { + version: import_base.reactAPICompatVersion, + memo: import_base.memo, + Fragment: import_base.Fragment, + StrictMode: import_base.Fragment, + isValidElement: import_base.isValidElement, + createElement: import_base.jsx, + cloneElement: import_base.cloneElement, + ErrorBoundary: import_components.ErrorBoundary, + createContext: import_context.createContext, + useContext: import_context.useContext, + useState: import_hooks2.useState, + useEffect: import_hooks2.useEffect, + useRef: import_hooks2.useRef, + useCallback: import_hooks2.useCallback, + useReducer: import_hooks2.useReducer, + useId: import_hooks2.useId, + useDebugValue: import_hooks2.useDebugValue, + use: import_hooks2.use, + startTransition: import_hooks2.startTransition, + useTransition: import_hooks2.useTransition, + useDeferredValue: import_hooks2.useDeferredValue, + startViewTransition: import_hooks2.startViewTransition, + useViewTransition: import_hooks2.useViewTransition, + useMemo: import_hooks2.useMemo, + useLayoutEffect: import_hooks2.useLayoutEffect, + useInsertionEffect: import_hooks2.useInsertionEffect, + createRef: import_hooks2.createRef, + forwardRef: import_hooks2.forwardRef, + useImperativeHandle: import_hooks2.useImperativeHandle, + useSyncExternalStore: import_hooks2.useSyncExternalStore, + useActionState: import_hooks.useActionState, + useOptimistic: import_hooks.useOptimistic, + Suspense: import_streaming.Suspense, + Children: import_children.Children +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Children, + ErrorBoundary, + Fragment, + StrictMode, + Suspense, + cloneElement, + createContext, + createElement, + createRef, + forwardRef, + isValidElement, + jsx, + memo, + startTransition, + startViewTransition, + use, + useActionState, + useCallback, + useContext, + useDebugValue, + useDeferredValue, + useEffect, + useId, + useImperativeHandle, + useInsertionEffect, + useLayoutEffect, + useMemo, + useOptimistic, + useReducer, + useRef, + useState, + useSyncExternalStore, + useTransition, + useViewTransition, + version +}); diff --git a/node_modules/hono/dist/cjs/jsx/intrinsic-element/common.js b/node_modules/hono/dist/cjs/jsx/intrinsic-element/common.js new file mode 100644 index 000000000..c01838f11 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/intrinsic-element/common.js @@ -0,0 +1,40 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var common_exports = {}; +__export(common_exports, { + dataPrecedenceAttr: () => dataPrecedenceAttr, + deDupeKeyMap: () => deDupeKeyMap, + domRenderers: () => domRenderers +}); +module.exports = __toCommonJS(common_exports); +const deDupeKeyMap = { + title: [], + script: ["src"], + style: ["data-href"], + link: ["href"], + meta: ["name", "httpEquiv", "charset", "itemProp"] +}; +const domRenderers = {}; +const dataPrecedenceAttr = "data-precedence"; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + dataPrecedenceAttr, + deDupeKeyMap, + domRenderers +}); diff --git a/node_modules/hono/dist/cjs/jsx/intrinsic-element/components.js b/node_modules/hono/dist/cjs/jsx/intrinsic-element/components.js new file mode 100644 index 000000000..a945c466d --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/intrinsic-element/components.js @@ -0,0 +1,183 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var components_exports = {}; +__export(components_exports, { + button: () => button, + form: () => form, + input: () => input, + link: () => link, + meta: () => meta, + script: () => script, + style: () => style, + title: () => title +}); +module.exports = __toCommonJS(components_exports); +var import_html = require("../../helper/html"); +var import_base = require("../base"); +var import_children = require("../children"); +var import_constants = require("../constants"); +var import_context = require("../context"); +var import_common = require("./common"); +const metaTagMap = /* @__PURE__ */ new WeakMap(); +const insertIntoHead = (tagName, tag, props, precedence) => ({ buffer, context }) => { + if (!buffer) { + return; + } + const map = metaTagMap.get(context) || {}; + metaTagMap.set(context, map); + const tags = map[tagName] ||= []; + let duped = false; + const deDupeKeys = import_common.deDupeKeyMap[tagName]; + if (deDupeKeys.length > 0) { + LOOP: for (const [, tagProps] of tags) { + for (const key of deDupeKeys) { + if ((tagProps?.[key] ?? null) === props?.[key]) { + duped = true; + break LOOP; + } + } + } + } + if (duped) { + buffer[0] = buffer[0].replaceAll(tag, ""); + } else if (deDupeKeys.length > 0) { + tags.push([tag, props, precedence]); + } else { + tags.unshift([tag, props, precedence]); + } + if (buffer[0].indexOf("") !== -1) { + let insertTags; + if (precedence === void 0) { + insertTags = tags.map(([tag2]) => tag2); + } else { + const precedences = []; + insertTags = tags.map(([tag2, , precedence2]) => { + let order = precedences.indexOf(precedence2); + if (order === -1) { + precedences.push(precedence2); + order = precedences.length - 1; + } + return [tag2, order]; + }).sort((a, b) => a[1] - b[1]).map(([tag2]) => tag2); + } + insertTags.forEach((tag2) => { + buffer[0] = buffer[0].replaceAll(tag2, ""); + }); + buffer[0] = buffer[0].replace(/(?=<\/head>)/, insertTags.join("")); + } +}; +const returnWithoutSpecialBehavior = (tag, children, props) => (0, import_html.raw)(new import_base.JSXNode(tag, props, (0, import_children.toArray)(children ?? [])).toString()); +const documentMetadataTag = (tag, children, props, sort) => { + if ("itemProp" in props) { + return returnWithoutSpecialBehavior(tag, children, props); + } + let { precedence, blocking, ...restProps } = props; + precedence = sort ? precedence ?? "" : void 0; + if (sort) { + restProps[import_common.dataPrecedenceAttr] = precedence; + } + const string = new import_base.JSXNode(tag, restProps, (0, import_children.toArray)(children || [])).toString(); + if (string instanceof Promise) { + return string.then( + (resString) => (0, import_html.raw)(string, [ + ...resString.callbacks || [], + insertIntoHead(tag, resString, restProps, precedence) + ]) + ); + } else { + return (0, import_html.raw)(string, [insertIntoHead(tag, string, restProps, precedence)]); + } +}; +const title = ({ children, ...props }) => { + const nameSpaceContext = (0, import_base.getNameSpaceContext)(); + if (nameSpaceContext) { + const context = (0, import_context.useContext)(nameSpaceContext); + if (context === "svg" || context === "head") { + return new import_base.JSXNode( + "title", + props, + (0, import_children.toArray)(children ?? []) + ); + } + } + return documentMetadataTag("title", children, props, false); +}; +const script = ({ + children, + ...props +}) => { + const nameSpaceContext = (0, import_base.getNameSpaceContext)(); + if (["src", "async"].some((k) => !props[k]) || nameSpaceContext && (0, import_context.useContext)(nameSpaceContext) === "head") { + return returnWithoutSpecialBehavior("script", children, props); + } + return documentMetadataTag("script", children, props, false); +}; +const style = ({ + children, + ...props +}) => { + if (!["href", "precedence"].every((k) => k in props)) { + return returnWithoutSpecialBehavior("style", children, props); + } + props["data-href"] = props.href; + delete props.href; + return documentMetadataTag("style", children, props, true); +}; +const link = ({ children, ...props }) => { + if (["onLoad", "onError"].some((k) => k in props) || props.rel === "stylesheet" && (!("precedence" in props) || "disabled" in props)) { + return returnWithoutSpecialBehavior("link", children, props); + } + return documentMetadataTag("link", children, props, "precedence" in props); +}; +const meta = ({ children, ...props }) => { + const nameSpaceContext = (0, import_base.getNameSpaceContext)(); + if (nameSpaceContext && (0, import_context.useContext)(nameSpaceContext) === "head") { + return returnWithoutSpecialBehavior("meta", children, props); + } + return documentMetadataTag("meta", children, props, false); +}; +const newJSXNode = (tag, { children, ...props }) => ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + new import_base.JSXNode(tag, props, (0, import_children.toArray)(children ?? [])) +); +const form = (props) => { + if (typeof props.action === "function") { + props.action = import_constants.PERMALINK in props.action ? props.action[import_constants.PERMALINK] : void 0; + } + return newJSXNode("form", props); +}; +const formActionableElement = (tag, props) => { + if (typeof props.formAction === "function") { + props.formAction = import_constants.PERMALINK in props.formAction ? props.formAction[import_constants.PERMALINK] : void 0; + } + return newJSXNode(tag, props); +}; +const input = (props) => formActionableElement("input", props); +const button = (props) => formActionableElement("button", props); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + button, + form, + input, + link, + meta, + script, + style, + title +}); diff --git a/node_modules/hono/dist/cjs/jsx/intrinsic-elements.js b/node_modules/hono/dist/cjs/jsx/intrinsic-elements.js new file mode 100644 index 000000000..c0053b076 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/intrinsic-elements.js @@ -0,0 +1,16 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var intrinsic_elements_exports = {}; +module.exports = __toCommonJS(intrinsic_elements_exports); diff --git a/node_modules/hono/dist/cjs/jsx/jsx-dev-runtime.js b/node_modules/hono/dist/cjs/jsx/jsx-dev-runtime.js new file mode 100644 index 000000000..a5ee5ef7c --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/jsx-dev-runtime.js @@ -0,0 +1,42 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jsx_dev_runtime_exports = {}; +__export(jsx_dev_runtime_exports, { + Fragment: () => import_base2.Fragment, + jsxDEV: () => jsxDEV +}); +module.exports = __toCommonJS(jsx_dev_runtime_exports); +var import_base = require("./base"); +var import_base2 = require("./base"); +function jsxDEV(tag, props, key) { + let node; + if (!props || !("children" in props)) { + node = (0, import_base.jsxFn)(tag, props, []); + } else { + const children = props.children; + node = Array.isArray(children) ? (0, import_base.jsxFn)(tag, props, children) : (0, import_base.jsxFn)(tag, props, [children]); + } + node.key = key; + return node; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Fragment, + jsxDEV +}); diff --git a/node_modules/hono/dist/cjs/jsx/jsx-runtime.js b/node_modules/hono/dist/cjs/jsx/jsx-runtime.js new file mode 100644 index 000000000..c1f43066f --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/jsx-runtime.js @@ -0,0 +1,69 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jsx_runtime_exports = {}; +__export(jsx_runtime_exports, { + Fragment: () => import_jsx_dev_runtime.Fragment, + jsx: () => import_jsx_dev_runtime.jsxDEV, + jsxAttr: () => jsxAttr, + jsxEscape: () => jsxEscape, + jsxTemplate: () => import_html.html, + jsxs: () => import_jsx_dev_runtime2.jsxDEV +}); +module.exports = __toCommonJS(jsx_runtime_exports); +var import_jsx_dev_runtime = require("./jsx-dev-runtime"); +var import_jsx_dev_runtime2 = require("./jsx-dev-runtime"); +var import_html = require("../helper/html"); +var import_html2 = require("../utils/html"); +var import_utils = require("./utils"); +const jsxAttr = (key, v) => { + const buffer = [`${key}="`]; + if (key === "style" && typeof v === "object") { + let styleStr = ""; + (0, import_utils.styleObjectForEach)(v, (property, value) => { + if (value != null) { + styleStr += `${styleStr ? ";" : ""}${property}:${value}`; + } + }); + (0, import_html2.escapeToBuffer)(styleStr, buffer); + buffer[0] += '"'; + } else if (typeof v === "string") { + (0, import_html2.escapeToBuffer)(v, buffer); + buffer[0] += '"'; + } else if (v === null || v === void 0) { + return (0, import_html.raw)(""); + } else if (typeof v === "number" || v.isEscaped) { + buffer[0] += `${v}"`; + } else if (v instanceof Promise) { + buffer.unshift('"', v); + } else { + (0, import_html2.escapeToBuffer)(v.toString(), buffer); + buffer[0] += '"'; + } + return buffer.length === 1 ? (0, import_html.raw)(buffer[0]) : (0, import_html2.stringBufferToString)(buffer, void 0); +}; +const jsxEscape = (value) => value; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Fragment, + jsx, + jsxAttr, + jsxEscape, + jsxTemplate, + jsxs +}); diff --git a/node_modules/hono/dist/cjs/jsx/streaming.js b/node_modules/hono/dist/cjs/jsx/streaming.js new file mode 100644 index 000000000..fe1ecafd7 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/streaming.js @@ -0,0 +1,168 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var streaming_exports = {}; +__export(streaming_exports, { + StreamingContext: () => StreamingContext, + Suspense: () => Suspense, + renderToReadableStream: () => renderToReadableStream +}); +module.exports = __toCommonJS(streaming_exports); +var import_html = require("../helper/html"); +var import_html2 = require("../utils/html"); +var import_base = require("./base"); +var import_components = require("./components"); +var import_constants = require("./constants"); +var import_context = require("./context"); +var import_components2 = require("./dom/components"); +var import_render = require("./dom/render"); +const StreamingContext = (0, import_context.createContext)(null); +let suspenseCounter = 0; +const Suspense = async ({ + children, + fallback +}) => { + if (!Array.isArray(children)) { + children = [children]; + } + const nonce = (0, import_context.useContext)(StreamingContext)?.scriptNonce; + let resArray = []; + const stackNode = { [import_constants.DOM_STASH]: [0, []] }; + const popNodeStack = (value) => { + import_render.buildDataStack.pop(); + return value; + }; + try { + stackNode[import_constants.DOM_STASH][0] = 0; + import_render.buildDataStack.push([[], stackNode]); + resArray = children.map( + (c) => c == null || typeof c === "boolean" ? "" : c.toString() + ); + } catch (e) { + if (e instanceof Promise) { + resArray = [ + e.then(() => { + stackNode[import_constants.DOM_STASH][0] = 0; + import_render.buildDataStack.push([[], stackNode]); + return (0, import_components.childrenToString)(children).then(popNodeStack); + }) + ]; + } else { + throw e; + } + } finally { + popNodeStack(); + } + if (resArray.some((res) => res instanceof Promise)) { + const index = suspenseCounter++; + const fallbackStr = await fallback.toString(); + return (0, import_html.raw)(`${fallbackStr}`, [ + ...fallbackStr.callbacks || [], + ({ phase, buffer, context }) => { + if (phase === import_html2.HtmlEscapedCallbackPhase.BeforeStream) { + return; + } + return Promise.all(resArray).then(async (htmlArray) => { + htmlArray = htmlArray.flat(); + const content = htmlArray.join(""); + if (buffer) { + buffer[0] = buffer[0].replace( + new RegExp(`.*?`), + content + ); + } + let html = buffer ? "" : ` +((d,c,n) => { +c=d.currentScript.previousSibling +d=d.getElementById('H:${index}') +if(!d)return +do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$') +d.replaceWith(c.content) +})(document) +`; + const callbacks = htmlArray.map((html2) => html2.callbacks || []).flat(); + if (!callbacks.length) { + return html; + } + if (phase === import_html2.HtmlEscapedCallbackPhase.Stream) { + html = await (0, import_html2.resolveCallback)(html, import_html2.HtmlEscapedCallbackPhase.BeforeStream, true, context); + } + return (0, import_html.raw)(html, callbacks); + }); + } + ]); + } else { + return (0, import_html.raw)(resArray.join("")); + } +}; +Suspense[import_constants.DOM_RENDERER] = import_components2.Suspense; +const textEncoder = new TextEncoder(); +const renderToReadableStream = (content, onError = console.trace) => { + const reader = new ReadableStream({ + async start(controller) { + try { + if (content instanceof import_base.JSXNode) { + content = content.toString(); + } + const context = typeof content === "object" ? content : {}; + const resolved = await (0, import_html2.resolveCallback)( + content, + import_html2.HtmlEscapedCallbackPhase.BeforeStream, + true, + context + ); + controller.enqueue(textEncoder.encode(resolved)); + let resolvedCount = 0; + const callbacks = []; + const then = (promise) => { + callbacks.push( + promise.catch((err) => { + console.log(err); + onError(err); + return ""; + }).then(async (res) => { + res = await (0, import_html2.resolveCallback)( + res, + import_html2.HtmlEscapedCallbackPhase.BeforeStream, + true, + context + ); + res.callbacks?.map((c) => c({ phase: import_html2.HtmlEscapedCallbackPhase.Stream, context })).filter(Boolean).forEach(then); + resolvedCount++; + controller.enqueue(textEncoder.encode(res)); + }) + ); + }; + resolved.callbacks?.map((c) => c({ phase: import_html2.HtmlEscapedCallbackPhase.Stream, context })).filter(Boolean).forEach(then); + while (resolvedCount !== callbacks.length) { + await Promise.all(callbacks); + } + } catch (e) { + onError(e); + } + controller.close(); + } + }); + return reader; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + StreamingContext, + Suspense, + renderToReadableStream +}); diff --git a/node_modules/hono/dist/cjs/jsx/types.js b/node_modules/hono/dist/cjs/jsx/types.js new file mode 100644 index 000000000..43ae53610 --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/types.js @@ -0,0 +1,16 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var types_exports = {}; +module.exports = __toCommonJS(types_exports); diff --git a/node_modules/hono/dist/cjs/jsx/utils.js b/node_modules/hono/dist/cjs/jsx/utils.js new file mode 100644 index 000000000..7dcfe0d0f --- /dev/null +++ b/node_modules/hono/dist/cjs/jsx/utils.js @@ -0,0 +1,51 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var utils_exports = {}; +__export(utils_exports, { + normalizeIntrinsicElementKey: () => normalizeIntrinsicElementKey, + styleObjectForEach: () => styleObjectForEach +}); +module.exports = __toCommonJS(utils_exports); +const normalizeElementKeyMap = /* @__PURE__ */ new Map([ + ["className", "class"], + ["htmlFor", "for"], + ["crossOrigin", "crossorigin"], + ["httpEquiv", "http-equiv"], + ["itemProp", "itemprop"], + ["fetchPriority", "fetchpriority"], + ["noModule", "nomodule"], + ["formAction", "formaction"] +]); +const normalizeIntrinsicElementKey = (key) => normalizeElementKeyMap.get(key) || key; +const styleObjectForEach = (style, fn) => { + for (const [k, v] of Object.entries(style)) { + const key = k[0] === "-" || !/[A-Z]/.test(k) ? k : k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`); + fn( + key, + v == null ? null : typeof v === "number" ? !key.match( + /^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/ + ) ? `${v}px` : `${v}` : v + ); + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + normalizeIntrinsicElementKey, + styleObjectForEach +}); diff --git a/node_modules/hono/dist/cjs/middleware/basic-auth/index.js b/node_modules/hono/dist/cjs/middleware/basic-auth/index.js new file mode 100644 index 000000000..856049307 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/basic-auth/index.js @@ -0,0 +1,83 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var basic_auth_exports = {}; +__export(basic_auth_exports, { + basicAuth: () => basicAuth +}); +module.exports = __toCommonJS(basic_auth_exports); +var import_http_exception = require("../../http-exception"); +var import_basic_auth = require("../../utils/basic-auth"); +var import_buffer = require("../../utils/buffer"); +const basicAuth = (options, ...users) => { + const usernamePasswordInOptions = "username" in options && "password" in options; + const verifyUserInOptions = "verifyUser" in options; + if (!(usernamePasswordInOptions || verifyUserInOptions)) { + throw new Error( + 'basic auth middleware requires options for "username and password" or "verifyUser"' + ); + } + if (!options.realm) { + options.realm = "Secure Area"; + } + if (!options.invalidUserMessage) { + options.invalidUserMessage = "Unauthorized"; + } + if (usernamePasswordInOptions) { + users.unshift({ username: options.username, password: options.password }); + } + return async function basicAuth2(ctx, next) { + const requestUser = (0, import_basic_auth.auth)(ctx.req.raw); + if (requestUser) { + if (verifyUserInOptions) { + if (await options.verifyUser(requestUser.username, requestUser.password, ctx)) { + await next(); + return; + } + } else { + for (const user of users) { + const [usernameEqual, passwordEqual] = await Promise.all([ + (0, import_buffer.timingSafeEqual)(user.username, requestUser.username, options.hashFunction), + (0, import_buffer.timingSafeEqual)(user.password, requestUser.password, options.hashFunction) + ]); + if (usernameEqual && passwordEqual) { + await next(); + return; + } + } + } + } + const status = 401; + const headers = { + "WWW-Authenticate": 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"' + }; + const responseMessage = typeof options.invalidUserMessage === "function" ? await options.invalidUserMessage(ctx) : options.invalidUserMessage; + const res = typeof responseMessage === "string" ? new Response(responseMessage, { status, headers }) : new Response(JSON.stringify(responseMessage), { + status, + headers: { + ...headers, + "content-type": "application/json" + } + }); + throw new import_http_exception.HTTPException(status, { res }); + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + basicAuth +}); diff --git a/node_modules/hono/dist/cjs/middleware/bearer-auth/index.js b/node_modules/hono/dist/cjs/middleware/bearer-auth/index.js new file mode 100644 index 000000000..58d0c2bab --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/bearer-auth/index.js @@ -0,0 +1,106 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var bearer_auth_exports = {}; +__export(bearer_auth_exports, { + bearerAuth: () => bearerAuth +}); +module.exports = __toCommonJS(bearer_auth_exports); +var import_http_exception = require("../../http-exception"); +var import_buffer = require("../../utils/buffer"); +const TOKEN_STRINGS = "[A-Za-z0-9._~+/-]+=*"; +const PREFIX = "Bearer"; +const HEADER = "Authorization"; +const bearerAuth = (options) => { + if (!("token" in options || "verifyToken" in options)) { + throw new Error('bearer auth middleware requires options for "token"'); + } + if (!options.realm) { + options.realm = ""; + } + if (options.prefix === void 0) { + options.prefix = PREFIX; + } + const realm = options.realm?.replace(/"/g, '\\"'); + const prefixRegexStr = options.prefix === "" ? "" : `${options.prefix} +`; + const regexp = new RegExp(`^${prefixRegexStr}(${TOKEN_STRINGS}) *$`); + const wwwAuthenticatePrefix = options.prefix === "" ? "" : `${options.prefix} `; + const throwHTTPException = async (c, status, wwwAuthenticateHeader, messageOption) => { + const wwwAuthenticateHeaderValue = typeof wwwAuthenticateHeader === "function" ? await wwwAuthenticateHeader(c) : wwwAuthenticateHeader; + const headers = { + "WWW-Authenticate": typeof wwwAuthenticateHeaderValue === "string" ? wwwAuthenticateHeaderValue : `${wwwAuthenticatePrefix}${Object.entries(wwwAuthenticateHeaderValue).map(([key, value]) => `${key}="${value}"`).join(",")}` + }; + const responseMessage = typeof messageOption === "function" ? await messageOption(c) : messageOption; + const res = typeof responseMessage === "string" ? new Response(responseMessage, { status, headers }) : new Response(JSON.stringify(responseMessage), { + status, + headers: { + ...headers, + "content-type": "application/json" + } + }); + throw new import_http_exception.HTTPException(status, { res }); + }; + return async function bearerAuth2(c, next) { + const headerToken = c.req.header(options.headerName || HEADER); + if (!headerToken) { + await throwHTTPException( + c, + 401, + options.noAuthenticationHeader?.wwwAuthenticateHeader || `${wwwAuthenticatePrefix}realm="${realm}"`, + options.noAuthenticationHeader?.message || options.noAuthenticationHeaderMessage || "Unauthorized" + ); + } else { + const match = regexp.exec(headerToken); + if (!match) { + await throwHTTPException( + c, + 400, + options.invalidAuthenticationHeader?.wwwAuthenticateHeader || `${wwwAuthenticatePrefix}error="invalid_request"`, + options.invalidAuthenticationHeader?.message || options.invalidAuthenticationHeaderMessage || "Bad Request" + ); + } else { + let equal = false; + if ("verifyToken" in options) { + equal = await options.verifyToken(match[1], c); + } else if (typeof options.token === "string") { + equal = await (0, import_buffer.timingSafeEqual)(options.token, match[1], options.hashFunction); + } else if (Array.isArray(options.token) && options.token.length > 0) { + for (const token of options.token) { + if (await (0, import_buffer.timingSafeEqual)(token, match[1], options.hashFunction)) { + equal = true; + break; + } + } + } + if (!equal) { + await throwHTTPException( + c, + 401, + options.invalidToken?.wwwAuthenticateHeader || `${wwwAuthenticatePrefix}error="invalid_token"`, + options.invalidToken?.message || options.invalidTokenMessage || "Unauthorized" + ); + } + } + } + await next(); + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + bearerAuth +}); diff --git a/node_modules/hono/dist/cjs/middleware/body-limit/index.js b/node_modules/hono/dist/cjs/middleware/body-limit/index.js new file mode 100644 index 000000000..6d65ab65b --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/body-limit/index.js @@ -0,0 +1,85 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var body_limit_exports = {}; +__export(body_limit_exports, { + bodyLimit: () => bodyLimit +}); +module.exports = __toCommonJS(body_limit_exports); +var import_http_exception = require("../../http-exception"); +const ERROR_MESSAGE = "Payload Too Large"; +class BodyLimitError extends Error { + constructor(message) { + super(message); + this.name = "BodyLimitError"; + } +} +const bodyLimit = (options) => { + const onError = options.onError || (() => { + const res = new Response(ERROR_MESSAGE, { + status: 413 + }); + throw new import_http_exception.HTTPException(413, { res }); + }); + const maxSize = options.maxSize; + return async function bodyLimit2(c, next) { + if (!c.req.raw.body) { + return next(); + } + const hasTransferEncoding = c.req.raw.headers.has("transfer-encoding"); + const hasContentLength = c.req.raw.headers.has("content-length"); + if (hasTransferEncoding && hasContentLength) { + } + if (hasContentLength && !hasTransferEncoding) { + const contentLength = parseInt(c.req.raw.headers.get("content-length") || "0", 10); + return contentLength > maxSize ? onError(c) : next(); + } + let size = 0; + const rawReader = c.req.raw.body.getReader(); + const reader = new ReadableStream({ + async start(controller) { + try { + for (; ; ) { + const { done, value } = await rawReader.read(); + if (done) { + break; + } + size += value.length; + if (size > maxSize) { + controller.error(new BodyLimitError(ERROR_MESSAGE)); + break; + } + controller.enqueue(value); + } + } finally { + controller.close(); + } + } + }); + const requestInit = { body: reader, duplex: "half" }; + c.req.raw = new Request(c.req.raw, requestInit); + await next(); + if (c.error instanceof BodyLimitError) { + c.res = await onError(c); + } + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + bodyLimit +}); diff --git a/node_modules/hono/dist/cjs/middleware/cache/index.js b/node_modules/hono/dist/cjs/middleware/cache/index.js new file mode 100644 index 000000000..1aba62249 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/cache/index.js @@ -0,0 +1,102 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var cache_exports = {}; +__export(cache_exports, { + cache: () => cache +}); +module.exports = __toCommonJS(cache_exports); +const defaultCacheableStatusCodes = [200]; +const shouldSkipCache = (res) => { + const vary = res.headers.get("Vary"); + return vary && vary.includes("*"); +}; +const cache = (options) => { + if (!globalThis.caches) { + console.log("Cache Middleware is not enabled because caches is not defined."); + return async (_c, next) => await next(); + } + if (options.wait === void 0) { + options.wait = false; + } + const cacheControlDirectives = options.cacheControl?.split(",").map((directive) => directive.toLowerCase()); + const varyDirectives = Array.isArray(options.vary) ? options.vary : options.vary?.split(",").map((directive) => directive.trim()); + if (options.vary?.includes("*")) { + throw new Error( + 'Middleware vary configuration cannot include "*", as it disallows effective caching.' + ); + } + const cacheableStatusCodes = new Set( + options.cacheableStatusCodes ?? defaultCacheableStatusCodes + ); + const addHeader = (c) => { + if (cacheControlDirectives) { + const existingDirectives = c.res.headers.get("Cache-Control")?.split(",").map((d) => d.trim().split("=", 1)[0]) ?? []; + for (const directive of cacheControlDirectives) { + let [name, value] = directive.trim().split("=", 2); + name = name.toLowerCase(); + if (!existingDirectives.includes(name)) { + c.header("Cache-Control", `${name}${value ? `=${value}` : ""}`, { append: true }); + } + } + } + if (varyDirectives) { + const existingDirectives = c.res.headers.get("Vary")?.split(",").map((d) => d.trim()) ?? []; + const vary = Array.from( + new Set( + [...existingDirectives, ...varyDirectives].map((directive) => directive.toLowerCase()) + ) + ).sort(); + if (vary.includes("*")) { + c.header("Vary", "*"); + } else { + c.header("Vary", vary.join(", ")); + } + } + }; + return async function cache2(c, next) { + let key = c.req.url; + if (options.keyGenerator) { + key = await options.keyGenerator(c); + } + const cacheName = typeof options.cacheName === "function" ? await options.cacheName(c) : options.cacheName; + const cache3 = await caches.open(cacheName); + const response = await cache3.match(key); + if (response) { + return new Response(response.body, response); + } + await next(); + if (!cacheableStatusCodes.has(c.res.status)) { + return; + } + addHeader(c); + if (shouldSkipCache(c.res)) { + return; + } + const res = c.res.clone(); + if (options.wait) { + await cache3.put(key, res); + } else { + c.executionCtx.waitUntil(cache3.put(key, res)); + } + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + cache +}); diff --git a/node_modules/hono/dist/cjs/middleware/combine/index.js b/node_modules/hono/dist/cjs/middleware/combine/index.js new file mode 100644 index 000000000..2889137be --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/combine/index.js @@ -0,0 +1,102 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except2, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except2) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var combine_exports = {}; +__export(combine_exports, { + every: () => every, + except: () => except, + some: () => some +}); +module.exports = __toCommonJS(combine_exports); +var import_compose = require("../../compose"); +var import_router = require("../../router"); +var import_trie_router = require("../../router/trie-router"); +const some = (...middleware) => { + return async function some2(c, next) { + let isNextCalled = false; + const wrappedNext = () => { + isNextCalled = true; + return next(); + }; + let lastError; + for (const handler of middleware) { + try { + const result = await handler(c, wrappedNext); + if (result === true && !c.finalized) { + await wrappedNext(); + } else if (result === false) { + lastError = new Error("No successful middleware found"); + continue; + } + lastError = void 0; + break; + } catch (error) { + lastError = error; + if (isNextCalled) { + break; + } + } + } + if (lastError) { + throw lastError; + } + }; +}; +const every = (...middleware) => { + return async function every2(c, next) { + const currentRouteIndex = c.req.routeIndex; + await (0, import_compose.compose)( + middleware.map((m) => [ + [ + async (c2, next2) => { + c2.req.routeIndex = currentRouteIndex; + const res = await m(c2, next2); + if (res === false) { + throw new Error("Unmet condition"); + } + return res; + } + ] + ]) + )(c, next); + }; +}; +const except = (condition, ...middleware) => { + let router = void 0; + const conditions = (Array.isArray(condition) ? condition : [condition]).map((condition2) => { + if (typeof condition2 === "string") { + router ||= new import_trie_router.TrieRouter(); + router.add(import_router.METHOD_NAME_ALL, condition2, true); + } else { + return condition2; + } + }).filter(Boolean); + if (router) { + conditions.unshift((c) => !!router?.match(import_router.METHOD_NAME_ALL, c.req.path)?.[0]?.[0]?.[0]); + } + const handler = some((c) => conditions.some((cond) => cond(c)), every(...middleware)); + return async function except2(c, next) { + await handler(c, next); + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + every, + except, + some +}); diff --git a/node_modules/hono/dist/cjs/middleware/compress/index.js b/node_modules/hono/dist/cjs/middleware/compress/index.js new file mode 100644 index 000000000..3a29b4665 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/compress/index.js @@ -0,0 +1,62 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var compress_exports = {}; +__export(compress_exports, { + compress: () => compress +}); +module.exports = __toCommonJS(compress_exports); +var import_compress = require("../../utils/compress"); +const ENCODING_TYPES = ["gzip", "deflate"]; +const cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i; +const compress = (options) => { + const threshold = options?.threshold ?? 1024; + return async function compress2(ctx, next) { + await next(); + const contentLength = ctx.res.headers.get("Content-Length"); + if (ctx.res.headers.has("Content-Encoding") || // already encoded + ctx.res.headers.has("Transfer-Encoding") || // already encoded or chunked + ctx.req.method === "HEAD" || // HEAD request + contentLength && Number(contentLength) < threshold || // content-length below threshold + !shouldCompress(ctx.res) || // not compressible type + !shouldTransform(ctx.res)) { + return; + } + const accepted = ctx.req.header("Accept-Encoding"); + const encoding = options?.encoding ?? ENCODING_TYPES.find((encoding2) => accepted?.includes(encoding2)); + if (!encoding || !ctx.res.body) { + return; + } + const stream = new CompressionStream(encoding); + ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res); + ctx.res.headers.delete("Content-Length"); + ctx.res.headers.set("Content-Encoding", encoding); + }; +}; +const shouldCompress = (res) => { + const type = res.headers.get("Content-Type"); + return type && import_compress.COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type); +}; +const shouldTransform = (res) => { + const cacheControl = res.headers.get("Cache-Control"); + return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + compress +}); diff --git a/node_modules/hono/dist/cjs/middleware/context-storage/index.js b/node_modules/hono/dist/cjs/middleware/context-storage/index.js new file mode 100644 index 000000000..d1370ef56 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/context-storage/index.js @@ -0,0 +1,48 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var context_storage_exports = {}; +__export(context_storage_exports, { + contextStorage: () => contextStorage, + getContext: () => getContext, + tryGetContext: () => tryGetContext +}); +module.exports = __toCommonJS(context_storage_exports); +var import_node_async_hooks = require("node:async_hooks"); +const asyncLocalStorage = new import_node_async_hooks.AsyncLocalStorage(); +const contextStorage = () => { + return async function contextStorage2(c, next) { + await asyncLocalStorage.run(c, next); + }; +}; +const tryGetContext = () => { + return asyncLocalStorage.getStore(); +}; +const getContext = () => { + const context = tryGetContext(); + if (!context) { + throw new Error("Context is not available"); + } + return context; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + contextStorage, + getContext, + tryGetContext +}); diff --git a/node_modules/hono/dist/cjs/middleware/cors/index.js b/node_modules/hono/dist/cjs/middleware/cors/index.js new file mode 100644 index 000000000..db07713e6 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/cors/index.js @@ -0,0 +1,110 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var cors_exports = {}; +__export(cors_exports, { + cors: () => cors +}); +module.exports = __toCommonJS(cors_exports); +const cors = (options) => { + const defaults = { + origin: "*", + allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"], + allowHeaders: [], + exposeHeaders: [] + }; + const opts = { + ...defaults, + ...options + }; + const findAllowOrigin = ((optsOrigin) => { + if (typeof optsOrigin === "string") { + if (optsOrigin === "*") { + return () => optsOrigin; + } else { + return (origin) => optsOrigin === origin ? origin : null; + } + } else if (typeof optsOrigin === "function") { + return optsOrigin; + } else { + return (origin) => optsOrigin.includes(origin) ? origin : null; + } + })(opts.origin); + const findAllowMethods = ((optsAllowMethods) => { + if (typeof optsAllowMethods === "function") { + return optsAllowMethods; + } else if (Array.isArray(optsAllowMethods)) { + return () => optsAllowMethods; + } else { + return () => []; + } + })(opts.allowMethods); + return async function cors2(c, next) { + function set(key, value) { + c.res.headers.set(key, value); + } + const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c); + if (allowOrigin) { + set("Access-Control-Allow-Origin", allowOrigin); + } + if (opts.credentials) { + set("Access-Control-Allow-Credentials", "true"); + } + if (opts.exposeHeaders?.length) { + set("Access-Control-Expose-Headers", opts.exposeHeaders.join(",")); + } + if (c.req.method === "OPTIONS") { + if (opts.origin !== "*") { + set("Vary", "Origin"); + } + if (opts.maxAge != null) { + set("Access-Control-Max-Age", opts.maxAge.toString()); + } + const allowMethods = await findAllowMethods(c.req.header("origin") || "", c); + if (allowMethods.length) { + set("Access-Control-Allow-Methods", allowMethods.join(",")); + } + let headers = opts.allowHeaders; + if (!headers?.length) { + const requestHeaders = c.req.header("Access-Control-Request-Headers"); + if (requestHeaders) { + headers = requestHeaders.split(/\s*,\s*/); + } + } + if (headers?.length) { + set("Access-Control-Allow-Headers", headers.join(",")); + c.res.headers.append("Vary", "Access-Control-Request-Headers"); + } + c.res.headers.delete("Content-Length"); + c.res.headers.delete("Content-Type"); + return new Response(null, { + headers: c.res.headers, + status: 204, + statusText: "No Content" + }); + } + await next(); + if (opts.origin !== "*") { + c.header("Vary", "Origin", { append: true }); + } + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + cors +}); diff --git a/node_modules/hono/dist/cjs/middleware/csrf/index.js b/node_modules/hono/dist/cjs/middleware/csrf/index.js new file mode 100644 index 000000000..9434a5fd2 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/csrf/index.js @@ -0,0 +1,78 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var csrf_exports = {}; +__export(csrf_exports, { + csrf: () => csrf +}); +module.exports = __toCommonJS(csrf_exports); +var import_http_exception = require("../../http-exception"); +const secFetchSiteValues = ["same-origin", "same-site", "none", "cross-site"]; +const isSecFetchSite = (value) => secFetchSiteValues.includes(value); +const isSafeMethodRe = /^(GET|HEAD)$/; +const isRequestedByFormElementRe = /^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/i; +const csrf = (options) => { + const originHandler = ((optsOrigin) => { + if (!optsOrigin) { + return (origin, c) => origin === new URL(c.req.url).origin; + } else if (typeof optsOrigin === "string") { + return (origin) => origin === optsOrigin; + } else if (typeof optsOrigin === "function") { + return optsOrigin; + } else { + return (origin) => optsOrigin.includes(origin); + } + })(options?.origin); + const isAllowedOrigin = async (origin, c) => { + if (origin === void 0) { + return false; + } + return await originHandler(origin, c); + }; + const secFetchSiteHandler = ((optsSecFetchSite) => { + if (!optsSecFetchSite) { + return (secFetchSite) => secFetchSite === "same-origin"; + } else if (typeof optsSecFetchSite === "string") { + return (secFetchSite) => secFetchSite === optsSecFetchSite; + } else if (typeof optsSecFetchSite === "function") { + return optsSecFetchSite; + } else { + return (secFetchSite) => optsSecFetchSite.includes(secFetchSite); + } + })(options?.secFetchSite); + const isAllowedSecFetchSite = async (secFetchSite, c) => { + if (secFetchSite === void 0) { + return false; + } + if (!isSecFetchSite(secFetchSite)) { + return false; + } + return await secFetchSiteHandler(secFetchSite, c); + }; + return async function csrf2(c, next) { + if (!isSafeMethodRe.test(c.req.method) && isRequestedByFormElementRe.test(c.req.header("content-type") || "text/plain") && !await isAllowedSecFetchSite(c.req.header("sec-fetch-site"), c) && !await isAllowedOrigin(c.req.header("origin"), c)) { + const res = new Response("Forbidden", { status: 403 }); + throw new import_http_exception.HTTPException(403, { res }); + } + await next(); + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + csrf +}); diff --git a/node_modules/hono/dist/cjs/middleware/etag/digest.js b/node_modules/hono/dist/cjs/middleware/etag/digest.js new file mode 100644 index 000000000..cbfde282a --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/etag/digest.js @@ -0,0 +1,56 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var digest_exports = {}; +__export(digest_exports, { + generateDigest: () => generateDigest +}); +module.exports = __toCommonJS(digest_exports); +const mergeBuffers = (buffer1, buffer2) => { + if (!buffer1) { + return buffer2; + } + const merged = new Uint8Array( + new ArrayBuffer(buffer1.byteLength + buffer2.byteLength) + ); + merged.set(new Uint8Array(buffer1), 0); + merged.set(buffer2, buffer1.byteLength); + return merged; +}; +const generateDigest = async (stream, generator) => { + if (!stream) { + return null; + } + let result = void 0; + const reader = stream.getReader(); + for (; ; ) { + const { value, done } = await reader.read(); + if (done) { + break; + } + result = await generator(mergeBuffers(result, value)); + } + if (!result) { + return null; + } + return Array.prototype.map.call(new Uint8Array(result), (x) => x.toString(16).padStart(2, "0")).join(""); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + generateDigest +}); diff --git a/node_modules/hono/dist/cjs/middleware/etag/index.js b/node_modules/hono/dist/cjs/middleware/etag/index.js new file mode 100644 index 000000000..e65652ba9 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/etag/index.js @@ -0,0 +1,96 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var etag_exports = {}; +__export(etag_exports, { + RETAINED_304_HEADERS: () => RETAINED_304_HEADERS, + etag: () => etag +}); +module.exports = __toCommonJS(etag_exports); +var import_digest = require("./digest"); +const RETAINED_304_HEADERS = [ + "cache-control", + "content-location", + "date", + "etag", + "expires", + "vary" +]; +const stripWeak = (tag) => tag.replace(/^W\//, ""); +function etagMatches(etag2, ifNoneMatch) { + return ifNoneMatch != null && ifNoneMatch.split(/,\s*/).some((t) => stripWeak(t) === stripWeak(etag2)); +} +function initializeGenerator(generator) { + if (!generator) { + if (crypto && crypto.subtle) { + generator = (body) => crypto.subtle.digest( + { + name: "SHA-1" + }, + body + ); + } + } + return generator; +} +const etag = (options) => { + const retainedHeaders = options?.retainedHeaders ?? RETAINED_304_HEADERS; + const weak = options?.weak ?? false; + const generator = initializeGenerator(options?.generateDigest); + return async function etag2(c, next) { + const ifNoneMatch = c.req.header("If-None-Match") ?? null; + await next(); + const res = c.res; + let etag3 = res.headers.get("ETag"); + if (!etag3) { + if (!generator) { + return; + } + const hash = await (0, import_digest.generateDigest)( + // This type casing avoids the type error for `deno publish` + res.clone().body, + generator + ); + if (hash === null) { + return; + } + etag3 = weak ? `W/"${hash}"` : `"${hash}"`; + } + if (etagMatches(etag3, ifNoneMatch)) { + c.res = new Response(null, { + status: 304, + statusText: "Not Modified", + headers: { + ETag: etag3 + } + }); + c.res.headers.forEach((_, key) => { + if (retainedHeaders.indexOf(key.toLowerCase()) === -1) { + c.res.headers.delete(key); + } + }); + } else { + c.res.headers.set("ETag", etag3); + } + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + RETAINED_304_HEADERS, + etag +}); diff --git a/node_modules/hono/dist/cjs/middleware/ip-restriction/index.js b/node_modules/hono/dist/cjs/middleware/ip-restriction/index.js new file mode 100644 index 000000000..29738a0e5 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/ip-restriction/index.js @@ -0,0 +1,125 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var ip_restriction_exports = {}; +__export(ip_restriction_exports, { + ipRestriction: () => ipRestriction +}); +module.exports = __toCommonJS(ip_restriction_exports); +var import_http_exception = require("../../http-exception"); +var import_ipaddr = require("../../utils/ipaddr"); +const IS_CIDR_NOTATION_REGEX = /\/[0-9]{0,3}$/; +const buildMatcher = (rules) => { + const functionRules = []; + const staticRules = /* @__PURE__ */ new Set(); + const cidrRules = []; + for (let rule of rules) { + if (rule === "*") { + return () => true; + } else if (typeof rule === "function") { + functionRules.push(rule); + } else { + if (IS_CIDR_NOTATION_REGEX.test(rule)) { + const separatedRule = rule.split("/"); + const addrStr = separatedRule[0]; + const type2 = (0, import_ipaddr.distinctRemoteAddr)(addrStr); + if (type2 === void 0) { + throw new TypeError(`Invalid rule: ${rule}`); + } + const isIPv4 = type2 === "IPv4"; + const prefix = parseInt(separatedRule[1]); + if (isIPv4 ? prefix === 32 : prefix === 128) { + rule = addrStr; + } else { + const addr = (isIPv4 ? import_ipaddr.convertIPv4ToBinary : import_ipaddr.convertIPv6ToBinary)(addrStr); + const mask = (1n << BigInt(prefix)) - 1n << BigInt((isIPv4 ? 32 : 128) - prefix); + cidrRules.push([isIPv4, addr & mask, mask]); + continue; + } + } + const type = (0, import_ipaddr.distinctRemoteAddr)(rule); + if (type === void 0) { + throw new TypeError(`Invalid rule: ${rule}`); + } + staticRules.add( + type === "IPv4" ? rule : (0, import_ipaddr.convertIPv6BinaryToString)((0, import_ipaddr.convertIPv6ToBinary)(rule)) + // normalize IPv6 address (e.g. 0000:0000:0000:0000:0000:0000:0000:0001 => ::1) + ); + } + } + return (remote) => { + if (staticRules.has(remote.addr)) { + return true; + } + for (const [isIPv4, addr, mask] of cidrRules) { + if (isIPv4 !== remote.isIPv4) { + continue; + } + const remoteAddr = remote.binaryAddr ||= (isIPv4 ? import_ipaddr.convertIPv4ToBinary : import_ipaddr.convertIPv6ToBinary)(remote.addr); + if ((remoteAddr & mask) === addr) { + return true; + } + } + for (const rule of functionRules) { + if (rule({ addr: remote.addr, type: remote.type })) { + return true; + } + } + return false; + }; +}; +const ipRestriction = (getIP, { denyList = [], allowList = [] }, onError) => { + const allowLength = allowList.length; + const denyMatcher = buildMatcher(denyList); + const allowMatcher = buildMatcher(allowList); + const blockError = (c) => new import_http_exception.HTTPException(403, { + res: c.text("Forbidden", { + status: 403 + }) + }); + return async function ipRestriction2(c, next) { + const connInfo = getIP(c); + const addr = typeof connInfo === "string" ? connInfo : connInfo.remote.address; + if (!addr) { + throw blockError(c); + } + const type = typeof connInfo !== "string" && connInfo.remote.addressType || (0, import_ipaddr.distinctRemoteAddr)(addr); + const remoteData = { addr, type, isIPv4: type === "IPv4" }; + if (denyMatcher(remoteData)) { + if (onError) { + return onError({ addr, type }, c); + } + throw blockError(c); + } + if (allowMatcher(remoteData)) { + return await next(); + } + if (allowLength === 0) { + return await next(); + } else { + if (onError) { + return await onError({ addr, type }, c); + } + throw blockError(c); + } + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + ipRestriction +}); diff --git a/node_modules/hono/dist/cjs/middleware/jsx-renderer/index.js b/node_modules/hono/dist/cjs/middleware/jsx-renderer/index.js new file mode 100644 index 000000000..3d7c32df5 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/jsx-renderer/index.js @@ -0,0 +1,82 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jsx_renderer_exports = {}; +__export(jsx_renderer_exports, { + RequestContext: () => RequestContext, + jsxRenderer: () => jsxRenderer, + useRequestContext: () => useRequestContext +}); +module.exports = __toCommonJS(jsx_renderer_exports); +var import_html = require("../../helper/html"); +var import_jsx = require("../../jsx"); +var import_streaming = require("../../jsx/streaming"); +const RequestContext = (0, import_jsx.createContext)(null); +const createRenderer = (c, Layout, component, options) => (children, props) => { + const docType = typeof options?.docType === "string" ? options.docType : options?.docType === false ? "" : ""; + const currentLayout = component ? (0, import_jsx.jsx)( + (props2) => component(props2, c), + { + Layout, + ...props + }, + children + ) : children; + const body = import_html.html`${(0, import_html.raw)(docType)}${(0, import_jsx.jsx)( + RequestContext.Provider, + { value: c }, + currentLayout + )}`; + if (options?.stream) { + if (options.stream === true) { + c.header("Transfer-Encoding", "chunked"); + c.header("Content-Type", "text/html; charset=UTF-8"); + c.header("Content-Encoding", "Identity"); + } else { + for (const [key, value] of Object.entries(options.stream)) { + c.header(key, value); + } + } + return c.body((0, import_streaming.renderToReadableStream)(body)); + } else { + return c.html(body); + } +}; +const jsxRenderer = (component, options) => function jsxRenderer2(c, next) { + const Layout = c.getLayout() ?? import_jsx.Fragment; + if (component) { + c.setLayout((props) => { + return component({ ...props, Layout }, c); + }); + } + c.setRenderer(createRenderer(c, Layout, component, options)); + return next(); +}; +const useRequestContext = () => { + const c = (0, import_jsx.useContext)(RequestContext); + if (!c) { + throw new Error("RequestContext is not provided."); + } + return c; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + RequestContext, + jsxRenderer, + useRequestContext +}); diff --git a/node_modules/hono/dist/cjs/middleware/jwk/index.js b/node_modules/hono/dist/cjs/middleware/jwk/index.js new file mode 100644 index 000000000..1c22463d9 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/jwk/index.js @@ -0,0 +1,28 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jwk_exports = {}; +__export(jwk_exports, { + jwk: () => import_jwk.jwk +}); +module.exports = __toCommonJS(jwk_exports); +var import_jwk = require("./jwk"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + jwk +}); diff --git a/node_modules/hono/dist/cjs/middleware/jwk/jwk.js b/node_modules/hono/dist/cjs/middleware/jwk/jwk.js new file mode 100644 index 000000000..40dd842ef --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/jwk/jwk.js @@ -0,0 +1,135 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jwk_exports = {}; +__export(jwk_exports, { + jwk: () => jwk +}); +module.exports = __toCommonJS(jwk_exports); +var import_cookie = require("../../helper/cookie"); +var import_http_exception = require("../../http-exception"); +var import_jwt = require("../../utils/jwt"); +var import_context = require("../../context"); +const jwk = (options, init) => { + const verifyOpts = options.verification || {}; + if (!options || !(options.keys || options.jwks_uri)) { + throw new Error('JWK auth middleware requires options for either "keys" or "jwks_uri" or both'); + } + if (!crypto.subtle || !crypto.subtle.importKey) { + throw new Error("`crypto.subtle.importKey` is undefined. JWK auth middleware requires it."); + } + return async function jwk2(ctx, next) { + const headerName = options.headerName || "Authorization"; + const credentials = ctx.req.raw.headers.get(headerName); + let token; + if (credentials) { + const parts = credentials.split(/\s+/); + if (parts.length !== 2) { + const errDescription = "invalid credentials structure"; + throw new import_http_exception.HTTPException(401, { + message: errDescription, + res: unauthorizedResponse({ + ctx, + error: "invalid_request", + errDescription + }) + }); + } else { + token = parts[1]; + } + } else if (options.cookie) { + if (typeof options.cookie == "string") { + token = (0, import_cookie.getCookie)(ctx, options.cookie); + } else if (options.cookie.secret) { + if (options.cookie.prefixOptions) { + token = await (0, import_cookie.getSignedCookie)( + ctx, + options.cookie.secret, + options.cookie.key, + options.cookie.prefixOptions + ); + } else { + token = await (0, import_cookie.getSignedCookie)(ctx, options.cookie.secret, options.cookie.key); + } + } else { + if (options.cookie.prefixOptions) { + token = (0, import_cookie.getCookie)(ctx, options.cookie.key, options.cookie.prefixOptions); + } else { + token = (0, import_cookie.getCookie)(ctx, options.cookie.key); + } + } + } + if (!token) { + if (options.allow_anon) { + return next(); + } + const errDescription = "no authorization included in request"; + throw new import_http_exception.HTTPException(401, { + message: errDescription, + res: unauthorizedResponse({ + ctx, + error: "invalid_request", + errDescription + }) + }); + } + let payload; + let cause; + try { + const keys = typeof options.keys === "function" ? await options.keys(ctx) : options.keys; + const jwks_uri = typeof options.jwks_uri === "function" ? await options.jwks_uri(ctx) : options.jwks_uri; + payload = await import_jwt.Jwt.verifyWithJwks( + token, + { keys, jwks_uri, verification: verifyOpts, allowedAlgorithms: options.alg }, + init + ); + } catch (e) { + cause = e; + } + if (!payload) { + if (cause instanceof Error && cause.constructor === Error) { + throw cause; + } + throw new import_http_exception.HTTPException(401, { + message: "Unauthorized", + res: unauthorizedResponse({ + ctx, + error: "invalid_token", + statusText: "Unauthorized", + errDescription: "token verification failure" + }), + cause + }); + } + ctx.set("jwtPayload", payload); + await next(); + }; +}; +function unauthorizedResponse(opts) { + return new Response("Unauthorized", { + status: 401, + statusText: opts.statusText, + headers: { + "WWW-Authenticate": `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"` + } + }); +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + jwk +}); diff --git a/node_modules/hono/dist/cjs/middleware/jwt/index.js b/node_modules/hono/dist/cjs/middleware/jwt/index.js new file mode 100644 index 000000000..db35054ed --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/jwt/index.js @@ -0,0 +1,39 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jwt_exports = {}; +__export(jwt_exports, { + AlgorithmTypes: () => import_jwa.AlgorithmTypes, + decode: () => import_jwt.decode, + jwt: () => import_jwt.jwt, + sign: () => import_jwt.sign, + verify: () => import_jwt.verify, + verifyWithJwks: () => import_jwt.verifyWithJwks +}); +module.exports = __toCommonJS(jwt_exports); +var import_jwt = require("./jwt"); +var import_jwa = require("../../utils/jwt/jwa"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + AlgorithmTypes, + decode, + jwt, + sign, + verify, + verifyWithJwks +}); diff --git a/node_modules/hono/dist/cjs/middleware/jwt/jwt.js b/node_modules/hono/dist/cjs/middleware/jwt/jwt.js new file mode 100644 index 000000000..97a301f41 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/jwt/jwt.js @@ -0,0 +1,141 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jwt_exports = {}; +__export(jwt_exports, { + decode: () => decode, + jwt: () => jwt, + sign: () => sign, + verify: () => verify, + verifyWithJwks: () => verifyWithJwks +}); +module.exports = __toCommonJS(jwt_exports); +var import_cookie = require("../../helper/cookie"); +var import_http_exception = require("../../http-exception"); +var import_jwt = require("../../utils/jwt"); +var import_context = require("../../context"); +const jwt = (options) => { + const verifyOpts = options.verification || {}; + if (!options || !options.secret) { + throw new Error('JWT auth middleware requires options for "secret"'); + } + if (!options.alg) { + throw new Error('JWT auth middleware requires options for "alg"'); + } + if (!crypto.subtle || !crypto.subtle.importKey) { + throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it."); + } + return async function jwt2(ctx, next) { + const headerName = options.headerName || "Authorization"; + const credentials = ctx.req.raw.headers.get(headerName); + let token; + if (credentials) { + const parts = credentials.split(/\s+/); + if (parts.length !== 2) { + const errDescription = "invalid credentials structure"; + throw new import_http_exception.HTTPException(401, { + message: errDescription, + res: unauthorizedResponse({ + ctx, + error: "invalid_request", + errDescription + }) + }); + } else { + token = parts[1]; + } + } else if (options.cookie) { + if (typeof options.cookie == "string") { + token = (0, import_cookie.getCookie)(ctx, options.cookie); + } else if (options.cookie.secret) { + if (options.cookie.prefixOptions) { + token = await (0, import_cookie.getSignedCookie)( + ctx, + options.cookie.secret, + options.cookie.key, + options.cookie.prefixOptions + ); + } else { + token = await (0, import_cookie.getSignedCookie)(ctx, options.cookie.secret, options.cookie.key); + } + } else { + if (options.cookie.prefixOptions) { + token = (0, import_cookie.getCookie)(ctx, options.cookie.key, options.cookie.prefixOptions); + } else { + token = (0, import_cookie.getCookie)(ctx, options.cookie.key); + } + } + } + if (!token) { + const errDescription = "no authorization included in request"; + throw new import_http_exception.HTTPException(401, { + message: errDescription, + res: unauthorizedResponse({ + ctx, + error: "invalid_request", + errDescription + }) + }); + } + let payload; + let cause; + try { + payload = await import_jwt.Jwt.verify(token, options.secret, { + alg: options.alg, + ...verifyOpts + }); + } catch (e) { + cause = e; + } + if (!payload) { + throw new import_http_exception.HTTPException(401, { + message: "Unauthorized", + res: unauthorizedResponse({ + ctx, + error: "invalid_token", + statusText: "Unauthorized", + errDescription: "token verification failure" + }), + cause + }); + } + ctx.set("jwtPayload", payload); + await next(); + }; +}; +function unauthorizedResponse(opts) { + return new Response("Unauthorized", { + status: 401, + statusText: opts.statusText, + headers: { + "WWW-Authenticate": `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"` + } + }); +} +const verifyWithJwks = import_jwt.Jwt.verifyWithJwks; +const verify = import_jwt.Jwt.verify; +const decode = import_jwt.Jwt.decode; +const sign = import_jwt.Jwt.sign; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + decode, + jwt, + sign, + verify, + verifyWithJwks +}); diff --git a/node_modules/hono/dist/cjs/middleware/language/index.js b/node_modules/hono/dist/cjs/middleware/language/index.js new file mode 100644 index 000000000..133886f4f --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/language/index.js @@ -0,0 +1,36 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var language_exports = {}; +__export(language_exports, { + detectFromCookie: () => import_language.detectFromCookie, + detectFromHeader: () => import_language.detectFromHeader, + detectFromPath: () => import_language.detectFromPath, + detectFromQuery: () => import_language.detectFromQuery, + languageDetector: () => import_language.languageDetector +}); +module.exports = __toCommonJS(language_exports); +var import_language = require("./language"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + detectFromCookie, + detectFromHeader, + detectFromPath, + detectFromQuery, + languageDetector +}); diff --git a/node_modules/hono/dist/cjs/middleware/language/language.js b/node_modules/hono/dist/cjs/middleware/language/language.js new file mode 100644 index 000000000..ed6433d65 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/language/language.js @@ -0,0 +1,211 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var language_exports = {}; +__export(language_exports, { + DEFAULT_OPTIONS: () => DEFAULT_OPTIONS, + detectFromCookie: () => detectFromCookie, + detectFromHeader: () => detectFromHeader, + detectFromPath: () => detectFromPath, + detectFromQuery: () => detectFromQuery, + detectors: () => detectors, + languageDetector: () => languageDetector, + normalizeLanguage: () => normalizeLanguage, + parseAcceptLanguage: () => parseAcceptLanguage, + validateOptions: () => validateOptions +}); +module.exports = __toCommonJS(language_exports); +var import_cookie = require("../../helper/cookie"); +var import_accept = require("../../utils/accept"); +const DEFAULT_OPTIONS = { + order: ["querystring", "cookie", "header"], + lookupQueryString: "lang", + lookupCookie: "language", + lookupFromHeaderKey: "accept-language", + lookupFromPathIndex: 0, + caches: ["cookie"], + ignoreCase: true, + fallbackLanguage: "en", + supportedLanguages: ["en"], + cookieOptions: { + sameSite: "Strict", + secure: true, + maxAge: 365 * 24 * 60 * 60, + httpOnly: true + }, + debug: false +}; +function parseAcceptLanguage(header) { + return (0, import_accept.parseAccept)(header).map(({ type, q }) => ({ lang: type, q })); +} +const normalizeLanguage = (lang, options) => { + if (!lang) { + return void 0; + } + try { + let normalizedLang = lang.trim(); + if (options.convertDetectedLanguage) { + normalizedLang = options.convertDetectedLanguage(normalizedLang); + } + const compLang = options.ignoreCase ? normalizedLang.toLowerCase() : normalizedLang; + const compSupported = options.supportedLanguages.map( + (l) => options.ignoreCase ? l.toLowerCase() : l + ); + const matchedLang = compSupported.find((l) => l === compLang); + return matchedLang ? options.supportedLanguages[compSupported.indexOf(matchedLang)] : void 0; + } catch { + return void 0; + } +}; +const detectFromQuery = (c, options) => { + try { + const query = c.req.query(options.lookupQueryString); + return normalizeLanguage(query, options); + } catch { + return void 0; + } +}; +const detectFromCookie = (c, options) => { + try { + const cookie = (0, import_cookie.getCookie)(c, options.lookupCookie); + return normalizeLanguage(cookie, options); + } catch { + return void 0; + } +}; +function detectFromHeader(c, options) { + try { + const acceptLanguage = c.req.header(options.lookupFromHeaderKey); + if (!acceptLanguage) { + return void 0; + } + const languages = parseAcceptLanguage(acceptLanguage); + for (const { lang } of languages) { + const normalizedLang = normalizeLanguage(lang, options); + if (normalizedLang) { + return normalizedLang; + } + } + return void 0; + } catch { + return void 0; + } +} +function detectFromPath(c, options) { + try { + const url = new URL(c.req.url); + const pathSegments = url.pathname.split("/").filter(Boolean); + const langSegment = pathSegments[options.lookupFromPathIndex]; + return normalizeLanguage(langSegment, options); + } catch { + return void 0; + } +} +const detectors = { + querystring: detectFromQuery, + cookie: detectFromCookie, + header: detectFromHeader, + path: detectFromPath +}; +function validateOptions(options) { + if (!options.supportedLanguages.includes(options.fallbackLanguage)) { + throw new Error("Fallback language must be included in supported languages"); + } + if (options.lookupFromPathIndex < 0) { + throw new Error("Path index must be non-negative"); + } + if (!options.order.every((detector) => Object.keys(detectors).includes(detector))) { + throw new Error("Invalid detector type in order array"); + } +} +function cacheLanguage(c, language, options) { + if (!Array.isArray(options.caches) || !options.caches.includes("cookie")) { + return; + } + try { + (0, import_cookie.setCookie)(c, options.lookupCookie, language, options.cookieOptions); + } catch (error) { + if (options.debug) { + console.error("Failed to cache language:", error); + } + } +} +const detectLanguage = (c, options) => { + let detectedLang; + for (const detectorName of options.order) { + const detector = detectors[detectorName]; + if (!detector) { + continue; + } + try { + detectedLang = detector(c, options); + if (detectedLang) { + if (options.debug) { + console.log(`Language detected from ${detectorName}: ${detectedLang}`); + } + break; + } + } catch (error) { + if (options.debug) { + console.error(`Error in ${detectorName} detector:`, error); + } + continue; + } + } + const finalLang = detectedLang || options.fallbackLanguage; + if (detectedLang && options.caches) { + cacheLanguage(c, finalLang, options); + } + return finalLang; +}; +const languageDetector = (userOptions) => { + const options = { + ...DEFAULT_OPTIONS, + ...userOptions, + cookieOptions: { + ...DEFAULT_OPTIONS.cookieOptions, + ...userOptions.cookieOptions + } + }; + validateOptions(options); + return async function languageDetector2(ctx, next) { + try { + const lang = detectLanguage(ctx, options); + ctx.set("language", lang); + } catch (error) { + if (options.debug) { + console.error("Language detection failed:", error); + } + ctx.set("language", options.fallbackLanguage); + } + await next(); + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + DEFAULT_OPTIONS, + detectFromCookie, + detectFromHeader, + detectFromPath, + detectFromQuery, + detectors, + languageDetector, + normalizeLanguage, + parseAcceptLanguage, + validateOptions +}); diff --git a/node_modules/hono/dist/cjs/middleware/logger/index.js b/node_modules/hono/dist/cjs/middleware/logger/index.js new file mode 100644 index 000000000..ee709cfd4 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/logger/index.js @@ -0,0 +1,73 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var logger_exports = {}; +__export(logger_exports, { + logger: () => logger +}); +module.exports = __toCommonJS(logger_exports); +var import_color = require("../../utils/color"); +var LogPrefix = /* @__PURE__ */ ((LogPrefix2) => { + LogPrefix2["Outgoing"] = "-->"; + LogPrefix2["Incoming"] = "<--"; + LogPrefix2["Error"] = "xxx"; + return LogPrefix2; +})(LogPrefix || {}); +const humanize = (times) => { + const [delimiter, separator] = [",", "."]; + const orderTimes = times.map((v) => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter)); + return orderTimes.join(separator); +}; +const time = (start) => { + const delta = Date.now() - start; + return humanize([delta < 1e3 ? delta + "ms" : Math.round(delta / 1e3) + "s"]); +}; +const colorStatus = async (status) => { + const colorEnabled = await (0, import_color.getColorEnabledAsync)(); + if (colorEnabled) { + switch (status / 100 | 0) { + case 5: + return `\x1B[31m${status}\x1B[0m`; + case 4: + return `\x1B[33m${status}\x1B[0m`; + case 3: + return `\x1B[36m${status}\x1B[0m`; + case 2: + return `\x1B[32m${status}\x1B[0m`; + } + } + return `${status}`; +}; +async function log(fn, prefix, method, path, status = 0, elapsed) { + const out = prefix === "<--" /* Incoming */ ? `${prefix} ${method} ${path}` : `${prefix} ${method} ${path} ${await colorStatus(status)} ${elapsed}`; + fn(out); +} +const logger = (fn = console.log) => { + return async function logger2(c, next) { + const { method, url } = c.req; + const path = url.slice(url.indexOf("/", 8)); + await log(fn, "<--" /* Incoming */, method, path); + const start = Date.now(); + await next(); + await log(fn, "-->" /* Outgoing */, method, path, c.res.status, time(start)); + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + logger +}); diff --git a/node_modules/hono/dist/cjs/middleware/method-override/index.js b/node_modules/hono/dist/cjs/middleware/method-override/index.js new file mode 100644 index 000000000..dfbd952d0 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/method-override/index.js @@ -0,0 +1,105 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var method_override_exports = {}; +__export(method_override_exports, { + methodOverride: () => methodOverride +}); +module.exports = __toCommonJS(method_override_exports); +var import_body = require("../../utils/body"); +const DEFAULT_METHOD_FORM_NAME = "_method"; +const methodOverride = (options) => async function methodOverride2(c, next) { + if (c.req.method === "GET") { + return await next(); + } + const app = options.app; + if (!(options.header || options.query)) { + const contentType = c.req.header("content-type"); + const methodFormName = options.form || DEFAULT_METHOD_FORM_NAME; + const clonedRequest = c.req.raw.clone(); + const newRequest = clonedRequest.clone(); + if (contentType?.startsWith("multipart/form-data")) { + const form = await clonedRequest.formData(); + const method = form.get(methodFormName); + if (method) { + const newForm = await newRequest.formData(); + newForm.delete(methodFormName); + const newHeaders = new Headers(clonedRequest.headers); + newHeaders.delete("content-type"); + newHeaders.delete("content-length"); + const request = new Request(c.req.url, { + body: newForm, + headers: newHeaders, + method + }); + return app.fetch(request, c.env, getExecutionCtx(c)); + } + } + if (contentType === "application/x-www-form-urlencoded") { + const params = await (0, import_body.parseBody)(clonedRequest); + const method = params[methodFormName]; + if (method) { + delete params[methodFormName]; + const newParams = new URLSearchParams(params); + const request = new Request(newRequest, { + body: newParams, + method + }); + return app.fetch(request, c.env, getExecutionCtx(c)); + } + } + } else if (options.header) { + const headerName = options.header; + const method = c.req.header(headerName); + if (method) { + const newHeaders = new Headers(c.req.raw.headers); + newHeaders.delete(headerName); + const request = new Request(c.req.raw, { + headers: newHeaders, + method + }); + return app.fetch(request, c.env, getExecutionCtx(c)); + } + } else if (options.query) { + const queryName = options.query; + const method = c.req.query(queryName); + if (method) { + const url = new URL(c.req.url); + url.searchParams.delete(queryName); + const request = new Request(url.toString(), { + body: c.req.raw.body, + headers: c.req.raw.headers, + method + }); + return app.fetch(request, c.env, getExecutionCtx(c)); + } + } + await next(); +}; +const getExecutionCtx = (c) => { + let executionCtx; + try { + executionCtx = c.executionCtx; + } catch { + } + return executionCtx; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + methodOverride +}); diff --git a/node_modules/hono/dist/cjs/middleware/powered-by/index.js b/node_modules/hono/dist/cjs/middleware/powered-by/index.js new file mode 100644 index 000000000..5580b93af --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/powered-by/index.js @@ -0,0 +1,33 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var powered_by_exports = {}; +__export(powered_by_exports, { + poweredBy: () => poweredBy +}); +module.exports = __toCommonJS(powered_by_exports); +const poweredBy = (options) => { + return async function poweredBy2(c, next) { + await next(); + c.res.headers.set("X-Powered-By", options?.serverName ?? "Hono"); + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + poweredBy +}); diff --git a/node_modules/hono/dist/cjs/middleware/pretty-json/index.js b/node_modules/hono/dist/cjs/middleware/pretty-json/index.js new file mode 100644 index 000000000..0ca7c3963 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/pretty-json/index.js @@ -0,0 +1,38 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var pretty_json_exports = {}; +__export(pretty_json_exports, { + prettyJSON: () => prettyJSON +}); +module.exports = __toCommonJS(pretty_json_exports); +const prettyJSON = (options) => { + const targetQuery = options?.query ?? "pretty"; + return async function prettyJSON2(c, next) { + const pretty = options?.force || c.req.query(targetQuery) || c.req.query(targetQuery) === ""; + await next(); + if (pretty && c.res.headers.get("Content-Type")?.startsWith("application/json")) { + const obj = await c.res.json(); + c.res = new Response(JSON.stringify(obj, null, options?.space ?? 2), c.res); + } + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + prettyJSON +}); diff --git a/node_modules/hono/dist/cjs/middleware/request-id/index.js b/node_modules/hono/dist/cjs/middleware/request-id/index.js new file mode 100644 index 000000000..ec5ac3d77 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/request-id/index.js @@ -0,0 +1,28 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var request_id_exports = {}; +__export(request_id_exports, { + requestId: () => import_request_id.requestId +}); +module.exports = __toCommonJS(request_id_exports); +var import_request_id = require("./request-id"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + requestId +}); diff --git a/node_modules/hono/dist/cjs/middleware/request-id/request-id.js b/node_modules/hono/dist/cjs/middleware/request-id/request-id.js new file mode 100644 index 000000000..48e7cedb8 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/request-id/request-id.js @@ -0,0 +1,44 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var request_id_exports = {}; +__export(request_id_exports, { + requestId: () => requestId +}); +module.exports = __toCommonJS(request_id_exports); +const requestId = ({ + limitLength = 255, + headerName = "X-Request-Id", + generator = () => crypto.randomUUID() +} = {}) => { + return async function requestId2(c, next) { + let reqId = headerName ? c.req.header(headerName) : void 0; + if (!reqId || reqId.length > limitLength || /[^\w\-=]/.test(reqId)) { + reqId = generator(c); + } + c.set("requestId", reqId); + if (headerName) { + c.header(headerName, reqId); + } + await next(); + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + requestId +}); diff --git a/node_modules/hono/dist/cjs/middleware/secure-headers/index.js b/node_modules/hono/dist/cjs/middleware/secure-headers/index.js new file mode 100644 index 000000000..de33ce956 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/secure-headers/index.js @@ -0,0 +1,30 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var secure_headers_exports = {}; +__export(secure_headers_exports, { + NONCE: () => import_secure_headers.NONCE, + secureHeaders: () => import_secure_headers.secureHeaders +}); +module.exports = __toCommonJS(secure_headers_exports); +var import_secure_headers = require("./secure-headers"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + NONCE, + secureHeaders +}); diff --git a/node_modules/hono/dist/cjs/middleware/secure-headers/permissions-policy.js b/node_modules/hono/dist/cjs/middleware/secure-headers/permissions-policy.js new file mode 100644 index 000000000..468148d0c --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/secure-headers/permissions-policy.js @@ -0,0 +1,16 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var permissions_policy_exports = {}; +module.exports = __toCommonJS(permissions_policy_exports); diff --git a/node_modules/hono/dist/cjs/middleware/secure-headers/secure-headers.js b/node_modules/hono/dist/cjs/middleware/secure-headers/secure-headers.js new file mode 100644 index 000000000..b8c9bf445 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/secure-headers/secure-headers.js @@ -0,0 +1,190 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var secure_headers_exports = {}; +__export(secure_headers_exports, { + NONCE: () => NONCE, + secureHeaders: () => secureHeaders +}); +module.exports = __toCommonJS(secure_headers_exports); +var import_encode = require("../../utils/encode"); +const HEADERS_MAP = { + crossOriginEmbedderPolicy: ["Cross-Origin-Embedder-Policy", "require-corp"], + crossOriginResourcePolicy: ["Cross-Origin-Resource-Policy", "same-origin"], + crossOriginOpenerPolicy: ["Cross-Origin-Opener-Policy", "same-origin"], + originAgentCluster: ["Origin-Agent-Cluster", "?1"], + referrerPolicy: ["Referrer-Policy", "no-referrer"], + strictTransportSecurity: ["Strict-Transport-Security", "max-age=15552000; includeSubDomains"], + xContentTypeOptions: ["X-Content-Type-Options", "nosniff"], + xDnsPrefetchControl: ["X-DNS-Prefetch-Control", "off"], + xDownloadOptions: ["X-Download-Options", "noopen"], + xFrameOptions: ["X-Frame-Options", "SAMEORIGIN"], + xPermittedCrossDomainPolicies: ["X-Permitted-Cross-Domain-Policies", "none"], + xXssProtection: ["X-XSS-Protection", "0"] +}; +const DEFAULT_OPTIONS = { + crossOriginEmbedderPolicy: false, + crossOriginResourcePolicy: true, + crossOriginOpenerPolicy: true, + originAgentCluster: true, + referrerPolicy: true, + strictTransportSecurity: true, + xContentTypeOptions: true, + xDnsPrefetchControl: true, + xDownloadOptions: true, + xFrameOptions: true, + xPermittedCrossDomainPolicies: true, + xXssProtection: true, + removePoweredBy: true, + permissionsPolicy: {} +}; +const generateNonce = () => { + const arrayBuffer = new Uint8Array(16); + crypto.getRandomValues(arrayBuffer); + return (0, import_encode.encodeBase64)(arrayBuffer.buffer); +}; +const NONCE = (ctx) => { + const key = "secureHeadersNonce"; + const init = ctx.get(key); + const nonce = init || generateNonce(); + if (init == null) { + ctx.set(key, nonce); + } + return `'nonce-${nonce}'`; +}; +const secureHeaders = (customOptions) => { + const options = { ...DEFAULT_OPTIONS, ...customOptions }; + const headersToSet = getFilteredHeaders(options); + const callbacks = []; + if (options.contentSecurityPolicy) { + const [callback, value] = getCSPDirectives(options.contentSecurityPolicy); + if (callback) { + callbacks.push(callback); + } + headersToSet.push(["Content-Security-Policy", value]); + } + if (options.contentSecurityPolicyReportOnly) { + const [callback, value] = getCSPDirectives(options.contentSecurityPolicyReportOnly); + if (callback) { + callbacks.push(callback); + } + headersToSet.push(["Content-Security-Policy-Report-Only", value]); + } + if (options.permissionsPolicy && Object.keys(options.permissionsPolicy).length > 0) { + headersToSet.push([ + "Permissions-Policy", + getPermissionsPolicyDirectives(options.permissionsPolicy) + ]); + } + if (options.reportingEndpoints) { + headersToSet.push(["Reporting-Endpoints", getReportingEndpoints(options.reportingEndpoints)]); + } + if (options.reportTo) { + headersToSet.push(["Report-To", getReportToOptions(options.reportTo)]); + } + return async function secureHeaders2(ctx, next) { + const headersToSetForReq = callbacks.length === 0 ? headersToSet : callbacks.reduce((acc, cb) => cb(ctx, acc), headersToSet); + await next(); + setHeaders(ctx, headersToSetForReq); + if (options?.removePoweredBy) { + ctx.res.headers.delete("X-Powered-By"); + } + }; +}; +function getFilteredHeaders(options) { + return Object.entries(HEADERS_MAP).filter(([key]) => options[key]).map(([key, defaultValue]) => { + const overrideValue = options[key]; + return typeof overrideValue === "string" ? [defaultValue[0], overrideValue] : defaultValue; + }); +} +function getCSPDirectives(contentSecurityPolicy) { + const callbacks = []; + const resultValues = []; + for (const [directive, value] of Object.entries(contentSecurityPolicy)) { + const valueArray = Array.isArray(value) ? value : [value]; + valueArray.forEach((value2, i) => { + if (typeof value2 === "function") { + const index = i * 2 + 2 + resultValues.length; + callbacks.push((ctx, values) => { + values[index] = value2(ctx, directive); + }); + } + }); + resultValues.push( + directive.replace( + /[A-Z]+(?![a-z])|[A-Z]/g, + (match, offset) => offset ? "-" + match.toLowerCase() : match.toLowerCase() + ), + ...valueArray.flatMap((value2) => [" ", value2]), + "; " + ); + } + resultValues.pop(); + return callbacks.length === 0 ? [void 0, resultValues.join("")] : [ + (ctx, headersToSet) => headersToSet.map((values) => { + if (values[0] === "Content-Security-Policy" || values[0] === "Content-Security-Policy-Report-Only") { + const clone = values[1].slice(); + callbacks.forEach((cb) => { + cb(ctx, clone); + }); + return [values[0], clone.join("")]; + } else { + return values; + } + }), + resultValues + ]; +} +function getPermissionsPolicyDirectives(policy) { + return Object.entries(policy).map(([directive, value]) => { + const kebabDirective = camelToKebab(directive); + if (typeof value === "boolean") { + return `${kebabDirective}=${value ? "*" : "none"}`; + } + if (Array.isArray(value)) { + if (value.length === 0) { + return `${kebabDirective}=()`; + } + if (value.length === 1 && (value[0] === "*" || value[0] === "none")) { + return `${kebabDirective}=${value[0]}`; + } + const allowlist = value.map((item) => ["self", "src"].includes(item) ? item : `"${item}"`); + return `${kebabDirective}=(${allowlist.join(" ")})`; + } + return ""; + }).filter(Boolean).join(", "); +} +function camelToKebab(str) { + return str.replace(/([a-z\d])([A-Z])/g, "$1-$2").toLowerCase(); +} +function getReportingEndpoints(reportingEndpoints = []) { + return reportingEndpoints.map((endpoint) => `${endpoint.name}="${endpoint.url}"`).join(", "); +} +function getReportToOptions(reportTo = []) { + return reportTo.map((option) => JSON.stringify(option)).join(", "); +} +function setHeaders(ctx, headersToSet) { + headersToSet.forEach(([header, value]) => { + ctx.res.headers.set(header, value); + }); +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + NONCE, + secureHeaders +}); diff --git a/node_modules/hono/dist/cjs/middleware/serve-static/index.js b/node_modules/hono/dist/cjs/middleware/serve-static/index.js new file mode 100644 index 000000000..ffd483d73 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/serve-static/index.js @@ -0,0 +1,99 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var serve_static_exports = {}; +__export(serve_static_exports, { + serveStatic: () => serveStatic +}); +module.exports = __toCommonJS(serve_static_exports); +var import_compress = require("../../utils/compress"); +var import_mime = require("../../utils/mime"); +var import_path = require("./path"); +const ENCODINGS = { + br: ".br", + zstd: ".zst", + gzip: ".gz" +}; +const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS); +const DEFAULT_DOCUMENT = "index.html"; +const serveStatic = (options) => { + const root = options.root ?? "./"; + const optionPath = options.path; + const join = options.join ?? import_path.defaultJoin; + return async (c, next) => { + if (c.finalized) { + return next(); + } + let filename; + if (options.path) { + filename = options.path; + } else { + try { + filename = decodeURIComponent(c.req.path); + if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) { + throw new Error(); + } + } catch { + await options.onNotFound?.(c.req.path, c); + return next(); + } + } + let path = join( + root, + !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename + ); + if (options.isDir && await options.isDir(path)) { + path = join(path, DEFAULT_DOCUMENT); + } + const getContent = options.getContent; + let content = await getContent(path, c); + if (content instanceof Response) { + return c.newResponse(content.body, content); + } + if (content) { + const mimeType = options.mimes && (0, import_mime.getMimeType)(path, options.mimes) || (0, import_mime.getMimeType)(path); + c.header("Content-Type", mimeType || "application/octet-stream"); + if (options.precompressed && (!mimeType || import_compress.COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) { + const acceptEncodingSet = new Set( + c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()) + ); + for (const encoding of ENCODINGS_ORDERED_KEYS) { + if (!acceptEncodingSet.has(encoding)) { + continue; + } + const compressedContent = await getContent(path + ENCODINGS[encoding], c); + if (compressedContent) { + content = compressedContent; + c.header("Content-Encoding", encoding); + c.header("Vary", "Accept-Encoding", { append: true }); + break; + } + } + } + await options.onFound?.(path, c); + return c.body(content); + } + await options.onNotFound?.(path, c); + await next(); + return; + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + serveStatic +}); diff --git a/node_modules/hono/dist/cjs/middleware/serve-static/path.js b/node_modules/hono/dist/cjs/middleware/serve-static/path.js new file mode 100644 index 000000000..ff620aaf8 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/serve-static/path.js @@ -0,0 +1,41 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var path_exports = {}; +__export(path_exports, { + defaultJoin: () => defaultJoin +}); +module.exports = __toCommonJS(path_exports); +const defaultJoin = (...paths) => { + let result = paths.filter((p) => p !== "").join("/"); + result = result.replace(/(?<=\/)\/+/g, ""); + const segments = result.split("/"); + const resolved = []; + for (const segment of segments) { + if (segment === ".." && resolved.length > 0 && resolved.at(-1) !== "..") { + resolved.pop(); + } else if (segment !== ".") { + resolved.push(segment); + } + } + return resolved.join("/") || "."; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + defaultJoin +}); diff --git a/node_modules/hono/dist/cjs/middleware/timeout/index.js b/node_modules/hono/dist/cjs/middleware/timeout/index.js new file mode 100644 index 000000000..1df7d7601 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/timeout/index.js @@ -0,0 +1,48 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var timeout_exports = {}; +__export(timeout_exports, { + timeout: () => timeout +}); +module.exports = __toCommonJS(timeout_exports); +var import_http_exception = require("../../http-exception"); +const defaultTimeoutException = new import_http_exception.HTTPException(504, { + message: "Gateway Timeout" +}); +const timeout = (duration, exception = defaultTimeoutException) => { + return async function timeout2(context, next) { + let timer; + const timeoutPromise = new Promise((_, reject) => { + timer = setTimeout(() => { + reject(typeof exception === "function" ? exception(context) : exception); + }, duration); + }); + try { + await Promise.race([next(), timeoutPromise]); + } finally { + if (timer !== void 0) { + clearTimeout(timer); + } + } + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + timeout +}); diff --git a/node_modules/hono/dist/cjs/middleware/timing/index.js b/node_modules/hono/dist/cjs/middleware/timing/index.js new file mode 100644 index 000000000..277540656 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/timing/index.js @@ -0,0 +1,36 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var timing_exports = {}; +__export(timing_exports, { + endTime: () => import_timing.endTime, + setMetric: () => import_timing.setMetric, + startTime: () => import_timing.startTime, + timing: () => import_timing.timing, + wrapTime: () => import_timing.wrapTime +}); +module.exports = __toCommonJS(timing_exports); +var import_timing = require("./timing"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + endTime, + setMetric, + startTime, + timing, + wrapTime +}); diff --git a/node_modules/hono/dist/cjs/middleware/timing/timing.js b/node_modules/hono/dist/cjs/middleware/timing/timing.js new file mode 100644 index 000000000..7c25a94f0 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/timing/timing.js @@ -0,0 +1,129 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var timing_exports = {}; +__export(timing_exports, { + endTime: () => endTime, + setMetric: () => setMetric, + startTime: () => startTime, + timing: () => timing, + wrapTime: () => wrapTime +}); +module.exports = __toCommonJS(timing_exports); +var import_context = require("../../context"); +const getTime = () => { + try { + return performance.now(); + } catch { + } + return Date.now(); +}; +const timing = (config) => { + const options = { + total: true, + enabled: true, + totalDescription: "Total Response Time", + autoEnd: true, + crossOrigin: false, + ...config + }; + return async function timing2(c, next) { + const headers = []; + const timers = /* @__PURE__ */ new Map(); + if (c.get("metric")) { + return await next(); + } + c.set("metric", { headers, timers }); + if (options.total) { + startTime(c, "total", options.totalDescription); + } + await next(); + if (options.total) { + endTime(c, "total"); + } + if (options.autoEnd) { + timers.forEach((_, key) => endTime(c, key)); + } + const enabled = typeof options.enabled === "function" ? options.enabled(c) : options.enabled; + if (enabled) { + c.res.headers.append("Server-Timing", headers.join(",")); + const crossOrigin = typeof options.crossOrigin === "function" ? options.crossOrigin(c) : options.crossOrigin; + if (crossOrigin) { + c.res.headers.append( + "Timing-Allow-Origin", + typeof crossOrigin === "string" ? crossOrigin : "*" + ); + } + } + }; +}; +const setMetric = (c, name, valueDescription, description, precision) => { + const metrics = c.get("metric"); + if (!metrics) { + console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!"); + return; + } + if (typeof valueDescription === "number") { + const dur = valueDescription.toFixed(precision || 1); + const metric = description ? `${name};dur=${dur};desc="${description}"` : `${name};dur=${dur}`; + metrics.headers.push(metric); + } else { + const metric = valueDescription ? `${name};desc="${valueDescription}"` : `${name}`; + metrics.headers.push(metric); + } +}; +const startTime = (c, name, description) => { + const metrics = c.get("metric"); + if (!metrics) { + console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!"); + return; + } + metrics.timers.set(name, { description, start: getTime() }); +}; +const endTime = (c, name, precision) => { + const metrics = c.get("metric"); + if (!metrics) { + console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!"); + return; + } + const timer = metrics.timers.get(name); + if (!timer) { + console.warn(`Timer "${name}" does not exist!`); + return; + } + const { description, start } = timer; + const duration = getTime() - start; + setMetric(c, name, duration, description, precision); + metrics.timers.delete(name); +}; +async function wrapTime(c, name, callable, description, precision) { + startTime(c, name, description); + try { + return await callable; + } finally { + endTime(c, name, precision); + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + endTime, + setMetric, + startTime, + timing, + wrapTime +}); diff --git a/node_modules/hono/dist/cjs/middleware/trailing-slash/index.js b/node_modules/hono/dist/cjs/middleware/trailing-slash/index.js new file mode 100644 index 000000000..085f34ce1 --- /dev/null +++ b/node_modules/hono/dist/cjs/middleware/trailing-slash/index.js @@ -0,0 +1,49 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var trailing_slash_exports = {}; +__export(trailing_slash_exports, { + appendTrailingSlash: () => appendTrailingSlash, + trimTrailingSlash: () => trimTrailingSlash +}); +module.exports = __toCommonJS(trailing_slash_exports); +const trimTrailingSlash = () => { + return async function trimTrailingSlash2(c, next) { + await next(); + if (c.res.status === 404 && (c.req.method === "GET" || c.req.method === "HEAD") && c.req.path !== "/" && c.req.path.at(-1) === "/") { + const url = new URL(c.req.url); + url.pathname = url.pathname.substring(0, url.pathname.length - 1); + c.res = c.redirect(url.toString(), 301); + } + }; +}; +const appendTrailingSlash = () => { + return async function appendTrailingSlash2(c, next) { + await next(); + if (c.res.status === 404 && (c.req.method === "GET" || c.req.method === "HEAD") && c.req.path.at(-1) !== "/") { + const url = new URL(c.req.url); + url.pathname += "/"; + c.res = c.redirect(url.toString(), 301); + } + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + appendTrailingSlash, + trimTrailingSlash +}); diff --git a/node_modules/hono/dist/cjs/package.json b/node_modules/hono/dist/cjs/package.json new file mode 100644 index 000000000..5bbefffba --- /dev/null +++ b/node_modules/hono/dist/cjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/hono/dist/cjs/preset/quick.js b/node_modules/hono/dist/cjs/preset/quick.js new file mode 100644 index 000000000..793f3d8c0 --- /dev/null +++ b/node_modules/hono/dist/cjs/preset/quick.js @@ -0,0 +1,39 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var quick_exports = {}; +__export(quick_exports, { + Hono: () => Hono +}); +module.exports = __toCommonJS(quick_exports); +var import_hono_base = require("../hono-base"); +var import_linear_router = require("../router/linear-router"); +var import_smart_router = require("../router/smart-router"); +var import_trie_router = require("../router/trie-router"); +class Hono extends import_hono_base.HonoBase { + constructor(options = {}) { + super(options); + this.router = new import_smart_router.SmartRouter({ + routers: [new import_linear_router.LinearRouter(), new import_trie_router.TrieRouter()] + }); + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Hono +}); diff --git a/node_modules/hono/dist/cjs/preset/tiny.js b/node_modules/hono/dist/cjs/preset/tiny.js new file mode 100644 index 000000000..1fd547844 --- /dev/null +++ b/node_modules/hono/dist/cjs/preset/tiny.js @@ -0,0 +1,35 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var tiny_exports = {}; +__export(tiny_exports, { + Hono: () => Hono +}); +module.exports = __toCommonJS(tiny_exports); +var import_hono_base = require("../hono-base"); +var import_pattern_router = require("../router/pattern-router"); +class Hono extends import_hono_base.HonoBase { + constructor(options = {}) { + super(options); + this.router = new import_pattern_router.PatternRouter(); + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Hono +}); diff --git a/node_modules/hono/dist/cjs/request.js b/node_modules/hono/dist/cjs/request.js new file mode 100644 index 000000000..51c192fe0 --- /dev/null +++ b/node_modules/hono/dist/cjs/request.js @@ -0,0 +1,325 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var request_exports = {}; +__export(request_exports, { + HonoRequest: () => HonoRequest, + cloneRawRequest: () => cloneRawRequest +}); +module.exports = __toCommonJS(request_exports); +var import_http_exception = require("./http-exception"); +var import_constants = require("./request/constants"); +var import_body = require("./utils/body"); +var import_url = require("./utils/url"); +const tryDecodeURIComponent = (str) => (0, import_url.tryDecode)(str, import_url.decodeURIComponent_); +class HonoRequest { + /** + * `.raw` can get the raw Request object. + * + * @see {@link https://hono.dev/docs/api/request#raw} + * + * @example + * ```ts + * // For Cloudflare Workers + * app.post('/', async (c) => { + * const metadata = c.req.raw.cf?.hostMetadata? + * ... + * }) + * ``` + */ + raw; + #validatedData; + // Short name of validatedData + #matchResult; + routeIndex = 0; + /** + * `.path` can get the pathname of the request. + * + * @see {@link https://hono.dev/docs/api/request#path} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const pathname = c.req.path // `/about/me` + * }) + * ``` + */ + path; + bodyCache = {}; + constructor(request, path = "/", matchResult = [[]]) { + this.raw = request; + this.path = path; + this.#matchResult = matchResult; + this.#validatedData = {}; + } + param(key) { + return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams(); + } + #getDecodedParam(key) { + const paramKey = this.#matchResult[0][this.routeIndex][1][key]; + const param = this.#getParamValue(paramKey); + return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param; + } + #getAllDecodedParams() { + const decoded = {}; + const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]); + for (const key of keys) { + const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]); + if (value !== void 0) { + decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value; + } + } + return decoded; + } + #getParamValue(paramKey) { + return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey; + } + query(key) { + return (0, import_url.getQueryParam)(this.url, key); + } + queries(key) { + return (0, import_url.getQueryParams)(this.url, key); + } + header(name) { + if (name) { + return this.raw.headers.get(name) ?? void 0; + } + const headerData = {}; + this.raw.headers.forEach((value, key) => { + headerData[key] = value; + }); + return headerData; + } + async parseBody(options) { + return this.bodyCache.parsedBody ??= await (0, import_body.parseBody)(this, options); + } + #cachedBody = (key) => { + const { bodyCache, raw } = this; + const cachedBody = bodyCache[key]; + if (cachedBody) { + return cachedBody; + } + const anyCachedKey = Object.keys(bodyCache)[0]; + if (anyCachedKey) { + return bodyCache[anyCachedKey].then((body) => { + if (anyCachedKey === "json") { + body = JSON.stringify(body); + } + return new Response(body)[key](); + }); + } + return bodyCache[key] = raw[key](); + }; + /** + * `.json()` can parse Request body of type `application/json` + * + * @see {@link https://hono.dev/docs/api/request#json} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.json() + * }) + * ``` + */ + json() { + return this.#cachedBody("text").then((text) => JSON.parse(text)); + } + /** + * `.text()` can parse Request body of type `text/plain` + * + * @see {@link https://hono.dev/docs/api/request#text} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.text() + * }) + * ``` + */ + text() { + return this.#cachedBody("text"); + } + /** + * `.arrayBuffer()` parse Request body as an `ArrayBuffer` + * + * @see {@link https://hono.dev/docs/api/request#arraybuffer} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.arrayBuffer() + * }) + * ``` + */ + arrayBuffer() { + return this.#cachedBody("arrayBuffer"); + } + /** + * Parses the request body as a `Blob`. + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.blob(); + * }); + * ``` + * @see https://hono.dev/docs/api/request#blob + */ + blob() { + return this.#cachedBody("blob"); + } + /** + * Parses the request body as `FormData`. + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.formData(); + * }); + * ``` + * @see https://hono.dev/docs/api/request#formdata + */ + formData() { + return this.#cachedBody("formData"); + } + /** + * Adds validated data to the request. + * + * @param target - The target of the validation. + * @param data - The validated data to add. + */ + addValidatedData(target, data) { + this.#validatedData[target] = data; + } + valid(target) { + return this.#validatedData[target]; + } + /** + * `.url()` can get the request url strings. + * + * @see {@link https://hono.dev/docs/api/request#url} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const url = c.req.url // `http://localhost:8787/about/me` + * ... + * }) + * ``` + */ + get url() { + return this.raw.url; + } + /** + * `.method()` can get the method name of the request. + * + * @see {@link https://hono.dev/docs/api/request#method} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const method = c.req.method // `GET` + * }) + * ``` + */ + get method() { + return this.raw.method; + } + get [import_constants.GET_MATCH_RESULT]() { + return this.#matchResult; + } + /** + * `.matchedRoutes()` can return a matched route in the handler + * + * @deprecated + * + * Use matchedRoutes helper defined in "hono/route" instead. + * + * @see {@link https://hono.dev/docs/api/request#matchedroutes} + * + * @example + * ```ts + * app.use('*', async function logger(c, next) { + * await next() + * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => { + * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]') + * console.log( + * method, + * ' ', + * path, + * ' '.repeat(Math.max(10 - path.length, 0)), + * name, + * i === c.req.routeIndex ? '<- respond from here' : '' + * ) + * }) + * }) + * ``` + */ + get matchedRoutes() { + return this.#matchResult[0].map(([[, route]]) => route); + } + /** + * `routePath()` can retrieve the path registered within the handler + * + * @deprecated + * + * Use routePath helper defined in "hono/route" instead. + * + * @see {@link https://hono.dev/docs/api/request#routepath} + * + * @example + * ```ts + * app.get('/posts/:id', (c) => { + * return c.json({ path: c.req.routePath }) + * }) + * ``` + */ + get routePath() { + return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path; + } +} +const cloneRawRequest = async (req) => { + if (!req.raw.bodyUsed) { + return req.raw.clone(); + } + const cacheKey = Object.keys(req.bodyCache)[0]; + if (!cacheKey) { + throw new import_http_exception.HTTPException(500, { + message: "Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly." + }); + } + const requestInit = { + body: await req[cacheKey](), + cache: req.raw.cache, + credentials: req.raw.credentials, + headers: req.header(), + integrity: req.raw.integrity, + keepalive: req.raw.keepalive, + method: req.method, + mode: req.raw.mode, + redirect: req.raw.redirect, + referrer: req.raw.referrer, + referrerPolicy: req.raw.referrerPolicy, + signal: req.raw.signal + }; + return new Request(req.url, requestInit); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + HonoRequest, + cloneRawRequest +}); diff --git a/node_modules/hono/dist/cjs/request/constants.js b/node_modules/hono/dist/cjs/request/constants.js new file mode 100644 index 000000000..322f24d50 --- /dev/null +++ b/node_modules/hono/dist/cjs/request/constants.js @@ -0,0 +1,28 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var constants_exports = {}; +__export(constants_exports, { + GET_MATCH_RESULT: () => GET_MATCH_RESULT +}); +module.exports = __toCommonJS(constants_exports); +const GET_MATCH_RESULT = /* @__PURE__ */ Symbol(); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + GET_MATCH_RESULT +}); diff --git a/node_modules/hono/dist/cjs/router.js b/node_modules/hono/dist/cjs/router.js new file mode 100644 index 000000000..b05b67fdd --- /dev/null +++ b/node_modules/hono/dist/cjs/router.js @@ -0,0 +1,41 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var router_exports = {}; +__export(router_exports, { + MESSAGE_MATCHER_IS_ALREADY_BUILT: () => MESSAGE_MATCHER_IS_ALREADY_BUILT, + METHODS: () => METHODS, + METHOD_NAME_ALL: () => METHOD_NAME_ALL, + METHOD_NAME_ALL_LOWERCASE: () => METHOD_NAME_ALL_LOWERCASE, + UnsupportedPathError: () => UnsupportedPathError +}); +module.exports = __toCommonJS(router_exports); +const METHOD_NAME_ALL = "ALL"; +const METHOD_NAME_ALL_LOWERCASE = "all"; +const METHODS = ["get", "post", "put", "delete", "options", "patch"]; +const MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built."; +class UnsupportedPathError extends Error { +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + MESSAGE_MATCHER_IS_ALREADY_BUILT, + METHODS, + METHOD_NAME_ALL, + METHOD_NAME_ALL_LOWERCASE, + UnsupportedPathError +}); diff --git a/node_modules/hono/dist/cjs/router/linear-router/index.js b/node_modules/hono/dist/cjs/router/linear-router/index.js new file mode 100644 index 000000000..10ed2b209 --- /dev/null +++ b/node_modules/hono/dist/cjs/router/linear-router/index.js @@ -0,0 +1,28 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var linear_router_exports = {}; +__export(linear_router_exports, { + LinearRouter: () => import_router.LinearRouter +}); +module.exports = __toCommonJS(linear_router_exports); +var import_router = require("./router"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + LinearRouter +}); diff --git a/node_modules/hono/dist/cjs/router/linear-router/router.js b/node_modules/hono/dist/cjs/router/linear-router/router.js new file mode 100644 index 000000000..c72e7ca11 --- /dev/null +++ b/node_modules/hono/dist/cjs/router/linear-router/router.js @@ -0,0 +1,141 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var router_exports = {}; +__export(router_exports, { + LinearRouter: () => LinearRouter +}); +module.exports = __toCommonJS(router_exports); +var import_router = require("../../router"); +var import_url = require("../../utils/url"); +const emptyParams = /* @__PURE__ */ Object.create(null); +const splitPathRe = /\/(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/[^\/\?]+|(\?)/g; +const splitByStarRe = /\*/; +class LinearRouter { + name = "LinearRouter"; + #routes = []; + add(method, path, handler) { + for (let i = 0, paths = (0, import_url.checkOptionalParameter)(path) || [path], len = paths.length; i < len; i++) { + this.#routes.push([method, paths[i], handler]); + } + } + match(method, path) { + const handlers = []; + ROUTES_LOOP: for (let i = 0, len = this.#routes.length; i < len; i++) { + const [routeMethod, routePath, handler] = this.#routes[i]; + if (routeMethod === method || routeMethod === import_router.METHOD_NAME_ALL) { + if (routePath === "*" || routePath === "/*") { + handlers.push([handler, emptyParams]); + continue; + } + const hasStar = routePath.indexOf("*") !== -1; + const hasLabel = routePath.indexOf(":") !== -1; + if (!hasStar && !hasLabel) { + if (routePath === path || routePath + "/" === path) { + handlers.push([handler, emptyParams]); + } + } else if (hasStar && !hasLabel) { + const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 42; + const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe); + const lastIndex = parts.length - 1; + for (let j = 0, pos = 0, len2 = parts.length; j < len2; j++) { + const part = parts[j]; + const index = path.indexOf(part, pos); + if (index !== pos) { + continue ROUTES_LOOP; + } + pos += part.length; + if (j === lastIndex) { + if (!endsWithStar && pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) { + continue ROUTES_LOOP; + } + } else { + const index2 = path.indexOf("/", pos); + if (index2 === -1) { + continue ROUTES_LOOP; + } + pos = index2; + } + } + handlers.push([handler, emptyParams]); + } else if (hasLabel && !hasStar) { + const params = /* @__PURE__ */ Object.create(null); + const parts = routePath.match(splitPathRe); + const lastIndex = parts.length - 1; + for (let j = 0, pos = 0, len2 = parts.length; j < len2; j++) { + if (pos === -1 || pos >= path.length) { + continue ROUTES_LOOP; + } + const part = parts[j]; + if (part.charCodeAt(1) === 58) { + if (path.charCodeAt(pos) !== 47) { + continue ROUTES_LOOP; + } + let name = part.slice(2); + let value; + if (name.charCodeAt(name.length - 1) === 125) { + const openBracePos = name.indexOf("{"); + const next = parts[j + 1]; + const lookahead = next && next[1] !== ":" && next[1] !== "*" ? `(?=${next})` : ""; + const pattern = name.slice(openBracePos + 1, -1) + lookahead; + const restPath = path.slice(pos + 1); + const match = new RegExp(pattern, "d").exec(restPath); + if (!match || match.indices[0][0] !== 0 || match.indices[0][1] === 0) { + continue ROUTES_LOOP; + } + name = name.slice(0, openBracePos); + value = restPath.slice(...match.indices[0]); + pos += match.indices[0][1] + 1; + } else { + let endValuePos = path.indexOf("/", pos + 1); + if (endValuePos === -1) { + if (pos + 1 === path.length) { + continue ROUTES_LOOP; + } + endValuePos = path.length; + } + value = path.slice(pos + 1, endValuePos); + pos = endValuePos; + } + params[name] ||= value; + } else { + const index = path.indexOf(part, pos); + if (index !== pos) { + continue ROUTES_LOOP; + } + pos += part.length; + } + if (j === lastIndex) { + if (pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) { + continue ROUTES_LOOP; + } + } + } + handlers.push([handler, params]); + } else if (hasLabel && hasStar) { + throw new import_router.UnsupportedPathError(); + } + } + } + return [handlers]; + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + LinearRouter +}); diff --git a/node_modules/hono/dist/cjs/router/pattern-router/index.js b/node_modules/hono/dist/cjs/router/pattern-router/index.js new file mode 100644 index 000000000..54e9757dc --- /dev/null +++ b/node_modules/hono/dist/cjs/router/pattern-router/index.js @@ -0,0 +1,28 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var pattern_router_exports = {}; +__export(pattern_router_exports, { + PatternRouter: () => import_router.PatternRouter +}); +module.exports = __toCommonJS(pattern_router_exports); +var import_router = require("./router"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + PatternRouter +}); diff --git a/node_modules/hono/dist/cjs/router/pattern-router/router.js b/node_modules/hono/dist/cjs/router/pattern-router/router.js new file mode 100644 index 000000000..a9592d947 --- /dev/null +++ b/node_modules/hono/dist/cjs/router/pattern-router/router.js @@ -0,0 +1,71 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var router_exports = {}; +__export(router_exports, { + PatternRouter: () => PatternRouter +}); +module.exports = __toCommonJS(router_exports); +var import_router = require("../../router"); +const emptyParams = /* @__PURE__ */ Object.create(null); +class PatternRouter { + name = "PatternRouter"; + #routes = []; + add(method, path, handler) { + const endsWithWildcard = path.at(-1) === "*"; + if (endsWithWildcard) { + path = path.slice(0, -2); + } + if (path.at(-1) === "?") { + path = path.slice(0, -1); + this.add(method, path.replace(/\/[^/]+$/, ""), handler); + } + const parts = (path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g) || []).map( + (part) => { + const match = part.match(/^\/:([^{]+)(?:{(.*)})?/); + return match ? `/(?<${match[1]}>${match[2] || "[^/]+"})` : part === "/*" ? "/[^/]+" : part.replace(/[.\\+*[^\]$()]/g, "\\$&"); + } + ); + try { + this.#routes.push([ + new RegExp(`^${parts.join("")}${endsWithWildcard ? "" : "/?$"}`), + method, + handler + ]); + } catch { + throw new import_router.UnsupportedPathError(); + } + } + match(method, path) { + const handlers = []; + for (let i = 0, len = this.#routes.length; i < len; i++) { + const [pattern, routeMethod, handler] = this.#routes[i]; + if (routeMethod === method || routeMethod === import_router.METHOD_NAME_ALL) { + const match = pattern.exec(path); + if (match) { + handlers.push([handler, match.groups || emptyParams]); + } + } + } + return [handlers]; + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + PatternRouter +}); diff --git a/node_modules/hono/dist/cjs/router/reg-exp-router/index.js b/node_modules/hono/dist/cjs/router/reg-exp-router/index.js new file mode 100644 index 000000000..46ad45107 --- /dev/null +++ b/node_modules/hono/dist/cjs/router/reg-exp-router/index.js @@ -0,0 +1,35 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var reg_exp_router_exports = {}; +__export(reg_exp_router_exports, { + PreparedRegExpRouter: () => import_prepared_router.PreparedRegExpRouter, + RegExpRouter: () => import_router.RegExpRouter, + buildInitParams: () => import_prepared_router.buildInitParams, + serializeInitParams: () => import_prepared_router.serializeInitParams +}); +module.exports = __toCommonJS(reg_exp_router_exports); +var import_router = require("./router"); +var import_prepared_router = require("./prepared-router"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + PreparedRegExpRouter, + RegExpRouter, + buildInitParams, + serializeInitParams +}); diff --git a/node_modules/hono/dist/cjs/router/reg-exp-router/matcher.js b/node_modules/hono/dist/cjs/router/reg-exp-router/matcher.js new file mode 100644 index 000000000..cacc3360e --- /dev/null +++ b/node_modules/hono/dist/cjs/router/reg-exp-router/matcher.js @@ -0,0 +1,49 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var matcher_exports = {}; +__export(matcher_exports, { + emptyParam: () => emptyParam, + match: () => match +}); +module.exports = __toCommonJS(matcher_exports); +var import_router = require("../../router"); +const emptyParam = []; +function match(method, path) { + const matchers = this.buildAllMatchers(); + const match2 = ((method2, path2) => { + const matcher = matchers[method2] || matchers[import_router.METHOD_NAME_ALL]; + const staticMatch = matcher[2][path2]; + if (staticMatch) { + return staticMatch; + } + const match3 = path2.match(matcher[0]); + if (!match3) { + return [[], emptyParam]; + } + const index = match3.indexOf("", 1); + return [matcher[1][index], match3]; + }); + this.match = match2; + return match2(method, path); +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + emptyParam, + match +}); diff --git a/node_modules/hono/dist/cjs/router/reg-exp-router/node.js b/node_modules/hono/dist/cjs/router/reg-exp-router/node.js new file mode 100644 index 000000000..c5486a9f3 --- /dev/null +++ b/node_modules/hono/dist/cjs/router/reg-exp-router/node.js @@ -0,0 +1,135 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var node_exports = {}; +__export(node_exports, { + Node: () => Node, + PATH_ERROR: () => PATH_ERROR +}); +module.exports = __toCommonJS(node_exports); +const LABEL_REG_EXP_STR = "[^/]+"; +const ONLY_WILDCARD_REG_EXP_STR = ".*"; +const TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)"; +const PATH_ERROR = /* @__PURE__ */ Symbol(); +const regExpMetaChars = new Set(".\\+*[^]$()"); +function compareKey(a, b) { + if (a.length === 1) { + return b.length === 1 ? a < b ? -1 : 1 : -1; + } + if (b.length === 1) { + return 1; + } + if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) { + return 1; + } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) { + return -1; + } + if (a === LABEL_REG_EXP_STR) { + return 1; + } else if (b === LABEL_REG_EXP_STR) { + return -1; + } + return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length; +} +class Node { + #index; + #varIndex; + #children = /* @__PURE__ */ Object.create(null); + insert(tokens, index, paramMap, context, pathErrorCheckOnly) { + if (tokens.length === 0) { + if (this.#index !== void 0) { + throw PATH_ERROR; + } + if (pathErrorCheckOnly) { + return; + } + this.#index = index; + return; + } + const [token, ...restTokens] = tokens; + const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); + let node; + if (pattern) { + const name = pattern[1]; + let regexpStr = pattern[2] || LABEL_REG_EXP_STR; + if (name && pattern[2]) { + if (regexpStr === ".*") { + throw PATH_ERROR; + } + regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:"); + if (/\((?!\?:)/.test(regexpStr)) { + throw PATH_ERROR; + } + } + node = this.#children[regexpStr]; + if (!node) { + if (Object.keys(this.#children).some( + (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR + )) { + throw PATH_ERROR; + } + if (pathErrorCheckOnly) { + return; + } + node = this.#children[regexpStr] = new Node(); + if (name !== "") { + node.#varIndex = context.varIndex++; + } + } + if (!pathErrorCheckOnly && name !== "") { + paramMap.push([name, node.#varIndex]); + } + } else { + node = this.#children[token]; + if (!node) { + if (Object.keys(this.#children).some( + (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR + )) { + throw PATH_ERROR; + } + if (pathErrorCheckOnly) { + return; + } + node = this.#children[token] = new Node(); + } + } + node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly); + } + buildRegExpStr() { + const childKeys = Object.keys(this.#children).sort(compareKey); + const strList = childKeys.map((k) => { + const c = this.#children[k]; + return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr(); + }); + if (typeof this.#index === "number") { + strList.unshift(`#${this.#index}`); + } + if (strList.length === 0) { + return ""; + } + if (strList.length === 1) { + return strList[0]; + } + return "(?:" + strList.join("|") + ")"; + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Node, + PATH_ERROR +}); diff --git a/node_modules/hono/dist/cjs/router/reg-exp-router/prepared-router.js b/node_modules/hono/dist/cjs/router/reg-exp-router/prepared-router.js new file mode 100644 index 000000000..678551572 --- /dev/null +++ b/node_modules/hono/dist/cjs/router/reg-exp-router/prepared-router.js @@ -0,0 +1,167 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var prepared_router_exports = {}; +__export(prepared_router_exports, { + PreparedRegExpRouter: () => PreparedRegExpRouter, + buildInitParams: () => buildInitParams, + serializeInitParams: () => serializeInitParams +}); +module.exports = __toCommonJS(prepared_router_exports); +var import_router = require("../../router"); +var import_matcher = require("./matcher"); +var import_router2 = require("./router"); +class PreparedRegExpRouter { + name = "PreparedRegExpRouter"; + #matchers; + #relocateMap; + constructor(matchers, relocateMap) { + this.#matchers = matchers; + this.#relocateMap = relocateMap; + } + #addWildcard(method, handlerData) { + const matcher = this.#matchers[method]; + matcher[1].forEach((list) => list && list.push(handlerData)); + Object.values(matcher[2]).forEach((list) => list[0].push(handlerData)); + } + #addPath(method, path, handler, indexes, map) { + const matcher = this.#matchers[method]; + if (!map) { + matcher[2][path][0].push([handler, {}]); + } else { + indexes.forEach((index) => { + if (typeof index === "number") { + matcher[1][index].push([handler, map]); + } else { + ; + matcher[2][index || path][0].push([handler, map]); + } + }); + } + } + add(method, path, handler) { + if (!this.#matchers[method]) { + const all = this.#matchers[import_router.METHOD_NAME_ALL]; + const staticMap = {}; + for (const key in all[2]) { + staticMap[key] = [all[2][key][0].slice(), import_matcher.emptyParam]; + } + this.#matchers[method] = [ + all[0], + all[1].map((list) => Array.isArray(list) ? list.slice() : 0), + staticMap + ]; + } + if (path === "/*" || path === "*") { + const handlerData = [handler, {}]; + if (method === import_router.METHOD_NAME_ALL) { + for (const m in this.#matchers) { + this.#addWildcard(m, handlerData); + } + } else { + this.#addWildcard(method, handlerData); + } + return; + } + const data = this.#relocateMap[path]; + if (!data) { + throw new Error(`Path ${path} is not registered`); + } + for (const [indexes, map] of data) { + if (method === import_router.METHOD_NAME_ALL) { + for (const m in this.#matchers) { + this.#addPath(m, path, handler, indexes, map); + } + } else { + this.#addPath(method, path, handler, indexes, map); + } + } + } + buildAllMatchers() { + return this.#matchers; + } + match = import_matcher.match; +} +const buildInitParams = ({ paths }) => { + const RegExpRouterWithMatcherExport = class extends import_router2.RegExpRouter { + buildAndExportAllMatchers() { + return this.buildAllMatchers(); + } + }; + const router = new RegExpRouterWithMatcherExport(); + for (const path of paths) { + router.add(import_router.METHOD_NAME_ALL, path, path); + } + const matchers = router.buildAndExportAllMatchers(); + const all = matchers[import_router.METHOD_NAME_ALL]; + const relocateMap = {}; + for (const path of paths) { + if (path === "/*" || path === "*") { + continue; + } + all[1].forEach((list, i) => { + list.forEach(([p, map]) => { + if (p === path) { + if (relocateMap[path]) { + relocateMap[path][0][1] = { + ...relocateMap[path][0][1], + ...map + }; + } else { + relocateMap[path] = [[[], map]]; + } + if (relocateMap[path][0][0].findIndex((j) => j === i) === -1) { + relocateMap[path][0][0].push(i); + } + } + }); + }); + for (const path2 in all[2]) { + all[2][path2][0].forEach(([p]) => { + if (p === path) { + relocateMap[path] ||= [[[]]]; + const value = path2 === path ? "" : path2; + if (relocateMap[path][0][0].findIndex((v) => v === value) === -1) { + relocateMap[path][0][0].push(value); + } + } + }); + } + } + for (let i = 0, len = all[1].length; i < len; i++) { + all[1][i] = all[1][i] ? [] : 0; + } + for (const path in all[2]) { + all[2][path][0] = []; + } + return [matchers, relocateMap]; +}; +const serializeInitParams = ([matchers, relocateMap]) => { + const matchersStr = JSON.stringify( + matchers, + (_, value) => value instanceof RegExp ? `##${value.toString()}##` : value + ).replace(/"##(.+?)##"/g, (_, str) => str.replace(/\\\\/g, "\\")); + const relocateMapStr = JSON.stringify(relocateMap); + return `[${matchersStr},${relocateMapStr}]`; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + PreparedRegExpRouter, + buildInitParams, + serializeInitParams +}); diff --git a/node_modules/hono/dist/cjs/router/reg-exp-router/router.js b/node_modules/hono/dist/cjs/router/reg-exp-router/router.js new file mode 100644 index 000000000..0b66be900 --- /dev/null +++ b/node_modules/hono/dist/cjs/router/reg-exp-router/router.js @@ -0,0 +1,209 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var router_exports = {}; +__export(router_exports, { + RegExpRouter: () => RegExpRouter +}); +module.exports = __toCommonJS(router_exports); +var import_router = require("../../router"); +var import_url = require("../../utils/url"); +var import_matcher = require("./matcher"); +var import_node = require("./node"); +var import_trie = require("./trie"); +const nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)]; +let wildcardRegExpCache = /* @__PURE__ */ Object.create(null); +function buildWildcardRegExp(path) { + return wildcardRegExpCache[path] ??= new RegExp( + path === "*" ? "" : `^${path.replace( + /\/\*$|([.\\+*[^\]$()])/g, + (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)" + )}$` + ); +} +function clearWildcardRegExpCache() { + wildcardRegExpCache = /* @__PURE__ */ Object.create(null); +} +function buildMatcherFromPreprocessedRoutes(routes) { + const trie = new import_trie.Trie(); + const handlerData = []; + if (routes.length === 0) { + return nullMatcher; + } + const routesWithStaticPathFlag = routes.map( + (route) => [!/\*|\/:/.test(route[0]), ...route] + ).sort( + ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length + ); + const staticMap = /* @__PURE__ */ Object.create(null); + for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) { + const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i]; + if (pathErrorCheckOnly) { + staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), import_matcher.emptyParam]; + } else { + j++; + } + let paramAssoc; + try { + paramAssoc = trie.insert(path, j, pathErrorCheckOnly); + } catch (e) { + throw e === import_node.PATH_ERROR ? new import_router.UnsupportedPathError(path) : e; + } + if (pathErrorCheckOnly) { + continue; + } + handlerData[j] = handlers.map(([h, paramCount]) => { + const paramIndexMap = /* @__PURE__ */ Object.create(null); + paramCount -= 1; + for (; paramCount >= 0; paramCount--) { + const [key, value] = paramAssoc[paramCount]; + paramIndexMap[key] = value; + } + return [h, paramIndexMap]; + }); + } + const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp(); + for (let i = 0, len = handlerData.length; i < len; i++) { + for (let j = 0, len2 = handlerData[i].length; j < len2; j++) { + const map = handlerData[i][j]?.[1]; + if (!map) { + continue; + } + const keys = Object.keys(map); + for (let k = 0, len3 = keys.length; k < len3; k++) { + map[keys[k]] = paramReplacementMap[map[keys[k]]]; + } + } + } + const handlerMap = []; + for (const i in indexReplacementMap) { + handlerMap[i] = handlerData[indexReplacementMap[i]]; + } + return [regexp, handlerMap, staticMap]; +} +function findMiddleware(middleware, path) { + if (!middleware) { + return void 0; + } + for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) { + if (buildWildcardRegExp(k).test(path)) { + return [...middleware[k]]; + } + } + return void 0; +} +class RegExpRouter { + name = "RegExpRouter"; + #middleware; + #routes; + constructor() { + this.#middleware = { [import_router.METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }; + this.#routes = { [import_router.METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }; + } + add(method, path, handler) { + const middleware = this.#middleware; + const routes = this.#routes; + if (!middleware || !routes) { + throw new Error(import_router.MESSAGE_MATCHER_IS_ALREADY_BUILT); + } + if (!middleware[method]) { + ; + [middleware, routes].forEach((handlerMap) => { + handlerMap[method] = /* @__PURE__ */ Object.create(null); + Object.keys(handlerMap[import_router.METHOD_NAME_ALL]).forEach((p) => { + handlerMap[method][p] = [...handlerMap[import_router.METHOD_NAME_ALL][p]]; + }); + }); + } + if (path === "/*") { + path = "*"; + } + const paramCount = (path.match(/\/:/g) || []).length; + if (/\*$/.test(path)) { + const re = buildWildcardRegExp(path); + if (method === import_router.METHOD_NAME_ALL) { + Object.keys(middleware).forEach((m) => { + middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[import_router.METHOD_NAME_ALL], path) || []; + }); + } else { + middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[import_router.METHOD_NAME_ALL], path) || []; + } + Object.keys(middleware).forEach((m) => { + if (method === import_router.METHOD_NAME_ALL || method === m) { + Object.keys(middleware[m]).forEach((p) => { + re.test(p) && middleware[m][p].push([handler, paramCount]); + }); + } + }); + Object.keys(routes).forEach((m) => { + if (method === import_router.METHOD_NAME_ALL || method === m) { + Object.keys(routes[m]).forEach( + (p) => re.test(p) && routes[m][p].push([handler, paramCount]) + ); + } + }); + return; + } + const paths = (0, import_url.checkOptionalParameter)(path) || [path]; + for (let i = 0, len = paths.length; i < len; i++) { + const path2 = paths[i]; + Object.keys(routes).forEach((m) => { + if (method === import_router.METHOD_NAME_ALL || method === m) { + routes[m][path2] ||= [ + ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[import_router.METHOD_NAME_ALL], path2) || [] + ]; + routes[m][path2].push([handler, paramCount - len + i + 1]); + } + }); + } + } + match = import_matcher.match; + buildAllMatchers() { + const matchers = /* @__PURE__ */ Object.create(null); + Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => { + matchers[method] ||= this.#buildMatcher(method); + }); + this.#middleware = this.#routes = void 0; + clearWildcardRegExpCache(); + return matchers; + } + #buildMatcher(method) { + const routes = []; + let hasOwnRoute = method === import_router.METHOD_NAME_ALL; + [this.#middleware, this.#routes].forEach((r) => { + const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : []; + if (ownRoute.length !== 0) { + hasOwnRoute ||= true; + routes.push(...ownRoute); + } else if (method !== import_router.METHOD_NAME_ALL) { + routes.push( + ...Object.keys(r[import_router.METHOD_NAME_ALL]).map((path) => [path, r[import_router.METHOD_NAME_ALL][path]]) + ); + } + }); + if (!hasOwnRoute) { + return null; + } else { + return buildMatcherFromPreprocessedRoutes(routes); + } + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + RegExpRouter +}); diff --git a/node_modules/hono/dist/cjs/router/reg-exp-router/trie.js b/node_modules/hono/dist/cjs/router/reg-exp-router/trie.js new file mode 100644 index 000000000..70754e131 --- /dev/null +++ b/node_modules/hono/dist/cjs/router/reg-exp-router/trie.js @@ -0,0 +1,82 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var trie_exports = {}; +__export(trie_exports, { + Trie: () => Trie +}); +module.exports = __toCommonJS(trie_exports); +var import_node = require("./node"); +class Trie { + #context = { varIndex: 0 }; + #root = new import_node.Node(); + insert(path, index, pathErrorCheckOnly) { + const paramAssoc = []; + const groups = []; + for (let i = 0; ; ) { + let replaced = false; + path = path.replace(/\{[^}]+\}/g, (m) => { + const mark = `@\\${i}`; + groups[i] = [mark, m]; + i++; + replaced = true; + return mark; + }); + if (!replaced) { + break; + } + } + const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []; + for (let i = groups.length - 1; i >= 0; i--) { + const [mark] = groups[i]; + for (let j = tokens.length - 1; j >= 0; j--) { + if (tokens[j].indexOf(mark) !== -1) { + tokens[j] = tokens[j].replace(mark, groups[i][1]); + break; + } + } + } + this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly); + return paramAssoc; + } + buildRegExp() { + let regexp = this.#root.buildRegExpStr(); + if (regexp === "") { + return [/^$/, [], []]; + } + let captureIndex = 0; + const indexReplacementMap = []; + const paramReplacementMap = []; + regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => { + if (handlerIndex !== void 0) { + indexReplacementMap[++captureIndex] = Number(handlerIndex); + return "$()"; + } + if (paramIndex !== void 0) { + paramReplacementMap[Number(paramIndex)] = ++captureIndex; + return ""; + } + return ""; + }); + return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]; + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Trie +}); diff --git a/node_modules/hono/dist/cjs/router/smart-router/index.js b/node_modules/hono/dist/cjs/router/smart-router/index.js new file mode 100644 index 000000000..1d31883a8 --- /dev/null +++ b/node_modules/hono/dist/cjs/router/smart-router/index.js @@ -0,0 +1,28 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var smart_router_exports = {}; +__export(smart_router_exports, { + SmartRouter: () => import_router.SmartRouter +}); +module.exports = __toCommonJS(smart_router_exports); +var import_router = require("./router"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + SmartRouter +}); diff --git a/node_modules/hono/dist/cjs/router/smart-router/router.js b/node_modules/hono/dist/cjs/router/smart-router/router.js new file mode 100644 index 000000000..2e431782a --- /dev/null +++ b/node_modules/hono/dist/cjs/router/smart-router/router.js @@ -0,0 +1,81 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var router_exports = {}; +__export(router_exports, { + SmartRouter: () => SmartRouter +}); +module.exports = __toCommonJS(router_exports); +var import_router = require("../../router"); +class SmartRouter { + name = "SmartRouter"; + #routers = []; + #routes = []; + constructor(init) { + this.#routers = init.routers; + } + add(method, path, handler) { + if (!this.#routes) { + throw new Error(import_router.MESSAGE_MATCHER_IS_ALREADY_BUILT); + } + this.#routes.push([method, path, handler]); + } + match(method, path) { + if (!this.#routes) { + throw new Error("Fatal error"); + } + const routers = this.#routers; + const routes = this.#routes; + const len = routers.length; + let i = 0; + let res; + for (; i < len; i++) { + const router = routers[i]; + try { + for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) { + router.add(...routes[i2]); + } + res = router.match(method, path); + } catch (e) { + if (e instanceof import_router.UnsupportedPathError) { + continue; + } + throw e; + } + this.match = router.match.bind(router); + this.#routers = [router]; + this.#routes = void 0; + break; + } + if (i === len) { + throw new Error("Fatal error"); + } + this.name = `SmartRouter + ${this.activeRouter.name}`; + return res; + } + get activeRouter() { + if (this.#routes || this.#routers.length !== 1) { + throw new Error("No active router has been determined yet."); + } + return this.#routers[0]; + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + SmartRouter +}); diff --git a/node_modules/hono/dist/cjs/router/trie-router/index.js b/node_modules/hono/dist/cjs/router/trie-router/index.js new file mode 100644 index 000000000..feaeadbde --- /dev/null +++ b/node_modules/hono/dist/cjs/router/trie-router/index.js @@ -0,0 +1,28 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var trie_router_exports = {}; +__export(trie_router_exports, { + TrieRouter: () => import_router.TrieRouter +}); +module.exports = __toCommonJS(trie_router_exports); +var import_router = require("./router"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + TrieRouter +}); diff --git a/node_modules/hono/dist/cjs/router/trie-router/node.js b/node_modules/hono/dist/cjs/router/trie-router/node.js new file mode 100644 index 000000000..e41f3d09f --- /dev/null +++ b/node_modules/hono/dist/cjs/router/trie-router/node.js @@ -0,0 +1,185 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var node_exports = {}; +__export(node_exports, { + Node: () => Node +}); +module.exports = __toCommonJS(node_exports); +var import_router = require("../../router"); +var import_url = require("../../utils/url"); +const emptyParams = /* @__PURE__ */ Object.create(null); +class Node { + #methods; + #children; + #patterns; + #order = 0; + #params = emptyParams; + constructor(method, handler, children) { + this.#children = children || /* @__PURE__ */ Object.create(null); + this.#methods = []; + if (method && handler) { + const m = /* @__PURE__ */ Object.create(null); + m[method] = { handler, possibleKeys: [], score: 0 }; + this.#methods = [m]; + } + this.#patterns = []; + } + insert(method, path, handler) { + this.#order = ++this.#order; + let curNode = this; + const parts = (0, import_url.splitRoutingPath)(path); + const possibleKeys = []; + for (let i = 0, len = parts.length; i < len; i++) { + const p = parts[i]; + const nextP = parts[i + 1]; + const pattern = (0, import_url.getPattern)(p, nextP); + const key = Array.isArray(pattern) ? pattern[0] : p; + if (key in curNode.#children) { + curNode = curNode.#children[key]; + if (pattern) { + possibleKeys.push(pattern[1]); + } + continue; + } + curNode.#children[key] = new Node(); + if (pattern) { + curNode.#patterns.push(pattern); + possibleKeys.push(pattern[1]); + } + curNode = curNode.#children[key]; + } + curNode.#methods.push({ + [method]: { + handler, + possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i), + score: this.#order + } + }); + return curNode; + } + #getHandlerSets(node, method, nodeParams, params) { + const handlerSets = []; + for (let i = 0, len = node.#methods.length; i < len; i++) { + const m = node.#methods[i]; + const handlerSet = m[method] || m[import_router.METHOD_NAME_ALL]; + const processedSet = {}; + if (handlerSet !== void 0) { + handlerSet.params = /* @__PURE__ */ Object.create(null); + handlerSets.push(handlerSet); + if (nodeParams !== emptyParams || params && params !== emptyParams) { + for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) { + const key = handlerSet.possibleKeys[i2]; + const processed = processedSet[handlerSet.score]; + handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key]; + processedSet[handlerSet.score] = true; + } + } + } + } + return handlerSets; + } + search(method, path) { + const handlerSets = []; + this.#params = emptyParams; + const curNode = this; + let curNodes = [curNode]; + const parts = (0, import_url.splitPath)(path); + const curNodesQueue = []; + for (let i = 0, len = parts.length; i < len; i++) { + const part = parts[i]; + const isLast = i === len - 1; + const tempNodes = []; + for (let j = 0, len2 = curNodes.length; j < len2; j++) { + const node = curNodes[j]; + const nextNode = node.#children[part]; + if (nextNode) { + nextNode.#params = node.#params; + if (isLast) { + if (nextNode.#children["*"]) { + handlerSets.push( + ...this.#getHandlerSets(nextNode.#children["*"], method, node.#params) + ); + } + handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params)); + } else { + tempNodes.push(nextNode); + } + } + for (let k = 0, len3 = node.#patterns.length; k < len3; k++) { + const pattern = node.#patterns[k]; + const params = node.#params === emptyParams ? {} : { ...node.#params }; + if (pattern === "*") { + const astNode = node.#children["*"]; + if (astNode) { + handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params)); + astNode.#params = params; + tempNodes.push(astNode); + } + continue; + } + const [key, name, matcher] = pattern; + if (!part && !(matcher instanceof RegExp)) { + continue; + } + const child = node.#children[key]; + const restPathString = parts.slice(i).join("/"); + if (matcher instanceof RegExp) { + const m = matcher.exec(restPathString); + if (m) { + params[name] = m[0]; + handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params)); + if (Object.keys(child.#children).length) { + child.#params = params; + const componentCount = m[0].match(/\//)?.length ?? 0; + const targetCurNodes = curNodesQueue[componentCount] ||= []; + targetCurNodes.push(child); + } + continue; + } + } + if (matcher === true || matcher.test(part)) { + params[name] = part; + if (isLast) { + handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params)); + if (child.#children["*"]) { + handlerSets.push( + ...this.#getHandlerSets(child.#children["*"], method, params, node.#params) + ); + } + } else { + child.#params = params; + tempNodes.push(child); + } + } + } + } + curNodes = tempNodes.concat(curNodesQueue.shift() ?? []); + } + if (handlerSets.length > 1) { + handlerSets.sort((a, b) => { + return a.score - b.score; + }); + } + return [handlerSets.map(({ handler, params }) => [handler, params])]; + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Node +}); diff --git a/node_modules/hono/dist/cjs/router/trie-router/router.js b/node_modules/hono/dist/cjs/router/trie-router/router.js new file mode 100644 index 000000000..9c2133f2a --- /dev/null +++ b/node_modules/hono/dist/cjs/router/trie-router/router.js @@ -0,0 +1,49 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var router_exports = {}; +__export(router_exports, { + TrieRouter: () => TrieRouter +}); +module.exports = __toCommonJS(router_exports); +var import_url = require("../../utils/url"); +var import_node = require("./node"); +class TrieRouter { + name = "TrieRouter"; + #node; + constructor() { + this.#node = new import_node.Node(); + } + add(method, path, handler) { + const results = (0, import_url.checkOptionalParameter)(path); + if (results) { + for (let i = 0, len = results.length; i < len; i++) { + this.#node.insert(method, results[i], handler); + } + return; + } + this.#node.insert(method, path, handler); + } + match(method, path) { + return this.#node.search(method, path); + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + TrieRouter +}); diff --git a/node_modules/hono/dist/cjs/types.js b/node_modules/hono/dist/cjs/types.js new file mode 100644 index 000000000..2daf7300d --- /dev/null +++ b/node_modules/hono/dist/cjs/types.js @@ -0,0 +1,29 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var types_exports = {}; +__export(types_exports, { + FetchEventLike: () => FetchEventLike +}); +module.exports = __toCommonJS(types_exports); +class FetchEventLike { +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + FetchEventLike +}); diff --git a/node_modules/hono/dist/cjs/utils/accept.js b/node_modules/hono/dist/cjs/utils/accept.js new file mode 100644 index 000000000..d7177578f --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/accept.js @@ -0,0 +1,86 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var accept_exports = {}; +__export(accept_exports, { + parseAccept: () => parseAccept +}); +module.exports = __toCommonJS(accept_exports); +const parseAccept = (acceptHeader) => { + if (!acceptHeader) { + return []; + } + const acceptValues = acceptHeader.split(",").map((value, index) => ({ value, index })); + return acceptValues.map(parseAcceptValue).filter((item) => Boolean(item)).sort(sortByQualityAndIndex).map(({ type, params, q }) => ({ type, params, q })); +}; +const parseAcceptValueRegex = /;(?=(?:(?:[^"]*"){2})*[^"]*$)/; +const parseAcceptValue = ({ value, index }) => { + const parts = value.trim().split(parseAcceptValueRegex).map((s) => s.trim()); + const type = parts[0]; + if (!type) { + return null; + } + const params = parseParams(parts.slice(1)); + const q = parseQuality(params.q); + return { type, params, q, index }; +}; +const parseParams = (paramParts) => { + return paramParts.reduce((acc, param) => { + const [key, val] = param.split("=").map((s) => s.trim()); + if (key && val) { + acc[key] = val; + } + return acc; + }, {}); +}; +const parseQuality = (qVal) => { + if (qVal === void 0) { + return 1; + } + if (qVal === "") { + return 1; + } + if (qVal === "NaN") { + return 0; + } + const num = Number(qVal); + if (num === Infinity) { + return 1; + } + if (num === -Infinity) { + return 0; + } + if (Number.isNaN(num)) { + return 1; + } + if (num < 0 || num > 1) { + return 1; + } + return num; +}; +const sortByQualityAndIndex = (a, b) => { + const qDiff = b.q - a.q; + if (qDiff !== 0) { + return qDiff; + } + return a.index - b.index; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + parseAccept +}); diff --git a/node_modules/hono/dist/cjs/utils/basic-auth.js b/node_modules/hono/dist/cjs/utils/basic-auth.js new file mode 100644 index 000000000..a8d4719c0 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/basic-auth.js @@ -0,0 +1,46 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var basic_auth_exports = {}; +__export(basic_auth_exports, { + auth: () => auth +}); +module.exports = __toCommonJS(basic_auth_exports); +var import_encode = require("./encode"); +const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/; +const USER_PASS_REGEXP = /^([^:]*):(.*)$/; +const utf8Decoder = new TextDecoder(); +const auth = (req) => { + const match = CREDENTIALS_REGEXP.exec(req.headers.get("Authorization") || ""); + if (!match) { + return void 0; + } + let userPass = void 0; + try { + userPass = USER_PASS_REGEXP.exec(utf8Decoder.decode((0, import_encode.decodeBase64)(match[1]))); + } catch { + } + if (!userPass) { + return void 0; + } + return { username: userPass[1], password: userPass[2] }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + auth +}); diff --git a/node_modules/hono/dist/cjs/utils/body.js b/node_modules/hono/dist/cjs/utils/body.js new file mode 100644 index 000000000..cbcb7610d --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/body.js @@ -0,0 +1,95 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var body_exports = {}; +__export(body_exports, { + parseBody: () => parseBody +}); +module.exports = __toCommonJS(body_exports); +var import_request = require("../request"); +const parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => { + const { all = false, dot = false } = options; + const headers = request instanceof import_request.HonoRequest ? request.raw.headers : request.headers; + const contentType = headers.get("Content-Type"); + if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) { + return parseFormData(request, { all, dot }); + } + return {}; +}; +async function parseFormData(request, options) { + const formData = await request.formData(); + if (formData) { + return convertFormDataToBodyData(formData, options); + } + return {}; +} +function convertFormDataToBodyData(formData, options) { + const form = /* @__PURE__ */ Object.create(null); + formData.forEach((value, key) => { + const shouldParseAllValues = options.all || key.endsWith("[]"); + if (!shouldParseAllValues) { + form[key] = value; + } else { + handleParsingAllValues(form, key, value); + } + }); + if (options.dot) { + Object.entries(form).forEach(([key, value]) => { + const shouldParseDotValues = key.includes("."); + if (shouldParseDotValues) { + handleParsingNestedValues(form, key, value); + delete form[key]; + } + }); + } + return form; +} +const handleParsingAllValues = (form, key, value) => { + if (form[key] !== void 0) { + if (Array.isArray(form[key])) { + ; + form[key].push(value); + } else { + form[key] = [form[key], value]; + } + } else { + if (!key.endsWith("[]")) { + form[key] = value; + } else { + form[key] = [value]; + } + } +}; +const handleParsingNestedValues = (form, key, value) => { + let nestedForm = form; + const keys = key.split("."); + keys.forEach((key2, index) => { + if (index === keys.length - 1) { + nestedForm[key2] = value; + } else { + if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) { + nestedForm[key2] = /* @__PURE__ */ Object.create(null); + } + nestedForm = nestedForm[key2]; + } + }); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + parseBody +}); diff --git a/node_modules/hono/dist/cjs/utils/buffer.js b/node_modules/hono/dist/cjs/utils/buffer.js new file mode 100644 index 000000000..fbd826f3c --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/buffer.js @@ -0,0 +1,76 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var buffer_exports = {}; +__export(buffer_exports, { + bufferToFormData: () => bufferToFormData, + bufferToString: () => bufferToString, + equal: () => equal, + timingSafeEqual: () => timingSafeEqual +}); +module.exports = __toCommonJS(buffer_exports); +var import_crypto = require("./crypto"); +const equal = (a, b) => { + if (a === b) { + return true; + } + if (a.byteLength !== b.byteLength) { + return false; + } + const va = new DataView(a); + const vb = new DataView(b); + let i = va.byteLength; + while (i--) { + if (va.getUint8(i) !== vb.getUint8(i)) { + return false; + } + } + return true; +}; +const timingSafeEqual = async (a, b, hashFunction) => { + if (!hashFunction) { + hashFunction = import_crypto.sha256; + } + const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]); + if (!sa || !sb) { + return false; + } + return sa === sb && a === b; +}; +const bufferToString = (buffer) => { + if (buffer instanceof ArrayBuffer) { + const enc = new TextDecoder("utf-8"); + return enc.decode(buffer); + } + return buffer; +}; +const bufferToFormData = (arrayBuffer, contentType) => { + const response = new Response(arrayBuffer, { + headers: { + "Content-Type": contentType + } + }); + return response.formData(); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + bufferToFormData, + bufferToString, + equal, + timingSafeEqual +}); diff --git a/node_modules/hono/dist/cjs/utils/color.js b/node_modules/hono/dist/cjs/utils/color.js new file mode 100644 index 000000000..9383515eb --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/color.js @@ -0,0 +1,49 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var color_exports = {}; +__export(color_exports, { + getColorEnabled: () => getColorEnabled, + getColorEnabledAsync: () => getColorEnabledAsync +}); +module.exports = __toCommonJS(color_exports); +function getColorEnabled() { + const { process, Deno } = globalThis; + const isNoColor = typeof Deno?.noColor === "boolean" ? Deno.noColor : process !== void 0 ? ( + // eslint-disable-next-line no-unsafe-optional-chaining + "NO_COLOR" in process?.env + ) : false; + return !isNoColor; +} +async function getColorEnabledAsync() { + const { navigator } = globalThis; + const cfWorkers = "cloudflare:workers"; + const isNoColor = navigator !== void 0 && navigator.userAgent === "Cloudflare-Workers" ? await (async () => { + try { + return "NO_COLOR" in ((await import(cfWorkers)).env ?? {}); + } catch { + return false; + } + })() : !getColorEnabled(); + return !isNoColor; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + getColorEnabled, + getColorEnabledAsync +}); diff --git a/node_modules/hono/dist/cjs/utils/compress.js b/node_modules/hono/dist/cjs/utils/compress.js new file mode 100644 index 000000000..a7c209841 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/compress.js @@ -0,0 +1,28 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var compress_exports = {}; +__export(compress_exports, { + COMPRESSIBLE_CONTENT_TYPE_REGEX: () => COMPRESSIBLE_CONTENT_TYPE_REGEX +}); +module.exports = __toCommonJS(compress_exports); +const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + COMPRESSIBLE_CONTENT_TYPE_REGEX +}); diff --git a/node_modules/hono/dist/cjs/utils/concurrent.js b/node_modules/hono/dist/cjs/utils/concurrent.js new file mode 100644 index 000000000..56fa28dd8 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/concurrent.js @@ -0,0 +1,62 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var concurrent_exports = {}; +__export(concurrent_exports, { + createPool: () => createPool +}); +module.exports = __toCommonJS(concurrent_exports); +const DEFAULT_CONCURRENCY = 1024; +const createPool = ({ + concurrency, + interval +} = {}) => { + concurrency ||= DEFAULT_CONCURRENCY; + if (concurrency === Infinity) { + return { + run: async (fn) => fn() + }; + } + const pool = /* @__PURE__ */ new Set(); + const run = async (fn, promise, resolve) => { + if (pool.size >= concurrency) { + promise ||= new Promise((r) => resolve = r); + setTimeout(() => run(fn, promise, resolve)); + return promise; + } + const marker = {}; + pool.add(marker); + const result = await fn(); + if (interval) { + setTimeout(() => pool.delete(marker), interval); + } else { + pool.delete(marker); + } + if (resolve) { + resolve(result); + return promise; + } else { + return result; + } + }; + return { run }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + createPool +}); diff --git a/node_modules/hono/dist/cjs/utils/constants.js b/node_modules/hono/dist/cjs/utils/constants.js new file mode 100644 index 000000000..08c127f0a --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/constants.js @@ -0,0 +1,28 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var constants_exports = {}; +__export(constants_exports, { + COMPOSED_HANDLER: () => COMPOSED_HANDLER +}); +module.exports = __toCommonJS(constants_exports); +const COMPOSED_HANDLER = "__COMPOSED_HANDLER"; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + COMPOSED_HANDLER +}); diff --git a/node_modules/hono/dist/cjs/utils/cookie.js b/node_modules/hono/dist/cjs/utils/cookie.js new file mode 100644 index 000000000..e8f11343a --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/cookie.js @@ -0,0 +1,173 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var cookie_exports = {}; +__export(cookie_exports, { + parse: () => parse, + parseSigned: () => parseSigned, + serialize: () => serialize, + serializeSigned: () => serializeSigned +}); +module.exports = __toCommonJS(cookie_exports); +var import_url = require("./url"); +const algorithm = { name: "HMAC", hash: "SHA-256" }; +const getCryptoKey = async (secret) => { + const secretBuf = typeof secret === "string" ? new TextEncoder().encode(secret) : secret; + return await crypto.subtle.importKey("raw", secretBuf, algorithm, false, ["sign", "verify"]); +}; +const makeSignature = async (value, secret) => { + const key = await getCryptoKey(secret); + const signature = await crypto.subtle.sign(algorithm.name, key, new TextEncoder().encode(value)); + return btoa(String.fromCharCode(...new Uint8Array(signature))); +}; +const verifySignature = async (base64Signature, value, secret) => { + try { + const signatureBinStr = atob(base64Signature); + const signature = new Uint8Array(signatureBinStr.length); + for (let i = 0, len = signatureBinStr.length; i < len; i++) { + signature[i] = signatureBinStr.charCodeAt(i); + } + return await crypto.subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value)); + } catch { + return false; + } +}; +const validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/; +const validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/; +const parse = (cookie, name) => { + if (name && cookie.indexOf(name) === -1) { + return {}; + } + const pairs = cookie.trim().split(";"); + const parsedCookie = {}; + for (let pairStr of pairs) { + pairStr = pairStr.trim(); + const valueStartPos = pairStr.indexOf("="); + if (valueStartPos === -1) { + continue; + } + const cookieName = pairStr.substring(0, valueStartPos).trim(); + if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName)) { + continue; + } + let cookieValue = pairStr.substring(valueStartPos + 1).trim(); + if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) { + cookieValue = cookieValue.slice(1, -1); + } + if (validCookieValueRegEx.test(cookieValue)) { + parsedCookie[cookieName] = cookieValue.indexOf("%") !== -1 ? (0, import_url.tryDecode)(cookieValue, import_url.decodeURIComponent_) : cookieValue; + if (name) { + break; + } + } + } + return parsedCookie; +}; +const parseSigned = async (cookie, secret, name) => { + const parsedCookie = {}; + const secretKey = await getCryptoKey(secret); + for (const [key, value] of Object.entries(parse(cookie, name))) { + const signatureStartPos = value.lastIndexOf("."); + if (signatureStartPos < 1) { + continue; + } + const signedValue = value.substring(0, signatureStartPos); + const signature = value.substring(signatureStartPos + 1); + if (signature.length !== 44 || !signature.endsWith("=")) { + continue; + } + const isVerified = await verifySignature(signature, signedValue, secretKey); + parsedCookie[key] = isVerified ? signedValue : false; + } + return parsedCookie; +}; +const _serialize = (name, value, opt = {}) => { + let cookie = `${name}=${value}`; + if (name.startsWith("__Secure-") && !opt.secure) { + throw new Error("__Secure- Cookie must have Secure attributes"); + } + if (name.startsWith("__Host-")) { + if (!opt.secure) { + throw new Error("__Host- Cookie must have Secure attributes"); + } + if (opt.path !== "/") { + throw new Error('__Host- Cookie must have Path attributes with "/"'); + } + if (opt.domain) { + throw new Error("__Host- Cookie must not have Domain attributes"); + } + } + if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) { + if (opt.maxAge > 3456e4) { + throw new Error( + "Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration." + ); + } + cookie += `; Max-Age=${opt.maxAge | 0}`; + } + if (opt.domain && opt.prefix !== "host") { + cookie += `; Domain=${opt.domain}`; + } + if (opt.path) { + cookie += `; Path=${opt.path}`; + } + if (opt.expires) { + if (opt.expires.getTime() - Date.now() > 3456e7) { + throw new Error( + "Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future." + ); + } + cookie += `; Expires=${opt.expires.toUTCString()}`; + } + if (opt.httpOnly) { + cookie += "; HttpOnly"; + } + if (opt.secure) { + cookie += "; Secure"; + } + if (opt.sameSite) { + cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`; + } + if (opt.priority) { + cookie += `; Priority=${opt.priority.charAt(0).toUpperCase() + opt.priority.slice(1)}`; + } + if (opt.partitioned) { + if (!opt.secure) { + throw new Error("Partitioned Cookie must have Secure attributes"); + } + cookie += "; Partitioned"; + } + return cookie; +}; +const serialize = (name, value, opt) => { + value = encodeURIComponent(value); + return _serialize(name, value, opt); +}; +const serializeSigned = async (name, value, secret, opt = {}) => { + const signature = await makeSignature(value, secret); + value = `${value}.${signature}`; + value = encodeURIComponent(value); + return _serialize(name, value, opt); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + parse, + parseSigned, + serialize, + serializeSigned +}); diff --git a/node_modules/hono/dist/cjs/utils/crypto.js b/node_modules/hono/dist/cjs/utils/crypto.js new file mode 100644 index 000000000..90e3757b8 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/crypto.js @@ -0,0 +1,70 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var crypto_exports = {}; +__export(crypto_exports, { + createHash: () => createHash, + md5: () => md5, + sha1: () => sha1, + sha256: () => sha256 +}); +module.exports = __toCommonJS(crypto_exports); +const sha256 = async (data) => { + const algorithm = { name: "SHA-256", alias: "sha256" }; + const hash = await createHash(data, algorithm); + return hash; +}; +const sha1 = async (data) => { + const algorithm = { name: "SHA-1", alias: "sha1" }; + const hash = await createHash(data, algorithm); + return hash; +}; +const md5 = async (data) => { + const algorithm = { name: "MD5", alias: "md5" }; + const hash = await createHash(data, algorithm); + return hash; +}; +const createHash = async (data, algorithm) => { + let sourceBuffer; + if (ArrayBuffer.isView(data) || data instanceof ArrayBuffer) { + sourceBuffer = data; + } else { + if (typeof data === "object") { + data = JSON.stringify(data); + } + sourceBuffer = new TextEncoder().encode(String(data)); + } + if (crypto && crypto.subtle) { + const buffer = await crypto.subtle.digest( + { + name: algorithm.name + }, + sourceBuffer + ); + const hash = Array.prototype.map.call(new Uint8Array(buffer), (x) => ("00" + x.toString(16)).slice(-2)).join(""); + return hash; + } + return null; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + createHash, + md5, + sha1, + sha256 +}); diff --git a/node_modules/hono/dist/cjs/utils/encode.js b/node_modules/hono/dist/cjs/utils/encode.js new file mode 100644 index 000000000..dcb6469d9 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/encode.js @@ -0,0 +1,55 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var encode_exports = {}; +__export(encode_exports, { + decodeBase64: () => decodeBase64, + decodeBase64Url: () => decodeBase64Url, + encodeBase64: () => encodeBase64, + encodeBase64Url: () => encodeBase64Url +}); +module.exports = __toCommonJS(encode_exports); +const decodeBase64Url = (str) => { + return decodeBase64(str.replace(/_|-/g, (m) => ({ _: "/", "-": "+" })[m] ?? m)); +}; +const encodeBase64Url = (buf) => encodeBase64(buf).replace(/\/|\+/g, (m) => ({ "/": "_", "+": "-" })[m] ?? m); +const encodeBase64 = (buf) => { + let binary = ""; + const bytes = new Uint8Array(buf); + for (let i = 0, len = bytes.length; i < len; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); +}; +const decodeBase64 = (str) => { + const binary = atob(str); + const bytes = new Uint8Array(new ArrayBuffer(binary.length)); + const half = binary.length / 2; + for (let i = 0, j = binary.length - 1; i <= half; i++, j--) { + bytes[i] = binary.charCodeAt(i); + bytes[j] = binary.charCodeAt(j); + } + return bytes; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + decodeBase64, + decodeBase64Url, + encodeBase64, + encodeBase64Url +}); diff --git a/node_modules/hono/dist/cjs/utils/filepath.js b/node_modules/hono/dist/cjs/utils/filepath.js new file mode 100644 index 000000000..59b6ff66f --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/filepath.js @@ -0,0 +1,59 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var filepath_exports = {}; +__export(filepath_exports, { + getFilePath: () => getFilePath, + getFilePathWithoutDefaultDocument: () => getFilePathWithoutDefaultDocument +}); +module.exports = __toCommonJS(filepath_exports); +const getFilePath = (options) => { + let filename = options.filename; + const defaultDocument = options.defaultDocument || "index.html"; + if (filename.endsWith("/")) { + filename = filename.concat(defaultDocument); + } else if (!filename.match(/\.[a-zA-Z0-9_-]+$/)) { + filename = filename.concat("/" + defaultDocument); + } + const path = getFilePathWithoutDefaultDocument({ + root: options.root, + filename + }); + return path; +}; +const getFilePathWithoutDefaultDocument = (options) => { + let root = options.root || ""; + let filename = options.filename; + if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) { + return; + } + filename = filename.replace(/^\.?[\/\\]/, ""); + filename = filename.replace(/\\/, "/"); + root = root.replace(/\/$/, ""); + let path = root ? root + "/" + filename : filename; + path = path.replace(/^\.?\//, ""); + if (root[0] !== "/" && path[0] === "/") { + return; + } + return path; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + getFilePath, + getFilePathWithoutDefaultDocument +}); diff --git a/node_modules/hono/dist/cjs/utils/handler.js b/node_modules/hono/dist/cjs/utils/handler.js new file mode 100644 index 000000000..c3d51dad8 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/handler.js @@ -0,0 +1,37 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var handler_exports = {}; +__export(handler_exports, { + findTargetHandler: () => findTargetHandler, + isMiddleware: () => isMiddleware +}); +module.exports = __toCommonJS(handler_exports); +var import_constants = require("./constants"); +const isMiddleware = (handler) => handler.length > 1; +const findTargetHandler = (handler) => { + return handler[import_constants.COMPOSED_HANDLER] ? ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + findTargetHandler(handler[import_constants.COMPOSED_HANDLER]) + ) : handler; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + findTargetHandler, + isMiddleware +}); diff --git a/node_modules/hono/dist/cjs/utils/headers.js b/node_modules/hono/dist/cjs/utils/headers.js new file mode 100644 index 000000000..e58ee3892 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/headers.js @@ -0,0 +1,16 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var headers_exports = {}; +module.exports = __toCommonJS(headers_exports); diff --git a/node_modules/hono/dist/cjs/utils/html.js b/node_modules/hono/dist/cjs/utils/html.js new file mode 100644 index 000000000..508c4bef0 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/html.js @@ -0,0 +1,151 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var html_exports = {}; +__export(html_exports, { + HtmlEscapedCallbackPhase: () => HtmlEscapedCallbackPhase, + escapeToBuffer: () => escapeToBuffer, + raw: () => raw, + resolveCallback: () => resolveCallback, + resolveCallbackSync: () => resolveCallbackSync, + stringBufferToString: () => stringBufferToString +}); +module.exports = __toCommonJS(html_exports); +const HtmlEscapedCallbackPhase = { + Stringify: 1, + BeforeStream: 2, + Stream: 3 +}; +const raw = (value, callbacks) => { + const escapedString = new String(value); + escapedString.isEscaped = true; + escapedString.callbacks = callbacks; + return escapedString; +}; +const escapeRe = /[&<>'"]/; +const stringBufferToString = async (buffer, callbacks) => { + let str = ""; + callbacks ||= []; + const resolvedBuffer = await Promise.all(buffer); + for (let i = resolvedBuffer.length - 1; ; i--) { + str += resolvedBuffer[i]; + i--; + if (i < 0) { + break; + } + let r = resolvedBuffer[i]; + if (typeof r === "object") { + callbacks.push(...r.callbacks || []); + } + const isEscaped = r.isEscaped; + r = await (typeof r === "object" ? r.toString() : r); + if (typeof r === "object") { + callbacks.push(...r.callbacks || []); + } + if (r.isEscaped ?? isEscaped) { + str += r; + } else { + const buf = [str]; + escapeToBuffer(r, buf); + str = buf[0]; + } + } + return raw(str, callbacks); +}; +const escapeToBuffer = (str, buffer) => { + const match = str.search(escapeRe); + if (match === -1) { + buffer[0] += str; + return; + } + let escape; + let index; + let lastIndex = 0; + for (index = match; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: + escape = """; + break; + case 39: + escape = "'"; + break; + case 38: + escape = "&"; + break; + case 60: + escape = "<"; + break; + case 62: + escape = ">"; + break; + default: + continue; + } + buffer[0] += str.substring(lastIndex, index) + escape; + lastIndex = index + 1; + } + buffer[0] += str.substring(lastIndex, index); +}; +const resolveCallbackSync = (str) => { + const callbacks = str.callbacks; + if (!callbacks?.length) { + return str; + } + const buffer = [str]; + const context = {}; + callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context })); + return buffer[0]; +}; +const resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => { + if (typeof str === "object" && !(str instanceof String)) { + if (!(str instanceof Promise)) { + str = str.toString(); + } + if (str instanceof Promise) { + str = await str; + } + } + const callbacks = str.callbacks; + if (!callbacks?.length) { + return Promise.resolve(str); + } + if (buffer) { + buffer[0] += str; + } else { + buffer = [str]; + } + const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then( + (res) => Promise.all( + res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer)) + ).then(() => buffer[0]) + ); + if (preserveCallbacks) { + return raw(await resStr, callbacks); + } else { + return resStr; + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + HtmlEscapedCallbackPhase, + escapeToBuffer, + raw, + resolveCallback, + resolveCallbackSync, + stringBufferToString +}); diff --git a/node_modules/hono/dist/cjs/utils/http-status.js b/node_modules/hono/dist/cjs/utils/http-status.js new file mode 100644 index 000000000..cbc154b18 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/http-status.js @@ -0,0 +1,16 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var http_status_exports = {}; +module.exports = __toCommonJS(http_status_exports); diff --git a/node_modules/hono/dist/cjs/utils/ipaddr.js b/node_modules/hono/dist/cjs/utils/ipaddr.js new file mode 100644 index 000000000..29d67b25d --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/ipaddr.js @@ -0,0 +1,129 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var ipaddr_exports = {}; +__export(ipaddr_exports, { + convertIPv4BinaryToString: () => convertIPv4BinaryToString, + convertIPv4ToBinary: () => convertIPv4ToBinary, + convertIPv6BinaryToString: () => convertIPv6BinaryToString, + convertIPv6ToBinary: () => convertIPv6ToBinary, + distinctRemoteAddr: () => distinctRemoteAddr, + expandIPv6: () => expandIPv6 +}); +module.exports = __toCommonJS(ipaddr_exports); +const expandIPv6 = (ipV6) => { + const sections = ipV6.split(":"); + if (IPV4_REGEX.test(sections.at(-1))) { + sections.splice( + -1, + 1, + ...convertIPv6BinaryToString(convertIPv4ToBinary(sections.at(-1))).substring(2).split(":") + // => ['7f00', '0001'] + ); + } + for (let i = 0; i < sections.length; i++) { + const node = sections[i]; + if (node !== "") { + sections[i] = node.padStart(4, "0"); + } else { + sections[i + 1] === "" && sections.splice(i + 1, 1); + sections[i] = new Array(8 - sections.length + 1).fill("0000").join(":"); + } + } + return sections.join(":"); +}; +const IPV4_REGEX = /^[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}$/; +const distinctRemoteAddr = (remoteAddr) => { + if (IPV4_REGEX.test(remoteAddr)) { + return "IPv4"; + } + if (remoteAddr.includes(":")) { + return "IPv6"; + } +}; +const convertIPv4ToBinary = (ipv4) => { + const parts = ipv4.split("."); + let result = 0n; + for (let i = 0; i < 4; i++) { + result <<= 8n; + result += BigInt(parts[i]); + } + return result; +}; +const convertIPv6ToBinary = (ipv6) => { + const sections = expandIPv6(ipv6).split(":"); + let result = 0n; + for (let i = 0; i < 8; i++) { + result <<= 16n; + result += BigInt(parseInt(sections[i], 16)); + } + return result; +}; +const convertIPv4BinaryToString = (ipV4) => { + const sections = []; + for (let i = 0; i < 4; i++) { + sections.push(ipV4 >> BigInt(8 * (3 - i)) & 0xffn); + } + return sections.join("."); +}; +const convertIPv6BinaryToString = (ipV6) => { + if (ipV6 >> 32n === 0xffffn) { + return `::ffff:${convertIPv4BinaryToString(ipV6 & 0xffffffffn)}`; + } + const sections = []; + for (let i = 0; i < 8; i++) { + sections.push((ipV6 >> BigInt(16 * (7 - i)) & 0xffffn).toString(16)); + } + let currentZeroStart = -1; + let maxZeroStart = -1; + let maxZeroEnd = -1; + for (let i = 0; i < 8; i++) { + if (sections[i] === "0") { + if (currentZeroStart === -1) { + currentZeroStart = i; + } + } else { + if (currentZeroStart > -1) { + if (i - currentZeroStart > maxZeroEnd - maxZeroStart) { + maxZeroStart = currentZeroStart; + maxZeroEnd = i; + } + currentZeroStart = -1; + } + } + } + if (currentZeroStart > -1) { + if (8 - currentZeroStart > maxZeroEnd - maxZeroStart) { + maxZeroStart = currentZeroStart; + maxZeroEnd = 8; + } + } + if (maxZeroStart !== -1) { + sections.splice(maxZeroStart, maxZeroEnd - maxZeroStart, ":"); + } + return sections.join(":").replace(/:{2,}/g, "::"); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + convertIPv4BinaryToString, + convertIPv4ToBinary, + convertIPv6BinaryToString, + convertIPv6ToBinary, + distinctRemoteAddr, + expandIPv6 +}); diff --git a/node_modules/hono/dist/cjs/utils/jwt/index.js b/node_modules/hono/dist/cjs/utils/jwt/index.js new file mode 100644 index 000000000..eade56149 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/jwt/index.js @@ -0,0 +1,29 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jwt_exports = {}; +__export(jwt_exports, { + Jwt: () => Jwt +}); +module.exports = __toCommonJS(jwt_exports); +var import_jwt = require("./jwt"); +const Jwt = { sign: import_jwt.sign, verify: import_jwt.verify, decode: import_jwt.decode, verifyWithJwks: import_jwt.verifyWithJwks }; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Jwt +}); diff --git a/node_modules/hono/dist/cjs/utils/jwt/jwa.js b/node_modules/hono/dist/cjs/utils/jwt/jwa.js new file mode 100644 index 000000000..5094b50e1 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/jwt/jwa.js @@ -0,0 +1,43 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jwa_exports = {}; +__export(jwa_exports, { + AlgorithmTypes: () => AlgorithmTypes +}); +module.exports = __toCommonJS(jwa_exports); +var AlgorithmTypes = /* @__PURE__ */ ((AlgorithmTypes2) => { + AlgorithmTypes2["HS256"] = "HS256"; + AlgorithmTypes2["HS384"] = "HS384"; + AlgorithmTypes2["HS512"] = "HS512"; + AlgorithmTypes2["RS256"] = "RS256"; + AlgorithmTypes2["RS384"] = "RS384"; + AlgorithmTypes2["RS512"] = "RS512"; + AlgorithmTypes2["PS256"] = "PS256"; + AlgorithmTypes2["PS384"] = "PS384"; + AlgorithmTypes2["PS512"] = "PS512"; + AlgorithmTypes2["ES256"] = "ES256"; + AlgorithmTypes2["ES384"] = "ES384"; + AlgorithmTypes2["ES512"] = "ES512"; + AlgorithmTypes2["EdDSA"] = "EdDSA"; + return AlgorithmTypes2; +})(AlgorithmTypes || {}); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + AlgorithmTypes +}); diff --git a/node_modules/hono/dist/cjs/utils/jwt/jws.js b/node_modules/hono/dist/cjs/utils/jwt/jws.js new file mode 100644 index 000000000..0f0c88e59 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/jwt/jws.js @@ -0,0 +1,216 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jws_exports = {}; +__export(jws_exports, { + signing: () => signing, + verifying: () => verifying +}); +module.exports = __toCommonJS(jws_exports); +var import_adapter = require("../../helper/adapter"); +var import_encode = require("../encode"); +var import_types = require("./types"); +var import_utf8 = require("./utf8"); +async function signing(privateKey, alg, data) { + const algorithm = getKeyAlgorithm(alg); + const cryptoKey = await importPrivateKey(privateKey, algorithm); + return await crypto.subtle.sign(algorithm, cryptoKey, data); +} +async function verifying(publicKey, alg, signature, data) { + const algorithm = getKeyAlgorithm(alg); + const cryptoKey = await importPublicKey(publicKey, algorithm); + return await crypto.subtle.verify(algorithm, cryptoKey, signature, data); +} +function pemToBinary(pem) { + return (0, import_encode.decodeBase64)(pem.replace(/-+(BEGIN|END).*/g, "").replace(/\s/g, "")); +} +async function importPrivateKey(key, alg) { + if (!crypto.subtle || !crypto.subtle.importKey) { + throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it."); + } + if (isCryptoKey(key)) { + if (key.type !== "private" && key.type !== "secret") { + throw new Error( + `unexpected key type: CryptoKey.type is ${key.type}, expected private or secret` + ); + } + return key; + } + const usages = [import_types.CryptoKeyUsage.Sign]; + if (typeof key === "object") { + return await crypto.subtle.importKey("jwk", key, alg, false, usages); + } + if (key.includes("PRIVATE")) { + return await crypto.subtle.importKey("pkcs8", pemToBinary(key), alg, false, usages); + } + return await crypto.subtle.importKey("raw", import_utf8.utf8Encoder.encode(key), alg, false, usages); +} +async function importPublicKey(key, alg) { + if (!crypto.subtle || !crypto.subtle.importKey) { + throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it."); + } + if (isCryptoKey(key)) { + if (key.type === "public" || key.type === "secret") { + return key; + } + key = await exportPublicJwkFrom(key); + } + if (typeof key === "string" && key.includes("PRIVATE")) { + const privateKey = await crypto.subtle.importKey("pkcs8", pemToBinary(key), alg, true, [ + import_types.CryptoKeyUsage.Sign + ]); + key = await exportPublicJwkFrom(privateKey); + } + const usages = [import_types.CryptoKeyUsage.Verify]; + if (typeof key === "object") { + return await crypto.subtle.importKey("jwk", key, alg, false, usages); + } + if (key.includes("PUBLIC")) { + return await crypto.subtle.importKey("spki", pemToBinary(key), alg, false, usages); + } + return await crypto.subtle.importKey("raw", import_utf8.utf8Encoder.encode(key), alg, false, usages); +} +async function exportPublicJwkFrom(privateKey) { + if (privateKey.type !== "private") { + throw new Error(`unexpected key type: ${privateKey.type}`); + } + if (!privateKey.extractable) { + throw new Error("unexpected private key is unextractable"); + } + const jwk = await crypto.subtle.exportKey("jwk", privateKey); + const { kty } = jwk; + const { alg, e, n } = jwk; + const { crv, x, y } = jwk; + return { kty, alg, e, n, crv, x, y, key_ops: [import_types.CryptoKeyUsage.Verify] }; +} +function getKeyAlgorithm(name) { + switch (name) { + case "HS256": + return { + name: "HMAC", + hash: { + name: "SHA-256" + } + }; + case "HS384": + return { + name: "HMAC", + hash: { + name: "SHA-384" + } + }; + case "HS512": + return { + name: "HMAC", + hash: { + name: "SHA-512" + } + }; + case "RS256": + return { + name: "RSASSA-PKCS1-v1_5", + hash: { + name: "SHA-256" + } + }; + case "RS384": + return { + name: "RSASSA-PKCS1-v1_5", + hash: { + name: "SHA-384" + } + }; + case "RS512": + return { + name: "RSASSA-PKCS1-v1_5", + hash: { + name: "SHA-512" + } + }; + case "PS256": + return { + name: "RSA-PSS", + hash: { + name: "SHA-256" + }, + saltLength: 32 + // 256 >> 3 + }; + case "PS384": + return { + name: "RSA-PSS", + hash: { + name: "SHA-384" + }, + saltLength: 48 + // 384 >> 3 + }; + case "PS512": + return { + name: "RSA-PSS", + hash: { + name: "SHA-512" + }, + saltLength: 64 + // 512 >> 3, + }; + case "ES256": + return { + name: "ECDSA", + hash: { + name: "SHA-256" + }, + namedCurve: "P-256" + }; + case "ES384": + return { + name: "ECDSA", + hash: { + name: "SHA-384" + }, + namedCurve: "P-384" + }; + case "ES512": + return { + name: "ECDSA", + hash: { + name: "SHA-512" + }, + namedCurve: "P-521" + }; + case "EdDSA": + return { + name: "Ed25519", + namedCurve: "Ed25519" + }; + default: + throw new import_types.JwtAlgorithmNotImplemented(name); + } +} +function isCryptoKey(key) { + const runtime = (0, import_adapter.getRuntimeKey)(); + if (runtime === "node" && !!crypto.webcrypto) { + return key instanceof crypto.webcrypto.CryptoKey; + } + return key instanceof CryptoKey; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + signing, + verifying +}); diff --git a/node_modules/hono/dist/cjs/utils/jwt/jwt.js b/node_modules/hono/dist/cjs/utils/jwt/jwt.js new file mode 100644 index 000000000..f4e8d2a24 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/jwt/jwt.js @@ -0,0 +1,210 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jwt_exports = {}; +__export(jwt_exports, { + decode: () => decode, + decodeHeader: () => decodeHeader, + isTokenHeader: () => isTokenHeader, + sign: () => sign, + verify: () => verify, + verifyWithJwks: () => verifyWithJwks +}); +module.exports = __toCommonJS(jwt_exports); +var import_encode = require("../../utils/encode"); +var import_jwa = require("./jwa"); +var import_jws = require("./jws"); +var import_types = require("./types"); +var import_utf8 = require("./utf8"); +const encodeJwtPart = (part) => (0, import_encode.encodeBase64Url)(import_utf8.utf8Encoder.encode(JSON.stringify(part)).buffer).replace(/=/g, ""); +const encodeSignaturePart = (buf) => (0, import_encode.encodeBase64Url)(buf).replace(/=/g, ""); +const decodeJwtPart = (part) => JSON.parse(import_utf8.utf8Decoder.decode((0, import_encode.decodeBase64Url)(part))); +function isTokenHeader(obj) { + if (typeof obj === "object" && obj !== null) { + const objWithAlg = obj; + return "alg" in objWithAlg && Object.values(import_jwa.AlgorithmTypes).includes(objWithAlg.alg) && (!("typ" in objWithAlg) || objWithAlg.typ === "JWT"); + } + return false; +} +const sign = async (payload, privateKey, alg = "HS256") => { + const encodedPayload = encodeJwtPart(payload); + let encodedHeader; + if (typeof privateKey === "object" && "alg" in privateKey) { + alg = privateKey.alg; + encodedHeader = encodeJwtPart({ alg, typ: "JWT", kid: privateKey.kid }); + } else { + encodedHeader = encodeJwtPart({ alg, typ: "JWT" }); + } + const partialToken = `${encodedHeader}.${encodedPayload}`; + const signaturePart = await (0, import_jws.signing)(privateKey, alg, import_utf8.utf8Encoder.encode(partialToken)); + const signature = encodeSignaturePart(signaturePart); + return `${partialToken}.${signature}`; +}; +const verify = async (token, publicKey, algOrOptions) => { + if (!algOrOptions) { + throw new import_types.JwtAlgorithmRequired(); + } + const { + alg, + iss, + nbf = true, + exp = true, + iat = true, + aud + } = typeof algOrOptions === "string" ? { alg: algOrOptions } : algOrOptions; + if (!alg) { + throw new import_types.JwtAlgorithmRequired(); + } + const tokenParts = token.split("."); + if (tokenParts.length !== 3) { + throw new import_types.JwtTokenInvalid(token); + } + const { header, payload } = decode(token); + if (!isTokenHeader(header)) { + throw new import_types.JwtHeaderInvalid(header); + } + if (header.alg !== alg) { + throw new import_types.JwtAlgorithmMismatch(alg, header.alg); + } + const now = Date.now() / 1e3 | 0; + if (nbf && payload.nbf && payload.nbf > now) { + throw new import_types.JwtTokenNotBefore(token); + } + if (exp && payload.exp && payload.exp <= now) { + throw new import_types.JwtTokenExpired(token); + } + if (iat && payload.iat && now < payload.iat) { + throw new import_types.JwtTokenIssuedAt(now, payload.iat); + } + if (iss) { + if (!payload.iss) { + throw new import_types.JwtTokenIssuer(iss, null); + } + if (typeof iss === "string" && payload.iss !== iss) { + throw new import_types.JwtTokenIssuer(iss, payload.iss); + } + if (iss instanceof RegExp && !iss.test(payload.iss)) { + throw new import_types.JwtTokenIssuer(iss, payload.iss); + } + } + if (aud) { + if (!payload.aud) { + throw new import_types.JwtPayloadRequiresAud(payload); + } + const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; + const matched = audiences.some( + (payloadAud) => aud instanceof RegExp ? aud.test(payloadAud) : typeof aud === "string" ? payloadAud === aud : Array.isArray(aud) && aud.includes(payloadAud) + ); + if (!matched) { + throw new import_types.JwtTokenAudience(aud, payload.aud); + } + } + const headerPayload = token.substring(0, token.lastIndexOf(".")); + const verified = await (0, import_jws.verifying)( + publicKey, + alg, + (0, import_encode.decodeBase64Url)(tokenParts[2]), + import_utf8.utf8Encoder.encode(headerPayload) + ); + if (!verified) { + throw new import_types.JwtTokenSignatureMismatched(token); + } + return payload; +}; +const symmetricAlgorithms = [ + import_jwa.AlgorithmTypes.HS256, + import_jwa.AlgorithmTypes.HS384, + import_jwa.AlgorithmTypes.HS512 +]; +const verifyWithJwks = async (token, options, init) => { + const verifyOpts = options.verification || {}; + const header = decodeHeader(token); + if (!isTokenHeader(header)) { + throw new import_types.JwtHeaderInvalid(header); + } + if (!header.kid) { + throw new import_types.JwtHeaderRequiresKid(header); + } + if (symmetricAlgorithms.includes(header.alg)) { + throw new import_types.JwtSymmetricAlgorithmNotAllowed(header.alg); + } + if (!options.allowedAlgorithms.includes(header.alg)) { + throw new import_types.JwtAlgorithmNotAllowed(header.alg, options.allowedAlgorithms); + } + if (options.jwks_uri) { + const response = await fetch(options.jwks_uri, init); + if (!response.ok) { + throw new Error(`failed to fetch JWKS from ${options.jwks_uri}`); + } + const data = await response.json(); + if (!data.keys) { + throw new Error('invalid JWKS response. "keys" field is missing'); + } + if (!Array.isArray(data.keys)) { + throw new Error('invalid JWKS response. "keys" field is not an array'); + } + if (options.keys) { + options.keys.push(...data.keys); + } else { + options.keys = data.keys; + } + } else if (!options.keys) { + throw new Error('verifyWithJwks requires options for either "keys" or "jwks_uri" or both'); + } + const matchingKey = options.keys.find((key) => key.kid === header.kid); + if (!matchingKey) { + throw new import_types.JwtTokenInvalid(token); + } + if (matchingKey.alg && matchingKey.alg !== header.alg) { + throw new import_types.JwtAlgorithmMismatch(matchingKey.alg, header.alg); + } + return await verify(token, matchingKey, { + alg: header.alg, + ...verifyOpts + }); +}; +const decode = (token) => { + try { + const [h, p] = token.split("."); + const header = decodeJwtPart(h); + const payload = decodeJwtPart(p); + return { + header, + payload + }; + } catch { + throw new import_types.JwtTokenInvalid(token); + } +}; +const decodeHeader = (token) => { + try { + const [h] = token.split("."); + return decodeJwtPart(h); + } catch { + throw new import_types.JwtTokenInvalid(token); + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + decode, + decodeHeader, + isTokenHeader, + sign, + verify, + verifyWithJwks +}); diff --git a/node_modules/hono/dist/cjs/utils/jwt/types.js b/node_modules/hono/dist/cjs/utils/jwt/types.js new file mode 100644 index 000000000..855f79319 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/jwt/types.js @@ -0,0 +1,162 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var types_exports = {}; +__export(types_exports, { + CryptoKeyUsage: () => CryptoKeyUsage, + JwtAlgorithmMismatch: () => JwtAlgorithmMismatch, + JwtAlgorithmNotAllowed: () => JwtAlgorithmNotAllowed, + JwtAlgorithmNotImplemented: () => JwtAlgorithmNotImplemented, + JwtAlgorithmRequired: () => JwtAlgorithmRequired, + JwtHeaderInvalid: () => JwtHeaderInvalid, + JwtHeaderRequiresKid: () => JwtHeaderRequiresKid, + JwtPayloadRequiresAud: () => JwtPayloadRequiresAud, + JwtSymmetricAlgorithmNotAllowed: () => JwtSymmetricAlgorithmNotAllowed, + JwtTokenAudience: () => JwtTokenAudience, + JwtTokenExpired: () => JwtTokenExpired, + JwtTokenInvalid: () => JwtTokenInvalid, + JwtTokenIssuedAt: () => JwtTokenIssuedAt, + JwtTokenIssuer: () => JwtTokenIssuer, + JwtTokenNotBefore: () => JwtTokenNotBefore, + JwtTokenSignatureMismatched: () => JwtTokenSignatureMismatched +}); +module.exports = __toCommonJS(types_exports); +class JwtAlgorithmNotImplemented extends Error { + constructor(alg) { + super(`${alg} is not an implemented algorithm`); + this.name = "JwtAlgorithmNotImplemented"; + } +} +class JwtAlgorithmRequired extends Error { + constructor() { + super('JWT verification requires "alg" option to be specified'); + this.name = "JwtAlgorithmRequired"; + } +} +class JwtAlgorithmMismatch extends Error { + constructor(expected, actual) { + super(`JWT algorithm mismatch: expected "${expected}", got "${actual}"`); + this.name = "JwtAlgorithmMismatch"; + } +} +class JwtTokenInvalid extends Error { + constructor(token) { + super(`invalid JWT token: ${token}`); + this.name = "JwtTokenInvalid"; + } +} +class JwtTokenNotBefore extends Error { + constructor(token) { + super(`token (${token}) is being used before it's valid`); + this.name = "JwtTokenNotBefore"; + } +} +class JwtTokenExpired extends Error { + constructor(token) { + super(`token (${token}) expired`); + this.name = "JwtTokenExpired"; + } +} +class JwtTokenIssuedAt extends Error { + constructor(currentTimestamp, iat) { + super( + `Invalid "iat" claim, must be a valid number lower than "${currentTimestamp}" (iat: "${iat}")` + ); + this.name = "JwtTokenIssuedAt"; + } +} +class JwtTokenIssuer extends Error { + constructor(expected, iss) { + super(`expected issuer "${expected}", got ${iss ? `"${iss}"` : "none"} `); + this.name = "JwtTokenIssuer"; + } +} +class JwtHeaderInvalid extends Error { + constructor(header) { + super(`jwt header is invalid: ${JSON.stringify(header)}`); + this.name = "JwtHeaderInvalid"; + } +} +class JwtHeaderRequiresKid extends Error { + constructor(header) { + super(`required "kid" in jwt header: ${JSON.stringify(header)}`); + this.name = "JwtHeaderRequiresKid"; + } +} +class JwtSymmetricAlgorithmNotAllowed extends Error { + constructor(alg) { + super(`symmetric algorithm "${alg}" is not allowed for JWK verification`); + this.name = "JwtSymmetricAlgorithmNotAllowed"; + } +} +class JwtAlgorithmNotAllowed extends Error { + constructor(alg, allowedAlgorithms) { + super(`algorithm "${alg}" is not in the allowed list: [${allowedAlgorithms.join(", ")}]`); + this.name = "JwtAlgorithmNotAllowed"; + } +} +class JwtTokenSignatureMismatched extends Error { + constructor(token) { + super(`token(${token}) signature mismatched`); + this.name = "JwtTokenSignatureMismatched"; + } +} +class JwtPayloadRequiresAud extends Error { + constructor(payload) { + super(`required "aud" in jwt payload: ${JSON.stringify(payload)}`); + this.name = "JwtPayloadRequiresAud"; + } +} +class JwtTokenAudience extends Error { + constructor(expected, aud) { + super( + `expected audience "${Array.isArray(expected) ? expected.join(", ") : expected}", got "${aud}"` + ); + this.name = "JwtTokenAudience"; + } +} +var CryptoKeyUsage = /* @__PURE__ */ ((CryptoKeyUsage2) => { + CryptoKeyUsage2["Encrypt"] = "encrypt"; + CryptoKeyUsage2["Decrypt"] = "decrypt"; + CryptoKeyUsage2["Sign"] = "sign"; + CryptoKeyUsage2["Verify"] = "verify"; + CryptoKeyUsage2["DeriveKey"] = "deriveKey"; + CryptoKeyUsage2["DeriveBits"] = "deriveBits"; + CryptoKeyUsage2["WrapKey"] = "wrapKey"; + CryptoKeyUsage2["UnwrapKey"] = "unwrapKey"; + return CryptoKeyUsage2; +})(CryptoKeyUsage || {}); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + CryptoKeyUsage, + JwtAlgorithmMismatch, + JwtAlgorithmNotAllowed, + JwtAlgorithmNotImplemented, + JwtAlgorithmRequired, + JwtHeaderInvalid, + JwtHeaderRequiresKid, + JwtPayloadRequiresAud, + JwtSymmetricAlgorithmNotAllowed, + JwtTokenAudience, + JwtTokenExpired, + JwtTokenInvalid, + JwtTokenIssuedAt, + JwtTokenIssuer, + JwtTokenNotBefore, + JwtTokenSignatureMismatched +}); diff --git a/node_modules/hono/dist/cjs/utils/jwt/utf8.js b/node_modules/hono/dist/cjs/utils/jwt/utf8.js new file mode 100644 index 000000000..9afa12386 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/jwt/utf8.js @@ -0,0 +1,31 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var utf8_exports = {}; +__export(utf8_exports, { + utf8Decoder: () => utf8Decoder, + utf8Encoder: () => utf8Encoder +}); +module.exports = __toCommonJS(utf8_exports); +const utf8Encoder = new TextEncoder(); +const utf8Decoder = new TextDecoder(); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + utf8Decoder, + utf8Encoder +}); diff --git a/node_modules/hono/dist/cjs/utils/mime.js b/node_modules/hono/dist/cjs/utils/mime.js new file mode 100644 index 000000000..f3b1b82eb --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/mime.js @@ -0,0 +1,109 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var mime_exports = {}; +__export(mime_exports, { + getExtension: () => getExtension, + getMimeType: () => getMimeType, + mimes: () => baseMimes +}); +module.exports = __toCommonJS(mime_exports); +const getMimeType = (filename, mimes = baseMimes) => { + const regexp = /\.([a-zA-Z0-9]+?)$/; + const match = filename.match(regexp); + if (!match) { + return; + } + let mimeType = mimes[match[1]]; + if (mimeType && mimeType.startsWith("text")) { + mimeType += "; charset=utf-8"; + } + return mimeType; +}; +const getExtension = (mimeType) => { + for (const ext in baseMimes) { + if (baseMimes[ext] === mimeType) { + return ext; + } + } +}; +const _baseMimes = { + aac: "audio/aac", + avi: "video/x-msvideo", + avif: "image/avif", + av1: "video/av1", + bin: "application/octet-stream", + bmp: "image/bmp", + css: "text/css", + csv: "text/csv", + eot: "application/vnd.ms-fontobject", + epub: "application/epub+zip", + gif: "image/gif", + gz: "application/gzip", + htm: "text/html", + html: "text/html", + ico: "image/x-icon", + ics: "text/calendar", + jpeg: "image/jpeg", + jpg: "image/jpeg", + js: "text/javascript", + json: "application/json", + jsonld: "application/ld+json", + map: "application/json", + mid: "audio/x-midi", + midi: "audio/x-midi", + mjs: "text/javascript", + mp3: "audio/mpeg", + mp4: "video/mp4", + mpeg: "video/mpeg", + oga: "audio/ogg", + ogv: "video/ogg", + ogx: "application/ogg", + opus: "audio/opus", + otf: "font/otf", + pdf: "application/pdf", + png: "image/png", + rtf: "application/rtf", + svg: "image/svg+xml", + tif: "image/tiff", + tiff: "image/tiff", + ts: "video/mp2t", + ttf: "font/ttf", + txt: "text/plain", + wasm: "application/wasm", + webm: "video/webm", + weba: "audio/webm", + webmanifest: "application/manifest+json", + webp: "image/webp", + woff: "font/woff", + woff2: "font/woff2", + xhtml: "application/xhtml+xml", + xml: "application/xml", + zip: "application/zip", + "3gp": "video/3gpp", + "3g2": "video/3gpp2", + gltf: "model/gltf+json", + glb: "model/gltf-binary" +}; +const baseMimes = _baseMimes; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + getExtension, + getMimeType, + mimes +}); diff --git a/node_modules/hono/dist/cjs/utils/stream.js b/node_modules/hono/dist/cjs/utils/stream.js new file mode 100644 index 000000000..bbcdc0183 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/stream.js @@ -0,0 +1,102 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var stream_exports = {}; +__export(stream_exports, { + StreamingApi: () => StreamingApi +}); +module.exports = __toCommonJS(stream_exports); +class StreamingApi { + writer; + encoder; + writable; + abortSubscribers = []; + responseReadable; + /** + * Whether the stream has been aborted. + */ + aborted = false; + /** + * Whether the stream has been closed normally. + */ + closed = false; + constructor(writable, _readable) { + this.writable = writable; + this.writer = writable.getWriter(); + this.encoder = new TextEncoder(); + const reader = _readable.getReader(); + this.abortSubscribers.push(async () => { + await reader.cancel(); + }); + this.responseReadable = new ReadableStream({ + async pull(controller) { + const { done, value } = await reader.read(); + done ? controller.close() : controller.enqueue(value); + }, + cancel: () => { + this.abort(); + } + }); + } + async write(input) { + try { + if (typeof input === "string") { + input = this.encoder.encode(input); + } + await this.writer.write(input); + } catch { + } + return this; + } + async writeln(input) { + await this.write(input + "\n"); + return this; + } + sleep(ms) { + return new Promise((res) => setTimeout(res, ms)); + } + async close() { + try { + await this.writer.close(); + } catch { + } + this.closed = true; + } + async pipe(body) { + this.writer.releaseLock(); + await body.pipeTo(this.writable, { preventClose: true }); + this.writer = this.writable.getWriter(); + } + onAbort(listener) { + this.abortSubscribers.push(listener); + } + /** + * Abort the stream. + * You can call this method when stream is aborted by external event. + */ + abort() { + if (!this.aborted) { + this.aborted = true; + this.abortSubscribers.forEach((subscriber) => subscriber()); + } + } +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + StreamingApi +}); diff --git a/node_modules/hono/dist/cjs/utils/types.js b/node_modules/hono/dist/cjs/utils/types.js new file mode 100644 index 000000000..43ae53610 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/types.js @@ -0,0 +1,16 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var types_exports = {}; +module.exports = __toCommonJS(types_exports); diff --git a/node_modules/hono/dist/cjs/utils/url.js b/node_modules/hono/dist/cjs/utils/url.js new file mode 100644 index 000000000..21ddfab67 --- /dev/null +++ b/node_modules/hono/dist/cjs/utils/url.js @@ -0,0 +1,253 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var url_exports = {}; +__export(url_exports, { + checkOptionalParameter: () => checkOptionalParameter, + decodeURIComponent_: () => decodeURIComponent_, + getPath: () => getPath, + getPathNoStrict: () => getPathNoStrict, + getPattern: () => getPattern, + getQueryParam: () => getQueryParam, + getQueryParams: () => getQueryParams, + getQueryStrings: () => getQueryStrings, + mergePath: () => mergePath, + splitPath: () => splitPath, + splitRoutingPath: () => splitRoutingPath, + tryDecode: () => tryDecode +}); +module.exports = __toCommonJS(url_exports); +const splitPath = (path) => { + const paths = path.split("/"); + if (paths[0] === "") { + paths.shift(); + } + return paths; +}; +const splitRoutingPath = (routePath) => { + const { groups, path } = extractGroupsFromPath(routePath); + const paths = splitPath(path); + return replaceGroupMarks(paths, groups); +}; +const extractGroupsFromPath = (path) => { + const groups = []; + path = path.replace(/\{[^}]+\}/g, (match, index) => { + const mark = `@${index}`; + groups.push([mark, match]); + return mark; + }); + return { groups, path }; +}; +const replaceGroupMarks = (paths, groups) => { + for (let i = groups.length - 1; i >= 0; i--) { + const [mark] = groups[i]; + for (let j = paths.length - 1; j >= 0; j--) { + if (paths[j].includes(mark)) { + paths[j] = paths[j].replace(mark, groups[i][1]); + break; + } + } + } + return paths; +}; +const patternCache = {}; +const getPattern = (label, next) => { + if (label === "*") { + return "*"; + } + const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); + if (match) { + const cacheKey = `${label}#${next}`; + if (!patternCache[cacheKey]) { + if (match[2]) { + patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)]; + } else { + patternCache[cacheKey] = [label, match[1], true]; + } + } + return patternCache[cacheKey]; + } + return null; +}; +const tryDecode = (str, decoder) => { + try { + return decoder(str); + } catch { + return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => { + try { + return decoder(match); + } catch { + return match; + } + }); + } +}; +const tryDecodeURI = (str) => tryDecode(str, decodeURI); +const getPath = (request) => { + const url = request.url; + const start = url.indexOf("/", url.indexOf(":") + 4); + let i = start; + for (; i < url.length; i++) { + const charCode = url.charCodeAt(i); + if (charCode === 37) { + const queryIndex = url.indexOf("?", i); + const path = url.slice(start, queryIndex === -1 ? void 0 : queryIndex); + return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path); + } else if (charCode === 63) { + break; + } + } + return url.slice(start, i); +}; +const getQueryStrings = (url) => { + const queryIndex = url.indexOf("?", 8); + return queryIndex === -1 ? "" : "?" + url.slice(queryIndex + 1); +}; +const getPathNoStrict = (request) => { + const result = getPath(request); + return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result; +}; +const mergePath = (base, sub, ...rest) => { + if (rest.length) { + sub = mergePath(sub, ...rest); + } + return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`; +}; +const checkOptionalParameter = (path) => { + if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) { + return null; + } + const segments = path.split("/"); + const results = []; + let basePath = ""; + segments.forEach((segment) => { + if (segment !== "" && !/\:/.test(segment)) { + basePath += "/" + segment; + } else if (/\:/.test(segment)) { + if (/\?/.test(segment)) { + if (results.length === 0 && basePath === "") { + results.push("/"); + } else { + results.push(basePath); + } + const optionalSegment = segment.replace("?", ""); + basePath += "/" + optionalSegment; + results.push(basePath); + } else { + basePath += "/" + segment; + } + } + }); + return results.filter((v, i, a) => a.indexOf(v) === i); +}; +const _decodeURI = (value) => { + if (!/[%+]/.test(value)) { + return value; + } + if (value.indexOf("+") !== -1) { + value = value.replace(/\+/g, " "); + } + return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value; +}; +const _getQueryParam = (url, key, multiple) => { + let encoded; + if (!multiple && key && !/[%+]/.test(key)) { + let keyIndex2 = url.indexOf("?", 8); + if (keyIndex2 === -1) { + return void 0; + } + if (!url.startsWith(key, keyIndex2 + 1)) { + keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1); + } + while (keyIndex2 !== -1) { + const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1); + if (trailingKeyCode === 61) { + const valueIndex = keyIndex2 + key.length + 2; + const endIndex = url.indexOf("&", valueIndex); + return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex)); + } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) { + return ""; + } + keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1); + } + encoded = /[%+]/.test(url); + if (!encoded) { + return void 0; + } + } + const results = {}; + encoded ??= /[%+]/.test(url); + let keyIndex = url.indexOf("?", 8); + while (keyIndex !== -1) { + const nextKeyIndex = url.indexOf("&", keyIndex + 1); + let valueIndex = url.indexOf("=", keyIndex); + if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) { + valueIndex = -1; + } + let name = url.slice( + keyIndex + 1, + valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex + ); + if (encoded) { + name = _decodeURI(name); + } + keyIndex = nextKeyIndex; + if (name === "") { + continue; + } + let value; + if (valueIndex === -1) { + value = ""; + } else { + value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex); + if (encoded) { + value = _decodeURI(value); + } + } + if (multiple) { + if (!(results[name] && Array.isArray(results[name]))) { + results[name] = []; + } + ; + results[name].push(value); + } else { + results[name] ??= value; + } + } + return key ? results[key] : results; +}; +const getQueryParam = _getQueryParam; +const getQueryParams = (url, key) => { + return _getQueryParam(url, key, true); +}; +const decodeURIComponent_ = decodeURIComponent; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + checkOptionalParameter, + decodeURIComponent_, + getPath, + getPathNoStrict, + getPattern, + getQueryParam, + getQueryParams, + getQueryStrings, + mergePath, + splitPath, + splitRoutingPath, + tryDecode +}); diff --git a/node_modules/hono/dist/cjs/validator/index.js b/node_modules/hono/dist/cjs/validator/index.js new file mode 100644 index 000000000..cbaa47f73 --- /dev/null +++ b/node_modules/hono/dist/cjs/validator/index.js @@ -0,0 +1,28 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var validator_exports = {}; +__export(validator_exports, { + validator: () => import_validator.validator +}); +module.exports = __toCommonJS(validator_exports); +var import_validator = require("./validator"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + validator +}); diff --git a/node_modules/hono/dist/cjs/validator/utils.js b/node_modules/hono/dist/cjs/validator/utils.js new file mode 100644 index 000000000..cfe4f8afa --- /dev/null +++ b/node_modules/hono/dist/cjs/validator/utils.js @@ -0,0 +1,16 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var utils_exports = {}; +module.exports = __toCommonJS(utils_exports); diff --git a/node_modules/hono/dist/cjs/validator/validator.js b/node_modules/hono/dist/cjs/validator/validator.js new file mode 100644 index 000000000..552cd6007 --- /dev/null +++ b/node_modules/hono/dist/cjs/validator/validator.js @@ -0,0 +1,109 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var validator_exports = {}; +__export(validator_exports, { + validator: () => validator +}); +module.exports = __toCommonJS(validator_exports); +var import_cookie = require("../helper/cookie"); +var import_http_exception = require("../http-exception"); +var import_buffer = require("../utils/buffer"); +const jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/; +const multipartRegex = /^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/; +const urlencodedRegex = /^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/; +const validator = (target, validationFunc) => { + return async (c, next) => { + let value = {}; + const contentType = c.req.header("Content-Type"); + switch (target) { + case "json": + if (!contentType || !jsonRegex.test(contentType)) { + break; + } + try { + value = await c.req.json(); + } catch { + const message = "Malformed JSON in request body"; + throw new import_http_exception.HTTPException(400, { message }); + } + break; + case "form": { + if (!contentType || !(multipartRegex.test(contentType) || urlencodedRegex.test(contentType))) { + break; + } + let formData; + if (c.req.bodyCache.formData) { + formData = await c.req.bodyCache.formData; + } else { + try { + const arrayBuffer = await c.req.arrayBuffer(); + formData = await (0, import_buffer.bufferToFormData)(arrayBuffer, contentType); + c.req.bodyCache.formData = formData; + } catch (e) { + let message = "Malformed FormData request."; + message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`; + throw new import_http_exception.HTTPException(400, { message }); + } + } + const form = {}; + formData.forEach((value2, key) => { + if (key.endsWith("[]")) { + ; + (form[key] ??= []).push(value2); + } else if (Array.isArray(form[key])) { + ; + form[key].push(value2); + } else if (key in form) { + form[key] = [form[key], value2]; + } else { + form[key] = value2; + } + }); + value = form; + break; + } + case "query": + value = Object.fromEntries( + Object.entries(c.req.queries()).map(([k, v]) => { + return v.length === 1 ? [k, v[0]] : [k, v]; + }) + ); + break; + case "param": + value = c.req.param(); + break; + case "header": + value = c.req.header(); + break; + case "cookie": + value = (0, import_cookie.getCookie)(c); + break; + } + const res = await validationFunc(value, c); + if (res instanceof Response) { + return res; + } + c.req.addValidatedData(target, res); + return await next(); + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + validator +}); diff --git a/node_modules/hono/dist/client/client.js b/node_modules/hono/dist/client/client.js new file mode 100644 index 000000000..6b9ef67a6 --- /dev/null +++ b/node_modules/hono/dist/client/client.js @@ -0,0 +1,174 @@ +// src/client/client.ts +import { serialize } from "../utils/cookie.js"; +import { + buildSearchParams, + deepMerge, + mergePath, + removeIndexString, + replaceUrlParam, + replaceUrlProtocol +} from "./utils.js"; +var createProxy = (callback, path) => { + const proxy = new Proxy(() => { + }, { + get(_obj, key) { + if (typeof key !== "string" || key === "then") { + return void 0; + } + return createProxy(callback, [...path, key]); + }, + apply(_1, _2, args) { + return callback({ + path, + args + }); + } + }); + return proxy; +}; +var ClientRequestImpl = class { + url; + method; + buildSearchParams; + queryParams = void 0; + pathParams = {}; + rBody; + cType = void 0; + constructor(url, method, options) { + this.url = url; + this.method = method; + this.buildSearchParams = options.buildSearchParams; + } + fetch = async (args, opt) => { + if (args) { + if (args.query) { + this.queryParams = this.buildSearchParams(args.query); + } + if (args.form) { + const form = new FormData(); + for (const [k, v] of Object.entries(args.form)) { + if (Array.isArray(v)) { + for (const v2 of v) { + form.append(k, v2); + } + } else { + form.append(k, v); + } + } + this.rBody = form; + } + if (args.json) { + this.rBody = JSON.stringify(args.json); + this.cType = "application/json"; + } + if (args.param) { + this.pathParams = args.param; + } + } + let methodUpperCase = this.method.toUpperCase(); + const headerValues = { + ...args?.header, + ...typeof opt?.headers === "function" ? await opt.headers() : opt?.headers + }; + if (args?.cookie) { + const cookies = []; + for (const [key, value] of Object.entries(args.cookie)) { + cookies.push(serialize(key, value, { path: "/" })); + } + headerValues["Cookie"] = cookies.join(","); + } + if (this.cType) { + headerValues["Content-Type"] = this.cType; + } + const headers = new Headers(headerValues ?? void 0); + let url = this.url; + url = removeIndexString(url); + url = replaceUrlParam(url, this.pathParams); + if (this.queryParams) { + url = url + "?" + this.queryParams.toString(); + } + methodUpperCase = this.method.toUpperCase(); + const setBody = !(methodUpperCase === "GET" || methodUpperCase === "HEAD"); + return (opt?.fetch || fetch)(url, { + body: setBody ? this.rBody : void 0, + method: methodUpperCase, + headers, + ...opt?.init + }); + }; +}; +var hc = (baseUrl, options) => createProxy(function proxyCallback(opts) { + const buildSearchParamsOption = options?.buildSearchParams ?? buildSearchParams; + const parts = [...opts.path]; + const lastParts = parts.slice(-3).reverse(); + if (lastParts[0] === "toString") { + if (lastParts[1] === "name") { + return lastParts[2] || ""; + } + return proxyCallback.toString(); + } + if (lastParts[0] === "valueOf") { + if (lastParts[1] === "name") { + return lastParts[2] || ""; + } + return proxyCallback; + } + let method = ""; + if (/^\$/.test(lastParts[0])) { + const last = parts.pop(); + if (last) { + method = last.replace(/^\$/, ""); + } + } + const path = parts.join("/"); + const url = mergePath(baseUrl, path); + if (method === "url") { + let result = url; + if (opts.args[0]) { + if (opts.args[0].param) { + result = replaceUrlParam(url, opts.args[0].param); + } + if (opts.args[0].query) { + result = result + "?" + buildSearchParamsOption(opts.args[0].query).toString(); + } + } + result = removeIndexString(result); + return new URL(result); + } + if (method === "ws") { + const webSocketUrl = replaceUrlProtocol( + opts.args[0] && opts.args[0].param ? replaceUrlParam(url, opts.args[0].param) : url, + "ws" + ); + const targetUrl = new URL(webSocketUrl); + const queryParams = opts.args[0]?.query; + if (queryParams) { + Object.entries(queryParams).forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((item) => targetUrl.searchParams.append(key, item)); + } else { + targetUrl.searchParams.set(key, value); + } + }); + } + const establishWebSocket = (...args) => { + if (options?.webSocket !== void 0 && typeof options.webSocket === "function") { + return options.webSocket(...args); + } + return new WebSocket(...args); + }; + return establishWebSocket(targetUrl.toString()); + } + const req = new ClientRequestImpl(url, method, { + buildSearchParams: buildSearchParamsOption + }); + if (method) { + options ??= {}; + const args = deepMerge(options, { ...opts.args[1] }); + return req.fetch(opts.args[0], args); + } + return req; +}, []); +export { + hc +}; diff --git a/node_modules/hono/dist/client/fetch-result-please.js b/node_modules/hono/dist/client/fetch-result-please.js new file mode 100644 index 000000000..9f7a81345 --- /dev/null +++ b/node_modules/hono/dist/client/fetch-result-please.js @@ -0,0 +1,62 @@ +// src/client/fetch-result-please.ts +var nullBodyResponses = /* @__PURE__ */ new Set([101, 204, 205, 304]); +async function fetchRP(fetchRes) { + const _fetchRes = await fetchRes; + const hasBody = (_fetchRes.body || _fetchRes._bodyInit) && !nullBodyResponses.has(_fetchRes.status); + if (hasBody) { + const responseType = detectResponseType(_fetchRes); + _fetchRes._data = await _fetchRes[responseType](); + } + if (!_fetchRes.ok) { + throw new DetailedError(`${_fetchRes.status} ${_fetchRes.statusText}`, { + statusCode: _fetchRes?.status, + detail: { + data: _fetchRes?._data, + statusText: _fetchRes?.statusText + } + }); + } + return _fetchRes._data; +} +var DetailedError = class extends Error { + /** + * Additional `message` that will be logged AND returned to client + */ + detail; + /** + * Additional `code` that will be logged AND returned to client + */ + code; + /** + * Additional value that will be logged AND NOT returned to client + */ + log; + /** + * Optionally set the status code to return, in a web server context + */ + statusCode; + constructor(message, options = {}) { + super(message); + this.name = "DetailedError"; + this.log = options.log; + this.detail = options.detail; + this.code = options.code; + this.statusCode = options.statusCode; + } +}; +var jsonRegex = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(?:;.+)?$/i; +function detectResponseType(response) { + const _contentType = response.headers.get("content-type"); + if (!_contentType) { + return "text"; + } + const contentType = _contentType.split(";").shift(); + if (jsonRegex.test(contentType)) { + return "json"; + } + return "text"; +} +export { + DetailedError, + fetchRP +}; diff --git a/node_modules/hono/dist/client/index.js b/node_modules/hono/dist/client/index.js new file mode 100644 index 000000000..e133afaf2 --- /dev/null +++ b/node_modules/hono/dist/client/index.js @@ -0,0 +1,8 @@ +// src/client/index.ts +import { hc } from "./client.js"; +import { parseResponse, DetailedError } from "./utils.js"; +export { + DetailedError, + hc, + parseResponse +}; diff --git a/node_modules/hono/dist/client/types.js b/node_modules/hono/dist/client/types.js new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/hono/dist/client/utils.js b/node_modules/hono/dist/client/utils.js new file mode 100644 index 000000000..1842ff88a --- /dev/null +++ b/node_modules/hono/dist/client/utils.js @@ -0,0 +1,76 @@ +// src/client/utils.ts +import { fetchRP, DetailedError } from "./fetch-result-please.js"; +var mergePath = (base, path) => { + base = base.replace(/\/+$/, ""); + base = base + "/"; + path = path.replace(/^\/+/, ""); + return base + path; +}; +var replaceUrlParam = (urlString, params) => { + for (const [k, v] of Object.entries(params)) { + const reg = new RegExp("/:" + k + "(?:{[^/]+})?\\??"); + urlString = urlString.replace(reg, v ? `/${v}` : ""); + } + return urlString; +}; +var buildSearchParams = (query) => { + const searchParams = new URLSearchParams(); + for (const [k, v] of Object.entries(query)) { + if (v === void 0) { + continue; + } + if (Array.isArray(v)) { + for (const v2 of v) { + searchParams.append(k, v2); + } + } else { + searchParams.set(k, v); + } + } + return searchParams; +}; +var replaceUrlProtocol = (urlString, protocol) => { + switch (protocol) { + case "ws": + return urlString.replace(/^http/, "ws"); + case "http": + return urlString.replace(/^ws/, "http"); + } +}; +var removeIndexString = (urlString) => { + if (/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(urlString)) { + return urlString.replace(/\/index(?=\?|$)/, "/"); + } + return urlString.replace(/\/index(?=\?|$)/, ""); +}; +function isObject(item) { + return typeof item === "object" && item !== null && !Array.isArray(item); +} +function deepMerge(target, source) { + if (!isObject(target) && !isObject(source)) { + return source; + } + const merged = { ...target }; + for (const key in source) { + const value = source[key]; + if (isObject(merged[key]) && isObject(value)) { + merged[key] = deepMerge(merged[key], value); + } else { + merged[key] = value; + } + } + return merged; +} +async function parseResponse(fetchRes) { + return fetchRP(fetchRes); +} +export { + DetailedError, + buildSearchParams, + deepMerge, + mergePath, + parseResponse, + removeIndexString, + replaceUrlParam, + replaceUrlProtocol +}; diff --git a/node_modules/hono/dist/compose.js b/node_modules/hono/dist/compose.js new file mode 100644 index 000000000..8e1326fc3 --- /dev/null +++ b/node_modules/hono/dist/compose.js @@ -0,0 +1,46 @@ +// src/compose.ts +var compose = (middleware, onError, onNotFound) => { + return (context, next) => { + let index = -1; + return dispatch(0); + async function dispatch(i) { + if (i <= index) { + throw new Error("next() called multiple times"); + } + index = i; + let res; + let isError = false; + let handler; + if (middleware[i]) { + handler = middleware[i][0][0]; + context.req.routeIndex = i; + } else { + handler = i === middleware.length && next || void 0; + } + if (handler) { + try { + res = await handler(context, () => dispatch(i + 1)); + } catch (err) { + if (err instanceof Error && onError) { + context.error = err; + res = await onError(err, context); + isError = true; + } else { + throw err; + } + } + } else { + if (context.finalized === false && onNotFound) { + res = await onNotFound(context); + } + } + if (res && (context.finalized === false || isError)) { + context.res = res; + } + return context; + } + }; +}; +export { + compose +}; diff --git a/node_modules/hono/dist/context.js b/node_modules/hono/dist/context.js new file mode 100644 index 000000000..3d8a9c651 --- /dev/null +++ b/node_modules/hono/dist/context.js @@ -0,0 +1,411 @@ +// src/context.ts +import { HonoRequest } from "./request.js"; +import { HtmlEscapedCallbackPhase, resolveCallback } from "./utils/html.js"; +var TEXT_PLAIN = "text/plain; charset=UTF-8"; +var setDefaultContentType = (contentType, headers) => { + return { + "Content-Type": contentType, + ...headers + }; +}; +var Context = class { + #rawRequest; + #req; + /** + * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers. + * + * @see {@link https://hono.dev/docs/api/context#env} + * + * @example + * ```ts + * // Environment object for Cloudflare Workers + * app.get('*', async c => { + * const counter = c.env.COUNTER + * }) + * ``` + */ + env = {}; + #var; + finalized = false; + /** + * `.error` can get the error object from the middleware if the Handler throws an error. + * + * @see {@link https://hono.dev/docs/api/context#error} + * + * @example + * ```ts + * app.use('*', async (c, next) => { + * await next() + * if (c.error) { + * // do something... + * } + * }) + * ``` + */ + error; + #status; + #executionCtx; + #res; + #layout; + #renderer; + #notFoundHandler; + #preparedHeaders; + #matchResult; + #path; + /** + * Creates an instance of the Context class. + * + * @param req - The Request object. + * @param options - Optional configuration options for the context. + */ + constructor(req, options) { + this.#rawRequest = req; + if (options) { + this.#executionCtx = options.executionCtx; + this.env = options.env; + this.#notFoundHandler = options.notFoundHandler; + this.#path = options.path; + this.#matchResult = options.matchResult; + } + } + /** + * `.req` is the instance of {@link HonoRequest}. + */ + get req() { + this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult); + return this.#req; + } + /** + * @see {@link https://hono.dev/docs/api/context#event} + * The FetchEvent associated with the current request. + * + * @throws Will throw an error if the context does not have a FetchEvent. + */ + get event() { + if (this.#executionCtx && "respondWith" in this.#executionCtx) { + return this.#executionCtx; + } else { + throw Error("This context has no FetchEvent"); + } + } + /** + * @see {@link https://hono.dev/docs/api/context#executionctx} + * The ExecutionContext associated with the current request. + * + * @throws Will throw an error if the context does not have an ExecutionContext. + */ + get executionCtx() { + if (this.#executionCtx) { + return this.#executionCtx; + } else { + throw Error("This context has no ExecutionContext"); + } + } + /** + * @see {@link https://hono.dev/docs/api/context#res} + * The Response object for the current request. + */ + get res() { + return this.#res ||= new Response(null, { + headers: this.#preparedHeaders ??= new Headers() + }); + } + /** + * Sets the Response object for the current request. + * + * @param _res - The Response object to set. + */ + set res(_res) { + if (this.#res && _res) { + _res = new Response(_res.body, _res); + for (const [k, v] of this.#res.headers.entries()) { + if (k === "content-type") { + continue; + } + if (k === "set-cookie") { + const cookies = this.#res.headers.getSetCookie(); + _res.headers.delete("set-cookie"); + for (const cookie of cookies) { + _res.headers.append("set-cookie", cookie); + } + } else { + _res.headers.set(k, v); + } + } + } + this.#res = _res; + this.finalized = true; + } + /** + * `.render()` can create a response within a layout. + * + * @see {@link https://hono.dev/docs/api/context#render-setrenderer} + * + * @example + * ```ts + * app.get('/', (c) => { + * return c.render('Hello!') + * }) + * ``` + */ + render = (...args) => { + this.#renderer ??= (content) => this.html(content); + return this.#renderer(...args); + }; + /** + * Sets the layout for the response. + * + * @param layout - The layout to set. + * @returns The layout function. + */ + setLayout = (layout) => this.#layout = layout; + /** + * Gets the current layout for the response. + * + * @returns The current layout function. + */ + getLayout = () => this.#layout; + /** + * `.setRenderer()` can set the layout in the custom middleware. + * + * @see {@link https://hono.dev/docs/api/context#render-setrenderer} + * + * @example + * ```tsx + * app.use('*', async (c, next) => { + * c.setRenderer((content) => { + * return c.html( + * + * + *

{content}

+ * + * + * ) + * }) + * await next() + * }) + * ``` + */ + setRenderer = (renderer) => { + this.#renderer = renderer; + }; + /** + * `.header()` can set headers. + * + * @see {@link https://hono.dev/docs/api/context#header} + * + * @example + * ```ts + * app.get('/welcome', (c) => { + * // Set headers + * c.header('X-Message', 'Hello!') + * c.header('Content-Type', 'text/plain') + * + * return c.body('Thank you for coming') + * }) + * ``` + */ + header = (name, value, options) => { + if (this.finalized) { + this.#res = new Response(this.#res.body, this.#res); + } + const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers(); + if (value === void 0) { + headers.delete(name); + } else if (options?.append) { + headers.append(name, value); + } else { + headers.set(name, value); + } + }; + status = (status) => { + this.#status = status; + }; + /** + * `.set()` can set the value specified by the key. + * + * @see {@link https://hono.dev/docs/api/context#set-get} + * + * @example + * ```ts + * app.use('*', async (c, next) => { + * c.set('message', 'Hono is hot!!') + * await next() + * }) + * ``` + */ + set = (key, value) => { + this.#var ??= /* @__PURE__ */ new Map(); + this.#var.set(key, value); + }; + /** + * `.get()` can use the value specified by the key. + * + * @see {@link https://hono.dev/docs/api/context#set-get} + * + * @example + * ```ts + * app.get('/', (c) => { + * const message = c.get('message') + * return c.text(`The message is "${message}"`) + * }) + * ``` + */ + get = (key) => { + return this.#var ? this.#var.get(key) : void 0; + }; + /** + * `.var` can access the value of a variable. + * + * @see {@link https://hono.dev/docs/api/context#var} + * + * @example + * ```ts + * const result = c.var.client.oneMethod() + * ``` + */ + // c.var.propName is a read-only + get var() { + if (!this.#var) { + return {}; + } + return Object.fromEntries(this.#var); + } + #newResponse(data, arg, headers) { + const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers(); + if (typeof arg === "object" && "headers" in arg) { + const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers); + for (const [key, value] of argHeaders) { + if (key.toLowerCase() === "set-cookie") { + responseHeaders.append(key, value); + } else { + responseHeaders.set(key, value); + } + } + } + if (headers) { + for (const [k, v] of Object.entries(headers)) { + if (typeof v === "string") { + responseHeaders.set(k, v); + } else { + responseHeaders.delete(k); + for (const v2 of v) { + responseHeaders.append(k, v2); + } + } + } + } + const status = typeof arg === "number" ? arg : arg?.status ?? this.#status; + return new Response(data, { status, headers: responseHeaders }); + } + newResponse = (...args) => this.#newResponse(...args); + /** + * `.body()` can return the HTTP response. + * You can set headers with `.header()` and set HTTP status code with `.status`. + * This can also be set in `.text()`, `.json()` and so on. + * + * @see {@link https://hono.dev/docs/api/context#body} + * + * @example + * ```ts + * app.get('/welcome', (c) => { + * // Set headers + * c.header('X-Message', 'Hello!') + * c.header('Content-Type', 'text/plain') + * // Set HTTP status code + * c.status(201) + * + * // Return the response body + * return c.body('Thank you for coming') + * }) + * ``` + */ + body = (data, arg, headers) => this.#newResponse(data, arg, headers); + /** + * `.text()` can render text as `Content-Type:text/plain`. + * + * @see {@link https://hono.dev/docs/api/context#text} + * + * @example + * ```ts + * app.get('/say', (c) => { + * return c.text('Hello!') + * }) + * ``` + */ + text = (text, arg, headers) => { + return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse( + text, + arg, + setDefaultContentType(TEXT_PLAIN, headers) + ); + }; + /** + * `.json()` can render JSON as `Content-Type:application/json`. + * + * @see {@link https://hono.dev/docs/api/context#json} + * + * @example + * ```ts + * app.get('/api', (c) => { + * return c.json({ message: 'Hello!' }) + * }) + * ``` + */ + json = (object, arg, headers) => { + return this.#newResponse( + JSON.stringify(object), + arg, + setDefaultContentType("application/json", headers) + ); + }; + html = (html, arg, headers) => { + const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers)); + return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html); + }; + /** + * `.redirect()` can Redirect, default status code is 302. + * + * @see {@link https://hono.dev/docs/api/context#redirect} + * + * @example + * ```ts + * app.get('/redirect', (c) => { + * return c.redirect('/') + * }) + * app.get('/redirect-permanently', (c) => { + * return c.redirect('/', 301) + * }) + * ``` + */ + redirect = (location, status) => { + const locationString = String(location); + this.header( + "Location", + // Multibyes should be encoded + // eslint-disable-next-line no-control-regex + !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString) + ); + return this.newResponse(null, status ?? 302); + }; + /** + * `.notFound()` can return the Not Found Response. + * + * @see {@link https://hono.dev/docs/api/context#notfound} + * + * @example + * ```ts + * app.get('/notfound', (c) => { + * return c.notFound() + * }) + * ``` + */ + notFound = () => { + this.#notFoundHandler ??= () => new Response(); + return this.#notFoundHandler(this); + }; +}; +export { + Context, + TEXT_PLAIN +}; diff --git a/node_modules/hono/dist/helper/accepts/accepts.js b/node_modules/hono/dist/helper/accepts/accepts.js new file mode 100644 index 000000000..fd87c4cf6 --- /dev/null +++ b/node_modules/hono/dist/helper/accepts/accepts.js @@ -0,0 +1,20 @@ +// src/helper/accepts/accepts.ts +import { parseAccept } from "../../utils/accept.js"; +var defaultMatch = (accepts2, config) => { + const { supports, default: defaultSupport } = config; + const accept = accepts2.sort((a, b) => b.q - a.q).find((accept2) => supports.includes(accept2.type)); + return accept ? accept.type : defaultSupport; +}; +var accepts = (c, options) => { + const acceptHeader = c.req.header(options.header); + if (!acceptHeader) { + return options.default; + } + const accepts2 = parseAccept(acceptHeader); + const match = options.match || defaultMatch; + return match(accepts2, options); +}; +export { + accepts, + defaultMatch +}; diff --git a/node_modules/hono/dist/helper/accepts/index.js b/node_modules/hono/dist/helper/accepts/index.js new file mode 100644 index 000000000..f80f3c80e --- /dev/null +++ b/node_modules/hono/dist/helper/accepts/index.js @@ -0,0 +1,5 @@ +// src/helper/accepts/index.ts +import { accepts } from "./accepts.js"; +export { + accepts +}; diff --git a/node_modules/hono/dist/helper/adapter/index.js b/node_modules/hono/dist/helper/adapter/index.js new file mode 100644 index 000000000..7eb7803de --- /dev/null +++ b/node_modules/hono/dist/helper/adapter/index.js @@ -0,0 +1,56 @@ +// src/helper/adapter/index.ts +var env = (c, runtime) => { + const global = globalThis; + const globalEnv = global?.process?.env; + runtime ??= getRuntimeKey(); + const runtimeEnvHandlers = { + bun: () => globalEnv, + node: () => globalEnv, + "edge-light": () => globalEnv, + deno: () => { + return Deno.env.toObject(); + }, + workerd: () => c.env, + // On Fastly Compute, you can use the ConfigStore to manage user-defined data. + fastly: () => ({}), + other: () => ({}) + }; + return runtimeEnvHandlers[runtime](); +}; +var knownUserAgents = { + deno: "Deno", + bun: "Bun", + workerd: "Cloudflare-Workers", + node: "Node.js" +}; +var getRuntimeKey = () => { + const global = globalThis; + const userAgentSupported = typeof navigator !== "undefined" && typeof navigator.userAgent === "string"; + if (userAgentSupported) { + for (const [runtimeKey, userAgent] of Object.entries(knownUserAgents)) { + if (checkUserAgentEquals(userAgent)) { + return runtimeKey; + } + } + } + if (typeof global?.EdgeRuntime === "string") { + return "edge-light"; + } + if (global?.fastly !== void 0) { + return "fastly"; + } + if (global?.process?.release?.name === "node") { + return "node"; + } + return "other"; +}; +var checkUserAgentEquals = (platform) => { + const userAgent = navigator.userAgent; + return userAgent.startsWith(platform); +}; +export { + checkUserAgentEquals, + env, + getRuntimeKey, + knownUserAgents +}; diff --git a/node_modules/hono/dist/helper/conninfo/index.js b/node_modules/hono/dist/helper/conninfo/index.js new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/hono/dist/helper/conninfo/types.js b/node_modules/hono/dist/helper/conninfo/types.js new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/hono/dist/helper/cookie/index.js b/node_modules/hono/dist/helper/cookie/index.js new file mode 100644 index 000000000..59f996837 --- /dev/null +++ b/node_modules/hono/dist/helper/cookie/index.js @@ -0,0 +1,102 @@ +// src/helper/cookie/index.ts +import { parse, parseSigned, serialize, serializeSigned } from "../../utils/cookie.js"; +var getCookie = (c, key, prefix) => { + const cookie = c.req.raw.headers.get("Cookie"); + if (typeof key === "string") { + if (!cookie) { + return void 0; + } + let finalKey = key; + if (prefix === "secure") { + finalKey = "__Secure-" + key; + } else if (prefix === "host") { + finalKey = "__Host-" + key; + } + const obj2 = parse(cookie, finalKey); + return obj2[finalKey]; + } + if (!cookie) { + return {}; + } + const obj = parse(cookie); + return obj; +}; +var getSignedCookie = async (c, secret, key, prefix) => { + const cookie = c.req.raw.headers.get("Cookie"); + if (typeof key === "string") { + if (!cookie) { + return void 0; + } + let finalKey = key; + if (prefix === "secure") { + finalKey = "__Secure-" + key; + } else if (prefix === "host") { + finalKey = "__Host-" + key; + } + const obj2 = await parseSigned(cookie, secret, finalKey); + return obj2[finalKey]; + } + if (!cookie) { + return {}; + } + const obj = await parseSigned(cookie, secret); + return obj; +}; +var generateCookie = (name, value, opt) => { + let cookie; + if (opt?.prefix === "secure") { + cookie = serialize("__Secure-" + name, value, { path: "/", ...opt, secure: true }); + } else if (opt?.prefix === "host") { + cookie = serialize("__Host-" + name, value, { + ...opt, + path: "/", + secure: true, + domain: void 0 + }); + } else { + cookie = serialize(name, value, { path: "/", ...opt }); + } + return cookie; +}; +var setCookie = (c, name, value, opt) => { + const cookie = generateCookie(name, value, opt); + c.header("Set-Cookie", cookie, { append: true }); +}; +var generateSignedCookie = async (name, value, secret, opt) => { + let cookie; + if (opt?.prefix === "secure") { + cookie = await serializeSigned("__Secure-" + name, value, secret, { + path: "/", + ...opt, + secure: true + }); + } else if (opt?.prefix === "host") { + cookie = await serializeSigned("__Host-" + name, value, secret, { + ...opt, + path: "/", + secure: true, + domain: void 0 + }); + } else { + cookie = await serializeSigned(name, value, secret, { path: "/", ...opt }); + } + return cookie; +}; +var setSignedCookie = async (c, name, value, secret, opt) => { + const cookie = await generateSignedCookie(name, value, secret, opt); + c.header("set-cookie", cookie, { append: true }); +}; +var deleteCookie = (c, name, opt) => { + const deletedCookie = getCookie(c, name, opt?.prefix); + setCookie(c, name, "", { ...opt, maxAge: 0 }); + return deletedCookie; +}; +export { + deleteCookie, + generateCookie, + generateSignedCookie, + getCookie, + getSignedCookie, + setCookie, + setSignedCookie +}; diff --git a/node_modules/hono/dist/helper/css/common.js b/node_modules/hono/dist/helper/css/common.js new file mode 100644 index 000000000..a48d4378b --- /dev/null +++ b/node_modules/hono/dist/helper/css/common.js @@ -0,0 +1,185 @@ +// src/helper/css/common.ts +var PSEUDO_GLOBAL_SELECTOR = ":-hono-global"; +var isPseudoGlobalSelectorRe = new RegExp(`^${PSEUDO_GLOBAL_SELECTOR}{(.*)}$`); +var DEFAULT_STYLE_ID = "hono-css"; +var SELECTOR = /* @__PURE__ */ Symbol(); +var CLASS_NAME = /* @__PURE__ */ Symbol(); +var STYLE_STRING = /* @__PURE__ */ Symbol(); +var SELECTORS = /* @__PURE__ */ Symbol(); +var EXTERNAL_CLASS_NAMES = /* @__PURE__ */ Symbol(); +var CSS_ESCAPED = /* @__PURE__ */ Symbol(); +var IS_CSS_ESCAPED = /* @__PURE__ */ Symbol(); +var rawCssString = (value) => { + return { + [CSS_ESCAPED]: value + }; +}; +var toHash = (str) => { + let i = 0, out = 11; + while (i < str.length) { + out = 101 * out + str.charCodeAt(i++) >>> 0; + } + return "css-" + out; +}; +var cssStringReStr = [ + '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', + // double quoted string + "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'" + // single quoted string +].join("|"); +var minifyCssRe = new RegExp( + [ + "(" + cssStringReStr + ")", + // $1: quoted string + "(?:" + [ + "^\\s+", + // head whitespace + "\\/\\*.*?\\*\\/\\s*", + // multi-line comment + "\\/\\/.*\\n\\s*", + // single-line comment + "\\s+$" + // tail whitespace + ].join("|") + ")", + "\\s*;\\s*(}|$)\\s*", + // $2: trailing semicolon + "\\s*([{};:,])\\s*", + // $3: whitespace around { } : , ; + "(\\s)\\s+" + // $4: 2+ spaces + ].join("|"), + "g" +); +var minify = (css) => { + return css.replace(minifyCssRe, (_, $1, $2, $3, $4) => $1 || $2 || $3 || $4 || ""); +}; +var buildStyleString = (strings, values) => { + const selectors = []; + const externalClassNames = []; + const label = strings[0].match(/^\s*\/\*(.*?)\*\//)?.[1] || ""; + let styleString = ""; + for (let i = 0, len = strings.length; i < len; i++) { + styleString += strings[i]; + let vArray = values[i]; + if (typeof vArray === "boolean" || vArray === null || vArray === void 0) { + continue; + } + if (!Array.isArray(vArray)) { + vArray = [vArray]; + } + for (let j = 0, len2 = vArray.length; j < len2; j++) { + let value = vArray[j]; + if (typeof value === "boolean" || value === null || value === void 0) { + continue; + } + if (typeof value === "string") { + if (/([\\"'\/])/.test(value)) { + styleString += value.replace(/([\\"']|(?<=<)\/)/g, "\\$1"); + } else { + styleString += value; + } + } else if (typeof value === "number") { + styleString += value; + } else if (value[CSS_ESCAPED]) { + styleString += value[CSS_ESCAPED]; + } else if (value[CLASS_NAME].startsWith("@keyframes ")) { + selectors.push(value); + styleString += ` ${value[CLASS_NAME].substring(11)} `; + } else { + if (strings[i + 1]?.match(/^\s*{/)) { + selectors.push(value); + value = `.${value[CLASS_NAME]}`; + } else { + selectors.push(...value[SELECTORS]); + externalClassNames.push(...value[EXTERNAL_CLASS_NAMES]); + value = value[STYLE_STRING]; + const valueLen = value.length; + if (valueLen > 0) { + const lastChar = value[valueLen - 1]; + if (lastChar !== ";" && lastChar !== "}") { + value += ";"; + } + } + } + styleString += `${value || ""}`; + } + } + } + return [label, minify(styleString), selectors, externalClassNames]; +}; +var cssCommon = (strings, values) => { + let [label, thisStyleString, selectors, externalClassNames] = buildStyleString(strings, values); + const isPseudoGlobal = isPseudoGlobalSelectorRe.exec(thisStyleString); + if (isPseudoGlobal) { + thisStyleString = isPseudoGlobal[1]; + } + const selector = (isPseudoGlobal ? PSEUDO_GLOBAL_SELECTOR : "") + toHash(label + thisStyleString); + const className = (isPseudoGlobal ? selectors.map((s) => s[CLASS_NAME]) : [selector, ...externalClassNames]).join(" "); + return { + [SELECTOR]: selector, + [CLASS_NAME]: className, + [STYLE_STRING]: thisStyleString, + [SELECTORS]: selectors, + [EXTERNAL_CLASS_NAMES]: externalClassNames + }; +}; +var cxCommon = (args) => { + for (let i = 0, len = args.length; i < len; i++) { + const arg = args[i]; + if (typeof arg === "string") { + args[i] = { + [SELECTOR]: "", + [CLASS_NAME]: "", + [STYLE_STRING]: "", + [SELECTORS]: [], + [EXTERNAL_CLASS_NAMES]: [arg] + }; + } + } + return args; +}; +var keyframesCommon = (strings, ...values) => { + const [label, styleString] = buildStyleString(strings, values); + return { + [SELECTOR]: "", + [CLASS_NAME]: `@keyframes ${toHash(label + styleString)}`, + [STYLE_STRING]: styleString, + [SELECTORS]: [], + [EXTERNAL_CLASS_NAMES]: [] + }; +}; +var viewTransitionNameIndex = 0; +var viewTransitionCommon = ((strings, values) => { + if (!strings) { + strings = [`/* h-v-t ${viewTransitionNameIndex++} */`]; + } + const content = Array.isArray(strings) ? cssCommon(strings, values) : strings; + const transitionName = content[CLASS_NAME]; + const res = cssCommon(["view-transition-name:", ""], [transitionName]); + content[CLASS_NAME] = PSEUDO_GLOBAL_SELECTOR + content[CLASS_NAME]; + content[STYLE_STRING] = content[STYLE_STRING].replace( + /(?<=::view-transition(?:[a-z-]*)\()(?=\))/g, + transitionName + ); + res[CLASS_NAME] = res[SELECTOR] = transitionName; + res[SELECTORS] = [...content[SELECTORS], content]; + return res; +}); +export { + CLASS_NAME, + DEFAULT_STYLE_ID, + EXTERNAL_CLASS_NAMES, + IS_CSS_ESCAPED, + PSEUDO_GLOBAL_SELECTOR, + SELECTOR, + SELECTORS, + STYLE_STRING, + buildStyleString, + cssCommon, + cxCommon, + isPseudoGlobalSelectorRe, + keyframesCommon, + minify, + rawCssString, + viewTransitionCommon +}; diff --git a/node_modules/hono/dist/helper/css/index.js b/node_modules/hono/dist/helper/css/index.js new file mode 100644 index 000000000..b60a2c7c9 --- /dev/null +++ b/node_modules/hono/dist/helper/css/index.js @@ -0,0 +1,125 @@ +// src/helper/css/index.ts +import { raw } from "../../helper/html/index.js"; +import { DOM_RENDERER } from "../../jsx/constants.js"; +import { createCssJsxDomObjects } from "../../jsx/dom/css.js"; +import { + CLASS_NAME, + DEFAULT_STYLE_ID, + PSEUDO_GLOBAL_SELECTOR, + SELECTOR, + SELECTORS, + STYLE_STRING, + cssCommon, + cxCommon, + keyframesCommon, + viewTransitionCommon +} from "./common.js"; +import { rawCssString } from "./common.js"; +var createCssContext = ({ id }) => { + const [cssJsxDomObject, StyleRenderToDom] = createCssJsxDomObjects({ id }); + const contextMap = /* @__PURE__ */ new WeakMap(); + const nonceMap = /* @__PURE__ */ new WeakMap(); + const replaceStyleRe = new RegExp(`()`); + const newCssClassNameObject = (cssClassName) => { + const appendStyle = ({ buffer, context }) => { + const [toAdd, added] = contextMap.get(context); + const names = Object.keys(toAdd); + if (!names.length) { + return; + } + let stylesStr = ""; + names.forEach((className2) => { + added[className2] = true; + stylesStr += className2.startsWith(PSEUDO_GLOBAL_SELECTOR) ? toAdd[className2] : `${className2[0] === "@" ? "" : "."}${className2}{${toAdd[className2]}}`; + }); + contextMap.set(context, [{}, added]); + if (buffer && replaceStyleRe.test(buffer[0])) { + buffer[0] = buffer[0].replace(replaceStyleRe, (_, pre, post) => `${pre}${stylesStr}${post}`); + return; + } + const nonce = nonceMap.get(context); + const appendStyleScript = `document.querySelector('#${id}').textContent+=${JSON.stringify(stylesStr)}`; + if (buffer) { + buffer[0] = `${appendStyleScript}${buffer[0]}`; + return; + } + return Promise.resolve(appendStyleScript); + }; + const addClassNameToContext = ({ context }) => { + if (!contextMap.has(context)) { + contextMap.set(context, [{}, {}]); + } + const [toAdd, added] = contextMap.get(context); + let allAdded = true; + if (!added[cssClassName[SELECTOR]]) { + allAdded = false; + toAdd[cssClassName[SELECTOR]] = cssClassName[STYLE_STRING]; + } + cssClassName[SELECTORS].forEach( + ({ [CLASS_NAME]: className2, [STYLE_STRING]: styleString }) => { + if (!added[className2]) { + allAdded = false; + toAdd[className2] = styleString; + } + } + ); + if (allAdded) { + return; + } + return Promise.resolve(raw("", [appendStyle])); + }; + const className = new String(cssClassName[CLASS_NAME]); + Object.assign(className, cssClassName); + className.isEscaped = true; + className.callbacks = [addClassNameToContext]; + const promise = Promise.resolve(className); + Object.assign(promise, cssClassName); + promise.toString = cssJsxDomObject.toString; + return promise; + }; + const css2 = (strings, ...values) => { + return newCssClassNameObject(cssCommon(strings, values)); + }; + const cx2 = (...args) => { + args = cxCommon(args); + return css2(Array(args.length).fill(""), ...args); + }; + const keyframes2 = keyframesCommon; + const viewTransition2 = ((strings, ...values) => { + return newCssClassNameObject(viewTransitionCommon(strings, values)); + }); + const Style2 = ({ children, nonce } = {}) => raw( + ``, + [ + ({ context }) => { + nonceMap.set(context, nonce); + return void 0; + } + ] + ); + Style2[DOM_RENDERER] = StyleRenderToDom; + return { + css: css2, + cx: cx2, + keyframes: keyframes2, + viewTransition: viewTransition2, + Style: Style2 + }; +}; +var defaultContext = createCssContext({ + id: DEFAULT_STYLE_ID +}); +var css = defaultContext.css; +var cx = defaultContext.cx; +var keyframes = defaultContext.keyframes; +var viewTransition = defaultContext.viewTransition; +var Style = defaultContext.Style; +export { + Style, + createCssContext, + css, + cx, + keyframes, + rawCssString, + viewTransition +}; diff --git a/node_modules/hono/dist/helper/dev/index.js b/node_modules/hono/dist/helper/dev/index.js new file mode 100644 index 000000000..98244efeb --- /dev/null +++ b/node_modules/hono/dist/helper/dev/index.js @@ -0,0 +1,55 @@ +// src/helper/dev/index.ts +import { getColorEnabled } from "../../utils/color.js"; +import { findTargetHandler, isMiddleware } from "../../utils/handler.js"; +var handlerName = (handler) => { + return handler.name || (isMiddleware(handler) ? "[middleware]" : "[handler]"); +}; +var inspectRoutes = (hono) => { + return hono.routes.map(({ path, method, handler }) => { + const targetHandler = findTargetHandler(handler); + return { + path, + method, + name: handlerName(targetHandler), + isMiddleware: isMiddleware(targetHandler) + }; + }); +}; +var showRoutes = (hono, opts) => { + const colorEnabled = opts?.colorize ?? getColorEnabled(); + const routeData = {}; + let maxMethodLength = 0; + let maxPathLength = 0; + inspectRoutes(hono).filter(({ isMiddleware: isMiddleware2 }) => opts?.verbose || !isMiddleware2).map((route) => { + const key = `${route.method}-${route.path}`; + (routeData[key] ||= []).push(route); + if (routeData[key].length > 1) { + return; + } + maxMethodLength = Math.max(maxMethodLength, route.method.length); + maxPathLength = Math.max(maxPathLength, route.path.length); + return { method: route.method, path: route.path, routes: routeData[key] }; + }).forEach((data) => { + if (!data) { + return; + } + const { method, path, routes } = data; + const methodStr = colorEnabled ? `\x1B[32m${method}\x1B[0m` : method; + console.log(`${methodStr} ${" ".repeat(maxMethodLength - method.length)} ${path}`); + if (!opts?.verbose) { + return; + } + routes.forEach(({ name }) => { + console.log(`${" ".repeat(maxMethodLength + 3)} ${name}`); + }); + }); +}; +var getRouterName = (app) => { + app.router.match("GET", "/"); + return app.router.name; +}; +export { + getRouterName, + inspectRoutes, + showRoutes +}; diff --git a/node_modules/hono/dist/helper/factory/index.js b/node_modules/hono/dist/helper/factory/index.js new file mode 100644 index 000000000..6b48e9179 --- /dev/null +++ b/node_modules/hono/dist/helper/factory/index.js @@ -0,0 +1,30 @@ +// src/helper/factory/index.ts +import { Hono } from "../../hono.js"; +var Factory = class { + initApp; + #defaultAppOptions; + constructor(init) { + this.initApp = init?.initApp; + this.#defaultAppOptions = init?.defaultAppOptions; + } + createApp = (options) => { + const app = new Hono( + options && this.#defaultAppOptions ? { ...this.#defaultAppOptions, ...options } : options ?? this.#defaultAppOptions + ); + if (this.initApp) { + this.initApp(app); + } + return app; + }; + createMiddleware = (middleware) => middleware; + createHandlers = (...handlers) => { + return handlers.filter((handler) => handler !== void 0); + }; +}; +var createFactory = (init) => new Factory(init); +var createMiddleware = (middleware) => middleware; +export { + Factory, + createFactory, + createMiddleware +}; diff --git a/node_modules/hono/dist/helper/html/index.js b/node_modules/hono/dist/helper/html/index.js new file mode 100644 index 000000000..d5726ca22 --- /dev/null +++ b/node_modules/hono/dist/helper/html/index.js @@ -0,0 +1,41 @@ +// src/helper/html/index.ts +import { escapeToBuffer, raw, resolveCallbackSync, stringBufferToString } from "../../utils/html.js"; +var html = (strings, ...values) => { + const buffer = [""]; + for (let i = 0, len = strings.length - 1; i < len; i++) { + buffer[0] += strings[i]; + const children = Array.isArray(values[i]) ? values[i].flat(Infinity) : [values[i]]; + for (let i2 = 0, len2 = children.length; i2 < len2; i2++) { + const child = children[i2]; + if (typeof child === "string") { + escapeToBuffer(child, buffer); + } else if (typeof child === "number") { + ; + buffer[0] += child; + } else if (typeof child === "boolean" || child === null || child === void 0) { + continue; + } else if (typeof child === "object" && child.isEscaped) { + if (child.callbacks) { + buffer.unshift("", child); + } else { + const tmp = child.toString(); + if (tmp instanceof Promise) { + buffer.unshift("", tmp); + } else { + buffer[0] += tmp; + } + } + } else if (child instanceof Promise) { + buffer.unshift("", child); + } else { + escapeToBuffer(child.toString(), buffer); + } + } + } + buffer[0] += strings.at(-1); + return buffer.length === 1 ? "callbacks" in buffer ? raw(resolveCallbackSync(raw(buffer[0], buffer.callbacks))) : raw(buffer[0]) : stringBufferToString(buffer, buffer.callbacks); +}; +export { + html, + raw +}; diff --git a/node_modules/hono/dist/helper/proxy/index.js b/node_modules/hono/dist/helper/proxy/index.js new file mode 100644 index 000000000..e666f7aa5 --- /dev/null +++ b/node_modules/hono/dist/helper/proxy/index.js @@ -0,0 +1,89 @@ +// src/helper/proxy/index.ts +import { HTTPException } from "../../http-exception.js"; +var hopByHopHeaders = [ + "connection", + "keep-alive", + "proxy-authenticate", + "proxy-authorization", + "te", + "trailer", + "transfer-encoding", + "upgrade" +]; +var ALLOWED_TOKEN_PATTERN = /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/; +var buildRequestInitFromRequest = (request, strictConnectionProcessing) => { + if (!request) { + return {}; + } + const headers = new Headers(request.headers); + if (strictConnectionProcessing) { + const connectionValue = headers.get("connection"); + if (connectionValue) { + const headerNames = connectionValue.split(",").map((h) => h.trim()); + const invalidHeaders = headerNames.filter((h) => !ALLOWED_TOKEN_PATTERN.test(h)); + if (invalidHeaders.length > 0) { + throw new HTTPException(400, { + message: `Invalid Connection header value: ${invalidHeaders.join(", ")}` + }); + } + headerNames.forEach((headerName) => { + headers.delete(headerName); + }); + } + } + hopByHopHeaders.forEach((header) => { + headers.delete(header); + }); + return { + method: request.method, + body: request.body, + duplex: request.body ? "half" : void 0, + headers, + signal: request.signal + }; +}; +var preprocessRequestInit = (requestInit) => { + if (!requestInit.headers || Array.isArray(requestInit.headers) || requestInit.headers instanceof Headers) { + return requestInit; + } + const headers = new Headers(); + for (const [key, value] of Object.entries(requestInit.headers)) { + if (value == null) { + headers.delete(key); + } else { + headers.set(key, value); + } + } + requestInit.headers = headers; + return requestInit; +}; +var proxy = async (input, proxyInit) => { + const { + raw, + customFetch, + strictConnectionProcessing = false, + ...requestInit + } = proxyInit instanceof Request ? { raw: proxyInit } : proxyInit ?? {}; + const req = new Request(input, { + ...buildRequestInitFromRequest(raw, strictConnectionProcessing), + ...preprocessRequestInit(requestInit) + }); + req.headers.delete("accept-encoding"); + const res = await (customFetch || fetch)(req); + const resHeaders = new Headers(res.headers); + hopByHopHeaders.forEach((header) => { + resHeaders.delete(header); + }); + if (resHeaders.has("content-encoding")) { + resHeaders.delete("content-encoding"); + resHeaders.delete("content-length"); + } + return new Response(res.body, { + status: res.status, + statusText: res.statusText, + headers: resHeaders + }); +}; +export { + proxy +}; diff --git a/node_modules/hono/dist/helper/route/index.js b/node_modules/hono/dist/helper/route/index.js new file mode 100644 index 000000000..457d362d2 --- /dev/null +++ b/node_modules/hono/dist/helper/route/index.js @@ -0,0 +1,46 @@ +// src/helper/route/index.ts +import { GET_MATCH_RESULT } from "../../request/constants.js"; +import { getPattern, splitRoutingPath } from "../../utils/url.js"; +var matchedRoutes = (c) => ( + // @ts-expect-error c.req[GET_MATCH_RESULT] is not typed + c.req[GET_MATCH_RESULT][0].map(([[, route]]) => route) +); +var routePath = (c, index) => matchedRoutes(c).at(index ?? c.req.routeIndex)?.path ?? ""; +var baseRoutePath = (c, index) => matchedRoutes(c).at(index ?? c.req.routeIndex)?.basePath ?? ""; +var basePathCacheMap = /* @__PURE__ */ new WeakMap(); +var basePath = (c, index) => { + index ??= c.req.routeIndex; + const cache = basePathCacheMap.get(c) || []; + if (typeof cache[index] === "string") { + return cache[index]; + } + let result; + const rp = baseRoutePath(c, index); + if (!/[:*]/.test(rp)) { + result = rp; + } else { + const paths = splitRoutingPath(rp); + const reqPath = c.req.path; + let basePathLength = 0; + for (let i = 0, len = paths.length; i < len; i++) { + const pattern = getPattern(paths[i], paths[i + 1]); + if (pattern) { + const re = pattern[2] === true || pattern === "*" ? /[^\/]+/ : pattern[2]; + basePathLength += reqPath.substring(basePathLength + 1).match(re)?.[0].length || 0; + } else { + basePathLength += paths[i].length; + } + basePathLength += 1; + } + result = reqPath.substring(0, basePathLength); + } + cache[index] = result; + basePathCacheMap.set(c, cache); + return result; +}; +export { + basePath, + baseRoutePath, + matchedRoutes, + routePath +}; diff --git a/node_modules/hono/dist/helper/ssg/index.js b/node_modules/hono/dist/helper/ssg/index.js new file mode 100644 index 000000000..68bcb8ea1 --- /dev/null +++ b/node_modules/hono/dist/helper/ssg/index.js @@ -0,0 +1,16 @@ +// src/helper/ssg/index.ts +export * from "./ssg.js"; +import { + X_HONO_DISABLE_SSG_HEADER_KEY, + ssgParams, + isSSGContext, + disableSSG, + onlySSG +} from "./middleware.js"; +export { + X_HONO_DISABLE_SSG_HEADER_KEY, + disableSSG, + isSSGContext, + onlySSG, + ssgParams +}; diff --git a/node_modules/hono/dist/helper/ssg/middleware.js b/node_modules/hono/dist/helper/ssg/middleware.js new file mode 100644 index 000000000..ddb59bd6b --- /dev/null +++ b/node_modules/hono/dist/helper/ssg/middleware.js @@ -0,0 +1,45 @@ +// src/helper/ssg/middleware.ts +import { isDynamicRoute } from "./utils.js"; +var SSG_CONTEXT = "HONO_SSG_CONTEXT"; +var X_HONO_DISABLE_SSG_HEADER_KEY = "x-hono-disable-ssg"; +var SSG_DISABLED_RESPONSE = (() => { + try { + return new Response("SSG is disabled", { + status: 404, + headers: { [X_HONO_DISABLE_SSG_HEADER_KEY]: "true" } + }); + } catch { + return null; + } +})(); +var ssgParams = (params) => async (c, next) => { + if (isDynamicRoute(c.req.path)) { + ; + c.req.raw.ssgParams = Array.isArray(params) ? params : await params(c); + return c.notFound(); + } + await next(); +}; +var isSSGContext = (c) => !!c.env?.[SSG_CONTEXT]; +var disableSSG = () => async function disableSSG2(c, next) { + if (isSSGContext(c)) { + c.header(X_HONO_DISABLE_SSG_HEADER_KEY, "true"); + return c.notFound(); + } + await next(); +}; +var onlySSG = () => async function onlySSG2(c, next) { + if (!isSSGContext(c)) { + return c.notFound(); + } + await next(); +}; +export { + SSG_CONTEXT, + SSG_DISABLED_RESPONSE, + X_HONO_DISABLE_SSG_HEADER_KEY, + disableSSG, + isSSGContext, + onlySSG, + ssgParams +}; diff --git a/node_modules/hono/dist/helper/ssg/ssg.js b/node_modules/hono/dist/helper/ssg/ssg.js new file mode 100644 index 000000000..d51f07d1e --- /dev/null +++ b/node_modules/hono/dist/helper/ssg/ssg.js @@ -0,0 +1,295 @@ +// src/helper/ssg/ssg.ts +import { replaceUrlParam } from "../../client/utils.js"; +import { createPool } from "../../utils/concurrent.js"; +import { getExtension } from "../../utils/mime.js"; +import { SSG_CONTEXT, X_HONO_DISABLE_SSG_HEADER_KEY } from "./middleware.js"; +import { dirname, filterStaticGenerateRoutes, isDynamicRoute, joinPaths } from "./utils.js"; +var DEFAULT_CONCURRENCY = 2; +var DEFAULT_CONTENT_TYPE = "text/plain"; +var DEFAULT_OUTPUT_DIR = "./static"; +var generateFilePath = (routePath, outDir, mimeType, extensionMap) => { + const extension = determineExtension(mimeType, extensionMap); + if (routePath.endsWith(`.${extension}`)) { + return joinPaths(outDir, routePath); + } + if (routePath === "/") { + return joinPaths(outDir, `index.${extension}`); + } + if (routePath.endsWith("/")) { + return joinPaths(outDir, routePath, `index.${extension}`); + } + return joinPaths(outDir, `${routePath}.${extension}`); +}; +var parseResponseContent = async (response) => { + const contentType = response.headers.get("Content-Type"); + try { + if (contentType?.includes("text") || contentType?.includes("json")) { + return await response.text(); + } else { + return await response.arrayBuffer(); + } + } catch (error) { + throw new Error( + `Error processing response: ${error instanceof Error ? error.message : "Unknown error"}` + ); + } +}; +var defaultExtensionMap = { + "text/html": "html", + "text/xml": "xml", + "application/xml": "xml", + "application/yaml": "yaml" +}; +var determineExtension = (mimeType, userExtensionMap) => { + const extensionMap = userExtensionMap || defaultExtensionMap; + if (mimeType in extensionMap) { + return extensionMap[mimeType]; + } + return getExtension(mimeType) || "html"; +}; +var combineBeforeRequestHooks = (hooks) => { + if (!Array.isArray(hooks)) { + return hooks; + } + return async (req) => { + let currentReq = req; + for (const hook of hooks) { + const result = await hook(currentReq); + if (result === false) { + return false; + } + if (result instanceof Request) { + currentReq = result; + } + } + return currentReq; + }; +}; +var combineAfterResponseHooks = (hooks) => { + if (!Array.isArray(hooks)) { + return hooks; + } + return async (res) => { + let currentRes = res; + for (const hook of hooks) { + const result = await hook(currentRes); + if (result === false) { + return false; + } + if (result instanceof Response) { + currentRes = result; + } + } + return currentRes; + }; +}; +var combineAfterGenerateHooks = (hooks, fsModule, options) => { + if (!Array.isArray(hooks)) { + return hooks; + } + return async (result) => { + for (const hook of hooks) { + await hook(result, fsModule, options); + } + }; +}; +var fetchRoutesContent = function* (app, beforeRequestHook, afterResponseHook, concurrency) { + const baseURL = "http://localhost"; + const pool = createPool({ concurrency }); + for (const route of filterStaticGenerateRoutes(app)) { + const thisRouteBaseURL = new URL(route.path, baseURL).toString(); + let forGetInfoURLRequest = new Request(thisRouteBaseURL); + yield new Promise(async (resolveGetInfo, rejectGetInfo) => { + try { + if (beforeRequestHook) { + const maybeRequest = await beforeRequestHook(forGetInfoURLRequest); + if (!maybeRequest) { + resolveGetInfo(void 0); + return; + } + forGetInfoURLRequest = maybeRequest; + } + await pool.run(() => app.fetch(forGetInfoURLRequest)); + if (!forGetInfoURLRequest.ssgParams) { + if (isDynamicRoute(route.path)) { + resolveGetInfo(void 0); + return; + } + forGetInfoURLRequest.ssgParams = [{}]; + } + const requestInit = { + method: forGetInfoURLRequest.method, + headers: forGetInfoURLRequest.headers + }; + resolveGetInfo( + (function* () { + for (const param of forGetInfoURLRequest.ssgParams) { + yield new Promise(async (resolveReq, rejectReq) => { + try { + const replacedUrlParam = replaceUrlParam(route.path, param); + let response = await pool.run( + () => app.request(replacedUrlParam, requestInit, { + [SSG_CONTEXT]: true + }) + ); + if (response.headers.get(X_HONO_DISABLE_SSG_HEADER_KEY)) { + resolveReq(void 0); + return; + } + if (afterResponseHook) { + const maybeResponse = await afterResponseHook(response); + if (!maybeResponse) { + resolveReq(void 0); + return; + } + response = maybeResponse; + } + const mimeType = response.headers.get("Content-Type")?.split(";")[0] || DEFAULT_CONTENT_TYPE; + const content = await parseResponseContent(response); + resolveReq({ + routePath: replacedUrlParam, + mimeType, + content + }); + } catch (error) { + rejectReq(error); + } + }); + } + })() + ); + } catch (error) { + rejectGetInfo(error); + } + }); + } +}; +var createdDirs = /* @__PURE__ */ new Set(); +var saveContentToFile = async (data, fsModule, outDir, extensionMap) => { + const awaitedData = await data; + if (!awaitedData) { + return; + } + const { routePath, content, mimeType } = awaitedData; + const filePath = generateFilePath(routePath, outDir, mimeType, extensionMap); + const dirPath = dirname(filePath); + if (!createdDirs.has(dirPath)) { + await fsModule.mkdir(dirPath, { recursive: true }); + createdDirs.add(dirPath); + } + if (typeof content === "string") { + await fsModule.writeFile(filePath, content); + } else if (content instanceof ArrayBuffer) { + await fsModule.writeFile(filePath, new Uint8Array(content)); + } + return filePath; +}; +var defaultPlugin = { + afterResponseHook: (res) => { + if (res.status !== 200) { + return false; + } + return res; + } +}; +var toSSG = async (app, fs, options) => { + let result; + const getInfoPromises = []; + const savePromises = []; + const plugins = options?.plugins || [defaultPlugin]; + const beforeRequestHooks = []; + const afterResponseHooks = []; + const afterGenerateHooks = []; + if (options?.beforeRequestHook) { + beforeRequestHooks.push( + ...Array.isArray(options.beforeRequestHook) ? options.beforeRequestHook : [options.beforeRequestHook] + ); + } + if (options?.afterResponseHook) { + afterResponseHooks.push( + ...Array.isArray(options.afterResponseHook) ? options.afterResponseHook : [options.afterResponseHook] + ); + } + if (options?.afterGenerateHook) { + afterGenerateHooks.push( + ...Array.isArray(options.afterGenerateHook) ? options.afterGenerateHook : [options.afterGenerateHook] + ); + } + for (const plugin of plugins) { + if (plugin.beforeRequestHook) { + beforeRequestHooks.push( + ...Array.isArray(plugin.beforeRequestHook) ? plugin.beforeRequestHook : [plugin.beforeRequestHook] + ); + } + if (plugin.afterResponseHook) { + afterResponseHooks.push( + ...Array.isArray(plugin.afterResponseHook) ? plugin.afterResponseHook : [plugin.afterResponseHook] + ); + } + if (plugin.afterGenerateHook) { + afterGenerateHooks.push( + ...Array.isArray(plugin.afterGenerateHook) ? plugin.afterGenerateHook : [plugin.afterGenerateHook] + ); + } + } + try { + const outputDir = options?.dir ?? DEFAULT_OUTPUT_DIR; + const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY; + const combinedBeforeRequestHook = combineBeforeRequestHooks( + beforeRequestHooks.length > 0 ? beforeRequestHooks : [(req) => req] + ); + const combinedAfterResponseHook = combineAfterResponseHooks( + afterResponseHooks.length > 0 ? afterResponseHooks : [(req) => req] + ); + const getInfoGen = fetchRoutesContent( + app, + combinedBeforeRequestHook, + combinedAfterResponseHook, + concurrency + ); + for (const getInfo of getInfoGen) { + getInfoPromises.push( + getInfo.then((getContentGen) => { + if (!getContentGen) { + return; + } + for (const content of getContentGen) { + savePromises.push( + saveContentToFile(content, fs, outputDir, options?.extensionMap).catch((e) => e) + ); + } + }) + ); + } + await Promise.all(getInfoPromises); + const files = []; + for (const savePromise of savePromises) { + const fileOrError = await savePromise; + if (typeof fileOrError === "string") { + files.push(fileOrError); + } else if (fileOrError) { + throw fileOrError; + } + } + result = { success: true, files }; + } catch (error) { + const errorObj = error instanceof Error ? error : new Error(String(error)); + result = { success: false, files: [], error: errorObj }; + } + if (afterGenerateHooks.length > 0) { + const combinedAfterGenerateHooks = combineAfterGenerateHooks(afterGenerateHooks, fs, options); + await combinedAfterGenerateHooks(result, fs, options); + } + return result; +}; +export { + DEFAULT_OUTPUT_DIR, + combineAfterGenerateHooks, + combineAfterResponseHooks, + combineBeforeRequestHooks, + defaultExtensionMap, + defaultPlugin, + fetchRoutesContent, + saveContentToFile, + toSSG +}; diff --git a/node_modules/hono/dist/helper/ssg/utils.js b/node_modules/hono/dist/helper/ssg/utils.js new file mode 100644 index 000000000..793b5dc88 --- /dev/null +++ b/node_modules/hono/dist/helper/ssg/utils.js @@ -0,0 +1,59 @@ +// src/helper/ssg/utils.ts +import { METHOD_NAME_ALL } from "../../router.js"; +import { findTargetHandler, isMiddleware } from "../../utils/handler.js"; +var dirname = (path) => { + const separatedPath = path.split(/[\/\\]/); + return separatedPath.slice(0, -1).join("/"); +}; +var normalizePath = (path) => { + return path.replace(/(\\)/g, "/").replace(/\/$/g, ""); +}; +var handleParent = (resultPaths, beforeParentFlag) => { + if (resultPaths.length === 0 || beforeParentFlag) { + resultPaths.push(".."); + } else { + resultPaths.pop(); + } +}; +var handleNonDot = (path, resultPaths) => { + path = path.replace(/^\.(?!.)/, ""); + if (path !== "") { + resultPaths.push(path); + } +}; +var handleSegments = (paths, resultPaths) => { + let beforeParentFlag = false; + for (const path of paths) { + if (path === "..") { + handleParent(resultPaths, beforeParentFlag); + beforeParentFlag = true; + } else { + handleNonDot(path, resultPaths); + beforeParentFlag = false; + } + } +}; +var joinPaths = (...paths) => { + paths = paths.map(normalizePath); + const resultPaths = []; + handleSegments(paths.join("/").split("/"), resultPaths); + return (paths[0][0] === "/" ? "/" : "") + resultPaths.join("/"); +}; +var filterStaticGenerateRoutes = (hono) => { + return hono.routes.reduce((acc, { method, handler, path }) => { + const targetHandler = findTargetHandler(handler); + if (["GET", METHOD_NAME_ALL].includes(method) && !isMiddleware(targetHandler)) { + acc.push({ path }); + } + return acc; + }, []); +}; +var isDynamicRoute = (path) => { + return path.split("/").some((segment) => segment.startsWith(":") || segment.includes("*")); +}; +export { + dirname, + filterStaticGenerateRoutes, + isDynamicRoute, + joinPaths +}; diff --git a/node_modules/hono/dist/helper/streaming/index.js b/node_modules/hono/dist/helper/streaming/index.js new file mode 100644 index 000000000..c59a2d007 --- /dev/null +++ b/node_modules/hono/dist/helper/streaming/index.js @@ -0,0 +1,10 @@ +// src/helper/streaming/index.ts +import { stream } from "./stream.js"; +import { streamSSE, SSEStreamingApi } from "./sse.js"; +import { streamText } from "./text.js"; +export { + SSEStreamingApi, + stream, + streamSSE, + streamText +}; diff --git a/node_modules/hono/dist/helper/streaming/sse.js b/node_modules/hono/dist/helper/streaming/sse.js new file mode 100644 index 000000000..cc8b51d98 --- /dev/null +++ b/node_modules/hono/dist/helper/streaming/sse.js @@ -0,0 +1,62 @@ +// src/helper/streaming/sse.ts +import { HtmlEscapedCallbackPhase, resolveCallback } from "../../utils/html.js"; +import { StreamingApi } from "../../utils/stream.js"; +import { isOldBunVersion } from "./utils.js"; +var SSEStreamingApi = class extends StreamingApi { + constructor(writable, readable) { + super(writable, readable); + } + async writeSSE(message) { + const data = await resolveCallback(message.data, HtmlEscapedCallbackPhase.Stringify, false, {}); + const dataLines = data.split("\n").map((line) => { + return `data: ${line}`; + }).join("\n"); + const sseData = [ + message.event && `event: ${message.event}`, + dataLines, + message.id && `id: ${message.id}`, + message.retry && `retry: ${message.retry}` + ].filter(Boolean).join("\n") + "\n\n"; + await this.write(sseData); + } +}; +var run = async (stream, cb, onError) => { + try { + await cb(stream); + } catch (e) { + if (e instanceof Error && onError) { + await onError(e, stream); + await stream.writeSSE({ + event: "error", + data: e.message + }); + } else { + console.error(e); + } + } finally { + stream.close(); + } +}; +var contextStash = /* @__PURE__ */ new WeakMap(); +var streamSSE = (c, cb, onError) => { + const { readable, writable } = new TransformStream(); + const stream = new SSEStreamingApi(writable, readable); + if (isOldBunVersion()) { + c.req.raw.signal.addEventListener("abort", () => { + if (!stream.closed) { + stream.abort(); + } + }); + } + contextStash.set(stream.responseReadable, c); + c.header("Transfer-Encoding", "chunked"); + c.header("Content-Type", "text/event-stream"); + c.header("Cache-Control", "no-cache"); + c.header("Connection", "keep-alive"); + run(stream, cb, onError); + return c.newResponse(stream.responseReadable); +}; +export { + SSEStreamingApi, + streamSSE +}; diff --git a/node_modules/hono/dist/helper/streaming/stream.js b/node_modules/hono/dist/helper/streaming/stream.js new file mode 100644 index 000000000..8a3feb45a --- /dev/null +++ b/node_modules/hono/dist/helper/streaming/stream.js @@ -0,0 +1,34 @@ +// src/helper/streaming/stream.ts +import { StreamingApi } from "../../utils/stream.js"; +import { isOldBunVersion } from "./utils.js"; +var contextStash = /* @__PURE__ */ new WeakMap(); +var stream = (c, cb, onError) => { + const { readable, writable } = new TransformStream(); + const stream2 = new StreamingApi(writable, readable); + if (isOldBunVersion()) { + c.req.raw.signal.addEventListener("abort", () => { + if (!stream2.closed) { + stream2.abort(); + } + }); + } + contextStash.set(stream2.responseReadable, c); + (async () => { + try { + await cb(stream2); + } catch (e) { + if (e === void 0) { + } else if (e instanceof Error && onError) { + await onError(e, stream2); + } else { + console.error(e); + } + } finally { + stream2.close(); + } + })(); + return c.newResponse(stream2.responseReadable); +}; +export { + stream +}; diff --git a/node_modules/hono/dist/helper/streaming/text.js b/node_modules/hono/dist/helper/streaming/text.js new file mode 100644 index 000000000..9e93cabdd --- /dev/null +++ b/node_modules/hono/dist/helper/streaming/text.js @@ -0,0 +1,12 @@ +// src/helper/streaming/text.ts +import { TEXT_PLAIN } from "../../context.js"; +import { stream } from "./index.js"; +var streamText = (c, cb, onError) => { + c.header("Content-Type", TEXT_PLAIN); + c.header("X-Content-Type-Options", "nosniff"); + c.header("Transfer-Encoding", "chunked"); + return stream(c, cb, onError); +}; +export { + streamText +}; diff --git a/node_modules/hono/dist/helper/streaming/utils.js b/node_modules/hono/dist/helper/streaming/utils.js new file mode 100644 index 000000000..671f4412f --- /dev/null +++ b/node_modules/hono/dist/helper/streaming/utils.js @@ -0,0 +1,13 @@ +// src/helper/streaming/utils.ts +var isOldBunVersion = () => { + const version = typeof Bun !== "undefined" ? Bun.version : void 0; + if (version === void 0) { + return false; + } + const result = version.startsWith("1.1") || version.startsWith("1.0") || version.startsWith("0."); + isOldBunVersion = () => result; + return result; +}; +export { + isOldBunVersion +}; diff --git a/node_modules/hono/dist/helper/testing/index.js b/node_modules/hono/dist/helper/testing/index.js new file mode 100644 index 000000000..7ba10346a --- /dev/null +++ b/node_modules/hono/dist/helper/testing/index.js @@ -0,0 +1,11 @@ +// src/helper/testing/index.ts +import { hc } from "../../client/index.js"; +var testClient = (app, Env, executionCtx, options) => { + const customFetch = (input, init) => { + return app.request(input, init, Env, executionCtx); + }; + return hc("http://localhost", { ...options, fetch: customFetch }); +}; +export { + testClient +}; diff --git a/node_modules/hono/dist/helper/websocket/index.js b/node_modules/hono/dist/helper/websocket/index.js new file mode 100644 index 000000000..1225415b7 --- /dev/null +++ b/node_modules/hono/dist/helper/websocket/index.js @@ -0,0 +1,57 @@ +// src/helper/websocket/index.ts +var WSContext = class { + #init; + constructor(init) { + this.#init = init; + this.raw = init.raw; + this.url = init.url ? new URL(init.url) : null; + this.protocol = init.protocol ?? null; + } + send(source, options) { + this.#init.send(source, options ?? {}); + } + raw; + binaryType = "arraybuffer"; + get readyState() { + return this.#init.readyState; + } + url; + protocol; + close(code, reason) { + this.#init.close(code, reason); + } +}; +var createWSMessageEvent = (source) => { + return new MessageEvent("message", { + data: source + }); +}; +var defineWebSocketHelper = (handler) => { + return ((...args) => { + if (typeof args[0] === "function") { + const [createEvents, options] = args; + return async function upgradeWebSocket(c, next) { + const events = await createEvents(c); + const result = await handler(c, events, options); + if (result) { + return result; + } + await next(); + }; + } else { + const [c, events, options] = args; + return (async () => { + const upgraded = await handler(c, events, options); + if (!upgraded) { + throw new Error("Failed to upgrade WebSocket"); + } + return upgraded; + })(); + } + }); +}; +export { + WSContext, + createWSMessageEvent, + defineWebSocketHelper +}; diff --git a/node_modules/hono/dist/hono-base.js b/node_modules/hono/dist/hono-base.js new file mode 100644 index 000000000..61003a872 --- /dev/null +++ b/node_modules/hono/dist/hono-base.js @@ -0,0 +1,378 @@ +// src/hono-base.ts +import { compose } from "./compose.js"; +import { Context } from "./context.js"; +import { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from "./router.js"; +import { COMPOSED_HANDLER } from "./utils/constants.js"; +import { getPath, getPathNoStrict, mergePath } from "./utils/url.js"; +var notFoundHandler = (c) => { + return c.text("404 Not Found", 404); +}; +var errorHandler = (err, c) => { + if ("getResponse" in err) { + const res = err.getResponse(); + return c.newResponse(res.body, res); + } + console.error(err); + return c.text("Internal Server Error", 500); +}; +var Hono = class _Hono { + get; + post; + put; + delete; + options; + patch; + all; + on; + use; + /* + This class is like an abstract class and does not have a router. + To use it, inherit the class and implement router in the constructor. + */ + router; + getPath; + // Cannot use `#` because it requires visibility at JavaScript runtime. + _basePath = "/"; + #path = "/"; + routes = []; + constructor(options = {}) { + const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]; + allMethods.forEach((method) => { + this[method] = (args1, ...args) => { + if (typeof args1 === "string") { + this.#path = args1; + } else { + this.#addRoute(method, this.#path, args1); + } + args.forEach((handler) => { + this.#addRoute(method, this.#path, handler); + }); + return this; + }; + }); + this.on = (method, path, ...handlers) => { + for (const p of [path].flat()) { + this.#path = p; + for (const m of [method].flat()) { + handlers.map((handler) => { + this.#addRoute(m.toUpperCase(), this.#path, handler); + }); + } + } + return this; + }; + this.use = (arg1, ...handlers) => { + if (typeof arg1 === "string") { + this.#path = arg1; + } else { + this.#path = "*"; + handlers.unshift(arg1); + } + handlers.forEach((handler) => { + this.#addRoute(METHOD_NAME_ALL, this.#path, handler); + }); + return this; + }; + const { strict, ...optionsWithoutStrict } = options; + Object.assign(this, optionsWithoutStrict); + this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict; + } + #clone() { + const clone = new _Hono({ + router: this.router, + getPath: this.getPath + }); + clone.errorHandler = this.errorHandler; + clone.#notFoundHandler = this.#notFoundHandler; + clone.routes = this.routes; + return clone; + } + #notFoundHandler = notFoundHandler; + // Cannot use `#` because it requires visibility at JavaScript runtime. + errorHandler = errorHandler; + /** + * `.route()` allows grouping other Hono instance in routes. + * + * @see {@link https://hono.dev/docs/api/routing#grouping} + * + * @param {string} path - base Path + * @param {Hono} app - other Hono instance + * @returns {Hono} routed Hono instance + * + * @example + * ```ts + * const app = new Hono() + * const app2 = new Hono() + * + * app2.get("/user", (c) => c.text("user")) + * app.route("/api", app2) // GET /api/user + * ``` + */ + route(path, app) { + const subApp = this.basePath(path); + app.routes.map((r) => { + let handler; + if (app.errorHandler === errorHandler) { + handler = r.handler; + } else { + handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res; + handler[COMPOSED_HANDLER] = r.handler; + } + subApp.#addRoute(r.method, r.path, handler); + }); + return this; + } + /** + * `.basePath()` allows base paths to be specified. + * + * @see {@link https://hono.dev/docs/api/routing#base-path} + * + * @param {string} path - base Path + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * const api = new Hono().basePath('/api') + * ``` + */ + basePath(path) { + const subApp = this.#clone(); + subApp._basePath = mergePath(this._basePath, path); + return subApp; + } + /** + * `.onError()` handles an error and returns a customized Response. + * + * @see {@link https://hono.dev/docs/api/hono#error-handling} + * + * @param {ErrorHandler} handler - request Handler for error + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * app.onError((err, c) => { + * console.error(`${err}`) + * return c.text('Custom Error Message', 500) + * }) + * ``` + */ + onError = (handler) => { + this.errorHandler = handler; + return this; + }; + /** + * `.notFound()` allows you to customize a Not Found Response. + * + * @see {@link https://hono.dev/docs/api/hono#not-found} + * + * @param {NotFoundHandler} handler - request handler for not-found + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * app.notFound((c) => { + * return c.text('Custom 404 Message', 404) + * }) + * ``` + */ + notFound = (handler) => { + this.#notFoundHandler = handler; + return this; + }; + /** + * `.mount()` allows you to mount applications built with other frameworks into your Hono application. + * + * @see {@link https://hono.dev/docs/api/hono#mount} + * + * @param {string} path - base Path + * @param {Function} applicationHandler - other Request Handler + * @param {MountOptions} [options] - options of `.mount()` + * @returns {Hono} mounted Hono instance + * + * @example + * ```ts + * import { Router as IttyRouter } from 'itty-router' + * import { Hono } from 'hono' + * // Create itty-router application + * const ittyRouter = IttyRouter() + * // GET /itty-router/hello + * ittyRouter.get('/hello', () => new Response('Hello from itty-router')) + * + * const app = new Hono() + * app.mount('/itty-router', ittyRouter.handle) + * ``` + * + * @example + * ```ts + * const app = new Hono() + * // Send the request to another application without modification. + * app.mount('/app', anotherApp, { + * replaceRequest: (req) => req, + * }) + * ``` + */ + mount(path, applicationHandler, options) { + let replaceRequest; + let optionHandler; + if (options) { + if (typeof options === "function") { + optionHandler = options; + } else { + optionHandler = options.optionHandler; + if (options.replaceRequest === false) { + replaceRequest = (request) => request; + } else { + replaceRequest = options.replaceRequest; + } + } + } + const getOptions = optionHandler ? (c) => { + const options2 = optionHandler(c); + return Array.isArray(options2) ? options2 : [options2]; + } : (c) => { + let executionContext = void 0; + try { + executionContext = c.executionCtx; + } catch { + } + return [c.env, executionContext]; + }; + replaceRequest ||= (() => { + const mergedPath = mergePath(this._basePath, path); + const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length; + return (request) => { + const url = new URL(request.url); + url.pathname = url.pathname.slice(pathPrefixLength) || "/"; + return new Request(url, request); + }; + })(); + const handler = async (c, next) => { + const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c)); + if (res) { + return res; + } + await next(); + }; + this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler); + return this; + } + #addRoute(method, path, handler) { + method = method.toUpperCase(); + path = mergePath(this._basePath, path); + const r = { basePath: this._basePath, path, method, handler }; + this.router.add(method, path, [handler, r]); + this.routes.push(r); + } + #handleError(err, c) { + if (err instanceof Error) { + return this.errorHandler(err, c); + } + throw err; + } + #dispatch(request, executionCtx, env, method) { + if (method === "HEAD") { + return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))(); + } + const path = this.getPath(request, { env }); + const matchResult = this.router.match(method, path); + const c = new Context(request, { + path, + matchResult, + env, + executionCtx, + notFoundHandler: this.#notFoundHandler + }); + if (matchResult[0].length === 1) { + let res; + try { + res = matchResult[0][0][0][0](c, async () => { + c.res = await this.#notFoundHandler(c); + }); + } catch (err) { + return this.#handleError(err, c); + } + return res instanceof Promise ? res.then( + (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c)) + ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c); + } + const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler); + return (async () => { + try { + const context = await composed(c); + if (!context.finalized) { + throw new Error( + "Context is not finalized. Did you forget to return a Response object or `await next()`?" + ); + } + return context.res; + } catch (err) { + return this.#handleError(err, c); + } + })(); + } + /** + * `.fetch()` will be entry point of your app. + * + * @see {@link https://hono.dev/docs/api/hono#fetch} + * + * @param {Request} request - request Object of request + * @param {Env} Env - env Object + * @param {ExecutionContext} - context of execution + * @returns {Response | Promise} response of request + * + */ + fetch = (request, ...rest) => { + return this.#dispatch(request, rest[1], rest[0], request.method); + }; + /** + * `.request()` is a useful method for testing. + * You can pass a URL or pathname to send a GET request. + * app will return a Response object. + * ```ts + * test('GET /hello is ok', async () => { + * const res = await app.request('/hello') + * expect(res.status).toBe(200) + * }) + * ``` + * @see https://hono.dev/docs/api/hono#request + */ + request = (input, requestInit, Env, executionCtx) => { + if (input instanceof Request) { + return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx); + } + input = input.toString(); + return this.fetch( + new Request( + /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, + requestInit + ), + Env, + executionCtx + ); + }; + /** + * `.fire()` automatically adds a global fetch event listener. + * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers. + * @deprecated + * Use `fire` from `hono/service-worker` instead. + * ```ts + * import { Hono } from 'hono' + * import { fire } from 'hono/service-worker' + * + * const app = new Hono() + * // ... + * fire(app) + * ``` + * @see https://hono.dev/docs/api/hono#fire + * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API + * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/ + */ + fire = () => { + addEventListener("fetch", (event) => { + event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method)); + }); + }; +}; +export { + Hono as HonoBase +}; diff --git a/node_modules/hono/dist/hono.js b/node_modules/hono/dist/hono.js new file mode 100644 index 000000000..ff6338680 --- /dev/null +++ b/node_modules/hono/dist/hono.js @@ -0,0 +1,21 @@ +// src/hono.ts +import { HonoBase } from "./hono-base.js"; +import { RegExpRouter } from "./router/reg-exp-router/index.js"; +import { SmartRouter } from "./router/smart-router/index.js"; +import { TrieRouter } from "./router/trie-router/index.js"; +var Hono = class extends HonoBase { + /** + * Creates an instance of the Hono class. + * + * @param options - Optional configuration options for the Hono instance. + */ + constructor(options = {}) { + super(options); + this.router = options.router ?? new SmartRouter({ + routers: [new RegExpRouter(), new TrieRouter()] + }); + } +}; +export { + Hono +}; diff --git a/node_modules/hono/dist/http-exception.js b/node_modules/hono/dist/http-exception.js new file mode 100644 index 000000000..070a51ff8 --- /dev/null +++ b/node_modules/hono/dist/http-exception.js @@ -0,0 +1,35 @@ +// src/http-exception.ts +var HTTPException = class extends Error { + res; + status; + /** + * Creates an instance of `HTTPException`. + * @param status - HTTP status code for the exception. Defaults to 500. + * @param options - Additional options for the exception. + */ + constructor(status = 500, options) { + super(options?.message, { cause: options?.cause }); + this.res = options?.res; + this.status = status; + } + /** + * Returns the response object associated with the exception. + * If a response object is not provided, a new response is created with the error message and status code. + * @returns The response object. + */ + getResponse() { + if (this.res) { + const newResponse = new Response(this.res.body, { + status: this.status, + headers: this.res.headers + }); + return newResponse; + } + return new Response(this.message, { + status: this.status + }); + } +}; +export { + HTTPException +}; diff --git a/node_modules/hono/dist/index.js b/node_modules/hono/dist/index.js new file mode 100644 index 000000000..7f45bb9a0 --- /dev/null +++ b/node_modules/hono/dist/index.js @@ -0,0 +1,5 @@ +// src/index.ts +import { Hono } from "./hono.js"; +export { + Hono +}; diff --git a/node_modules/hono/dist/jsx/base.js b/node_modules/hono/dist/jsx/base.js new file mode 100644 index 000000000..105e25c90 --- /dev/null +++ b/node_modules/hono/dist/jsx/base.js @@ -0,0 +1,331 @@ +// src/jsx/base.ts +import { raw } from "../helper/html/index.js"; +import { escapeToBuffer, resolveCallbackSync, stringBufferToString } from "../utils/html.js"; +import { DOM_RENDERER, DOM_MEMO } from "./constants.js"; +import { createContext, globalContexts, useContext } from "./context.js"; +import { domRenderers } from "./intrinsic-element/common.js"; +import * as intrinsicElementTags from "./intrinsic-element/components.js"; +import { normalizeIntrinsicElementKey, styleObjectForEach } from "./utils.js"; +var nameSpaceContext = void 0; +var getNameSpaceContext = () => nameSpaceContext; +var toSVGAttributeName = (key) => /[A-Z]/.test(key) && // Presentation attributes are findable in style object. "clip-path", "font-size", "stroke-width", etc. +// Or other un-deprecated kebab-case attributes. "overline-position", "paint-order", "strikethrough-position", etc. +key.match( + /^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/ +) ? key.replace(/([A-Z])/g, "-$1").toLowerCase() : key; +var emptyTags = [ + "area", + "base", + "br", + "col", + "embed", + "hr", + "img", + "input", + "keygen", + "link", + "meta", + "param", + "source", + "track", + "wbr" +]; +var booleanAttributes = [ + "allowfullscreen", + "async", + "autofocus", + "autoplay", + "checked", + "controls", + "default", + "defer", + "disabled", + "download", + "formnovalidate", + "hidden", + "inert", + "ismap", + "itemscope", + "loop", + "multiple", + "muted", + "nomodule", + "novalidate", + "open", + "playsinline", + "readonly", + "required", + "reversed", + "selected" +]; +var childrenToStringToBuffer = (children, buffer) => { + for (let i = 0, len = children.length; i < len; i++) { + const child = children[i]; + if (typeof child === "string") { + escapeToBuffer(child, buffer); + } else if (typeof child === "boolean" || child === null || child === void 0) { + continue; + } else if (child instanceof JSXNode) { + child.toStringToBuffer(buffer); + } else if (typeof child === "number" || child.isEscaped) { + ; + buffer[0] += child; + } else if (child instanceof Promise) { + buffer.unshift("", child); + } else { + childrenToStringToBuffer(child, buffer); + } + } +}; +var JSXNode = class { + tag; + props; + key; + children; + isEscaped = true; + localContexts; + constructor(tag, props, children) { + this.tag = tag; + this.props = props; + this.children = children; + } + get type() { + return this.tag; + } + // Added for compatibility with libraries that rely on React's internal structure + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get ref() { + return this.props.ref || null; + } + toString() { + const buffer = [""]; + this.localContexts?.forEach(([context, value]) => { + context.values.push(value); + }); + try { + this.toStringToBuffer(buffer); + } finally { + this.localContexts?.forEach(([context]) => { + context.values.pop(); + }); + } + return buffer.length === 1 ? "callbacks" in buffer ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString() : buffer[0] : stringBufferToString(buffer, buffer.callbacks); + } + toStringToBuffer(buffer) { + const tag = this.tag; + const props = this.props; + let { children } = this; + buffer[0] += `<${tag}`; + const normalizeKey = nameSpaceContext && useContext(nameSpaceContext) === "svg" ? (key) => toSVGAttributeName(normalizeIntrinsicElementKey(key)) : (key) => normalizeIntrinsicElementKey(key); + for (let [key, v] of Object.entries(props)) { + key = normalizeKey(key); + if (key === "children") { + } else if (key === "style" && typeof v === "object") { + let styleStr = ""; + styleObjectForEach(v, (property, value) => { + if (value != null) { + styleStr += `${styleStr ? ";" : ""}${property}:${value}`; + } + }); + buffer[0] += ' style="'; + escapeToBuffer(styleStr, buffer); + buffer[0] += '"'; + } else if (typeof v === "string") { + buffer[0] += ` ${key}="`; + escapeToBuffer(v, buffer); + buffer[0] += '"'; + } else if (v === null || v === void 0) { + } else if (typeof v === "number" || v.isEscaped) { + buffer[0] += ` ${key}="${v}"`; + } else if (typeof v === "boolean" && booleanAttributes.includes(key)) { + if (v) { + buffer[0] += ` ${key}=""`; + } + } else if (key === "dangerouslySetInnerHTML") { + if (children.length > 0) { + throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`."); + } + children = [raw(v.__html)]; + } else if (v instanceof Promise) { + buffer[0] += ` ${key}="`; + buffer.unshift('"', v); + } else if (typeof v === "function") { + if (!key.startsWith("on") && key !== "ref") { + throw new Error(`Invalid prop '${key}' of type 'function' supplied to '${tag}'.`); + } + } else { + buffer[0] += ` ${key}="`; + escapeToBuffer(v.toString(), buffer); + buffer[0] += '"'; + } + } + if (emptyTags.includes(tag) && children.length === 0) { + buffer[0] += "/>"; + return; + } + buffer[0] += ">"; + childrenToStringToBuffer(children, buffer); + buffer[0] += ``; + } +}; +var JSXFunctionNode = class extends JSXNode { + toStringToBuffer(buffer) { + const { children } = this; + const props = { ...this.props }; + if (children.length) { + props.children = children.length === 1 ? children[0] : children; + } + const res = this.tag.call(null, props); + if (typeof res === "boolean" || res == null) { + return; + } else if (res instanceof Promise) { + if (globalContexts.length === 0) { + buffer.unshift("", res); + } else { + const currentContexts = globalContexts.map((c) => [c, c.values.at(-1)]); + buffer.unshift( + "", + res.then((childRes) => { + if (childRes instanceof JSXNode) { + childRes.localContexts = currentContexts; + } + return childRes; + }) + ); + } + } else if (res instanceof JSXNode) { + res.toStringToBuffer(buffer); + } else if (typeof res === "number" || res.isEscaped) { + buffer[0] += res; + if (res.callbacks) { + buffer.callbacks ||= []; + buffer.callbacks.push(...res.callbacks); + } + } else { + escapeToBuffer(res, buffer); + } + } +}; +var JSXFragmentNode = class extends JSXNode { + toStringToBuffer(buffer) { + childrenToStringToBuffer(this.children, buffer); + } +}; +var jsx = (tag, props, ...children) => { + props ??= {}; + if (children.length) { + props.children = children.length === 1 ? children[0] : children; + } + const key = props.key; + delete props["key"]; + const node = jsxFn(tag, props, children); + node.key = key; + return node; +}; +var initDomRenderer = false; +var jsxFn = (tag, props, children) => { + if (!initDomRenderer) { + for (const k in domRenderers) { + ; + intrinsicElementTags[k][DOM_RENDERER] = domRenderers[k]; + } + initDomRenderer = true; + } + if (typeof tag === "function") { + return new JSXFunctionNode(tag, props, children); + } else if (intrinsicElementTags[tag]) { + return new JSXFunctionNode( + intrinsicElementTags[tag], + props, + children + ); + } else if (tag === "svg" || tag === "head") { + nameSpaceContext ||= createContext(""); + return new JSXNode(tag, props, [ + new JSXFunctionNode( + nameSpaceContext, + { + value: tag + }, + children + ) + ]); + } else { + return new JSXNode(tag, props, children); + } +}; +var shallowEqual = (a, b) => { + if (a === b) { + return true; + } + const aKeys = Object.keys(a).sort(); + const bKeys = Object.keys(b).sort(); + if (aKeys.length !== bKeys.length) { + return false; + } + for (let i = 0, len = aKeys.length; i < len; i++) { + if (aKeys[i] === "children" && bKeys[i] === "children" && !a.children?.length && !b.children?.length) { + continue; + } else if (a[aKeys[i]] !== b[aKeys[i]]) { + return false; + } + } + return true; +}; +var memo = (component, propsAreEqual = shallowEqual) => { + let computed = null; + let prevProps = void 0; + const wrapper = ((props) => { + if (prevProps && !propsAreEqual(prevProps, props)) { + computed = null; + } + prevProps = props; + return computed ||= component(props); + }); + wrapper[DOM_MEMO] = propsAreEqual; + wrapper[DOM_RENDERER] = component; + return wrapper; +}; +var Fragment = ({ + children +}) => { + return new JSXFragmentNode( + "", + { + children + }, + Array.isArray(children) ? children : children ? [children] : [] + ); +}; +var isValidElement = (element) => { + return !!(element && typeof element === "object" && "tag" in element && "props" in element); +}; +var cloneElement = (element, props, ...children) => { + let childrenToClone; + if (children.length > 0) { + childrenToClone = children; + } else { + const c = element.props.children; + childrenToClone = Array.isArray(c) ? c : [c]; + } + return jsx( + element.tag, + { ...element.props, ...props }, + ...childrenToClone + ); +}; +var reactAPICompatVersion = "19.0.0-hono-jsx"; +export { + Fragment, + JSXFragmentNode, + JSXNode, + booleanAttributes, + cloneElement, + getNameSpaceContext, + isValidElement, + jsx, + jsxFn, + memo, + reactAPICompatVersion, + shallowEqual +}; diff --git a/node_modules/hono/dist/jsx/children.js b/node_modules/hono/dist/jsx/children.js new file mode 100644 index 000000000..12ad95153 --- /dev/null +++ b/node_modules/hono/dist/jsx/children.js @@ -0,0 +1,21 @@ +// src/jsx/children.ts +var toArray = (children) => Array.isArray(children) ? children : [children]; +var Children = { + map: (children, fn) => toArray(children).map(fn), + forEach: (children, fn) => { + toArray(children).forEach(fn); + }, + count: (children) => toArray(children).length, + only: (_children) => { + const children = toArray(_children); + if (children.length !== 1) { + throw new Error("Children.only() expects only one child"); + } + return children[0]; + }, + toArray +}; +export { + Children, + toArray +}; diff --git a/node_modules/hono/dist/jsx/components.js b/node_modules/hono/dist/jsx/components.js new file mode 100644 index 000000000..c8052d599 --- /dev/null +++ b/node_modules/hono/dist/jsx/components.js @@ -0,0 +1,152 @@ +// src/jsx/components.ts +import { raw } from "../helper/html/index.js"; +import { HtmlEscapedCallbackPhase, resolveCallback } from "../utils/html.js"; +import { DOM_RENDERER } from "./constants.js"; +import { useContext } from "./context.js"; +import { ErrorBoundary as ErrorBoundaryDomRenderer } from "./dom/components.js"; +import { StreamingContext } from "./streaming.js"; +var errorBoundaryCounter = 0; +var childrenToString = async (children) => { + try { + return children.flat().map((c) => c == null || typeof c === "boolean" ? "" : c.toString()); + } catch (e) { + if (e instanceof Promise) { + await e; + return childrenToString(children); + } else { + throw e; + } + } +}; +var ErrorBoundary = async ({ children, fallback, fallbackRender, onError }) => { + if (!children) { + return raw(""); + } + if (!Array.isArray(children)) { + children = [children]; + } + const nonce = useContext(StreamingContext)?.scriptNonce; + let fallbackStr; + const fallbackRes = (error) => { + onError?.(error); + return (fallbackStr || fallbackRender?.(error) || "").toString(); + }; + let resArray = []; + try { + resArray = children.map( + (c) => c == null || typeof c === "boolean" ? "" : c.toString() + ); + } catch (e) { + fallbackStr = await fallback?.toString(); + if (e instanceof Promise) { + resArray = [ + e.then(() => childrenToString(children)).catch((e2) => fallbackRes(e2)) + ]; + } else { + resArray = [fallbackRes(e)]; + } + } + if (resArray.some((res) => res instanceof Promise)) { + fallbackStr ||= await fallback?.toString(); + const index = errorBoundaryCounter++; + const replaceRe = RegExp(`(.*?)(.*?)()`); + const caught = false; + const catchCallback = ({ error: error2, buffer }) => { + if (caught) { + return ""; + } + const fallbackResString = fallbackRes(error2); + if (buffer) { + buffer[0] = buffer[0].replace(replaceRe, fallbackResString); + } + return buffer ? "" : ``; + }; + let error; + const promiseAll = Promise.all(resArray).catch((e) => error = e); + return raw(``, [ + ({ phase, buffer, context }) => { + if (phase === HtmlEscapedCallbackPhase.BeforeStream) { + return; + } + return promiseAll.then(async (htmlArray) => { + if (error) { + throw error; + } + htmlArray = htmlArray.flat(); + const content = htmlArray.join(""); + let html = buffer ? "" : ` +((d,c) => { +c=d.currentScript.previousSibling +d=d.getElementById('E:${index}') +if(!d)return +d.parentElement.insertBefore(c.content,d.nextSibling) +})(document) +`; + if (htmlArray.every((html2) => !html2.callbacks?.length)) { + if (buffer) { + buffer[0] = buffer[0].replace(replaceRe, content); + } + return html; + } + if (buffer) { + buffer[0] = buffer[0].replace( + replaceRe, + (_all, pre, _, post) => `${pre}${content}${post}` + ); + } + const callbacks = htmlArray.map((html2) => html2.callbacks || []).flat(); + if (phase === HtmlEscapedCallbackPhase.Stream) { + html = await resolveCallback( + html, + HtmlEscapedCallbackPhase.BeforeStream, + true, + context + ); + } + let resolvedCount = 0; + const promises = callbacks.map( + (c) => (...args) => c(...args)?.then((content2) => { + resolvedCount++; + if (buffer) { + if (resolvedCount === callbacks.length) { + buffer[0] = buffer[0].replace(replaceRe, (_all, _pre, content3) => content3); + } + buffer[0] += content2; + return raw("", content2.callbacks); + } + return raw( + content2 + (resolvedCount !== callbacks.length ? "" : ``), + content2.callbacks + ); + }).catch((error2) => catchCallback({ error: error2, buffer })) + ); + return raw(html, promises); + }).catch((error2) => catchCallback({ error: error2, buffer })); + } + ]); + } else { + return raw(resArray.join("")); + } +}; +ErrorBoundary[DOM_RENDERER] = ErrorBoundaryDomRenderer; +export { + ErrorBoundary, + childrenToString +}; diff --git a/node_modules/hono/dist/jsx/constants.js b/node_modules/hono/dist/jsx/constants.js new file mode 100644 index 000000000..872b4bb77 --- /dev/null +++ b/node_modules/hono/dist/jsx/constants.js @@ -0,0 +1,15 @@ +// src/jsx/constants.ts +var DOM_RENDERER = /* @__PURE__ */ Symbol("RENDERER"); +var DOM_ERROR_HANDLER = /* @__PURE__ */ Symbol("ERROR_HANDLER"); +var DOM_STASH = /* @__PURE__ */ Symbol("STASH"); +var DOM_INTERNAL_TAG = /* @__PURE__ */ Symbol("INTERNAL"); +var DOM_MEMO = /* @__PURE__ */ Symbol("MEMO"); +var PERMALINK = /* @__PURE__ */ Symbol("PERMALINK"); +export { + DOM_ERROR_HANDLER, + DOM_INTERNAL_TAG, + DOM_MEMO, + DOM_RENDERER, + DOM_STASH, + PERMALINK +}; diff --git a/node_modules/hono/dist/jsx/context.js b/node_modules/hono/dist/jsx/context.js new file mode 100644 index 000000000..c60896a8b --- /dev/null +++ b/node_modules/hono/dist/jsx/context.js @@ -0,0 +1,36 @@ +// src/jsx/context.ts +import { raw } from "../helper/html/index.js"; +import { JSXFragmentNode } from "./base.js"; +import { DOM_RENDERER } from "./constants.js"; +import { createContextProviderFunction } from "./dom/context.js"; +var globalContexts = []; +var createContext = (defaultValue) => { + const values = [defaultValue]; + const context = ((props) => { + values.push(props.value); + let string; + try { + string = props.children ? (Array.isArray(props.children) ? new JSXFragmentNode("", {}, props.children) : props.children).toString() : ""; + } finally { + values.pop(); + } + if (string instanceof Promise) { + return string.then((resString) => raw(resString, resString.callbacks)); + } else { + return raw(string); + } + }); + context.values = values; + context.Provider = context; + context[DOM_RENDERER] = createContextProviderFunction(values); + globalContexts.push(context); + return context; +}; +var useContext = (context) => { + return context.values.at(-1); +}; +export { + createContext, + globalContexts, + useContext +}; diff --git a/node_modules/hono/dist/jsx/dom/client.js b/node_modules/hono/dist/jsx/dom/client.js new file mode 100644 index 000000000..4338249aa --- /dev/null +++ b/node_modules/hono/dist/jsx/dom/client.js @@ -0,0 +1,53 @@ +// src/jsx/dom/client.ts +import { useState } from "../hooks/index.js"; +import { buildNode, renderNode } from "./render.js"; +var createRoot = (element, options = {}) => { + let setJsxNode = ( + // unmounted + void 0 + ); + if (Object.keys(options).length > 0) { + console.warn("createRoot options are not supported yet"); + } + return { + render(jsxNode) { + if (setJsxNode === null) { + throw new Error("Cannot update an unmounted root"); + } + if (setJsxNode) { + setJsxNode(jsxNode); + } else { + renderNode( + buildNode({ + tag: () => { + const [_jsxNode, _setJsxNode] = useState(jsxNode); + setJsxNode = _setJsxNode; + return _jsxNode; + }, + props: {} + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }), + element + ); + } + }, + unmount() { + setJsxNode?.(null); + setJsxNode = null; + } + }; +}; +var hydrateRoot = (element, reactNode, options = {}) => { + const root = createRoot(element, options); + root.render(reactNode); + return root; +}; +var client_default = { + createRoot, + hydrateRoot +}; +export { + createRoot, + client_default as default, + hydrateRoot +}; diff --git a/node_modules/hono/dist/jsx/dom/components.js b/node_modules/hono/dist/jsx/dom/components.js new file mode 100644 index 000000000..ad120be9b --- /dev/null +++ b/node_modules/hono/dist/jsx/dom/components.js @@ -0,0 +1,32 @@ +// src/jsx/dom/components.ts +import { DOM_ERROR_HANDLER } from "../constants.js"; +import { Fragment } from "./jsx-runtime.js"; +var ErrorBoundary = (({ children, fallback, fallbackRender, onError }) => { + const res = Fragment({ children }); + res[DOM_ERROR_HANDLER] = (err) => { + if (err instanceof Promise) { + throw err; + } + onError?.(err); + return fallbackRender?.(err) || fallback; + }; + return res; +}); +var Suspense = (({ + children, + fallback +}) => { + const res = Fragment({ children }); + res[DOM_ERROR_HANDLER] = (err, retry) => { + if (!(err instanceof Promise)) { + throw err; + } + err.finally(retry); + return fallback; + }; + return res; +}); +export { + ErrorBoundary, + Suspense +}; diff --git a/node_modules/hono/dist/jsx/dom/context.js b/node_modules/hono/dist/jsx/dom/context.js new file mode 100644 index 000000000..5bc71a7ae --- /dev/null +++ b/node_modules/hono/dist/jsx/dom/context.js @@ -0,0 +1,48 @@ +// src/jsx/dom/context.ts +import { DOM_ERROR_HANDLER } from "../constants.js"; +import { globalContexts } from "../context.js"; +import { setInternalTagFlag } from "./utils.js"; +var createContextProviderFunction = (values) => ({ value, children }) => { + if (!children) { + return void 0; + } + const props = { + children: [ + { + tag: setInternalTagFlag(() => { + values.push(value); + }), + props: {} + } + ] + }; + if (Array.isArray(children)) { + props.children.push(...children.flat()); + } else { + props.children.push(children); + } + props.children.push({ + tag: setInternalTagFlag(() => { + values.pop(); + }), + props: {} + }); + const res = { tag: "", props, type: "" }; + res[DOM_ERROR_HANDLER] = (err) => { + values.pop(); + throw err; + }; + return res; +}; +var createContext = (defaultValue) => { + const values = [defaultValue]; + const context = createContextProviderFunction(values); + context.values = values; + context.Provider = context; + globalContexts.push(context); + return context; +}; +export { + createContext, + createContextProviderFunction +}; diff --git a/node_modules/hono/dist/jsx/dom/css.js b/node_modules/hono/dist/jsx/dom/css.js new file mode 100644 index 000000000..f5bc6de36 --- /dev/null +++ b/node_modules/hono/dist/jsx/dom/css.js @@ -0,0 +1,143 @@ +// src/jsx/dom/css.ts +import { + CLASS_NAME, + DEFAULT_STYLE_ID, + PSEUDO_GLOBAL_SELECTOR, + SELECTOR, + SELECTORS, + STYLE_STRING, + cssCommon, + cxCommon, + keyframesCommon, + viewTransitionCommon +} from "../../helper/css/common.js"; +import { rawCssString } from "../../helper/css/common.js"; +var splitRule = (rule) => { + const result = []; + let startPos = 0; + let depth = 0; + for (let i = 0, len = rule.length; i < len; i++) { + const char = rule[i]; + if (char === "'" || char === '"') { + const quote = char; + i++; + for (; i < len; i++) { + if (rule[i] === "\\") { + i++; + continue; + } + if (rule[i] === quote) { + break; + } + } + continue; + } + if (char === "{") { + depth++; + continue; + } + if (char === "}") { + depth--; + if (depth === 0) { + result.push(rule.slice(startPos, i + 1)); + startPos = i + 1; + } + continue; + } + } + return result; +}; +var createCssJsxDomObjects = ({ id }) => { + let styleSheet = void 0; + const findStyleSheet = () => { + if (!styleSheet) { + styleSheet = document.querySelector(`style#${id}`)?.sheet; + if (styleSheet) { + ; + styleSheet.addedStyles = /* @__PURE__ */ new Set(); + } + } + return styleSheet ? [styleSheet, styleSheet.addedStyles] : []; + }; + const insertRule = (className, styleString) => { + const [sheet, addedStyles] = findStyleSheet(); + if (!sheet || !addedStyles) { + Promise.resolve().then(() => { + if (!findStyleSheet()[0]) { + throw new Error("style sheet not found"); + } + insertRule(className, styleString); + }); + return; + } + if (!addedStyles.has(className)) { + addedStyles.add(className); + (className.startsWith(PSEUDO_GLOBAL_SELECTOR) ? splitRule(styleString) : [`${className[0] === "@" ? "" : "."}${className}{${styleString}}`]).forEach((rule) => { + sheet.insertRule(rule, sheet.cssRules.length); + }); + } + }; + const cssObject = { + toString() { + const selector = this[SELECTOR]; + insertRule(selector, this[STYLE_STRING]); + this[SELECTORS].forEach(({ [CLASS_NAME]: className, [STYLE_STRING]: styleString }) => { + insertRule(className, styleString); + }); + return this[CLASS_NAME]; + } + }; + const Style2 = ({ children, nonce }) => ({ + tag: "style", + props: { + id, + nonce, + children: children && (Array.isArray(children) ? children : [children]).map( + (c) => c[STYLE_STRING] + ) + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }); + return [cssObject, Style2]; +}; +var createCssContext = ({ id }) => { + const [cssObject, Style2] = createCssJsxDomObjects({ id }); + const newCssClassNameObject = (cssClassName) => { + cssClassName.toString = cssObject.toString; + return cssClassName; + }; + const css2 = (strings, ...values) => { + return newCssClassNameObject(cssCommon(strings, values)); + }; + const cx2 = (...args) => { + args = cxCommon(args); + return css2(Array(args.length).fill(""), ...args); + }; + const keyframes2 = keyframesCommon; + const viewTransition2 = ((strings, ...values) => { + return newCssClassNameObject(viewTransitionCommon(strings, values)); + }); + return { + css: css2, + cx: cx2, + keyframes: keyframes2, + viewTransition: viewTransition2, + Style: Style2 + }; +}; +var defaultContext = createCssContext({ id: DEFAULT_STYLE_ID }); +var css = defaultContext.css; +var cx = defaultContext.cx; +var keyframes = defaultContext.keyframes; +var viewTransition = defaultContext.viewTransition; +var Style = defaultContext.Style; +export { + Style, + createCssContext, + createCssJsxDomObjects, + css, + cx, + keyframes, + rawCssString, + viewTransition +}; diff --git a/node_modules/hono/dist/jsx/dom/hooks/index.js b/node_modules/hono/dist/jsx/dom/hooks/index.js new file mode 100644 index 000000000..5eed9827d --- /dev/null +++ b/node_modules/hono/dist/jsx/dom/hooks/index.js @@ -0,0 +1,48 @@ +// src/jsx/dom/hooks/index.ts +import { PERMALINK } from "../../constants.js"; +import { useContext } from "../../context.js"; +import { useCallback, useState } from "../../hooks/index.js"; +import { createContext } from "../context.js"; +var FormContext = createContext({ + pending: false, + data: null, + method: null, + action: null +}); +var actions = /* @__PURE__ */ new Set(); +var registerAction = (action) => { + actions.add(action); + action.finally(() => actions.delete(action)); +}; +var useFormStatus = () => { + return useContext(FormContext); +}; +var useOptimistic = (state, updateState) => { + const [optimisticState, setOptimisticState] = useState(state); + if (actions.size > 0) { + Promise.all(actions).finally(() => { + setOptimisticState(state); + }); + } else { + setOptimisticState(state); + } + const cb = useCallback((newData) => { + setOptimisticState((currentState) => updateState(currentState, newData)); + }, []); + return [optimisticState, cb]; +}; +var useActionState = (fn, initialState, permalink) => { + const [state, setState] = useState(initialState); + const actionState = async (data) => { + setState(await fn(state, data)); + }; + actionState[PERMALINK] = permalink; + return [state, actionState]; +}; +export { + FormContext, + registerAction, + useActionState, + useFormStatus, + useOptimistic +}; diff --git a/node_modules/hono/dist/jsx/dom/index.js b/node_modules/hono/dist/jsx/dom/index.js new file mode 100644 index 000000000..4e5fbd33c --- /dev/null +++ b/node_modules/hono/dist/jsx/dom/index.js @@ -0,0 +1,142 @@ +// src/jsx/dom/index.ts +import { isValidElement, reactAPICompatVersion, shallowEqual } from "../base.js"; +import { Children } from "../children.js"; +import { DOM_MEMO } from "../constants.js"; +import { useContext } from "../context.js"; +import { + createRef, + forwardRef, + startTransition, + startViewTransition, + use, + useCallback, + useDebugValue, + useDeferredValue, + useEffect, + useId, + useImperativeHandle, + useInsertionEffect, + useLayoutEffect, + useMemo, + useReducer, + useRef, + useState, + useSyncExternalStore, + useTransition, + useViewTransition +} from "../hooks/index.js"; +import { ErrorBoundary, Suspense } from "./components.js"; +import { createContext } from "./context.js"; +import { useActionState, useFormStatus, useOptimistic } from "./hooks/index.js"; +import { Fragment, jsx } from "./jsx-runtime.js"; +import { createPortal, flushSync } from "./render.js"; +import { render } from "./render.js"; +var createElement = (tag, props, ...children) => { + const jsxProps = props ? { ...props } : {}; + if (children.length) { + jsxProps.children = children.length === 1 ? children[0] : children; + } + let key = void 0; + if ("key" in jsxProps) { + key = jsxProps.key; + delete jsxProps.key; + } + return jsx(tag, jsxProps, key); +}; +var cloneElement = (element, props, ...children) => { + return jsx( + element.tag, + { + ...element.props, + ...props, + children: children.length ? children : element.props.children + }, + element.key + ); +}; +var memo = (component, propsAreEqual = shallowEqual) => { + const wrapper = ((props) => component(props)); + wrapper[DOM_MEMO] = propsAreEqual; + return wrapper; +}; +var dom_default = { + version: reactAPICompatVersion, + useState, + useEffect, + useRef, + useCallback, + use, + startTransition, + useTransition, + useDeferredValue, + startViewTransition, + useViewTransition, + useMemo, + useLayoutEffect, + useInsertionEffect, + useReducer, + useId, + useDebugValue, + createRef, + forwardRef, + useImperativeHandle, + useSyncExternalStore, + useFormStatus, + useActionState, + useOptimistic, + Suspense, + ErrorBoundary, + createContext, + useContext, + memo, + isValidElement, + createElement, + cloneElement, + Children, + Fragment, + StrictMode: Fragment, + flushSync, + createPortal +}; +export { + Children, + ErrorBoundary, + Fragment, + Fragment as StrictMode, + Suspense, + cloneElement, + createContext, + createElement, + createPortal, + createRef, + dom_default as default, + flushSync, + forwardRef, + isValidElement, + createElement as jsx, + memo, + render, + startTransition, + startViewTransition, + use, + useActionState, + useCallback, + useContext, + useDebugValue, + useDeferredValue, + useEffect, + useFormStatus, + useId, + useImperativeHandle, + useInsertionEffect, + useLayoutEffect, + useMemo, + useOptimistic, + useReducer, + useRef, + useState, + useSyncExternalStore, + useTransition, + useViewTransition, + reactAPICompatVersion as version +}; diff --git a/node_modules/hono/dist/jsx/dom/intrinsic-element/components.js b/node_modules/hono/dist/jsx/dom/intrinsic-element/components.js new file mode 100644 index 000000000..995b789ed --- /dev/null +++ b/node_modules/hono/dist/jsx/dom/intrinsic-element/components.js @@ -0,0 +1,337 @@ +// src/jsx/dom/intrinsic-element/components.ts +import { useContext } from "../../context.js"; +import { use, useCallback, useMemo, useState } from "../../hooks/index.js"; +import { dataPrecedenceAttr, deDupeKeyMap, domRenderers } from "../../intrinsic-element/common.js"; +import { FormContext, registerAction } from "../hooks/index.js"; +import { createPortal, getNameSpaceContext } from "../render.js"; +var clearCache = () => { + blockingPromiseMap = /* @__PURE__ */ Object.create(null); + createdElements = /* @__PURE__ */ Object.create(null); +}; +var composeRef = (ref, cb) => { + return useMemo( + () => (e) => { + let refCleanup; + if (ref) { + if (typeof ref === "function") { + refCleanup = ref(e) || (() => { + ref(null); + }); + } else if (ref && "current" in ref) { + ref.current = e; + refCleanup = () => { + ref.current = null; + }; + } + } + const cbCleanup = cb(e); + return () => { + cbCleanup?.(); + refCleanup?.(); + }; + }, + [ref] + ); +}; +var blockingPromiseMap = /* @__PURE__ */ Object.create(null); +var createdElements = /* @__PURE__ */ Object.create(null); +var documentMetadataTag = (tag, props, preserveNodeType, supportSort, supportBlocking) => { + if (props?.itemProp) { + return { + tag, + props, + type: tag, + ref: props.ref + }; + } + const head = document.head; + let { onLoad, onError, precedence, blocking, ...restProps } = props; + let element = null; + let created = false; + const deDupeKeys = deDupeKeyMap[tag]; + let existingElements = void 0; + if (deDupeKeys.length > 0) { + const tags = head.querySelectorAll(tag); + LOOP: for (const e of tags) { + for (const key of deDupeKeyMap[tag]) { + if (e.getAttribute(key) === props[key]) { + element = e; + break LOOP; + } + } + } + if (!element) { + const cacheKey = deDupeKeys.reduce( + (acc, key) => props[key] === void 0 ? acc : `${acc}-${key}-${props[key]}`, + tag + ); + created = !createdElements[cacheKey]; + element = createdElements[cacheKey] ||= (() => { + const e = document.createElement(tag); + for (const key of deDupeKeys) { + if (props[key] !== void 0) { + e.setAttribute(key, props[key]); + } + if (props.rel) { + e.setAttribute("rel", props.rel); + } + } + return e; + })(); + } + } else { + existingElements = head.querySelectorAll(tag); + } + precedence = supportSort ? precedence ?? "" : void 0; + if (supportSort) { + restProps[dataPrecedenceAttr] = precedence; + } + const insert = useCallback( + (e) => { + if (deDupeKeys.length > 0) { + let found = false; + for (const existingElement of head.querySelectorAll(tag)) { + if (found && existingElement.getAttribute(dataPrecedenceAttr) !== precedence) { + head.insertBefore(e, existingElement); + return; + } + if (existingElement.getAttribute(dataPrecedenceAttr) === precedence) { + found = true; + } + } + head.appendChild(e); + } else if (existingElements) { + let found = false; + for (const existingElement of existingElements) { + if (existingElement === e) { + found = true; + break; + } + } + if (!found) { + head.insertBefore( + e, + head.contains(existingElements[0]) ? existingElements[0] : head.querySelector(tag) + ); + } + existingElements = void 0; + } + }, + [precedence] + ); + const ref = composeRef(props.ref, (e) => { + const key = deDupeKeys[0]; + if (preserveNodeType === 2) { + e.innerHTML = ""; + } + if (created || existingElements) { + insert(e); + } + if (!onError && !onLoad) { + return; + } + let promise = blockingPromiseMap[e.getAttribute(key)] ||= new Promise( + (resolve, reject) => { + e.addEventListener("load", resolve); + e.addEventListener("error", reject); + } + ); + if (onLoad) { + promise = promise.then(onLoad); + } + if (onError) { + promise = promise.catch(onError); + } + promise.catch(() => { + }); + }); + if (supportBlocking && blocking === "render") { + const key = deDupeKeyMap[tag][0]; + if (props[key]) { + const value = props[key]; + const promise = blockingPromiseMap[value] ||= new Promise((resolve, reject) => { + insert(element); + element.addEventListener("load", resolve); + element.addEventListener("error", reject); + }); + use(promise); + } + } + const jsxNode = { + tag, + type: tag, + props: { + ...restProps, + ref + }, + ref + }; + jsxNode.p = preserveNodeType; + if (element) { + jsxNode.e = element; + } + return createPortal( + jsxNode, + head + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ); +}; +var title = (props) => { + const nameSpaceContext = getNameSpaceContext(); + const ns = nameSpaceContext && useContext(nameSpaceContext); + if (ns?.endsWith("svg")) { + return { + tag: "title", + props, + type: "title", + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ref: props.ref + }; + } + return documentMetadataTag("title", props, void 0, false, false); +}; +var script = (props) => { + if (!props || ["src", "async"].some((k) => !props[k])) { + return { + tag: "script", + props, + type: "script", + ref: props.ref + }; + } + return documentMetadataTag("script", props, 1, false, true); +}; +var style = (props) => { + if (!props || !["href", "precedence"].every((k) => k in props)) { + return { + tag: "style", + props, + type: "style", + ref: props.ref + }; + } + props["data-href"] = props.href; + delete props.href; + return documentMetadataTag("style", props, 2, true, true); +}; +var link = (props) => { + if (!props || ["onLoad", "onError"].some((k) => k in props) || props.rel === "stylesheet" && (!("precedence" in props) || "disabled" in props)) { + return { + tag: "link", + props, + type: "link", + ref: props.ref + }; + } + return documentMetadataTag("link", props, 1, "precedence" in props, true); +}; +var meta = (props) => { + return documentMetadataTag("meta", props, void 0, false, false); +}; +var customEventFormAction = /* @__PURE__ */ Symbol(); +var form = (props) => { + const { action, ...restProps } = props; + if (typeof action !== "function") { + ; + restProps.action = action; + } + const [state, setState] = useState([null, false]); + const onSubmit = useCallback( + async (ev) => { + const currentAction = ev.isTrusted ? action : ev.detail[customEventFormAction]; + if (typeof currentAction !== "function") { + return; + } + ev.preventDefault(); + const formData = new FormData(ev.target); + setState([formData, true]); + const actionRes = currentAction(formData); + if (actionRes instanceof Promise) { + registerAction(actionRes); + await actionRes; + } + setState([null, true]); + }, + [] + ); + const ref = composeRef(props.ref, (el) => { + el.addEventListener("submit", onSubmit); + return () => { + el.removeEventListener("submit", onSubmit); + }; + }); + const [data, isDirty] = state; + state[1] = false; + return { + tag: FormContext, + props: { + value: { + pending: data !== null, + data, + method: data ? "post" : null, + action: data ? action : null + }, + children: { + tag: "form", + props: { + ...restProps, + ref + }, + type: "form", + ref + } + }, + f: isDirty + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; +}; +var formActionableElement = (tag, { + formAction, + ...props +}) => { + if (typeof formAction === "function") { + const onClick = useCallback((ev) => { + ev.preventDefault(); + ev.currentTarget.form.dispatchEvent( + new CustomEvent("submit", { detail: { [customEventFormAction]: formAction } }) + ); + }, []); + props.ref = composeRef(props.ref, (el) => { + el.addEventListener("click", onClick); + return () => { + el.removeEventListener("click", onClick); + }; + }); + } + return { + tag, + props, + type: tag, + ref: props.ref + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; +}; +var input = (props) => formActionableElement("input", props); +var button = (props) => formActionableElement("button", props); +Object.assign(domRenderers, { + title, + script, + style, + link, + meta, + form, + input, + button +}); +export { + button, + clearCache, + composeRef, + form, + input, + link, + meta, + script, + style, + title +}; diff --git a/node_modules/hono/dist/jsx/dom/jsx-dev-runtime.js b/node_modules/hono/dist/jsx/dom/jsx-dev-runtime.js new file mode 100644 index 000000000..688a64245 --- /dev/null +++ b/node_modules/hono/dist/jsx/dom/jsx-dev-runtime.js @@ -0,0 +1,19 @@ +// src/jsx/dom/jsx-dev-runtime.ts +import * as intrinsicElementTags from "./intrinsic-element/components.js"; +var jsxDEV = (tag, props, key) => { + if (typeof tag === "string" && intrinsicElementTags[tag]) { + tag = intrinsicElementTags[tag]; + } + return { + tag, + type: tag, + props, + key, + ref: props.ref + }; +}; +var Fragment = (props) => jsxDEV("", props, void 0); +export { + Fragment, + jsxDEV +}; diff --git a/node_modules/hono/dist/jsx/dom/jsx-runtime.js b/node_modules/hono/dist/jsx/dom/jsx-runtime.js new file mode 100644 index 000000000..925d6dfd6 --- /dev/null +++ b/node_modules/hono/dist/jsx/dom/jsx-runtime.js @@ -0,0 +1,8 @@ +// src/jsx/dom/jsx-runtime.ts +import { jsxDEV, Fragment } from "./jsx-dev-runtime.js"; +import { jsxDEV as jsxDEV2 } from "./jsx-dev-runtime.js"; +export { + Fragment, + jsxDEV as jsx, + jsxDEV2 as jsxs +}; diff --git a/node_modules/hono/dist/jsx/dom/render.js b/node_modules/hono/dist/jsx/dom/render.js new file mode 100644 index 000000000..78730d655 --- /dev/null +++ b/node_modules/hono/dist/jsx/dom/render.js @@ -0,0 +1,597 @@ +// src/jsx/dom/render.ts +import { toArray } from "../children.js"; +import { + DOM_ERROR_HANDLER, + DOM_INTERNAL_TAG, + DOM_MEMO, + DOM_RENDERER, + DOM_STASH +} from "../constants.js"; +import { globalContexts as globalJSXContexts, useContext } from "../context.js"; +import { STASH_EFFECT } from "../hooks/index.js"; +import { normalizeIntrinsicElementKey, styleObjectForEach } from "../utils.js"; +import { createContext } from "./context.js"; +var HONO_PORTAL_ELEMENT = "_hp"; +var eventAliasMap = { + Change: "Input", + DoubleClick: "DblClick" +}; +var nameSpaceMap = { + svg: "2000/svg", + math: "1998/Math/MathML" +}; +var buildDataStack = []; +var refCleanupMap = /* @__PURE__ */ new WeakMap(); +var nameSpaceContext = void 0; +var getNameSpaceContext = () => nameSpaceContext; +var isNodeString = (node) => "t" in node; +var eventCache = { + // pre-define events that are used very frequently + onClick: ["click", false] +}; +var getEventSpec = (key) => { + if (!key.startsWith("on")) { + return void 0; + } + if (eventCache[key]) { + return eventCache[key]; + } + const match = key.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/); + if (match) { + const [, eventName, capture] = match; + return eventCache[key] = [(eventAliasMap[eventName] || eventName).toLowerCase(), !!capture]; + } + return void 0; +}; +var toAttributeName = (element, key) => nameSpaceContext && element instanceof SVGElement && /[A-Z]/.test(key) && (key in element.style || // Presentation attributes are findable in style object. "clip-path", "font-size", "stroke-width", etc. +key.match(/^(?:o|pai|str|u|ve)/)) ? key.replace(/([A-Z])/g, "-$1").toLowerCase() : key; +var applyProps = (container, attributes, oldAttributes) => { + attributes ||= {}; + for (let key in attributes) { + const value = attributes[key]; + if (key !== "children" && (!oldAttributes || oldAttributes[key] !== value)) { + key = normalizeIntrinsicElementKey(key); + const eventSpec = getEventSpec(key); + if (eventSpec) { + if (oldAttributes?.[key] !== value) { + if (oldAttributes) { + container.removeEventListener(eventSpec[0], oldAttributes[key], eventSpec[1]); + } + if (value != null) { + if (typeof value !== "function") { + throw new Error(`Event handler for "${key}" is not a function`); + } + container.addEventListener(eventSpec[0], value, eventSpec[1]); + } + } + } else if (key === "dangerouslySetInnerHTML" && value) { + container.innerHTML = value.__html; + } else if (key === "ref") { + let cleanup; + if (typeof value === "function") { + cleanup = value(container) || (() => value(null)); + } else if (value && "current" in value) { + value.current = container; + cleanup = () => value.current = null; + } + refCleanupMap.set(container, cleanup); + } else if (key === "style") { + const style = container.style; + if (typeof value === "string") { + style.cssText = value; + } else { + style.cssText = ""; + if (value != null) { + styleObjectForEach(value, style.setProperty.bind(style)); + } + } + } else { + if (key === "value") { + const nodeName = container.nodeName; + if (nodeName === "INPUT" || nodeName === "TEXTAREA" || nodeName === "SELECT") { + ; + container.value = value === null || value === void 0 || value === false ? null : value; + if (nodeName === "TEXTAREA") { + container.textContent = value; + continue; + } else if (nodeName === "SELECT") { + if (container.selectedIndex === -1) { + ; + container.selectedIndex = 0; + } + continue; + } + } + } else if (key === "checked" && container.nodeName === "INPUT" || key === "selected" && container.nodeName === "OPTION") { + ; + container[key] = value; + } + const k = toAttributeName(container, key); + if (value === null || value === void 0 || value === false) { + container.removeAttribute(k); + } else if (value === true) { + container.setAttribute(k, ""); + } else if (typeof value === "string" || typeof value === "number") { + container.setAttribute(k, value); + } else { + container.setAttribute(k, value.toString()); + } + } + } + } + if (oldAttributes) { + for (let key in oldAttributes) { + const value = oldAttributes[key]; + if (key !== "children" && !(key in attributes)) { + key = normalizeIntrinsicElementKey(key); + const eventSpec = getEventSpec(key); + if (eventSpec) { + container.removeEventListener(eventSpec[0], value, eventSpec[1]); + } else if (key === "ref") { + refCleanupMap.get(container)?.(); + } else { + container.removeAttribute(toAttributeName(container, key)); + } + } + } + } +}; +var invokeTag = (context, node) => { + node[DOM_STASH][0] = 0; + buildDataStack.push([context, node]); + const func = node.tag[DOM_RENDERER] || node.tag; + const props = func.defaultProps ? { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ...func.defaultProps, + ...node.props + } : node.props; + try { + return [func.call(null, props)]; + } finally { + buildDataStack.pop(); + } +}; +var getNextChildren = (node, container, nextChildren, childrenToRemove, callbacks) => { + if (node.vR?.length) { + childrenToRemove.push(...node.vR); + delete node.vR; + } + if (typeof node.tag === "function") { + node[DOM_STASH][1][STASH_EFFECT]?.forEach((data) => callbacks.push(data)); + } + node.vC.forEach((child) => { + if (isNodeString(child)) { + nextChildren.push(child); + } else { + if (typeof child.tag === "function" || child.tag === "") { + child.c = container; + const currentNextChildrenIndex = nextChildren.length; + getNextChildren(child, container, nextChildren, childrenToRemove, callbacks); + if (child.s) { + for (let i = currentNextChildrenIndex; i < nextChildren.length; i++) { + nextChildren[i].s = true; + } + child.s = false; + } + } else { + nextChildren.push(child); + if (child.vR?.length) { + childrenToRemove.push(...child.vR); + delete child.vR; + } + } + } + }); +}; +var findInsertBefore = (node) => { + for (; ; node = node.tag === HONO_PORTAL_ELEMENT || !node.vC || !node.pP ? node.nN : node.vC[0]) { + if (!node) { + return null; + } + if (node.tag !== HONO_PORTAL_ELEMENT && node.e) { + return node.e; + } + } +}; +var removeNode = (node) => { + if (!isNodeString(node)) { + node[DOM_STASH]?.[1][STASH_EFFECT]?.forEach((data) => data[2]?.()); + refCleanupMap.get(node.e)?.(); + if (node.p === 2) { + node.vC?.forEach((n) => n.p = 2); + } + node.vC?.forEach(removeNode); + } + if (!node.p) { + node.e?.remove(); + delete node.e; + } + if (typeof node.tag === "function") { + updateMap.delete(node); + fallbackUpdateFnArrayMap.delete(node); + delete node[DOM_STASH][3]; + node.a = true; + } +}; +var apply = (node, container, isNew) => { + node.c = container; + applyNodeObject(node, container, isNew); +}; +var findChildNodeIndex = (childNodes, child) => { + if (!child) { + return; + } + for (let i = 0, len = childNodes.length; i < len; i++) { + if (childNodes[i] === child) { + return i; + } + } + return; +}; +var cancelBuild = /* @__PURE__ */ Symbol(); +var applyNodeObject = (node, container, isNew) => { + const next = []; + const remove = []; + const callbacks = []; + getNextChildren(node, container, next, remove, callbacks); + remove.forEach(removeNode); + const childNodes = isNew ? void 0 : container.childNodes; + let offset; + let insertBeforeNode = null; + if (isNew) { + offset = -1; + } else if (!childNodes.length) { + offset = 0; + } else { + const offsetByNextNode = findChildNodeIndex(childNodes, findInsertBefore(node.nN)); + if (offsetByNextNode !== void 0) { + insertBeforeNode = childNodes[offsetByNextNode]; + offset = offsetByNextNode; + } else { + offset = findChildNodeIndex(childNodes, next.find((n) => n.tag !== HONO_PORTAL_ELEMENT && n.e)?.e) ?? -1; + } + if (offset === -1) { + isNew = true; + } + } + for (let i = 0, len = next.length; i < len; i++, offset++) { + const child = next[i]; + let el; + if (child.s && child.e) { + el = child.e; + child.s = false; + } else { + const isNewLocal = isNew || !child.e; + if (isNodeString(child)) { + if (child.e && child.d) { + child.e.textContent = child.t; + } + child.d = false; + el = child.e ||= document.createTextNode(child.t); + } else { + el = child.e ||= child.n ? document.createElementNS(child.n, child.tag) : document.createElement(child.tag); + applyProps(el, child.props, child.pP); + applyNodeObject(child, el, isNewLocal); + } + } + if (child.tag === HONO_PORTAL_ELEMENT) { + offset--; + } else if (isNew) { + if (!el.parentNode) { + container.appendChild(el); + } + } else if (childNodes[offset] !== el && childNodes[offset - 1] !== el) { + if (childNodes[offset + 1] === el) { + container.appendChild(childNodes[offset]); + } else { + container.insertBefore(el, insertBeforeNode || childNodes[offset] || null); + } + } + } + if (node.pP) { + delete node.pP; + } + if (callbacks.length) { + const useLayoutEffectCbs = []; + const useEffectCbs = []; + callbacks.forEach(([, useLayoutEffectCb, , useEffectCb, useInsertionEffectCb]) => { + if (useLayoutEffectCb) { + useLayoutEffectCbs.push(useLayoutEffectCb); + } + if (useEffectCb) { + useEffectCbs.push(useEffectCb); + } + useInsertionEffectCb?.(); + }); + useLayoutEffectCbs.forEach((cb) => cb()); + if (useEffectCbs.length) { + requestAnimationFrame(() => { + useEffectCbs.forEach((cb) => cb()); + }); + } + } +}; +var isSameContext = (oldContexts, newContexts) => !!(oldContexts && oldContexts.length === newContexts.length && oldContexts.every((ctx, i) => ctx[1] === newContexts[i][1])); +var fallbackUpdateFnArrayMap = /* @__PURE__ */ new WeakMap(); +var build = (context, node, children) => { + const buildWithPreviousChildren = !children && node.pC; + if (children) { + node.pC ||= node.vC; + } + let foundErrorHandler; + try { + children ||= typeof node.tag == "function" ? invokeTag(context, node) : toArray(node.props.children); + if (children[0]?.tag === "" && children[0][DOM_ERROR_HANDLER]) { + foundErrorHandler = children[0][DOM_ERROR_HANDLER]; + context[5].push([context, foundErrorHandler, node]); + } + const oldVChildren = buildWithPreviousChildren ? [...node.pC] : node.vC ? [...node.vC] : void 0; + const vChildren = []; + let prevNode; + for (let i = 0; i < children.length; i++) { + if (Array.isArray(children[i])) { + children.splice(i, 1, ...children[i].flat()); + } + let child = buildNode(children[i]); + if (child) { + if (typeof child.tag === "function" && // eslint-disable-next-line @typescript-eslint/no-explicit-any + !child.tag[DOM_INTERNAL_TAG]) { + if (globalJSXContexts.length > 0) { + child[DOM_STASH][2] = globalJSXContexts.map((c) => [c, c.values.at(-1)]); + } + if (context[5]?.length) { + child[DOM_STASH][3] = context[5].at(-1); + } + } + let oldChild; + if (oldVChildren && oldVChildren.length) { + const i2 = oldVChildren.findIndex( + isNodeString(child) ? (c) => isNodeString(c) : child.key !== void 0 ? (c) => c.key === child.key && c.tag === child.tag : (c) => c.tag === child.tag + ); + if (i2 !== -1) { + oldChild = oldVChildren[i2]; + oldVChildren.splice(i2, 1); + } + } + if (oldChild) { + if (isNodeString(child)) { + if (oldChild.t !== child.t) { + ; + oldChild.t = child.t; + oldChild.d = true; + } + child = oldChild; + } else { + const pP = oldChild.pP = oldChild.props; + oldChild.props = child.props; + oldChild.f ||= child.f || node.f; + if (typeof child.tag === "function") { + const oldContexts = oldChild[DOM_STASH][2]; + oldChild[DOM_STASH][2] = child[DOM_STASH][2] || []; + oldChild[DOM_STASH][3] = child[DOM_STASH][3]; + if (!oldChild.f && ((oldChild.o || oldChild) === child.o || // The code generated by the react compiler is memoized under this condition. + oldChild.tag[DOM_MEMO]?.(pP, oldChild.props)) && // The `memo` function is memoized under this condition. + isSameContext(oldContexts, oldChild[DOM_STASH][2])) { + oldChild.s = true; + } + } + child = oldChild; + } + } else if (!isNodeString(child) && nameSpaceContext) { + const ns = useContext(nameSpaceContext); + if (ns) { + child.n = ns; + } + } + if (!isNodeString(child) && !child.s) { + build(context, child); + delete child.f; + } + vChildren.push(child); + if (prevNode && !prevNode.s && !child.s) { + for (let p = prevNode; p && !isNodeString(p); p = p.vC?.at(-1)) { + p.nN = child; + } + } + prevNode = child; + } + } + node.vR = buildWithPreviousChildren ? [...node.vC, ...oldVChildren || []] : oldVChildren || []; + node.vC = vChildren; + if (buildWithPreviousChildren) { + delete node.pC; + } + } catch (e) { + node.f = true; + if (e === cancelBuild) { + if (foundErrorHandler) { + return; + } else { + throw e; + } + } + const [errorHandlerContext, errorHandler, errorHandlerNode] = node[DOM_STASH]?.[3] || []; + if (errorHandler) { + const fallbackUpdateFn = () => update([0, false, context[2]], errorHandlerNode); + const fallbackUpdateFnArray = fallbackUpdateFnArrayMap.get(errorHandlerNode) || []; + fallbackUpdateFnArray.push(fallbackUpdateFn); + fallbackUpdateFnArrayMap.set(errorHandlerNode, fallbackUpdateFnArray); + const fallback = errorHandler(e, () => { + const fnArray = fallbackUpdateFnArrayMap.get(errorHandlerNode); + if (fnArray) { + const i = fnArray.indexOf(fallbackUpdateFn); + if (i !== -1) { + fnArray.splice(i, 1); + return fallbackUpdateFn(); + } + } + }); + if (fallback) { + if (context[0] === 1) { + context[1] = true; + } else { + build(context, errorHandlerNode, [fallback]); + if ((errorHandler.length === 1 || context !== errorHandlerContext) && errorHandlerNode.c) { + apply(errorHandlerNode, errorHandlerNode.c, false); + return; + } + } + throw cancelBuild; + } + } + throw e; + } finally { + if (foundErrorHandler) { + context[5].pop(); + } + } +}; +var buildNode = (node) => { + if (node === void 0 || node === null || typeof node === "boolean") { + return void 0; + } else if (typeof node === "string" || typeof node === "number") { + return { t: node.toString(), d: true }; + } else { + if ("vR" in node) { + node = { + tag: node.tag, + props: node.props, + key: node.key, + f: node.f, + type: node.tag, + ref: node.props.ref, + o: node.o || node + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; + } + if (typeof node.tag === "function") { + ; + node[DOM_STASH] = [0, []]; + } else { + const ns = nameSpaceMap[node.tag]; + if (ns) { + nameSpaceContext ||= createContext(""); + node.props.children = [ + { + tag: nameSpaceContext, + props: { + value: node.n = `http://www.w3.org/${ns}`, + children: node.props.children + } + } + ]; + } + } + return node; + } +}; +var replaceContainer = (node, from, to) => { + if (node.c === from) { + node.c = to; + node.vC.forEach((child) => replaceContainer(child, from, to)); + } +}; +var updateSync = (context, node) => { + node[DOM_STASH][2]?.forEach(([c, v]) => { + c.values.push(v); + }); + try { + build(context, node, void 0); + } catch { + return; + } + if (node.a) { + delete node.a; + return; + } + node[DOM_STASH][2]?.forEach(([c]) => { + c.values.pop(); + }); + if (context[0] !== 1 || !context[1]) { + apply(node, node.c, false); + } +}; +var updateMap = /* @__PURE__ */ new WeakMap(); +var currentUpdateSets = []; +var update = async (context, node) => { + context[5] ||= []; + const existing = updateMap.get(node); + if (existing) { + existing[0](void 0); + } + let resolve; + const promise = new Promise((r) => resolve = r); + updateMap.set(node, [ + resolve, + () => { + if (context[2]) { + context[2](context, node, (context2) => { + updateSync(context2, node); + }).then(() => resolve(node)); + } else { + updateSync(context, node); + resolve(node); + } + } + ]); + if (currentUpdateSets.length) { + ; + currentUpdateSets.at(-1).add(node); + } else { + await Promise.resolve(); + const latest = updateMap.get(node); + if (latest) { + updateMap.delete(node); + latest[1](); + } + } + return promise; +}; +var renderNode = (node, container) => { + const context = []; + context[5] = []; + context[4] = true; + build(context, node, void 0); + context[4] = false; + const fragment = document.createDocumentFragment(); + apply(node, fragment, true); + replaceContainer(node, fragment, container); + container.replaceChildren(fragment); +}; +var render = (jsxNode, container) => { + renderNode(buildNode({ tag: "", props: { children: jsxNode } }), container); +}; +var flushSync = (callback) => { + const set = /* @__PURE__ */ new Set(); + currentUpdateSets.push(set); + callback(); + set.forEach((node) => { + const latest = updateMap.get(node); + if (latest) { + updateMap.delete(node); + latest[1](); + } + }); + currentUpdateSets.pop(); +}; +var createPortal = (children, container, key) => ({ + tag: HONO_PORTAL_ELEMENT, + props: { + children + }, + key, + e: container, + p: 1 + // eslint-disable-next-line @typescript-eslint/no-explicit-any +}); +export { + build, + buildDataStack, + buildNode, + createPortal, + flushSync, + getNameSpaceContext, + render, + renderNode, + update +}; diff --git a/node_modules/hono/dist/jsx/dom/server.js b/node_modules/hono/dist/jsx/dom/server.js new file mode 100644 index 000000000..a1110ddad --- /dev/null +++ b/node_modules/hono/dist/jsx/dom/server.js @@ -0,0 +1,33 @@ +// src/jsx/dom/server.ts +import { renderToReadableStream as renderToReadableStreamHono } from "../streaming.js"; +import version from "./index.js"; +var renderToString = (element, options = {}) => { + if (Object.keys(options).length > 0) { + console.warn("options are not supported yet"); + } + const res = element?.toString() ?? ""; + if (typeof res !== "string") { + throw new Error("Async component is not supported in renderToString"); + } + return res; +}; +var renderToReadableStream = async (element, options = {}) => { + if (Object.keys(options).some((key) => key !== "onError")) { + console.warn("options are not supported yet, except onError"); + } + if (!element || typeof element !== "object") { + element = element?.toString() ?? ""; + } + return renderToReadableStreamHono(element, options.onError); +}; +var server_default = { + renderToString, + renderToReadableStream, + version +}; +export { + server_default as default, + renderToReadableStream, + renderToString, + version +}; diff --git a/node_modules/hono/dist/jsx/dom/utils.js b/node_modules/hono/dist/jsx/dom/utils.js new file mode 100644 index 000000000..b8efa98b3 --- /dev/null +++ b/node_modules/hono/dist/jsx/dom/utils.js @@ -0,0 +1,10 @@ +// src/jsx/dom/utils.ts +import { DOM_INTERNAL_TAG } from "../constants.js"; +var setInternalTagFlag = (fn) => { + ; + fn[DOM_INTERNAL_TAG] = true; + return fn; +}; +export { + setInternalTagFlag +}; diff --git a/node_modules/hono/dist/jsx/hooks/index.js b/node_modules/hono/dist/jsx/hooks/index.js new file mode 100644 index 000000000..ec842c73a --- /dev/null +++ b/node_modules/hono/dist/jsx/hooks/index.js @@ -0,0 +1,328 @@ +// src/jsx/hooks/index.ts +import { DOM_STASH } from "../constants.js"; +import { buildDataStack, update } from "../dom/render.js"; +var STASH_SATE = 0; +var STASH_EFFECT = 1; +var STASH_CALLBACK = 2; +var STASH_MEMO = 3; +var STASH_REF = 4; +var resolvedPromiseValueMap = /* @__PURE__ */ new WeakMap(); +var isDepsChanged = (prevDeps, deps) => !prevDeps || !deps || prevDeps.length !== deps.length || deps.some((dep, i) => dep !== prevDeps[i]); +var viewTransitionState = void 0; +var documentStartViewTransition = (cb) => { + if (document?.startViewTransition) { + return document.startViewTransition(cb); + } else { + cb(); + return { finished: Promise.resolve() }; + } +}; +var updateHook = void 0; +var viewTransitionHook = (context, node, cb) => { + const state = [true, false]; + let lastVC = node.vC; + return documentStartViewTransition(() => { + if (lastVC === node.vC) { + viewTransitionState = state; + cb(context); + viewTransitionState = void 0; + lastVC = node.vC; + } + }).finished.then(() => { + if (state[1] && lastVC === node.vC) { + state[0] = false; + viewTransitionState = state; + cb(context); + viewTransitionState = void 0; + } + }); +}; +var startViewTransition = (callback) => { + updateHook = viewTransitionHook; + try { + callback(); + } finally { + updateHook = void 0; + } +}; +var useViewTransition = () => { + const buildData = buildDataStack.at(-1); + if (!buildData) { + return [false, () => { + }]; + } + if (viewTransitionState) { + viewTransitionState[1] = true; + } + return [!!viewTransitionState?.[0], startViewTransition]; +}; +var pendingStack = []; +var runCallback = (type, callback) => { + let resolve; + const promise = new Promise((r) => resolve = r); + pendingStack.push([type, promise]); + try { + const res = callback(); + if (res instanceof Promise) { + res.then(resolve, resolve); + } else { + resolve(); + } + } finally { + pendingStack.pop(); + } +}; +var startTransition = (callback) => { + runCallback(1, callback); +}; +var startTransitionHook = (callback) => { + runCallback(2, callback); +}; +var useTransition = () => { + const buildData = buildDataStack.at(-1); + if (!buildData) { + return [false, () => { + }]; + } + const [error, setError] = useState(); + const [state, updateState] = useState(); + if (error) { + throw error[0]; + } + const startTransitionLocalHook = useCallback( + (callback) => { + startTransitionHook(() => { + updateState((state2) => !state2); + let res = callback(); + if (res instanceof Promise) { + res = res.catch((e) => { + setError([e]); + }); + } + return res; + }); + }, + [state] + ); + const [context] = buildData; + return [context[0] === 2, startTransitionLocalHook]; +}; +var useDeferredValue = (value, ...rest) => { + const [values, setValues] = useState( + rest.length ? [rest[0], rest[0]] : [value, value] + ); + if (Object.is(values[1], value)) { + return values[1]; + } + pendingStack.push([3, Promise.resolve()]); + updateHook = async (context, _, cb) => { + cb(context); + values[0] = value; + }; + setValues([values[0], value]); + updateHook = void 0; + pendingStack.pop(); + return values[0]; +}; +var useState = (initialState) => { + const resolveInitialState = () => typeof initialState === "function" ? initialState() : initialState; + const buildData = buildDataStack.at(-1); + if (!buildData) { + return [resolveInitialState(), () => { + }]; + } + const [, node] = buildData; + const stateArray = node[DOM_STASH][1][STASH_SATE] ||= []; + const hookIndex = node[DOM_STASH][0]++; + return stateArray[hookIndex] ||= [ + resolveInitialState(), + (newState) => { + const localUpdateHook = updateHook; + const stateData = stateArray[hookIndex]; + if (typeof newState === "function") { + newState = newState(stateData[0]); + } + if (!Object.is(newState, stateData[0])) { + stateData[0] = newState; + if (pendingStack.length) { + const [pendingType, pendingPromise] = pendingStack.at(-1); + Promise.all([ + pendingType === 3 ? node : update([pendingType, false, localUpdateHook], node), + pendingPromise + ]).then(([node2]) => { + if (!node2 || !(pendingType === 2 || pendingType === 3)) { + return; + } + const lastVC = node2.vC; + const addUpdateTask = () => { + setTimeout(() => { + if (lastVC !== node2.vC) { + return; + } + update([pendingType === 3 ? 1 : 0, false, localUpdateHook], node2); + }); + }; + requestAnimationFrame(addUpdateTask); + }); + } else { + update([0, false, localUpdateHook], node); + } + } + } + ]; +}; +var useReducer = (reducer, initialArg, init) => { + const handler = useCallback( + (action) => { + setState((state2) => reducer(state2, action)); + }, + [reducer] + ); + const [state, setState] = useState(() => init ? init(initialArg) : initialArg); + return [state, handler]; +}; +var useEffectCommon = (index, effect, deps) => { + const buildData = buildDataStack.at(-1); + if (!buildData) { + return; + } + const [, node] = buildData; + const effectDepsArray = node[DOM_STASH][1][STASH_EFFECT] ||= []; + const hookIndex = node[DOM_STASH][0]++; + const [prevDeps, , prevCleanup] = effectDepsArray[hookIndex] ||= []; + if (isDepsChanged(prevDeps, deps)) { + if (prevCleanup) { + prevCleanup(); + } + const runner = () => { + data[index] = void 0; + data[2] = effect(); + }; + const data = [deps, void 0, void 0, void 0, void 0]; + data[index] = runner; + effectDepsArray[hookIndex] = data; + } +}; +var useEffect = (effect, deps) => useEffectCommon(3, effect, deps); +var useLayoutEffect = (effect, deps) => useEffectCommon(1, effect, deps); +var useInsertionEffect = (effect, deps) => useEffectCommon(4, effect, deps); +var useCallback = (callback, deps) => { + const buildData = buildDataStack.at(-1); + if (!buildData) { + return callback; + } + const [, node] = buildData; + const callbackArray = node[DOM_STASH][1][STASH_CALLBACK] ||= []; + const hookIndex = node[DOM_STASH][0]++; + const prevDeps = callbackArray[hookIndex]; + if (isDepsChanged(prevDeps?.[1], deps)) { + callbackArray[hookIndex] = [callback, deps]; + } else { + callback = callbackArray[hookIndex][0]; + } + return callback; +}; +var useRef = (initialValue) => { + const buildData = buildDataStack.at(-1); + if (!buildData) { + return { current: initialValue }; + } + const [, node] = buildData; + const refArray = node[DOM_STASH][1][STASH_REF] ||= []; + const hookIndex = node[DOM_STASH][0]++; + return refArray[hookIndex] ||= { current: initialValue }; +}; +var use = (promise) => { + const cachedRes = resolvedPromiseValueMap.get(promise); + if (cachedRes) { + if (cachedRes.length === 2) { + throw cachedRes[1]; + } + return cachedRes[0]; + } + promise.then( + (res) => resolvedPromiseValueMap.set(promise, [res]), + (e) => resolvedPromiseValueMap.set(promise, [void 0, e]) + ); + throw promise; +}; +var useMemo = (factory, deps) => { + const buildData = buildDataStack.at(-1); + if (!buildData) { + return factory(); + } + const [, node] = buildData; + const memoArray = node[DOM_STASH][1][STASH_MEMO] ||= []; + const hookIndex = node[DOM_STASH][0]++; + const prevDeps = memoArray[hookIndex]; + if (isDepsChanged(prevDeps?.[1], deps)) { + memoArray[hookIndex] = [factory(), deps]; + } + return memoArray[hookIndex][0]; +}; +var idCounter = 0; +var useId = () => useMemo(() => `:r${(idCounter++).toString(32)}:`, []); +var useDebugValue = (_value, _formatter) => { +}; +var createRef = () => { + return { current: null }; +}; +var forwardRef = (Component) => { + return (props) => { + const { ref, ...rest } = props; + return Component(rest, ref); + }; +}; +var useImperativeHandle = (ref, createHandle, deps) => { + useEffect(() => { + ref.current = createHandle(); + return () => { + ref.current = null; + }; + }, deps); +}; +var useSyncExternalStore = (subscribe, getSnapshot, getServerSnapshot) => { + const buildData = buildDataStack.at(-1); + if (!buildData) { + if (!getServerSnapshot) { + throw new Error("getServerSnapshot is required for server side rendering"); + } + return getServerSnapshot(); + } + const [serverSnapshotIsUsed] = useState(!!(buildData[0][4] && getServerSnapshot)); + const [state, setState] = useState( + () => serverSnapshotIsUsed ? getServerSnapshot() : getSnapshot() + ); + useEffect(() => { + if (serverSnapshotIsUsed) { + setState(getSnapshot()); + } + return subscribe(() => { + setState(getSnapshot()); + }); + }, []); + return state; +}; +export { + STASH_EFFECT, + createRef, + forwardRef, + startTransition, + startViewTransition, + use, + useCallback, + useDebugValue, + useDeferredValue, + useEffect, + useId, + useImperativeHandle, + useInsertionEffect, + useLayoutEffect, + useMemo, + useReducer, + useRef, + useState, + useSyncExternalStore, + useTransition, + useViewTransition +}; diff --git a/node_modules/hono/dist/jsx/index.js b/node_modules/hono/dist/jsx/index.js new file mode 100644 index 000000000..49b2df901 --- /dev/null +++ b/node_modules/hono/dist/jsx/index.js @@ -0,0 +1,103 @@ +// src/jsx/index.ts +import { Fragment, cloneElement, isValidElement, jsx, memo, reactAPICompatVersion } from "./base.js"; +import { Children } from "./children.js"; +import { ErrorBoundary } from "./components.js"; +import { createContext, useContext } from "./context.js"; +import { useActionState, useOptimistic } from "./dom/hooks/index.js"; +import { + createRef, + forwardRef, + startTransition, + startViewTransition, + use, + useCallback, + useDebugValue, + useDeferredValue, + useEffect, + useId, + useImperativeHandle, + useInsertionEffect, + useLayoutEffect, + useMemo, + useReducer, + useRef, + useState, + useSyncExternalStore, + useTransition, + useViewTransition +} from "./hooks/index.js"; +import { Suspense } from "./streaming.js"; +var jsx_default = { + version: reactAPICompatVersion, + memo, + Fragment, + StrictMode: Fragment, + isValidElement, + createElement: jsx, + cloneElement, + ErrorBoundary, + createContext, + useContext, + useState, + useEffect, + useRef, + useCallback, + useReducer, + useId, + useDebugValue, + use, + startTransition, + useTransition, + useDeferredValue, + startViewTransition, + useViewTransition, + useMemo, + useLayoutEffect, + useInsertionEffect, + createRef, + forwardRef, + useImperativeHandle, + useSyncExternalStore, + useActionState, + useOptimistic, + Suspense, + Children +}; +export { + Children, + ErrorBoundary, + Fragment, + Fragment as StrictMode, + Suspense, + cloneElement, + createContext, + jsx as createElement, + createRef, + jsx_default as default, + forwardRef, + isValidElement, + jsx, + memo, + startTransition, + startViewTransition, + use, + useActionState, + useCallback, + useContext, + useDebugValue, + useDeferredValue, + useEffect, + useId, + useImperativeHandle, + useInsertionEffect, + useLayoutEffect, + useMemo, + useOptimistic, + useReducer, + useRef, + useState, + useSyncExternalStore, + useTransition, + useViewTransition, + reactAPICompatVersion as version +}; diff --git a/node_modules/hono/dist/jsx/intrinsic-element/common.js b/node_modules/hono/dist/jsx/intrinsic-element/common.js new file mode 100644 index 000000000..b287db7f9 --- /dev/null +++ b/node_modules/hono/dist/jsx/intrinsic-element/common.js @@ -0,0 +1,15 @@ +// src/jsx/intrinsic-element/common.ts +var deDupeKeyMap = { + title: [], + script: ["src"], + style: ["data-href"], + link: ["href"], + meta: ["name", "httpEquiv", "charset", "itemProp"] +}; +var domRenderers = {}; +var dataPrecedenceAttr = "data-precedence"; +export { + dataPrecedenceAttr, + deDupeKeyMap, + domRenderers +}; diff --git a/node_modules/hono/dist/jsx/intrinsic-element/components.js b/node_modules/hono/dist/jsx/intrinsic-element/components.js new file mode 100644 index 000000000..116565fe6 --- /dev/null +++ b/node_modules/hono/dist/jsx/intrinsic-element/components.js @@ -0,0 +1,153 @@ +// src/jsx/intrinsic-element/components.ts +import { raw } from "../../helper/html/index.js"; +import { JSXNode, getNameSpaceContext } from "../base.js"; +import { toArray } from "../children.js"; +import { PERMALINK } from "../constants.js"; +import { useContext } from "../context.js"; +import { dataPrecedenceAttr, deDupeKeyMap } from "./common.js"; +var metaTagMap = /* @__PURE__ */ new WeakMap(); +var insertIntoHead = (tagName, tag, props, precedence) => ({ buffer, context }) => { + if (!buffer) { + return; + } + const map = metaTagMap.get(context) || {}; + metaTagMap.set(context, map); + const tags = map[tagName] ||= []; + let duped = false; + const deDupeKeys = deDupeKeyMap[tagName]; + if (deDupeKeys.length > 0) { + LOOP: for (const [, tagProps] of tags) { + for (const key of deDupeKeys) { + if ((tagProps?.[key] ?? null) === props?.[key]) { + duped = true; + break LOOP; + } + } + } + } + if (duped) { + buffer[0] = buffer[0].replaceAll(tag, ""); + } else if (deDupeKeys.length > 0) { + tags.push([tag, props, precedence]); + } else { + tags.unshift([tag, props, precedence]); + } + if (buffer[0].indexOf("") !== -1) { + let insertTags; + if (precedence === void 0) { + insertTags = tags.map(([tag2]) => tag2); + } else { + const precedences = []; + insertTags = tags.map(([tag2, , precedence2]) => { + let order = precedences.indexOf(precedence2); + if (order === -1) { + precedences.push(precedence2); + order = precedences.length - 1; + } + return [tag2, order]; + }).sort((a, b) => a[1] - b[1]).map(([tag2]) => tag2); + } + insertTags.forEach((tag2) => { + buffer[0] = buffer[0].replaceAll(tag2, ""); + }); + buffer[0] = buffer[0].replace(/(?=<\/head>)/, insertTags.join("")); + } +}; +var returnWithoutSpecialBehavior = (tag, children, props) => raw(new JSXNode(tag, props, toArray(children ?? [])).toString()); +var documentMetadataTag = (tag, children, props, sort) => { + if ("itemProp" in props) { + return returnWithoutSpecialBehavior(tag, children, props); + } + let { precedence, blocking, ...restProps } = props; + precedence = sort ? precedence ?? "" : void 0; + if (sort) { + restProps[dataPrecedenceAttr] = precedence; + } + const string = new JSXNode(tag, restProps, toArray(children || [])).toString(); + if (string instanceof Promise) { + return string.then( + (resString) => raw(string, [ + ...resString.callbacks || [], + insertIntoHead(tag, resString, restProps, precedence) + ]) + ); + } else { + return raw(string, [insertIntoHead(tag, string, restProps, precedence)]); + } +}; +var title = ({ children, ...props }) => { + const nameSpaceContext = getNameSpaceContext(); + if (nameSpaceContext) { + const context = useContext(nameSpaceContext); + if (context === "svg" || context === "head") { + return new JSXNode( + "title", + props, + toArray(children ?? []) + ); + } + } + return documentMetadataTag("title", children, props, false); +}; +var script = ({ + children, + ...props +}) => { + const nameSpaceContext = getNameSpaceContext(); + if (["src", "async"].some((k) => !props[k]) || nameSpaceContext && useContext(nameSpaceContext) === "head") { + return returnWithoutSpecialBehavior("script", children, props); + } + return documentMetadataTag("script", children, props, false); +}; +var style = ({ + children, + ...props +}) => { + if (!["href", "precedence"].every((k) => k in props)) { + return returnWithoutSpecialBehavior("style", children, props); + } + props["data-href"] = props.href; + delete props.href; + return documentMetadataTag("style", children, props, true); +}; +var link = ({ children, ...props }) => { + if (["onLoad", "onError"].some((k) => k in props) || props.rel === "stylesheet" && (!("precedence" in props) || "disabled" in props)) { + return returnWithoutSpecialBehavior("link", children, props); + } + return documentMetadataTag("link", children, props, "precedence" in props); +}; +var meta = ({ children, ...props }) => { + const nameSpaceContext = getNameSpaceContext(); + if (nameSpaceContext && useContext(nameSpaceContext) === "head") { + return returnWithoutSpecialBehavior("meta", children, props); + } + return documentMetadataTag("meta", children, props, false); +}; +var newJSXNode = (tag, { children, ...props }) => ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + new JSXNode(tag, props, toArray(children ?? [])) +); +var form = (props) => { + if (typeof props.action === "function") { + props.action = PERMALINK in props.action ? props.action[PERMALINK] : void 0; + } + return newJSXNode("form", props); +}; +var formActionableElement = (tag, props) => { + if (typeof props.formAction === "function") { + props.formAction = PERMALINK in props.formAction ? props.formAction[PERMALINK] : void 0; + } + return newJSXNode(tag, props); +}; +var input = (props) => formActionableElement("input", props); +var button = (props) => formActionableElement("button", props); +export { + button, + form, + input, + link, + meta, + script, + style, + title +}; diff --git a/node_modules/hono/dist/jsx/intrinsic-elements.js b/node_modules/hono/dist/jsx/intrinsic-elements.js new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/hono/dist/jsx/jsx-dev-runtime.js b/node_modules/hono/dist/jsx/jsx-dev-runtime.js new file mode 100644 index 000000000..2a6892020 --- /dev/null +++ b/node_modules/hono/dist/jsx/jsx-dev-runtime.js @@ -0,0 +1,18 @@ +// src/jsx/jsx-dev-runtime.ts +import { jsxFn } from "./base.js"; +import { Fragment } from "./base.js"; +function jsxDEV(tag, props, key) { + let node; + if (!props || !("children" in props)) { + node = jsxFn(tag, props, []); + } else { + const children = props.children; + node = Array.isArray(children) ? jsxFn(tag, props, children) : jsxFn(tag, props, [children]); + } + node.key = key; + return node; +} +export { + Fragment, + jsxDEV +}; diff --git a/node_modules/hono/dist/jsx/jsx-runtime.js b/node_modules/hono/dist/jsx/jsx-runtime.js new file mode 100644 index 000000000..7ad5df359 --- /dev/null +++ b/node_modules/hono/dist/jsx/jsx-runtime.js @@ -0,0 +1,41 @@ +// src/jsx/jsx-runtime.ts +import { jsxDEV, Fragment } from "./jsx-dev-runtime.js"; +import { jsxDEV as jsxDEV2 } from "./jsx-dev-runtime.js"; +import { html, raw } from "../helper/html/index.js"; +import { escapeToBuffer, stringBufferToString } from "../utils/html.js"; +import { styleObjectForEach } from "./utils.js"; +var jsxAttr = (key, v) => { + const buffer = [`${key}="`]; + if (key === "style" && typeof v === "object") { + let styleStr = ""; + styleObjectForEach(v, (property, value) => { + if (value != null) { + styleStr += `${styleStr ? ";" : ""}${property}:${value}`; + } + }); + escapeToBuffer(styleStr, buffer); + buffer[0] += '"'; + } else if (typeof v === "string") { + escapeToBuffer(v, buffer); + buffer[0] += '"'; + } else if (v === null || v === void 0) { + return raw(""); + } else if (typeof v === "number" || v.isEscaped) { + buffer[0] += `${v}"`; + } else if (v instanceof Promise) { + buffer.unshift('"', v); + } else { + escapeToBuffer(v.toString(), buffer); + buffer[0] += '"'; + } + return buffer.length === 1 ? raw(buffer[0]) : stringBufferToString(buffer, void 0); +}; +var jsxEscape = (value) => value; +export { + Fragment, + jsxDEV as jsx, + jsxAttr, + jsxEscape, + html as jsxTemplate, + jsxDEV2 as jsxs +}; diff --git a/node_modules/hono/dist/jsx/streaming.js b/node_modules/hono/dist/jsx/streaming.js new file mode 100644 index 000000000..ea64dc04e --- /dev/null +++ b/node_modules/hono/dist/jsx/streaming.js @@ -0,0 +1,143 @@ +// src/jsx/streaming.ts +import { raw } from "../helper/html/index.js"; +import { HtmlEscapedCallbackPhase, resolveCallback } from "../utils/html.js"; +import { JSXNode } from "./base.js"; +import { childrenToString } from "./components.js"; +import { DOM_RENDERER, DOM_STASH } from "./constants.js"; +import { createContext, useContext } from "./context.js"; +import { Suspense as SuspenseDomRenderer } from "./dom/components.js"; +import { buildDataStack } from "./dom/render.js"; +var StreamingContext = createContext(null); +var suspenseCounter = 0; +var Suspense = async ({ + children, + fallback +}) => { + if (!Array.isArray(children)) { + children = [children]; + } + const nonce = useContext(StreamingContext)?.scriptNonce; + let resArray = []; + const stackNode = { [DOM_STASH]: [0, []] }; + const popNodeStack = (value) => { + buildDataStack.pop(); + return value; + }; + try { + stackNode[DOM_STASH][0] = 0; + buildDataStack.push([[], stackNode]); + resArray = children.map( + (c) => c == null || typeof c === "boolean" ? "" : c.toString() + ); + } catch (e) { + if (e instanceof Promise) { + resArray = [ + e.then(() => { + stackNode[DOM_STASH][0] = 0; + buildDataStack.push([[], stackNode]); + return childrenToString(children).then(popNodeStack); + }) + ]; + } else { + throw e; + } + } finally { + popNodeStack(); + } + if (resArray.some((res) => res instanceof Promise)) { + const index = suspenseCounter++; + const fallbackStr = await fallback.toString(); + return raw(`${fallbackStr}`, [ + ...fallbackStr.callbacks || [], + ({ phase, buffer, context }) => { + if (phase === HtmlEscapedCallbackPhase.BeforeStream) { + return; + } + return Promise.all(resArray).then(async (htmlArray) => { + htmlArray = htmlArray.flat(); + const content = htmlArray.join(""); + if (buffer) { + buffer[0] = buffer[0].replace( + new RegExp(`.*?`), + content + ); + } + let html = buffer ? "" : ` +((d,c,n) => { +c=d.currentScript.previousSibling +d=d.getElementById('H:${index}') +if(!d)return +do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$') +d.replaceWith(c.content) +})(document) +`; + const callbacks = htmlArray.map((html2) => html2.callbacks || []).flat(); + if (!callbacks.length) { + return html; + } + if (phase === HtmlEscapedCallbackPhase.Stream) { + html = await resolveCallback(html, HtmlEscapedCallbackPhase.BeforeStream, true, context); + } + return raw(html, callbacks); + }); + } + ]); + } else { + return raw(resArray.join("")); + } +}; +Suspense[DOM_RENDERER] = SuspenseDomRenderer; +var textEncoder = new TextEncoder(); +var renderToReadableStream = (content, onError = console.trace) => { + const reader = new ReadableStream({ + async start(controller) { + try { + if (content instanceof JSXNode) { + content = content.toString(); + } + const context = typeof content === "object" ? content : {}; + const resolved = await resolveCallback( + content, + HtmlEscapedCallbackPhase.BeforeStream, + true, + context + ); + controller.enqueue(textEncoder.encode(resolved)); + let resolvedCount = 0; + const callbacks = []; + const then = (promise) => { + callbacks.push( + promise.catch((err) => { + console.log(err); + onError(err); + return ""; + }).then(async (res) => { + res = await resolveCallback( + res, + HtmlEscapedCallbackPhase.BeforeStream, + true, + context + ); + res.callbacks?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context })).filter(Boolean).forEach(then); + resolvedCount++; + controller.enqueue(textEncoder.encode(res)); + }) + ); + }; + resolved.callbacks?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context })).filter(Boolean).forEach(then); + while (resolvedCount !== callbacks.length) { + await Promise.all(callbacks); + } + } catch (e) { + onError(e); + } + controller.close(); + } + }); + return reader; +}; +export { + StreamingContext, + Suspense, + renderToReadableStream +}; diff --git a/node_modules/hono/dist/jsx/types.js b/node_modules/hono/dist/jsx/types.js new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/hono/dist/jsx/utils.js b/node_modules/hono/dist/jsx/utils.js new file mode 100644 index 000000000..7f3a21913 --- /dev/null +++ b/node_modules/hono/dist/jsx/utils.js @@ -0,0 +1,27 @@ +// src/jsx/utils.ts +var normalizeElementKeyMap = /* @__PURE__ */ new Map([ + ["className", "class"], + ["htmlFor", "for"], + ["crossOrigin", "crossorigin"], + ["httpEquiv", "http-equiv"], + ["itemProp", "itemprop"], + ["fetchPriority", "fetchpriority"], + ["noModule", "nomodule"], + ["formAction", "formaction"] +]); +var normalizeIntrinsicElementKey = (key) => normalizeElementKeyMap.get(key) || key; +var styleObjectForEach = (style, fn) => { + for (const [k, v] of Object.entries(style)) { + const key = k[0] === "-" || !/[A-Z]/.test(k) ? k : k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`); + fn( + key, + v == null ? null : typeof v === "number" ? !key.match( + /^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/ + ) ? `${v}px` : `${v}` : v + ); + } +}; +export { + normalizeIntrinsicElementKey, + styleObjectForEach +}; diff --git a/node_modules/hono/dist/middleware/basic-auth/index.js b/node_modules/hono/dist/middleware/basic-auth/index.js new file mode 100644 index 000000000..fc54a534d --- /dev/null +++ b/node_modules/hono/dist/middleware/basic-auth/index.js @@ -0,0 +1,60 @@ +// src/middleware/basic-auth/index.ts +import { HTTPException } from "../../http-exception.js"; +import { auth } from "../../utils/basic-auth.js"; +import { timingSafeEqual } from "../../utils/buffer.js"; +var basicAuth = (options, ...users) => { + const usernamePasswordInOptions = "username" in options && "password" in options; + const verifyUserInOptions = "verifyUser" in options; + if (!(usernamePasswordInOptions || verifyUserInOptions)) { + throw new Error( + 'basic auth middleware requires options for "username and password" or "verifyUser"' + ); + } + if (!options.realm) { + options.realm = "Secure Area"; + } + if (!options.invalidUserMessage) { + options.invalidUserMessage = "Unauthorized"; + } + if (usernamePasswordInOptions) { + users.unshift({ username: options.username, password: options.password }); + } + return async function basicAuth2(ctx, next) { + const requestUser = auth(ctx.req.raw); + if (requestUser) { + if (verifyUserInOptions) { + if (await options.verifyUser(requestUser.username, requestUser.password, ctx)) { + await next(); + return; + } + } else { + for (const user of users) { + const [usernameEqual, passwordEqual] = await Promise.all([ + timingSafeEqual(user.username, requestUser.username, options.hashFunction), + timingSafeEqual(user.password, requestUser.password, options.hashFunction) + ]); + if (usernameEqual && passwordEqual) { + await next(); + return; + } + } + } + } + const status = 401; + const headers = { + "WWW-Authenticate": 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"' + }; + const responseMessage = typeof options.invalidUserMessage === "function" ? await options.invalidUserMessage(ctx) : options.invalidUserMessage; + const res = typeof responseMessage === "string" ? new Response(responseMessage, { status, headers }) : new Response(JSON.stringify(responseMessage), { + status, + headers: { + ...headers, + "content-type": "application/json" + } + }); + throw new HTTPException(status, { res }); + }; +}; +export { + basicAuth +}; diff --git a/node_modules/hono/dist/middleware/bearer-auth/index.js b/node_modules/hono/dist/middleware/bearer-auth/index.js new file mode 100644 index 000000000..f08289921 --- /dev/null +++ b/node_modules/hono/dist/middleware/bearer-auth/index.js @@ -0,0 +1,83 @@ +// src/middleware/bearer-auth/index.ts +import { HTTPException } from "../../http-exception.js"; +import { timingSafeEqual } from "../../utils/buffer.js"; +var TOKEN_STRINGS = "[A-Za-z0-9._~+/-]+=*"; +var PREFIX = "Bearer"; +var HEADER = "Authorization"; +var bearerAuth = (options) => { + if (!("token" in options || "verifyToken" in options)) { + throw new Error('bearer auth middleware requires options for "token"'); + } + if (!options.realm) { + options.realm = ""; + } + if (options.prefix === void 0) { + options.prefix = PREFIX; + } + const realm = options.realm?.replace(/"/g, '\\"'); + const prefixRegexStr = options.prefix === "" ? "" : `${options.prefix} +`; + const regexp = new RegExp(`^${prefixRegexStr}(${TOKEN_STRINGS}) *$`); + const wwwAuthenticatePrefix = options.prefix === "" ? "" : `${options.prefix} `; + const throwHTTPException = async (c, status, wwwAuthenticateHeader, messageOption) => { + const wwwAuthenticateHeaderValue = typeof wwwAuthenticateHeader === "function" ? await wwwAuthenticateHeader(c) : wwwAuthenticateHeader; + const headers = { + "WWW-Authenticate": typeof wwwAuthenticateHeaderValue === "string" ? wwwAuthenticateHeaderValue : `${wwwAuthenticatePrefix}${Object.entries(wwwAuthenticateHeaderValue).map(([key, value]) => `${key}="${value}"`).join(",")}` + }; + const responseMessage = typeof messageOption === "function" ? await messageOption(c) : messageOption; + const res = typeof responseMessage === "string" ? new Response(responseMessage, { status, headers }) : new Response(JSON.stringify(responseMessage), { + status, + headers: { + ...headers, + "content-type": "application/json" + } + }); + throw new HTTPException(status, { res }); + }; + return async function bearerAuth2(c, next) { + const headerToken = c.req.header(options.headerName || HEADER); + if (!headerToken) { + await throwHTTPException( + c, + 401, + options.noAuthenticationHeader?.wwwAuthenticateHeader || `${wwwAuthenticatePrefix}realm="${realm}"`, + options.noAuthenticationHeader?.message || options.noAuthenticationHeaderMessage || "Unauthorized" + ); + } else { + const match = regexp.exec(headerToken); + if (!match) { + await throwHTTPException( + c, + 400, + options.invalidAuthenticationHeader?.wwwAuthenticateHeader || `${wwwAuthenticatePrefix}error="invalid_request"`, + options.invalidAuthenticationHeader?.message || options.invalidAuthenticationHeaderMessage || "Bad Request" + ); + } else { + let equal = false; + if ("verifyToken" in options) { + equal = await options.verifyToken(match[1], c); + } else if (typeof options.token === "string") { + equal = await timingSafeEqual(options.token, match[1], options.hashFunction); + } else if (Array.isArray(options.token) && options.token.length > 0) { + for (const token of options.token) { + if (await timingSafeEqual(token, match[1], options.hashFunction)) { + equal = true; + break; + } + } + } + if (!equal) { + await throwHTTPException( + c, + 401, + options.invalidToken?.wwwAuthenticateHeader || `${wwwAuthenticatePrefix}error="invalid_token"`, + options.invalidToken?.message || options.invalidTokenMessage || "Unauthorized" + ); + } + } + } + await next(); + }; +}; +export { + bearerAuth +}; diff --git a/node_modules/hono/dist/middleware/body-limit/index.js b/node_modules/hono/dist/middleware/body-limit/index.js new file mode 100644 index 000000000..01de75589 --- /dev/null +++ b/node_modules/hono/dist/middleware/body-limit/index.js @@ -0,0 +1,62 @@ +// src/middleware/body-limit/index.ts +import { HTTPException } from "../../http-exception.js"; +var ERROR_MESSAGE = "Payload Too Large"; +var BodyLimitError = class extends Error { + constructor(message) { + super(message); + this.name = "BodyLimitError"; + } +}; +var bodyLimit = (options) => { + const onError = options.onError || (() => { + const res = new Response(ERROR_MESSAGE, { + status: 413 + }); + throw new HTTPException(413, { res }); + }); + const maxSize = options.maxSize; + return async function bodyLimit2(c, next) { + if (!c.req.raw.body) { + return next(); + } + const hasTransferEncoding = c.req.raw.headers.has("transfer-encoding"); + const hasContentLength = c.req.raw.headers.has("content-length"); + if (hasTransferEncoding && hasContentLength) { + } + if (hasContentLength && !hasTransferEncoding) { + const contentLength = parseInt(c.req.raw.headers.get("content-length") || "0", 10); + return contentLength > maxSize ? onError(c) : next(); + } + let size = 0; + const rawReader = c.req.raw.body.getReader(); + const reader = new ReadableStream({ + async start(controller) { + try { + for (; ; ) { + const { done, value } = await rawReader.read(); + if (done) { + break; + } + size += value.length; + if (size > maxSize) { + controller.error(new BodyLimitError(ERROR_MESSAGE)); + break; + } + controller.enqueue(value); + } + } finally { + controller.close(); + } + } + }); + const requestInit = { body: reader, duplex: "half" }; + c.req.raw = new Request(c.req.raw, requestInit); + await next(); + if (c.error instanceof BodyLimitError) { + c.res = await onError(c); + } + }; +}; +export { + bodyLimit +}; diff --git a/node_modules/hono/dist/middleware/cache/index.js b/node_modules/hono/dist/middleware/cache/index.js new file mode 100644 index 000000000..3bb7bee22 --- /dev/null +++ b/node_modules/hono/dist/middleware/cache/index.js @@ -0,0 +1,79 @@ +// src/middleware/cache/index.ts +var defaultCacheableStatusCodes = [200]; +var shouldSkipCache = (res) => { + const vary = res.headers.get("Vary"); + return vary && vary.includes("*"); +}; +var cache = (options) => { + if (!globalThis.caches) { + console.log("Cache Middleware is not enabled because caches is not defined."); + return async (_c, next) => await next(); + } + if (options.wait === void 0) { + options.wait = false; + } + const cacheControlDirectives = options.cacheControl?.split(",").map((directive) => directive.toLowerCase()); + const varyDirectives = Array.isArray(options.vary) ? options.vary : options.vary?.split(",").map((directive) => directive.trim()); + if (options.vary?.includes("*")) { + throw new Error( + 'Middleware vary configuration cannot include "*", as it disallows effective caching.' + ); + } + const cacheableStatusCodes = new Set( + options.cacheableStatusCodes ?? defaultCacheableStatusCodes + ); + const addHeader = (c) => { + if (cacheControlDirectives) { + const existingDirectives = c.res.headers.get("Cache-Control")?.split(",").map((d) => d.trim().split("=", 1)[0]) ?? []; + for (const directive of cacheControlDirectives) { + let [name, value] = directive.trim().split("=", 2); + name = name.toLowerCase(); + if (!existingDirectives.includes(name)) { + c.header("Cache-Control", `${name}${value ? `=${value}` : ""}`, { append: true }); + } + } + } + if (varyDirectives) { + const existingDirectives = c.res.headers.get("Vary")?.split(",").map((d) => d.trim()) ?? []; + const vary = Array.from( + new Set( + [...existingDirectives, ...varyDirectives].map((directive) => directive.toLowerCase()) + ) + ).sort(); + if (vary.includes("*")) { + c.header("Vary", "*"); + } else { + c.header("Vary", vary.join(", ")); + } + } + }; + return async function cache2(c, next) { + let key = c.req.url; + if (options.keyGenerator) { + key = await options.keyGenerator(c); + } + const cacheName = typeof options.cacheName === "function" ? await options.cacheName(c) : options.cacheName; + const cache3 = await caches.open(cacheName); + const response = await cache3.match(key); + if (response) { + return new Response(response.body, response); + } + await next(); + if (!cacheableStatusCodes.has(c.res.status)) { + return; + } + addHeader(c); + if (shouldSkipCache(c.res)) { + return; + } + const res = c.res.clone(); + if (options.wait) { + await cache3.put(key, res); + } else { + c.executionCtx.waitUntil(cache3.put(key, res)); + } + }; +}; +export { + cache +}; diff --git a/node_modules/hono/dist/middleware/combine/index.js b/node_modules/hono/dist/middleware/combine/index.js new file mode 100644 index 000000000..c16d91f3e --- /dev/null +++ b/node_modules/hono/dist/middleware/combine/index.js @@ -0,0 +1,77 @@ +// src/middleware/combine/index.ts +import { compose } from "../../compose.js"; +import { METHOD_NAME_ALL } from "../../router.js"; +import { TrieRouter } from "../../router/trie-router/index.js"; +var some = (...middleware) => { + return async function some2(c, next) { + let isNextCalled = false; + const wrappedNext = () => { + isNextCalled = true; + return next(); + }; + let lastError; + for (const handler of middleware) { + try { + const result = await handler(c, wrappedNext); + if (result === true && !c.finalized) { + await wrappedNext(); + } else if (result === false) { + lastError = new Error("No successful middleware found"); + continue; + } + lastError = void 0; + break; + } catch (error) { + lastError = error; + if (isNextCalled) { + break; + } + } + } + if (lastError) { + throw lastError; + } + }; +}; +var every = (...middleware) => { + return async function every2(c, next) { + const currentRouteIndex = c.req.routeIndex; + await compose( + middleware.map((m) => [ + [ + async (c2, next2) => { + c2.req.routeIndex = currentRouteIndex; + const res = await m(c2, next2); + if (res === false) { + throw new Error("Unmet condition"); + } + return res; + } + ] + ]) + )(c, next); + }; +}; +var except = (condition, ...middleware) => { + let router = void 0; + const conditions = (Array.isArray(condition) ? condition : [condition]).map((condition2) => { + if (typeof condition2 === "string") { + router ||= new TrieRouter(); + router.add(METHOD_NAME_ALL, condition2, true); + } else { + return condition2; + } + }).filter(Boolean); + if (router) { + conditions.unshift((c) => !!router?.match(METHOD_NAME_ALL, c.req.path)?.[0]?.[0]?.[0]); + } + const handler = some((c) => conditions.some((cond) => cond(c)), every(...middleware)); + return async function except2(c, next) { + await handler(c, next); + }; +}; +export { + every, + except, + some +}; diff --git a/node_modules/hono/dist/middleware/compress/index.js b/node_modules/hono/dist/middleware/compress/index.js new file mode 100644 index 000000000..fcc3ae6fd --- /dev/null +++ b/node_modules/hono/dist/middleware/compress/index.js @@ -0,0 +1,39 @@ +// src/middleware/compress/index.ts +import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from "../../utils/compress.js"; +var ENCODING_TYPES = ["gzip", "deflate"]; +var cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i; +var compress = (options) => { + const threshold = options?.threshold ?? 1024; + return async function compress2(ctx, next) { + await next(); + const contentLength = ctx.res.headers.get("Content-Length"); + if (ctx.res.headers.has("Content-Encoding") || // already encoded + ctx.res.headers.has("Transfer-Encoding") || // already encoded or chunked + ctx.req.method === "HEAD" || // HEAD request + contentLength && Number(contentLength) < threshold || // content-length below threshold + !shouldCompress(ctx.res) || // not compressible type + !shouldTransform(ctx.res)) { + return; + } + const accepted = ctx.req.header("Accept-Encoding"); + const encoding = options?.encoding ?? ENCODING_TYPES.find((encoding2) => accepted?.includes(encoding2)); + if (!encoding || !ctx.res.body) { + return; + } + const stream = new CompressionStream(encoding); + ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res); + ctx.res.headers.delete("Content-Length"); + ctx.res.headers.set("Content-Encoding", encoding); + }; +}; +var shouldCompress = (res) => { + const type = res.headers.get("Content-Type"); + return type && COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type); +}; +var shouldTransform = (res) => { + const cacheControl = res.headers.get("Cache-Control"); + return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl); +}; +export { + compress +}; diff --git a/node_modules/hono/dist/middleware/context-storage/index.js b/node_modules/hono/dist/middleware/context-storage/index.js new file mode 100644 index 000000000..a1bd4c648 --- /dev/null +++ b/node_modules/hono/dist/middleware/context-storage/index.js @@ -0,0 +1,23 @@ +// src/middleware/context-storage/index.ts +import { AsyncLocalStorage } from "node:async_hooks"; +var asyncLocalStorage = new AsyncLocalStorage(); +var contextStorage = () => { + return async function contextStorage2(c, next) { + await asyncLocalStorage.run(c, next); + }; +}; +var tryGetContext = () => { + return asyncLocalStorage.getStore(); +}; +var getContext = () => { + const context = tryGetContext(); + if (!context) { + throw new Error("Context is not available"); + } + return context; +}; +export { + contextStorage, + getContext, + tryGetContext +}; diff --git a/node_modules/hono/dist/middleware/cors/index.js b/node_modules/hono/dist/middleware/cors/index.js new file mode 100644 index 000000000..9169e5a69 --- /dev/null +++ b/node_modules/hono/dist/middleware/cors/index.js @@ -0,0 +1,87 @@ +// src/middleware/cors/index.ts +var cors = (options) => { + const defaults = { + origin: "*", + allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"], + allowHeaders: [], + exposeHeaders: [] + }; + const opts = { + ...defaults, + ...options + }; + const findAllowOrigin = ((optsOrigin) => { + if (typeof optsOrigin === "string") { + if (optsOrigin === "*") { + return () => optsOrigin; + } else { + return (origin) => optsOrigin === origin ? origin : null; + } + } else if (typeof optsOrigin === "function") { + return optsOrigin; + } else { + return (origin) => optsOrigin.includes(origin) ? origin : null; + } + })(opts.origin); + const findAllowMethods = ((optsAllowMethods) => { + if (typeof optsAllowMethods === "function") { + return optsAllowMethods; + } else if (Array.isArray(optsAllowMethods)) { + return () => optsAllowMethods; + } else { + return () => []; + } + })(opts.allowMethods); + return async function cors2(c, next) { + function set(key, value) { + c.res.headers.set(key, value); + } + const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c); + if (allowOrigin) { + set("Access-Control-Allow-Origin", allowOrigin); + } + if (opts.credentials) { + set("Access-Control-Allow-Credentials", "true"); + } + if (opts.exposeHeaders?.length) { + set("Access-Control-Expose-Headers", opts.exposeHeaders.join(",")); + } + if (c.req.method === "OPTIONS") { + if (opts.origin !== "*") { + set("Vary", "Origin"); + } + if (opts.maxAge != null) { + set("Access-Control-Max-Age", opts.maxAge.toString()); + } + const allowMethods = await findAllowMethods(c.req.header("origin") || "", c); + if (allowMethods.length) { + set("Access-Control-Allow-Methods", allowMethods.join(",")); + } + let headers = opts.allowHeaders; + if (!headers?.length) { + const requestHeaders = c.req.header("Access-Control-Request-Headers"); + if (requestHeaders) { + headers = requestHeaders.split(/\s*,\s*/); + } + } + if (headers?.length) { + set("Access-Control-Allow-Headers", headers.join(",")); + c.res.headers.append("Vary", "Access-Control-Request-Headers"); + } + c.res.headers.delete("Content-Length"); + c.res.headers.delete("Content-Type"); + return new Response(null, { + headers: c.res.headers, + status: 204, + statusText: "No Content" + }); + } + await next(); + if (opts.origin !== "*") { + c.header("Vary", "Origin", { append: true }); + } + }; +}; +export { + cors +}; diff --git a/node_modules/hono/dist/middleware/csrf/index.js b/node_modules/hono/dist/middleware/csrf/index.js new file mode 100644 index 000000000..3df5b4ed2 --- /dev/null +++ b/node_modules/hono/dist/middleware/csrf/index.js @@ -0,0 +1,55 @@ +// src/middleware/csrf/index.ts +import { HTTPException } from "../../http-exception.js"; +var secFetchSiteValues = ["same-origin", "same-site", "none", "cross-site"]; +var isSecFetchSite = (value) => secFetchSiteValues.includes(value); +var isSafeMethodRe = /^(GET|HEAD)$/; +var isRequestedByFormElementRe = /^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/i; +var csrf = (options) => { + const originHandler = ((optsOrigin) => { + if (!optsOrigin) { + return (origin, c) => origin === new URL(c.req.url).origin; + } else if (typeof optsOrigin === "string") { + return (origin) => origin === optsOrigin; + } else if (typeof optsOrigin === "function") { + return optsOrigin; + } else { + return (origin) => optsOrigin.includes(origin); + } + })(options?.origin); + const isAllowedOrigin = async (origin, c) => { + if (origin === void 0) { + return false; + } + return await originHandler(origin, c); + }; + const secFetchSiteHandler = ((optsSecFetchSite) => { + if (!optsSecFetchSite) { + return (secFetchSite) => secFetchSite === "same-origin"; + } else if (typeof optsSecFetchSite === "string") { + return (secFetchSite) => secFetchSite === optsSecFetchSite; + } else if (typeof optsSecFetchSite === "function") { + return optsSecFetchSite; + } else { + return (secFetchSite) => optsSecFetchSite.includes(secFetchSite); + } + })(options?.secFetchSite); + const isAllowedSecFetchSite = async (secFetchSite, c) => { + if (secFetchSite === void 0) { + return false; + } + if (!isSecFetchSite(secFetchSite)) { + return false; + } + return await secFetchSiteHandler(secFetchSite, c); + }; + return async function csrf2(c, next) { + if (!isSafeMethodRe.test(c.req.method) && isRequestedByFormElementRe.test(c.req.header("content-type") || "text/plain") && !await isAllowedSecFetchSite(c.req.header("sec-fetch-site"), c) && !await isAllowedOrigin(c.req.header("origin"), c)) { + const res = new Response("Forbidden", { status: 403 }); + throw new HTTPException(403, { res }); + } + await next(); + }; +}; +export { + csrf +}; diff --git a/node_modules/hono/dist/middleware/etag/digest.js b/node_modules/hono/dist/middleware/etag/digest.js new file mode 100644 index 000000000..31f78bf4d --- /dev/null +++ b/node_modules/hono/dist/middleware/etag/digest.js @@ -0,0 +1,33 @@ +// src/middleware/etag/digest.ts +var mergeBuffers = (buffer1, buffer2) => { + if (!buffer1) { + return buffer2; + } + const merged = new Uint8Array( + new ArrayBuffer(buffer1.byteLength + buffer2.byteLength) + ); + merged.set(new Uint8Array(buffer1), 0); + merged.set(buffer2, buffer1.byteLength); + return merged; +}; +var generateDigest = async (stream, generator) => { + if (!stream) { + return null; + } + let result = void 0; + const reader = stream.getReader(); + for (; ; ) { + const { value, done } = await reader.read(); + if (done) { + break; + } + result = await generator(mergeBuffers(result, value)); + } + if (!result) { + return null; + } + return Array.prototype.map.call(new Uint8Array(result), (x) => x.toString(16).padStart(2, "0")).join(""); +}; +export { + generateDigest +}; diff --git a/node_modules/hono/dist/middleware/etag/index.js b/node_modules/hono/dist/middleware/etag/index.js new file mode 100644 index 000000000..2ad0110e9 --- /dev/null +++ b/node_modules/hono/dist/middleware/etag/index.js @@ -0,0 +1,72 @@ +// src/middleware/etag/index.ts +import { generateDigest } from "./digest.js"; +var RETAINED_304_HEADERS = [ + "cache-control", + "content-location", + "date", + "etag", + "expires", + "vary" +]; +var stripWeak = (tag) => tag.replace(/^W\//, ""); +function etagMatches(etag2, ifNoneMatch) { + return ifNoneMatch != null && ifNoneMatch.split(/,\s*/).some((t) => stripWeak(t) === stripWeak(etag2)); +} +function initializeGenerator(generator) { + if (!generator) { + if (crypto && crypto.subtle) { + generator = (body) => crypto.subtle.digest( + { + name: "SHA-1" + }, + body + ); + } + } + return generator; +} +var etag = (options) => { + const retainedHeaders = options?.retainedHeaders ?? RETAINED_304_HEADERS; + const weak = options?.weak ?? false; + const generator = initializeGenerator(options?.generateDigest); + return async function etag2(c, next) { + const ifNoneMatch = c.req.header("If-None-Match") ?? null; + await next(); + const res = c.res; + let etag3 = res.headers.get("ETag"); + if (!etag3) { + if (!generator) { + return; + } + const hash = await generateDigest( + // This type casing avoids the type error for `deno publish` + res.clone().body, + generator + ); + if (hash === null) { + return; + } + etag3 = weak ? `W/"${hash}"` : `"${hash}"`; + } + if (etagMatches(etag3, ifNoneMatch)) { + c.res = new Response(null, { + status: 304, + statusText: "Not Modified", + headers: { + ETag: etag3 + } + }); + c.res.headers.forEach((_, key) => { + if (retainedHeaders.indexOf(key.toLowerCase()) === -1) { + c.res.headers.delete(key); + } + }); + } else { + c.res.headers.set("ETag", etag3); + } + }; +}; +export { + RETAINED_304_HEADERS, + etag +}; diff --git a/node_modules/hono/dist/middleware/ip-restriction/index.js b/node_modules/hono/dist/middleware/ip-restriction/index.js new file mode 100644 index 000000000..b4b390e07 --- /dev/null +++ b/node_modules/hono/dist/middleware/ip-restriction/index.js @@ -0,0 +1,107 @@ +// src/middleware/ip-restriction/index.ts +import { HTTPException } from "../../http-exception.js"; +import { + convertIPv4ToBinary, + convertIPv6BinaryToString, + convertIPv6ToBinary, + distinctRemoteAddr +} from "../../utils/ipaddr.js"; +var IS_CIDR_NOTATION_REGEX = /\/[0-9]{0,3}$/; +var buildMatcher = (rules) => { + const functionRules = []; + const staticRules = /* @__PURE__ */ new Set(); + const cidrRules = []; + for (let rule of rules) { + if (rule === "*") { + return () => true; + } else if (typeof rule === "function") { + functionRules.push(rule); + } else { + if (IS_CIDR_NOTATION_REGEX.test(rule)) { + const separatedRule = rule.split("/"); + const addrStr = separatedRule[0]; + const type2 = distinctRemoteAddr(addrStr); + if (type2 === void 0) { + throw new TypeError(`Invalid rule: ${rule}`); + } + const isIPv4 = type2 === "IPv4"; + const prefix = parseInt(separatedRule[1]); + if (isIPv4 ? prefix === 32 : prefix === 128) { + rule = addrStr; + } else { + const addr = (isIPv4 ? convertIPv4ToBinary : convertIPv6ToBinary)(addrStr); + const mask = (1n << BigInt(prefix)) - 1n << BigInt((isIPv4 ? 32 : 128) - prefix); + cidrRules.push([isIPv4, addr & mask, mask]); + continue; + } + } + const type = distinctRemoteAddr(rule); + if (type === void 0) { + throw new TypeError(`Invalid rule: ${rule}`); + } + staticRules.add( + type === "IPv4" ? rule : convertIPv6BinaryToString(convertIPv6ToBinary(rule)) + // normalize IPv6 address (e.g. 0000:0000:0000:0000:0000:0000:0000:0001 => ::1) + ); + } + } + return (remote) => { + if (staticRules.has(remote.addr)) { + return true; + } + for (const [isIPv4, addr, mask] of cidrRules) { + if (isIPv4 !== remote.isIPv4) { + continue; + } + const remoteAddr = remote.binaryAddr ||= (isIPv4 ? convertIPv4ToBinary : convertIPv6ToBinary)(remote.addr); + if ((remoteAddr & mask) === addr) { + return true; + } + } + for (const rule of functionRules) { + if (rule({ addr: remote.addr, type: remote.type })) { + return true; + } + } + return false; + }; +}; +var ipRestriction = (getIP, { denyList = [], allowList = [] }, onError) => { + const allowLength = allowList.length; + const denyMatcher = buildMatcher(denyList); + const allowMatcher = buildMatcher(allowList); + const blockError = (c) => new HTTPException(403, { + res: c.text("Forbidden", { + status: 403 + }) + }); + return async function ipRestriction2(c, next) { + const connInfo = getIP(c); + const addr = typeof connInfo === "string" ? connInfo : connInfo.remote.address; + if (!addr) { + throw blockError(c); + } + const type = typeof connInfo !== "string" && connInfo.remote.addressType || distinctRemoteAddr(addr); + const remoteData = { addr, type, isIPv4: type === "IPv4" }; + if (denyMatcher(remoteData)) { + if (onError) { + return onError({ addr, type }, c); + } + throw blockError(c); + } + if (allowMatcher(remoteData)) { + return await next(); + } + if (allowLength === 0) { + return await next(); + } else { + if (onError) { + return await onError({ addr, type }, c); + } + throw blockError(c); + } + }; +}; +export { + ipRestriction +}; diff --git a/node_modules/hono/dist/middleware/jsx-renderer/index.js b/node_modules/hono/dist/middleware/jsx-renderer/index.js new file mode 100644 index 000000000..d43b2a73c --- /dev/null +++ b/node_modules/hono/dist/middleware/jsx-renderer/index.js @@ -0,0 +1,57 @@ +// src/middleware/jsx-renderer/index.ts +import { html, raw } from "../../helper/html/index.js"; +import { Fragment, createContext, jsx, useContext } from "../../jsx/index.js"; +import { renderToReadableStream } from "../../jsx/streaming.js"; +var RequestContext = createContext(null); +var createRenderer = (c, Layout, component, options) => (children, props) => { + const docType = typeof options?.docType === "string" ? options.docType : options?.docType === false ? "" : ""; + const currentLayout = component ? jsx( + (props2) => component(props2, c), + { + Layout, + ...props + }, + children + ) : children; + const body = html`${raw(docType)}${jsx( + RequestContext.Provider, + { value: c }, + currentLayout + )}`; + if (options?.stream) { + if (options.stream === true) { + c.header("Transfer-Encoding", "chunked"); + c.header("Content-Type", "text/html; charset=UTF-8"); + c.header("Content-Encoding", "Identity"); + } else { + for (const [key, value] of Object.entries(options.stream)) { + c.header(key, value); + } + } + return c.body(renderToReadableStream(body)); + } else { + return c.html(body); + } +}; +var jsxRenderer = (component, options) => function jsxRenderer2(c, next) { + const Layout = c.getLayout() ?? Fragment; + if (component) { + c.setLayout((props) => { + return component({ ...props, Layout }, c); + }); + } + c.setRenderer(createRenderer(c, Layout, component, options)); + return next(); +}; +var useRequestContext = () => { + const c = useContext(RequestContext); + if (!c) { + throw new Error("RequestContext is not provided."); + } + return c; +}; +export { + RequestContext, + jsxRenderer, + useRequestContext +}; diff --git a/node_modules/hono/dist/middleware/jwk/index.js b/node_modules/hono/dist/middleware/jwk/index.js new file mode 100644 index 000000000..310baa62d --- /dev/null +++ b/node_modules/hono/dist/middleware/jwk/index.js @@ -0,0 +1,5 @@ +// src/middleware/jwk/index.ts +import { jwk } from "./jwk.js"; +export { + jwk +}; diff --git a/node_modules/hono/dist/middleware/jwk/jwk.js b/node_modules/hono/dist/middleware/jwk/jwk.js new file mode 100644 index 000000000..2721f42ff --- /dev/null +++ b/node_modules/hono/dist/middleware/jwk/jwk.js @@ -0,0 +1,112 @@ +// src/middleware/jwk/jwk.ts +import { getCookie, getSignedCookie } from "../../helper/cookie/index.js"; +import { HTTPException } from "../../http-exception.js"; +import { Jwt } from "../../utils/jwt/index.js"; +import "../../context.js"; +var jwk = (options, init) => { + const verifyOpts = options.verification || {}; + if (!options || !(options.keys || options.jwks_uri)) { + throw new Error('JWK auth middleware requires options for either "keys" or "jwks_uri" or both'); + } + if (!crypto.subtle || !crypto.subtle.importKey) { + throw new Error("`crypto.subtle.importKey` is undefined. JWK auth middleware requires it."); + } + return async function jwk2(ctx, next) { + const headerName = options.headerName || "Authorization"; + const credentials = ctx.req.raw.headers.get(headerName); + let token; + if (credentials) { + const parts = credentials.split(/\s+/); + if (parts.length !== 2) { + const errDescription = "invalid credentials structure"; + throw new HTTPException(401, { + message: errDescription, + res: unauthorizedResponse({ + ctx, + error: "invalid_request", + errDescription + }) + }); + } else { + token = parts[1]; + } + } else if (options.cookie) { + if (typeof options.cookie == "string") { + token = getCookie(ctx, options.cookie); + } else if (options.cookie.secret) { + if (options.cookie.prefixOptions) { + token = await getSignedCookie( + ctx, + options.cookie.secret, + options.cookie.key, + options.cookie.prefixOptions + ); + } else { + token = await getSignedCookie(ctx, options.cookie.secret, options.cookie.key); + } + } else { + if (options.cookie.prefixOptions) { + token = getCookie(ctx, options.cookie.key, options.cookie.prefixOptions); + } else { + token = getCookie(ctx, options.cookie.key); + } + } + } + if (!token) { + if (options.allow_anon) { + return next(); + } + const errDescription = "no authorization included in request"; + throw new HTTPException(401, { + message: errDescription, + res: unauthorizedResponse({ + ctx, + error: "invalid_request", + errDescription + }) + }); + } + let payload; + let cause; + try { + const keys = typeof options.keys === "function" ? await options.keys(ctx) : options.keys; + const jwks_uri = typeof options.jwks_uri === "function" ? await options.jwks_uri(ctx) : options.jwks_uri; + payload = await Jwt.verifyWithJwks( + token, + { keys, jwks_uri, verification: verifyOpts, allowedAlgorithms: options.alg }, + init + ); + } catch (e) { + cause = e; + } + if (!payload) { + if (cause instanceof Error && cause.constructor === Error) { + throw cause; + } + throw new HTTPException(401, { + message: "Unauthorized", + res: unauthorizedResponse({ + ctx, + error: "invalid_token", + statusText: "Unauthorized", + errDescription: "token verification failure" + }), + cause + }); + } + ctx.set("jwtPayload", payload); + await next(); + }; +}; +function unauthorizedResponse(opts) { + return new Response("Unauthorized", { + status: 401, + statusText: opts.statusText, + headers: { + "WWW-Authenticate": `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"` + } + }); +} +export { + jwk +}; diff --git a/node_modules/hono/dist/middleware/jwt/index.js b/node_modules/hono/dist/middleware/jwt/index.js new file mode 100644 index 000000000..86bd76e8c --- /dev/null +++ b/node_modules/hono/dist/middleware/jwt/index.js @@ -0,0 +1,11 @@ +// src/middleware/jwt/index.ts +import { jwt, verifyWithJwks, verify, decode, sign } from "./jwt.js"; +import { AlgorithmTypes } from "../../utils/jwt/jwa.js"; +export { + AlgorithmTypes, + decode, + jwt, + sign, + verify, + verifyWithJwks +}; diff --git a/node_modules/hono/dist/middleware/jwt/jwt.js b/node_modules/hono/dist/middleware/jwt/jwt.js new file mode 100644 index 000000000..eb1ac182c --- /dev/null +++ b/node_modules/hono/dist/middleware/jwt/jwt.js @@ -0,0 +1,114 @@ +// src/middleware/jwt/jwt.ts +import { getCookie, getSignedCookie } from "../../helper/cookie/index.js"; +import { HTTPException } from "../../http-exception.js"; +import { Jwt } from "../../utils/jwt/index.js"; +import "../../context.js"; +var jwt = (options) => { + const verifyOpts = options.verification || {}; + if (!options || !options.secret) { + throw new Error('JWT auth middleware requires options for "secret"'); + } + if (!options.alg) { + throw new Error('JWT auth middleware requires options for "alg"'); + } + if (!crypto.subtle || !crypto.subtle.importKey) { + throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it."); + } + return async function jwt2(ctx, next) { + const headerName = options.headerName || "Authorization"; + const credentials = ctx.req.raw.headers.get(headerName); + let token; + if (credentials) { + const parts = credentials.split(/\s+/); + if (parts.length !== 2) { + const errDescription = "invalid credentials structure"; + throw new HTTPException(401, { + message: errDescription, + res: unauthorizedResponse({ + ctx, + error: "invalid_request", + errDescription + }) + }); + } else { + token = parts[1]; + } + } else if (options.cookie) { + if (typeof options.cookie == "string") { + token = getCookie(ctx, options.cookie); + } else if (options.cookie.secret) { + if (options.cookie.prefixOptions) { + token = await getSignedCookie( + ctx, + options.cookie.secret, + options.cookie.key, + options.cookie.prefixOptions + ); + } else { + token = await getSignedCookie(ctx, options.cookie.secret, options.cookie.key); + } + } else { + if (options.cookie.prefixOptions) { + token = getCookie(ctx, options.cookie.key, options.cookie.prefixOptions); + } else { + token = getCookie(ctx, options.cookie.key); + } + } + } + if (!token) { + const errDescription = "no authorization included in request"; + throw new HTTPException(401, { + message: errDescription, + res: unauthorizedResponse({ + ctx, + error: "invalid_request", + errDescription + }) + }); + } + let payload; + let cause; + try { + payload = await Jwt.verify(token, options.secret, { + alg: options.alg, + ...verifyOpts + }); + } catch (e) { + cause = e; + } + if (!payload) { + throw new HTTPException(401, { + message: "Unauthorized", + res: unauthorizedResponse({ + ctx, + error: "invalid_token", + statusText: "Unauthorized", + errDescription: "token verification failure" + }), + cause + }); + } + ctx.set("jwtPayload", payload); + await next(); + }; +}; +function unauthorizedResponse(opts) { + return new Response("Unauthorized", { + status: 401, + statusText: opts.statusText, + headers: { + "WWW-Authenticate": `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"` + } + }); +} +var verifyWithJwks = Jwt.verifyWithJwks; +var verify = Jwt.verify; +var decode = Jwt.decode; +var sign = Jwt.sign; +export { + decode, + jwt, + sign, + verify, + verifyWithJwks +}; diff --git a/node_modules/hono/dist/middleware/language/index.js b/node_modules/hono/dist/middleware/language/index.js new file mode 100644 index 000000000..9455c6194 --- /dev/null +++ b/node_modules/hono/dist/middleware/language/index.js @@ -0,0 +1,15 @@ +// src/middleware/language/index.ts +import { + languageDetector, + detectFromCookie, + detectFromHeader, + detectFromPath, + detectFromQuery +} from "./language.js"; +export { + detectFromCookie, + detectFromHeader, + detectFromPath, + detectFromQuery, + languageDetector +}; diff --git a/node_modules/hono/dist/middleware/language/language.js b/node_modules/hono/dist/middleware/language/language.js new file mode 100644 index 000000000..fe4316e1b --- /dev/null +++ b/node_modules/hono/dist/middleware/language/language.js @@ -0,0 +1,179 @@ +// src/middleware/language/language.ts +import { setCookie, getCookie } from "../../helper/cookie/index.js"; +import { parseAccept } from "../../utils/accept.js"; +var DEFAULT_OPTIONS = { + order: ["querystring", "cookie", "header"], + lookupQueryString: "lang", + lookupCookie: "language", + lookupFromHeaderKey: "accept-language", + lookupFromPathIndex: 0, + caches: ["cookie"], + ignoreCase: true, + fallbackLanguage: "en", + supportedLanguages: ["en"], + cookieOptions: { + sameSite: "Strict", + secure: true, + maxAge: 365 * 24 * 60 * 60, + httpOnly: true + }, + debug: false +}; +function parseAcceptLanguage(header) { + return parseAccept(header).map(({ type, q }) => ({ lang: type, q })); +} +var normalizeLanguage = (lang, options) => { + if (!lang) { + return void 0; + } + try { + let normalizedLang = lang.trim(); + if (options.convertDetectedLanguage) { + normalizedLang = options.convertDetectedLanguage(normalizedLang); + } + const compLang = options.ignoreCase ? normalizedLang.toLowerCase() : normalizedLang; + const compSupported = options.supportedLanguages.map( + (l) => options.ignoreCase ? l.toLowerCase() : l + ); + const matchedLang = compSupported.find((l) => l === compLang); + return matchedLang ? options.supportedLanguages[compSupported.indexOf(matchedLang)] : void 0; + } catch { + return void 0; + } +}; +var detectFromQuery = (c, options) => { + try { + const query = c.req.query(options.lookupQueryString); + return normalizeLanguage(query, options); + } catch { + return void 0; + } +}; +var detectFromCookie = (c, options) => { + try { + const cookie = getCookie(c, options.lookupCookie); + return normalizeLanguage(cookie, options); + } catch { + return void 0; + } +}; +function detectFromHeader(c, options) { + try { + const acceptLanguage = c.req.header(options.lookupFromHeaderKey); + if (!acceptLanguage) { + return void 0; + } + const languages = parseAcceptLanguage(acceptLanguage); + for (const { lang } of languages) { + const normalizedLang = normalizeLanguage(lang, options); + if (normalizedLang) { + return normalizedLang; + } + } + return void 0; + } catch { + return void 0; + } +} +function detectFromPath(c, options) { + try { + const url = new URL(c.req.url); + const pathSegments = url.pathname.split("/").filter(Boolean); + const langSegment = pathSegments[options.lookupFromPathIndex]; + return normalizeLanguage(langSegment, options); + } catch { + return void 0; + } +} +var detectors = { + querystring: detectFromQuery, + cookie: detectFromCookie, + header: detectFromHeader, + path: detectFromPath +}; +function validateOptions(options) { + if (!options.supportedLanguages.includes(options.fallbackLanguage)) { + throw new Error("Fallback language must be included in supported languages"); + } + if (options.lookupFromPathIndex < 0) { + throw new Error("Path index must be non-negative"); + } + if (!options.order.every((detector) => Object.keys(detectors).includes(detector))) { + throw new Error("Invalid detector type in order array"); + } +} +function cacheLanguage(c, language, options) { + if (!Array.isArray(options.caches) || !options.caches.includes("cookie")) { + return; + } + try { + setCookie(c, options.lookupCookie, language, options.cookieOptions); + } catch (error) { + if (options.debug) { + console.error("Failed to cache language:", error); + } + } +} +var detectLanguage = (c, options) => { + let detectedLang; + for (const detectorName of options.order) { + const detector = detectors[detectorName]; + if (!detector) { + continue; + } + try { + detectedLang = detector(c, options); + if (detectedLang) { + if (options.debug) { + console.log(`Language detected from ${detectorName}: ${detectedLang}`); + } + break; + } + } catch (error) { + if (options.debug) { + console.error(`Error in ${detectorName} detector:`, error); + } + continue; + } + } + const finalLang = detectedLang || options.fallbackLanguage; + if (detectedLang && options.caches) { + cacheLanguage(c, finalLang, options); + } + return finalLang; +}; +var languageDetector = (userOptions) => { + const options = { + ...DEFAULT_OPTIONS, + ...userOptions, + cookieOptions: { + ...DEFAULT_OPTIONS.cookieOptions, + ...userOptions.cookieOptions + } + }; + validateOptions(options); + return async function languageDetector2(ctx, next) { + try { + const lang = detectLanguage(ctx, options); + ctx.set("language", lang); + } catch (error) { + if (options.debug) { + console.error("Language detection failed:", error); + } + ctx.set("language", options.fallbackLanguage); + } + await next(); + }; +}; +export { + DEFAULT_OPTIONS, + detectFromCookie, + detectFromHeader, + detectFromPath, + detectFromQuery, + detectors, + languageDetector, + normalizeLanguage, + parseAcceptLanguage, + validateOptions +}; diff --git a/node_modules/hono/dist/middleware/logger/index.js b/node_modules/hono/dist/middleware/logger/index.js new file mode 100644 index 000000000..2a727b686 --- /dev/null +++ b/node_modules/hono/dist/middleware/logger/index.js @@ -0,0 +1,44 @@ +// src/middleware/logger/index.ts +import { getColorEnabledAsync } from "../../utils/color.js"; +var humanize = (times) => { + const [delimiter, separator] = [",", "."]; + const orderTimes = times.map((v) => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter)); + return orderTimes.join(separator); +}; +var time = (start) => { + const delta = Date.now() - start; + return humanize([delta < 1e3 ? delta + "ms" : Math.round(delta / 1e3) + "s"]); +}; +var colorStatus = async (status) => { + const colorEnabled = await getColorEnabledAsync(); + if (colorEnabled) { + switch (status / 100 | 0) { + case 5: + return `\x1B[31m${status}\x1B[0m`; + case 4: + return `\x1B[33m${status}\x1B[0m`; + case 3: + return `\x1B[36m${status}\x1B[0m`; + case 2: + return `\x1B[32m${status}\x1B[0m`; + } + } + return `${status}`; +}; +async function log(fn, prefix, method, path, status = 0, elapsed) { + const out = prefix === "<--" /* Incoming */ ? `${prefix} ${method} ${path}` : `${prefix} ${method} ${path} ${await colorStatus(status)} ${elapsed}`; + fn(out); +} +var logger = (fn = console.log) => { + return async function logger2(c, next) { + const { method, url } = c.req; + const path = url.slice(url.indexOf("/", 8)); + await log(fn, "<--" /* Incoming */, method, path); + const start = Date.now(); + await next(); + await log(fn, "-->" /* Outgoing */, method, path, c.res.status, time(start)); + }; +}; +export { + logger +}; diff --git a/node_modules/hono/dist/middleware/method-override/index.js b/node_modules/hono/dist/middleware/method-override/index.js new file mode 100644 index 000000000..e7daefeb4 --- /dev/null +++ b/node_modules/hono/dist/middleware/method-override/index.js @@ -0,0 +1,82 @@ +// src/middleware/method-override/index.ts +import { parseBody } from "../../utils/body.js"; +var DEFAULT_METHOD_FORM_NAME = "_method"; +var methodOverride = (options) => async function methodOverride2(c, next) { + if (c.req.method === "GET") { + return await next(); + } + const app = options.app; + if (!(options.header || options.query)) { + const contentType = c.req.header("content-type"); + const methodFormName = options.form || DEFAULT_METHOD_FORM_NAME; + const clonedRequest = c.req.raw.clone(); + const newRequest = clonedRequest.clone(); + if (contentType?.startsWith("multipart/form-data")) { + const form = await clonedRequest.formData(); + const method = form.get(methodFormName); + if (method) { + const newForm = await newRequest.formData(); + newForm.delete(methodFormName); + const newHeaders = new Headers(clonedRequest.headers); + newHeaders.delete("content-type"); + newHeaders.delete("content-length"); + const request = new Request(c.req.url, { + body: newForm, + headers: newHeaders, + method + }); + return app.fetch(request, c.env, getExecutionCtx(c)); + } + } + if (contentType === "application/x-www-form-urlencoded") { + const params = await parseBody(clonedRequest); + const method = params[methodFormName]; + if (method) { + delete params[methodFormName]; + const newParams = new URLSearchParams(params); + const request = new Request(newRequest, { + body: newParams, + method + }); + return app.fetch(request, c.env, getExecutionCtx(c)); + } + } + } else if (options.header) { + const headerName = options.header; + const method = c.req.header(headerName); + if (method) { + const newHeaders = new Headers(c.req.raw.headers); + newHeaders.delete(headerName); + const request = new Request(c.req.raw, { + headers: newHeaders, + method + }); + return app.fetch(request, c.env, getExecutionCtx(c)); + } + } else if (options.query) { + const queryName = options.query; + const method = c.req.query(queryName); + if (method) { + const url = new URL(c.req.url); + url.searchParams.delete(queryName); + const request = new Request(url.toString(), { + body: c.req.raw.body, + headers: c.req.raw.headers, + method + }); + return app.fetch(request, c.env, getExecutionCtx(c)); + } + } + await next(); +}; +var getExecutionCtx = (c) => { + let executionCtx; + try { + executionCtx = c.executionCtx; + } catch { + } + return executionCtx; +}; +export { + methodOverride +}; diff --git a/node_modules/hono/dist/middleware/powered-by/index.js b/node_modules/hono/dist/middleware/powered-by/index.js new file mode 100644 index 000000000..827f65f5b --- /dev/null +++ b/node_modules/hono/dist/middleware/powered-by/index.js @@ -0,0 +1,10 @@ +// src/middleware/powered-by/index.ts +var poweredBy = (options) => { + return async function poweredBy2(c, next) { + await next(); + c.res.headers.set("X-Powered-By", options?.serverName ?? "Hono"); + }; +}; +export { + poweredBy +}; diff --git a/node_modules/hono/dist/middleware/pretty-json/index.js b/node_modules/hono/dist/middleware/pretty-json/index.js new file mode 100644 index 000000000..5bb7163cd --- /dev/null +++ b/node_modules/hono/dist/middleware/pretty-json/index.js @@ -0,0 +1,15 @@ +// src/middleware/pretty-json/index.ts +var prettyJSON = (options) => { + const targetQuery = options?.query ?? "pretty"; + return async function prettyJSON2(c, next) { + const pretty = options?.force || c.req.query(targetQuery) || c.req.query(targetQuery) === ""; + await next(); + if (pretty && c.res.headers.get("Content-Type")?.startsWith("application/json")) { + const obj = await c.res.json(); + c.res = new Response(JSON.stringify(obj, null, options?.space ?? 2), c.res); + } + }; +}; +export { + prettyJSON +}; diff --git a/node_modules/hono/dist/middleware/request-id/index.js b/node_modules/hono/dist/middleware/request-id/index.js new file mode 100644 index 000000000..3f6a0772e --- /dev/null +++ b/node_modules/hono/dist/middleware/request-id/index.js @@ -0,0 +1,5 @@ +// src/middleware/request-id/index.ts +import { requestId } from "./request-id.js"; +export { + requestId +}; diff --git a/node_modules/hono/dist/middleware/request-id/request-id.js b/node_modules/hono/dist/middleware/request-id/request-id.js new file mode 100644 index 000000000..0c22de6e1 --- /dev/null +++ b/node_modules/hono/dist/middleware/request-id/request-id.js @@ -0,0 +1,21 @@ +// src/middleware/request-id/request-id.ts +var requestId = ({ + limitLength = 255, + headerName = "X-Request-Id", + generator = () => crypto.randomUUID() +} = {}) => { + return async function requestId2(c, next) { + let reqId = headerName ? c.req.header(headerName) : void 0; + if (!reqId || reqId.length > limitLength || /[^\w\-=]/.test(reqId)) { + reqId = generator(c); + } + c.set("requestId", reqId); + if (headerName) { + c.header(headerName, reqId); + } + await next(); + }; +}; +export { + requestId +}; diff --git a/node_modules/hono/dist/middleware/secure-headers/index.js b/node_modules/hono/dist/middleware/secure-headers/index.js new file mode 100644 index 000000000..7983a6f95 --- /dev/null +++ b/node_modules/hono/dist/middleware/secure-headers/index.js @@ -0,0 +1,6 @@ +// src/middleware/secure-headers/index.ts +import { NONCE, secureHeaders } from "./secure-headers.js"; +export { + NONCE, + secureHeaders +}; diff --git a/node_modules/hono/dist/middleware/secure-headers/permissions-policy.js b/node_modules/hono/dist/middleware/secure-headers/permissions-policy.js new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/hono/dist/middleware/secure-headers/secure-headers.js b/node_modules/hono/dist/middleware/secure-headers/secure-headers.js new file mode 100644 index 000000000..7124599bc --- /dev/null +++ b/node_modules/hono/dist/middleware/secure-headers/secure-headers.js @@ -0,0 +1,166 @@ +// src/middleware/secure-headers/secure-headers.ts +import { encodeBase64 } from "../../utils/encode.js"; +var HEADERS_MAP = { + crossOriginEmbedderPolicy: ["Cross-Origin-Embedder-Policy", "require-corp"], + crossOriginResourcePolicy: ["Cross-Origin-Resource-Policy", "same-origin"], + crossOriginOpenerPolicy: ["Cross-Origin-Opener-Policy", "same-origin"], + originAgentCluster: ["Origin-Agent-Cluster", "?1"], + referrerPolicy: ["Referrer-Policy", "no-referrer"], + strictTransportSecurity: ["Strict-Transport-Security", "max-age=15552000; includeSubDomains"], + xContentTypeOptions: ["X-Content-Type-Options", "nosniff"], + xDnsPrefetchControl: ["X-DNS-Prefetch-Control", "off"], + xDownloadOptions: ["X-Download-Options", "noopen"], + xFrameOptions: ["X-Frame-Options", "SAMEORIGIN"], + xPermittedCrossDomainPolicies: ["X-Permitted-Cross-Domain-Policies", "none"], + xXssProtection: ["X-XSS-Protection", "0"] +}; +var DEFAULT_OPTIONS = { + crossOriginEmbedderPolicy: false, + crossOriginResourcePolicy: true, + crossOriginOpenerPolicy: true, + originAgentCluster: true, + referrerPolicy: true, + strictTransportSecurity: true, + xContentTypeOptions: true, + xDnsPrefetchControl: true, + xDownloadOptions: true, + xFrameOptions: true, + xPermittedCrossDomainPolicies: true, + xXssProtection: true, + removePoweredBy: true, + permissionsPolicy: {} +}; +var generateNonce = () => { + const arrayBuffer = new Uint8Array(16); + crypto.getRandomValues(arrayBuffer); + return encodeBase64(arrayBuffer.buffer); +}; +var NONCE = (ctx) => { + const key = "secureHeadersNonce"; + const init = ctx.get(key); + const nonce = init || generateNonce(); + if (init == null) { + ctx.set(key, nonce); + } + return `'nonce-${nonce}'`; +}; +var secureHeaders = (customOptions) => { + const options = { ...DEFAULT_OPTIONS, ...customOptions }; + const headersToSet = getFilteredHeaders(options); + const callbacks = []; + if (options.contentSecurityPolicy) { + const [callback, value] = getCSPDirectives(options.contentSecurityPolicy); + if (callback) { + callbacks.push(callback); + } + headersToSet.push(["Content-Security-Policy", value]); + } + if (options.contentSecurityPolicyReportOnly) { + const [callback, value] = getCSPDirectives(options.contentSecurityPolicyReportOnly); + if (callback) { + callbacks.push(callback); + } + headersToSet.push(["Content-Security-Policy-Report-Only", value]); + } + if (options.permissionsPolicy && Object.keys(options.permissionsPolicy).length > 0) { + headersToSet.push([ + "Permissions-Policy", + getPermissionsPolicyDirectives(options.permissionsPolicy) + ]); + } + if (options.reportingEndpoints) { + headersToSet.push(["Reporting-Endpoints", getReportingEndpoints(options.reportingEndpoints)]); + } + if (options.reportTo) { + headersToSet.push(["Report-To", getReportToOptions(options.reportTo)]); + } + return async function secureHeaders2(ctx, next) { + const headersToSetForReq = callbacks.length === 0 ? headersToSet : callbacks.reduce((acc, cb) => cb(ctx, acc), headersToSet); + await next(); + setHeaders(ctx, headersToSetForReq); + if (options?.removePoweredBy) { + ctx.res.headers.delete("X-Powered-By"); + } + }; +}; +function getFilteredHeaders(options) { + return Object.entries(HEADERS_MAP).filter(([key]) => options[key]).map(([key, defaultValue]) => { + const overrideValue = options[key]; + return typeof overrideValue === "string" ? [defaultValue[0], overrideValue] : defaultValue; + }); +} +function getCSPDirectives(contentSecurityPolicy) { + const callbacks = []; + const resultValues = []; + for (const [directive, value] of Object.entries(contentSecurityPolicy)) { + const valueArray = Array.isArray(value) ? value : [value]; + valueArray.forEach((value2, i) => { + if (typeof value2 === "function") { + const index = i * 2 + 2 + resultValues.length; + callbacks.push((ctx, values) => { + values[index] = value2(ctx, directive); + }); + } + }); + resultValues.push( + directive.replace( + /[A-Z]+(?![a-z])|[A-Z]/g, + (match, offset) => offset ? "-" + match.toLowerCase() : match.toLowerCase() + ), + ...valueArray.flatMap((value2) => [" ", value2]), + "; " + ); + } + resultValues.pop(); + return callbacks.length === 0 ? [void 0, resultValues.join("")] : [ + (ctx, headersToSet) => headersToSet.map((values) => { + if (values[0] === "Content-Security-Policy" || values[0] === "Content-Security-Policy-Report-Only") { + const clone = values[1].slice(); + callbacks.forEach((cb) => { + cb(ctx, clone); + }); + return [values[0], clone.join("")]; + } else { + return values; + } + }), + resultValues + ]; +} +function getPermissionsPolicyDirectives(policy) { + return Object.entries(policy).map(([directive, value]) => { + const kebabDirective = camelToKebab(directive); + if (typeof value === "boolean") { + return `${kebabDirective}=${value ? "*" : "none"}`; + } + if (Array.isArray(value)) { + if (value.length === 0) { + return `${kebabDirective}=()`; + } + if (value.length === 1 && (value[0] === "*" || value[0] === "none")) { + return `${kebabDirective}=${value[0]}`; + } + const allowlist = value.map((item) => ["self", "src"].includes(item) ? item : `"${item}"`); + return `${kebabDirective}=(${allowlist.join(" ")})`; + } + return ""; + }).filter(Boolean).join(", "); +} +function camelToKebab(str) { + return str.replace(/([a-z\d])([A-Z])/g, "$1-$2").toLowerCase(); +} +function getReportingEndpoints(reportingEndpoints = []) { + return reportingEndpoints.map((endpoint) => `${endpoint.name}="${endpoint.url}"`).join(", "); +} +function getReportToOptions(reportTo = []) { + return reportTo.map((option) => JSON.stringify(option)).join(", "); +} +function setHeaders(ctx, headersToSet) { + headersToSet.forEach(([header, value]) => { + ctx.res.headers.set(header, value); + }); +} +export { + NONCE, + secureHeaders +}; diff --git a/node_modules/hono/dist/middleware/serve-static/index.js b/node_modules/hono/dist/middleware/serve-static/index.js new file mode 100644 index 000000000..7ed3d9a1c --- /dev/null +++ b/node_modules/hono/dist/middleware/serve-static/index.js @@ -0,0 +1,76 @@ +// src/middleware/serve-static/index.ts +import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from "../../utils/compress.js"; +import { getMimeType } from "../../utils/mime.js"; +import { defaultJoin } from "./path.js"; +var ENCODINGS = { + br: ".br", + zstd: ".zst", + gzip: ".gz" +}; +var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS); +var DEFAULT_DOCUMENT = "index.html"; +var serveStatic = (options) => { + const root = options.root ?? "./"; + const optionPath = options.path; + const join = options.join ?? defaultJoin; + return async (c, next) => { + if (c.finalized) { + return next(); + } + let filename; + if (options.path) { + filename = options.path; + } else { + try { + filename = decodeURIComponent(c.req.path); + if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) { + throw new Error(); + } + } catch { + await options.onNotFound?.(c.req.path, c); + return next(); + } + } + let path = join( + root, + !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename + ); + if (options.isDir && await options.isDir(path)) { + path = join(path, DEFAULT_DOCUMENT); + } + const getContent = options.getContent; + let content = await getContent(path, c); + if (content instanceof Response) { + return c.newResponse(content.body, content); + } + if (content) { + const mimeType = options.mimes && getMimeType(path, options.mimes) || getMimeType(path); + c.header("Content-Type", mimeType || "application/octet-stream"); + if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) { + const acceptEncodingSet = new Set( + c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()) + ); + for (const encoding of ENCODINGS_ORDERED_KEYS) { + if (!acceptEncodingSet.has(encoding)) { + continue; + } + const compressedContent = await getContent(path + ENCODINGS[encoding], c); + if (compressedContent) { + content = compressedContent; + c.header("Content-Encoding", encoding); + c.header("Vary", "Accept-Encoding", { append: true }); + break; + } + } + } + await options.onFound?.(path, c); + return c.body(content); + } + await options.onNotFound?.(path, c); + await next(); + return; + }; +}; +export { + serveStatic +}; diff --git a/node_modules/hono/dist/middleware/serve-static/path.js b/node_modules/hono/dist/middleware/serve-static/path.js new file mode 100644 index 000000000..ab7f8235c --- /dev/null +++ b/node_modules/hono/dist/middleware/serve-static/path.js @@ -0,0 +1,18 @@ +// src/middleware/serve-static/path.ts +var defaultJoin = (...paths) => { + let result = paths.filter((p) => p !== "").join("/"); + result = result.replace(/(?<=\/)\/+/g, ""); + const segments = result.split("/"); + const resolved = []; + for (const segment of segments) { + if (segment === ".." && resolved.length > 0 && resolved.at(-1) !== "..") { + resolved.pop(); + } else if (segment !== ".") { + resolved.push(segment); + } + } + return resolved.join("/") || "."; +}; +export { + defaultJoin +}; diff --git a/node_modules/hono/dist/middleware/timeout/index.js b/node_modules/hono/dist/middleware/timeout/index.js new file mode 100644 index 000000000..9fac713c7 --- /dev/null +++ b/node_modules/hono/dist/middleware/timeout/index.js @@ -0,0 +1,25 @@ +// src/middleware/timeout/index.ts +import { HTTPException } from "../../http-exception.js"; +var defaultTimeoutException = new HTTPException(504, { + message: "Gateway Timeout" +}); +var timeout = (duration, exception = defaultTimeoutException) => { + return async function timeout2(context, next) { + let timer; + const timeoutPromise = new Promise((_, reject) => { + timer = setTimeout(() => { + reject(typeof exception === "function" ? exception(context) : exception); + }, duration); + }); + try { + await Promise.race([next(), timeoutPromise]); + } finally { + if (timer !== void 0) { + clearTimeout(timer); + } + } + }; +}; +export { + timeout +}; diff --git a/node_modules/hono/dist/middleware/timing/index.js b/node_modules/hono/dist/middleware/timing/index.js new file mode 100644 index 000000000..4c0836bc9 --- /dev/null +++ b/node_modules/hono/dist/middleware/timing/index.js @@ -0,0 +1,9 @@ +// src/middleware/timing/index.ts +import { timing, setMetric, startTime, endTime, wrapTime } from "./timing.js"; +export { + endTime, + setMetric, + startTime, + timing, + wrapTime +}; diff --git a/node_modules/hono/dist/middleware/timing/timing.js b/node_modules/hono/dist/middleware/timing/timing.js new file mode 100644 index 000000000..df3014ca0 --- /dev/null +++ b/node_modules/hono/dist/middleware/timing/timing.js @@ -0,0 +1,102 @@ +// src/middleware/timing/timing.ts +import "../../context.js"; +var getTime = () => { + try { + return performance.now(); + } catch { + } + return Date.now(); +}; +var timing = (config) => { + const options = { + total: true, + enabled: true, + totalDescription: "Total Response Time", + autoEnd: true, + crossOrigin: false, + ...config + }; + return async function timing2(c, next) { + const headers = []; + const timers = /* @__PURE__ */ new Map(); + if (c.get("metric")) { + return await next(); + } + c.set("metric", { headers, timers }); + if (options.total) { + startTime(c, "total", options.totalDescription); + } + await next(); + if (options.total) { + endTime(c, "total"); + } + if (options.autoEnd) { + timers.forEach((_, key) => endTime(c, key)); + } + const enabled = typeof options.enabled === "function" ? options.enabled(c) : options.enabled; + if (enabled) { + c.res.headers.append("Server-Timing", headers.join(",")); + const crossOrigin = typeof options.crossOrigin === "function" ? options.crossOrigin(c) : options.crossOrigin; + if (crossOrigin) { + c.res.headers.append( + "Timing-Allow-Origin", + typeof crossOrigin === "string" ? crossOrigin : "*" + ); + } + } + }; +}; +var setMetric = (c, name, valueDescription, description, precision) => { + const metrics = c.get("metric"); + if (!metrics) { + console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!"); + return; + } + if (typeof valueDescription === "number") { + const dur = valueDescription.toFixed(precision || 1); + const metric = description ? `${name};dur=${dur};desc="${description}"` : `${name};dur=${dur}`; + metrics.headers.push(metric); + } else { + const metric = valueDescription ? `${name};desc="${valueDescription}"` : `${name}`; + metrics.headers.push(metric); + } +}; +var startTime = (c, name, description) => { + const metrics = c.get("metric"); + if (!metrics) { + console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!"); + return; + } + metrics.timers.set(name, { description, start: getTime() }); +}; +var endTime = (c, name, precision) => { + const metrics = c.get("metric"); + if (!metrics) { + console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!"); + return; + } + const timer = metrics.timers.get(name); + if (!timer) { + console.warn(`Timer "${name}" does not exist!`); + return; + } + const { description, start } = timer; + const duration = getTime() - start; + setMetric(c, name, duration, description, precision); + metrics.timers.delete(name); +}; +async function wrapTime(c, name, callable, description, precision) { + startTime(c, name, description); + try { + return await callable; + } finally { + endTime(c, name, precision); + } +} +export { + endTime, + setMetric, + startTime, + timing, + wrapTime +}; diff --git a/node_modules/hono/dist/middleware/trailing-slash/index.js b/node_modules/hono/dist/middleware/trailing-slash/index.js new file mode 100644 index 000000000..c7697499c --- /dev/null +++ b/node_modules/hono/dist/middleware/trailing-slash/index.js @@ -0,0 +1,25 @@ +// src/middleware/trailing-slash/index.ts +var trimTrailingSlash = () => { + return async function trimTrailingSlash2(c, next) { + await next(); + if (c.res.status === 404 && (c.req.method === "GET" || c.req.method === "HEAD") && c.req.path !== "/" && c.req.path.at(-1) === "/") { + const url = new URL(c.req.url); + url.pathname = url.pathname.substring(0, url.pathname.length - 1); + c.res = c.redirect(url.toString(), 301); + } + }; +}; +var appendTrailingSlash = () => { + return async function appendTrailingSlash2(c, next) { + await next(); + if (c.res.status === 404 && (c.req.method === "GET" || c.req.method === "HEAD") && c.req.path.at(-1) !== "/") { + const url = new URL(c.req.url); + url.pathname += "/"; + c.res = c.redirect(url.toString(), 301); + } + }; +}; +export { + appendTrailingSlash, + trimTrailingSlash +}; diff --git a/node_modules/hono/dist/preset/quick.js b/node_modules/hono/dist/preset/quick.js new file mode 100644 index 000000000..b8eca9707 --- /dev/null +++ b/node_modules/hono/dist/preset/quick.js @@ -0,0 +1,16 @@ +// src/preset/quick.ts +import { HonoBase } from "../hono-base.js"; +import { LinearRouter } from "../router/linear-router/index.js"; +import { SmartRouter } from "../router/smart-router/index.js"; +import { TrieRouter } from "../router/trie-router/index.js"; +var Hono = class extends HonoBase { + constructor(options = {}) { + super(options); + this.router = new SmartRouter({ + routers: [new LinearRouter(), new TrieRouter()] + }); + } +}; +export { + Hono +}; diff --git a/node_modules/hono/dist/preset/tiny.js b/node_modules/hono/dist/preset/tiny.js new file mode 100644 index 000000000..377e3b048 --- /dev/null +++ b/node_modules/hono/dist/preset/tiny.js @@ -0,0 +1,12 @@ +// src/preset/tiny.ts +import { HonoBase } from "../hono-base.js"; +import { PatternRouter } from "../router/pattern-router/index.js"; +var Hono = class extends HonoBase { + constructor(options = {}) { + super(options); + this.router = new PatternRouter(); + } +}; +export { + Hono +}; diff --git a/node_modules/hono/dist/request.js b/node_modules/hono/dist/request.js new file mode 100644 index 000000000..06a2bf9da --- /dev/null +++ b/node_modules/hono/dist/request.js @@ -0,0 +1,301 @@ +// src/request.ts +import { HTTPException } from "./http-exception.js"; +import { GET_MATCH_RESULT } from "./request/constants.js"; +import { parseBody } from "./utils/body.js"; +import { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from "./utils/url.js"; +var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_); +var HonoRequest = class { + /** + * `.raw` can get the raw Request object. + * + * @see {@link https://hono.dev/docs/api/request#raw} + * + * @example + * ```ts + * // For Cloudflare Workers + * app.post('/', async (c) => { + * const metadata = c.req.raw.cf?.hostMetadata? + * ... + * }) + * ``` + */ + raw; + #validatedData; + // Short name of validatedData + #matchResult; + routeIndex = 0; + /** + * `.path` can get the pathname of the request. + * + * @see {@link https://hono.dev/docs/api/request#path} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const pathname = c.req.path // `/about/me` + * }) + * ``` + */ + path; + bodyCache = {}; + constructor(request, path = "/", matchResult = [[]]) { + this.raw = request; + this.path = path; + this.#matchResult = matchResult; + this.#validatedData = {}; + } + param(key) { + return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams(); + } + #getDecodedParam(key) { + const paramKey = this.#matchResult[0][this.routeIndex][1][key]; + const param = this.#getParamValue(paramKey); + return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param; + } + #getAllDecodedParams() { + const decoded = {}; + const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]); + for (const key of keys) { + const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]); + if (value !== void 0) { + decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value; + } + } + return decoded; + } + #getParamValue(paramKey) { + return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey; + } + query(key) { + return getQueryParam(this.url, key); + } + queries(key) { + return getQueryParams(this.url, key); + } + header(name) { + if (name) { + return this.raw.headers.get(name) ?? void 0; + } + const headerData = {}; + this.raw.headers.forEach((value, key) => { + headerData[key] = value; + }); + return headerData; + } + async parseBody(options) { + return this.bodyCache.parsedBody ??= await parseBody(this, options); + } + #cachedBody = (key) => { + const { bodyCache, raw } = this; + const cachedBody = bodyCache[key]; + if (cachedBody) { + return cachedBody; + } + const anyCachedKey = Object.keys(bodyCache)[0]; + if (anyCachedKey) { + return bodyCache[anyCachedKey].then((body) => { + if (anyCachedKey === "json") { + body = JSON.stringify(body); + } + return new Response(body)[key](); + }); + } + return bodyCache[key] = raw[key](); + }; + /** + * `.json()` can parse Request body of type `application/json` + * + * @see {@link https://hono.dev/docs/api/request#json} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.json() + * }) + * ``` + */ + json() { + return this.#cachedBody("text").then((text) => JSON.parse(text)); + } + /** + * `.text()` can parse Request body of type `text/plain` + * + * @see {@link https://hono.dev/docs/api/request#text} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.text() + * }) + * ``` + */ + text() { + return this.#cachedBody("text"); + } + /** + * `.arrayBuffer()` parse Request body as an `ArrayBuffer` + * + * @see {@link https://hono.dev/docs/api/request#arraybuffer} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.arrayBuffer() + * }) + * ``` + */ + arrayBuffer() { + return this.#cachedBody("arrayBuffer"); + } + /** + * Parses the request body as a `Blob`. + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.blob(); + * }); + * ``` + * @see https://hono.dev/docs/api/request#blob + */ + blob() { + return this.#cachedBody("blob"); + } + /** + * Parses the request body as `FormData`. + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.formData(); + * }); + * ``` + * @see https://hono.dev/docs/api/request#formdata + */ + formData() { + return this.#cachedBody("formData"); + } + /** + * Adds validated data to the request. + * + * @param target - The target of the validation. + * @param data - The validated data to add. + */ + addValidatedData(target, data) { + this.#validatedData[target] = data; + } + valid(target) { + return this.#validatedData[target]; + } + /** + * `.url()` can get the request url strings. + * + * @see {@link https://hono.dev/docs/api/request#url} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const url = c.req.url // `http://localhost:8787/about/me` + * ... + * }) + * ``` + */ + get url() { + return this.raw.url; + } + /** + * `.method()` can get the method name of the request. + * + * @see {@link https://hono.dev/docs/api/request#method} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const method = c.req.method // `GET` + * }) + * ``` + */ + get method() { + return this.raw.method; + } + get [GET_MATCH_RESULT]() { + return this.#matchResult; + } + /** + * `.matchedRoutes()` can return a matched route in the handler + * + * @deprecated + * + * Use matchedRoutes helper defined in "hono/route" instead. + * + * @see {@link https://hono.dev/docs/api/request#matchedroutes} + * + * @example + * ```ts + * app.use('*', async function logger(c, next) { + * await next() + * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => { + * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]') + * console.log( + * method, + * ' ', + * path, + * ' '.repeat(Math.max(10 - path.length, 0)), + * name, + * i === c.req.routeIndex ? '<- respond from here' : '' + * ) + * }) + * }) + * ``` + */ + get matchedRoutes() { + return this.#matchResult[0].map(([[, route]]) => route); + } + /** + * `routePath()` can retrieve the path registered within the handler + * + * @deprecated + * + * Use routePath helper defined in "hono/route" instead. + * + * @see {@link https://hono.dev/docs/api/request#routepath} + * + * @example + * ```ts + * app.get('/posts/:id', (c) => { + * return c.json({ path: c.req.routePath }) + * }) + * ``` + */ + get routePath() { + return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path; + } +}; +var cloneRawRequest = async (req) => { + if (!req.raw.bodyUsed) { + return req.raw.clone(); + } + const cacheKey = Object.keys(req.bodyCache)[0]; + if (!cacheKey) { + throw new HTTPException(500, { + message: "Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly." + }); + } + const requestInit = { + body: await req[cacheKey](), + cache: req.raw.cache, + credentials: req.raw.credentials, + headers: req.header(), + integrity: req.raw.integrity, + keepalive: req.raw.keepalive, + method: req.method, + mode: req.raw.mode, + redirect: req.raw.redirect, + referrer: req.raw.referrer, + referrerPolicy: req.raw.referrerPolicy, + signal: req.raw.signal + }; + return new Request(req.url, requestInit); +}; +export { + HonoRequest, + cloneRawRequest +}; diff --git a/node_modules/hono/dist/request/constants.js b/node_modules/hono/dist/request/constants.js new file mode 100644 index 000000000..0dd1f541c --- /dev/null +++ b/node_modules/hono/dist/request/constants.js @@ -0,0 +1,5 @@ +// src/request/constants.ts +var GET_MATCH_RESULT = /* @__PURE__ */ Symbol(); +export { + GET_MATCH_RESULT +}; diff --git a/node_modules/hono/dist/router.js b/node_modules/hono/dist/router.js new file mode 100644 index 000000000..7e3111e2d --- /dev/null +++ b/node_modules/hono/dist/router.js @@ -0,0 +1,14 @@ +// src/router.ts +var METHOD_NAME_ALL = "ALL"; +var METHOD_NAME_ALL_LOWERCASE = "all"; +var METHODS = ["get", "post", "put", "delete", "options", "patch"]; +var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built."; +var UnsupportedPathError = class extends Error { +}; +export { + MESSAGE_MATCHER_IS_ALREADY_BUILT, + METHODS, + METHOD_NAME_ALL, + METHOD_NAME_ALL_LOWERCASE, + UnsupportedPathError +}; diff --git a/node_modules/hono/dist/router/linear-router/index.js b/node_modules/hono/dist/router/linear-router/index.js new file mode 100644 index 000000000..ed507118c --- /dev/null +++ b/node_modules/hono/dist/router/linear-router/index.js @@ -0,0 +1,5 @@ +// src/router/linear-router/index.ts +import { LinearRouter } from "./router.js"; +export { + LinearRouter +}; diff --git a/node_modules/hono/dist/router/linear-router/router.js b/node_modules/hono/dist/router/linear-router/router.js new file mode 100644 index 000000000..ca0a0c1a0 --- /dev/null +++ b/node_modules/hono/dist/router/linear-router/router.js @@ -0,0 +1,118 @@ +// src/router/linear-router/router.ts +import { METHOD_NAME_ALL, UnsupportedPathError } from "../../router.js"; +import { checkOptionalParameter } from "../../utils/url.js"; +var emptyParams = /* @__PURE__ */ Object.create(null); +var splitPathRe = /\/(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/[^\/\?]+|(\?)/g; +var splitByStarRe = /\*/; +var LinearRouter = class { + name = "LinearRouter"; + #routes = []; + add(method, path, handler) { + for (let i = 0, paths = checkOptionalParameter(path) || [path], len = paths.length; i < len; i++) { + this.#routes.push([method, paths[i], handler]); + } + } + match(method, path) { + const handlers = []; + ROUTES_LOOP: for (let i = 0, len = this.#routes.length; i < len; i++) { + const [routeMethod, routePath, handler] = this.#routes[i]; + if (routeMethod === method || routeMethod === METHOD_NAME_ALL) { + if (routePath === "*" || routePath === "/*") { + handlers.push([handler, emptyParams]); + continue; + } + const hasStar = routePath.indexOf("*") !== -1; + const hasLabel = routePath.indexOf(":") !== -1; + if (!hasStar && !hasLabel) { + if (routePath === path || routePath + "/" === path) { + handlers.push([handler, emptyParams]); + } + } else if (hasStar && !hasLabel) { + const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 42; + const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe); + const lastIndex = parts.length - 1; + for (let j = 0, pos = 0, len2 = parts.length; j < len2; j++) { + const part = parts[j]; + const index = path.indexOf(part, pos); + if (index !== pos) { + continue ROUTES_LOOP; + } + pos += part.length; + if (j === lastIndex) { + if (!endsWithStar && pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) { + continue ROUTES_LOOP; + } + } else { + const index2 = path.indexOf("/", pos); + if (index2 === -1) { + continue ROUTES_LOOP; + } + pos = index2; + } + } + handlers.push([handler, emptyParams]); + } else if (hasLabel && !hasStar) { + const params = /* @__PURE__ */ Object.create(null); + const parts = routePath.match(splitPathRe); + const lastIndex = parts.length - 1; + for (let j = 0, pos = 0, len2 = parts.length; j < len2; j++) { + if (pos === -1 || pos >= path.length) { + continue ROUTES_LOOP; + } + const part = parts[j]; + if (part.charCodeAt(1) === 58) { + if (path.charCodeAt(pos) !== 47) { + continue ROUTES_LOOP; + } + let name = part.slice(2); + let value; + if (name.charCodeAt(name.length - 1) === 125) { + const openBracePos = name.indexOf("{"); + const next = parts[j + 1]; + const lookahead = next && next[1] !== ":" && next[1] !== "*" ? `(?=${next})` : ""; + const pattern = name.slice(openBracePos + 1, -1) + lookahead; + const restPath = path.slice(pos + 1); + const match = new RegExp(pattern, "d").exec(restPath); + if (!match || match.indices[0][0] !== 0 || match.indices[0][1] === 0) { + continue ROUTES_LOOP; + } + name = name.slice(0, openBracePos); + value = restPath.slice(...match.indices[0]); + pos += match.indices[0][1] + 1; + } else { + let endValuePos = path.indexOf("/", pos + 1); + if (endValuePos === -1) { + if (pos + 1 === path.length) { + continue ROUTES_LOOP; + } + endValuePos = path.length; + } + value = path.slice(pos + 1, endValuePos); + pos = endValuePos; + } + params[name] ||= value; + } else { + const index = path.indexOf(part, pos); + if (index !== pos) { + continue ROUTES_LOOP; + } + pos += part.length; + } + if (j === lastIndex) { + if (pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) { + continue ROUTES_LOOP; + } + } + } + handlers.push([handler, params]); + } else if (hasLabel && hasStar) { + throw new UnsupportedPathError(); + } + } + } + return [handlers]; + } +}; +export { + LinearRouter +}; diff --git a/node_modules/hono/dist/router/pattern-router/index.js b/node_modules/hono/dist/router/pattern-router/index.js new file mode 100644 index 000000000..b4e9ab4bf --- /dev/null +++ b/node_modules/hono/dist/router/pattern-router/index.js @@ -0,0 +1,5 @@ +// src/router/pattern-router/index.ts +import { PatternRouter } from "./router.js"; +export { + PatternRouter +}; diff --git a/node_modules/hono/dist/router/pattern-router/router.js b/node_modules/hono/dist/router/pattern-router/router.js new file mode 100644 index 000000000..96eb0b89f --- /dev/null +++ b/node_modules/hono/dist/router/pattern-router/router.js @@ -0,0 +1,48 @@ +// src/router/pattern-router/router.ts +import { METHOD_NAME_ALL, UnsupportedPathError } from "../../router.js"; +var emptyParams = /* @__PURE__ */ Object.create(null); +var PatternRouter = class { + name = "PatternRouter"; + #routes = []; + add(method, path, handler) { + const endsWithWildcard = path.at(-1) === "*"; + if (endsWithWildcard) { + path = path.slice(0, -2); + } + if (path.at(-1) === "?") { + path = path.slice(0, -1); + this.add(method, path.replace(/\/[^/]+$/, ""), handler); + } + const parts = (path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g) || []).map( + (part) => { + const match = part.match(/^\/:([^{]+)(?:{(.*)})?/); + return match ? `/(?<${match[1]}>${match[2] || "[^/]+"})` : part === "/*" ? "/[^/]+" : part.replace(/[.\\+*[^\]$()]/g, "\\$&"); + } + ); + try { + this.#routes.push([ + new RegExp(`^${parts.join("")}${endsWithWildcard ? "" : "/?$"}`), + method, + handler + ]); + } catch { + throw new UnsupportedPathError(); + } + } + match(method, path) { + const handlers = []; + for (let i = 0, len = this.#routes.length; i < len; i++) { + const [pattern, routeMethod, handler] = this.#routes[i]; + if (routeMethod === method || routeMethod === METHOD_NAME_ALL) { + const match = pattern.exec(path); + if (match) { + handlers.push([handler, match.groups || emptyParams]); + } + } + } + return [handlers]; + } +}; +export { + PatternRouter +}; diff --git a/node_modules/hono/dist/router/reg-exp-router/index.js b/node_modules/hono/dist/router/reg-exp-router/index.js new file mode 100644 index 000000000..dc94aeba4 --- /dev/null +++ b/node_modules/hono/dist/router/reg-exp-router/index.js @@ -0,0 +1,9 @@ +// src/router/reg-exp-router/index.ts +import { RegExpRouter } from "./router.js"; +import { PreparedRegExpRouter, buildInitParams, serializeInitParams } from "./prepared-router.js"; +export { + PreparedRegExpRouter, + RegExpRouter, + buildInitParams, + serializeInitParams +}; diff --git a/node_modules/hono/dist/router/reg-exp-router/matcher.js b/node_modules/hono/dist/router/reg-exp-router/matcher.js new file mode 100644 index 000000000..3691559d2 --- /dev/null +++ b/node_modules/hono/dist/router/reg-exp-router/matcher.js @@ -0,0 +1,25 @@ +// src/router/reg-exp-router/matcher.ts +import { METHOD_NAME_ALL } from "../../router.js"; +var emptyParam = []; +function match(method, path) { + const matchers = this.buildAllMatchers(); + const match2 = ((method2, path2) => { + const matcher = matchers[method2] || matchers[METHOD_NAME_ALL]; + const staticMatch = matcher[2][path2]; + if (staticMatch) { + return staticMatch; + } + const match3 = path2.match(matcher[0]); + if (!match3) { + return [[], emptyParam]; + } + const index = match3.indexOf("", 1); + return [matcher[1][index], match3]; + }); + this.match = match2; + return match2(method, path); +} +export { + emptyParam, + match +}; diff --git a/node_modules/hono/dist/router/reg-exp-router/node.js b/node_modules/hono/dist/router/reg-exp-router/node.js new file mode 100644 index 000000000..fc4b2928b --- /dev/null +++ b/node_modules/hono/dist/router/reg-exp-router/node.js @@ -0,0 +1,111 @@ +// src/router/reg-exp-router/node.ts +var LABEL_REG_EXP_STR = "[^/]+"; +var ONLY_WILDCARD_REG_EXP_STR = ".*"; +var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)"; +var PATH_ERROR = /* @__PURE__ */ Symbol(); +var regExpMetaChars = new Set(".\\+*[^]$()"); +function compareKey(a, b) { + if (a.length === 1) { + return b.length === 1 ? a < b ? -1 : 1 : -1; + } + if (b.length === 1) { + return 1; + } + if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) { + return 1; + } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) { + return -1; + } + if (a === LABEL_REG_EXP_STR) { + return 1; + } else if (b === LABEL_REG_EXP_STR) { + return -1; + } + return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length; +} +var Node = class _Node { + #index; + #varIndex; + #children = /* @__PURE__ */ Object.create(null); + insert(tokens, index, paramMap, context, pathErrorCheckOnly) { + if (tokens.length === 0) { + if (this.#index !== void 0) { + throw PATH_ERROR; + } + if (pathErrorCheckOnly) { + return; + } + this.#index = index; + return; + } + const [token, ...restTokens] = tokens; + const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); + let node; + if (pattern) { + const name = pattern[1]; + let regexpStr = pattern[2] || LABEL_REG_EXP_STR; + if (name && pattern[2]) { + if (regexpStr === ".*") { + throw PATH_ERROR; + } + regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:"); + if (/\((?!\?:)/.test(regexpStr)) { + throw PATH_ERROR; + } + } + node = this.#children[regexpStr]; + if (!node) { + if (Object.keys(this.#children).some( + (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR + )) { + throw PATH_ERROR; + } + if (pathErrorCheckOnly) { + return; + } + node = this.#children[regexpStr] = new _Node(); + if (name !== "") { + node.#varIndex = context.varIndex++; + } + } + if (!pathErrorCheckOnly && name !== "") { + paramMap.push([name, node.#varIndex]); + } + } else { + node = this.#children[token]; + if (!node) { + if (Object.keys(this.#children).some( + (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR + )) { + throw PATH_ERROR; + } + if (pathErrorCheckOnly) { + return; + } + node = this.#children[token] = new _Node(); + } + } + node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly); + } + buildRegExpStr() { + const childKeys = Object.keys(this.#children).sort(compareKey); + const strList = childKeys.map((k) => { + const c = this.#children[k]; + return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr(); + }); + if (typeof this.#index === "number") { + strList.unshift(`#${this.#index}`); + } + if (strList.length === 0) { + return ""; + } + if (strList.length === 1) { + return strList[0]; + } + return "(?:" + strList.join("|") + ")"; + } +}; +export { + Node, + PATH_ERROR +}; diff --git a/node_modules/hono/dist/router/reg-exp-router/prepared-router.js b/node_modules/hono/dist/router/reg-exp-router/prepared-router.js new file mode 100644 index 000000000..d329d7601 --- /dev/null +++ b/node_modules/hono/dist/router/reg-exp-router/prepared-router.js @@ -0,0 +1,142 @@ +// src/router/reg-exp-router/prepared-router.ts +import { METHOD_NAME_ALL } from "../../router.js"; +import { match, emptyParam } from "./matcher.js"; +import { RegExpRouter } from "./router.js"; +var PreparedRegExpRouter = class { + name = "PreparedRegExpRouter"; + #matchers; + #relocateMap; + constructor(matchers, relocateMap) { + this.#matchers = matchers; + this.#relocateMap = relocateMap; + } + #addWildcard(method, handlerData) { + const matcher = this.#matchers[method]; + matcher[1].forEach((list) => list && list.push(handlerData)); + Object.values(matcher[2]).forEach((list) => list[0].push(handlerData)); + } + #addPath(method, path, handler, indexes, map) { + const matcher = this.#matchers[method]; + if (!map) { + matcher[2][path][0].push([handler, {}]); + } else { + indexes.forEach((index) => { + if (typeof index === "number") { + matcher[1][index].push([handler, map]); + } else { + ; + matcher[2][index || path][0].push([handler, map]); + } + }); + } + } + add(method, path, handler) { + if (!this.#matchers[method]) { + const all = this.#matchers[METHOD_NAME_ALL]; + const staticMap = {}; + for (const key in all[2]) { + staticMap[key] = [all[2][key][0].slice(), emptyParam]; + } + this.#matchers[method] = [ + all[0], + all[1].map((list) => Array.isArray(list) ? list.slice() : 0), + staticMap + ]; + } + if (path === "/*" || path === "*") { + const handlerData = [handler, {}]; + if (method === METHOD_NAME_ALL) { + for (const m in this.#matchers) { + this.#addWildcard(m, handlerData); + } + } else { + this.#addWildcard(method, handlerData); + } + return; + } + const data = this.#relocateMap[path]; + if (!data) { + throw new Error(`Path ${path} is not registered`); + } + for (const [indexes, map] of data) { + if (method === METHOD_NAME_ALL) { + for (const m in this.#matchers) { + this.#addPath(m, path, handler, indexes, map); + } + } else { + this.#addPath(method, path, handler, indexes, map); + } + } + } + buildAllMatchers() { + return this.#matchers; + } + match = match; +}; +var buildInitParams = ({ paths }) => { + const RegExpRouterWithMatcherExport = class extends RegExpRouter { + buildAndExportAllMatchers() { + return this.buildAllMatchers(); + } + }; + const router = new RegExpRouterWithMatcherExport(); + for (const path of paths) { + router.add(METHOD_NAME_ALL, path, path); + } + const matchers = router.buildAndExportAllMatchers(); + const all = matchers[METHOD_NAME_ALL]; + const relocateMap = {}; + for (const path of paths) { + if (path === "/*" || path === "*") { + continue; + } + all[1].forEach((list, i) => { + list.forEach(([p, map]) => { + if (p === path) { + if (relocateMap[path]) { + relocateMap[path][0][1] = { + ...relocateMap[path][0][1], + ...map + }; + } else { + relocateMap[path] = [[[], map]]; + } + if (relocateMap[path][0][0].findIndex((j) => j === i) === -1) { + relocateMap[path][0][0].push(i); + } + } + }); + }); + for (const path2 in all[2]) { + all[2][path2][0].forEach(([p]) => { + if (p === path) { + relocateMap[path] ||= [[[]]]; + const value = path2 === path ? "" : path2; + if (relocateMap[path][0][0].findIndex((v) => v === value) === -1) { + relocateMap[path][0][0].push(value); + } + } + }); + } + } + for (let i = 0, len = all[1].length; i < len; i++) { + all[1][i] = all[1][i] ? [] : 0; + } + for (const path in all[2]) { + all[2][path][0] = []; + } + return [matchers, relocateMap]; +}; +var serializeInitParams = ([matchers, relocateMap]) => { + const matchersStr = JSON.stringify( + matchers, + (_, value) => value instanceof RegExp ? `##${value.toString()}##` : value + ).replace(/"##(.+?)##"/g, (_, str) => str.replace(/\\\\/g, "\\")); + const relocateMapStr = JSON.stringify(relocateMap); + return `[${matchersStr},${relocateMapStr}]`; +}; +export { + PreparedRegExpRouter, + buildInitParams, + serializeInitParams +}; diff --git a/node_modules/hono/dist/router/reg-exp-router/router.js b/node_modules/hono/dist/router/reg-exp-router/router.js new file mode 100644 index 000000000..c8abb7040 --- /dev/null +++ b/node_modules/hono/dist/router/reg-exp-router/router.js @@ -0,0 +1,190 @@ +// src/router/reg-exp-router/router.ts +import { + MESSAGE_MATCHER_IS_ALREADY_BUILT, + METHOD_NAME_ALL, + UnsupportedPathError +} from "../../router.js"; +import { checkOptionalParameter } from "../../utils/url.js"; +import { match, emptyParam } from "./matcher.js"; +import { PATH_ERROR } from "./node.js"; +import { Trie } from "./trie.js"; +var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)]; +var wildcardRegExpCache = /* @__PURE__ */ Object.create(null); +function buildWildcardRegExp(path) { + return wildcardRegExpCache[path] ??= new RegExp( + path === "*" ? "" : `^${path.replace( + /\/\*$|([.\\+*[^\]$()])/g, + (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)" + )}$` + ); +} +function clearWildcardRegExpCache() { + wildcardRegExpCache = /* @__PURE__ */ Object.create(null); +} +function buildMatcherFromPreprocessedRoutes(routes) { + const trie = new Trie(); + const handlerData = []; + if (routes.length === 0) { + return nullMatcher; + } + const routesWithStaticPathFlag = routes.map( + (route) => [!/\*|\/:/.test(route[0]), ...route] + ).sort( + ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length + ); + const staticMap = /* @__PURE__ */ Object.create(null); + for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) { + const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i]; + if (pathErrorCheckOnly) { + staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam]; + } else { + j++; + } + let paramAssoc; + try { + paramAssoc = trie.insert(path, j, pathErrorCheckOnly); + } catch (e) { + throw e === PATH_ERROR ? new UnsupportedPathError(path) : e; + } + if (pathErrorCheckOnly) { + continue; + } + handlerData[j] = handlers.map(([h, paramCount]) => { + const paramIndexMap = /* @__PURE__ */ Object.create(null); + paramCount -= 1; + for (; paramCount >= 0; paramCount--) { + const [key, value] = paramAssoc[paramCount]; + paramIndexMap[key] = value; + } + return [h, paramIndexMap]; + }); + } + const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp(); + for (let i = 0, len = handlerData.length; i < len; i++) { + for (let j = 0, len2 = handlerData[i].length; j < len2; j++) { + const map = handlerData[i][j]?.[1]; + if (!map) { + continue; + } + const keys = Object.keys(map); + for (let k = 0, len3 = keys.length; k < len3; k++) { + map[keys[k]] = paramReplacementMap[map[keys[k]]]; + } + } + } + const handlerMap = []; + for (const i in indexReplacementMap) { + handlerMap[i] = handlerData[indexReplacementMap[i]]; + } + return [regexp, handlerMap, staticMap]; +} +function findMiddleware(middleware, path) { + if (!middleware) { + return void 0; + } + for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) { + if (buildWildcardRegExp(k).test(path)) { + return [...middleware[k]]; + } + } + return void 0; +} +var RegExpRouter = class { + name = "RegExpRouter"; + #middleware; + #routes; + constructor() { + this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }; + this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }; + } + add(method, path, handler) { + const middleware = this.#middleware; + const routes = this.#routes; + if (!middleware || !routes) { + throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); + } + if (!middleware[method]) { + ; + [middleware, routes].forEach((handlerMap) => { + handlerMap[method] = /* @__PURE__ */ Object.create(null); + Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => { + handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]; + }); + }); + } + if (path === "/*") { + path = "*"; + } + const paramCount = (path.match(/\/:/g) || []).length; + if (/\*$/.test(path)) { + const re = buildWildcardRegExp(path); + if (method === METHOD_NAME_ALL) { + Object.keys(middleware).forEach((m) => { + middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || []; + }); + } else { + middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || []; + } + Object.keys(middleware).forEach((m) => { + if (method === METHOD_NAME_ALL || method === m) { + Object.keys(middleware[m]).forEach((p) => { + re.test(p) && middleware[m][p].push([handler, paramCount]); + }); + } + }); + Object.keys(routes).forEach((m) => { + if (method === METHOD_NAME_ALL || method === m) { + Object.keys(routes[m]).forEach( + (p) => re.test(p) && routes[m][p].push([handler, paramCount]) + ); + } + }); + return; + } + const paths = checkOptionalParameter(path) || [path]; + for (let i = 0, len = paths.length; i < len; i++) { + const path2 = paths[i]; + Object.keys(routes).forEach((m) => { + if (method === METHOD_NAME_ALL || method === m) { + routes[m][path2] ||= [ + ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || [] + ]; + routes[m][path2].push([handler, paramCount - len + i + 1]); + } + }); + } + } + match = match; + buildAllMatchers() { + const matchers = /* @__PURE__ */ Object.create(null); + Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => { + matchers[method] ||= this.#buildMatcher(method); + }); + this.#middleware = this.#routes = void 0; + clearWildcardRegExpCache(); + return matchers; + } + #buildMatcher(method) { + const routes = []; + let hasOwnRoute = method === METHOD_NAME_ALL; + [this.#middleware, this.#routes].forEach((r) => { + const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : []; + if (ownRoute.length !== 0) { + hasOwnRoute ||= true; + routes.push(...ownRoute); + } else if (method !== METHOD_NAME_ALL) { + routes.push( + ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]) + ); + } + }); + if (!hasOwnRoute) { + return null; + } else { + return buildMatcherFromPreprocessedRoutes(routes); + } + } +}; +export { + RegExpRouter +}; diff --git a/node_modules/hono/dist/router/reg-exp-router/trie.js b/node_modules/hono/dist/router/reg-exp-router/trie.js new file mode 100644 index 000000000..7de861e5d --- /dev/null +++ b/node_modules/hono/dist/router/reg-exp-router/trie.js @@ -0,0 +1,59 @@ +// src/router/reg-exp-router/trie.ts +import { Node } from "./node.js"; +var Trie = class { + #context = { varIndex: 0 }; + #root = new Node(); + insert(path, index, pathErrorCheckOnly) { + const paramAssoc = []; + const groups = []; + for (let i = 0; ; ) { + let replaced = false; + path = path.replace(/\{[^}]+\}/g, (m) => { + const mark = `@\\${i}`; + groups[i] = [mark, m]; + i++; + replaced = true; + return mark; + }); + if (!replaced) { + break; + } + } + const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []; + for (let i = groups.length - 1; i >= 0; i--) { + const [mark] = groups[i]; + for (let j = tokens.length - 1; j >= 0; j--) { + if (tokens[j].indexOf(mark) !== -1) { + tokens[j] = tokens[j].replace(mark, groups[i][1]); + break; + } + } + } + this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly); + return paramAssoc; + } + buildRegExp() { + let regexp = this.#root.buildRegExpStr(); + if (regexp === "") { + return [/^$/, [], []]; + } + let captureIndex = 0; + const indexReplacementMap = []; + const paramReplacementMap = []; + regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => { + if (handlerIndex !== void 0) { + indexReplacementMap[++captureIndex] = Number(handlerIndex); + return "$()"; + } + if (paramIndex !== void 0) { + paramReplacementMap[Number(paramIndex)] = ++captureIndex; + return ""; + } + return ""; + }); + return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]; + } +}; +export { + Trie +}; diff --git a/node_modules/hono/dist/router/smart-router/index.js b/node_modules/hono/dist/router/smart-router/index.js new file mode 100644 index 000000000..2e6837740 --- /dev/null +++ b/node_modules/hono/dist/router/smart-router/index.js @@ -0,0 +1,5 @@ +// src/router/smart-router/index.ts +import { SmartRouter } from "./router.js"; +export { + SmartRouter +}; diff --git a/node_modules/hono/dist/router/smart-router/router.js b/node_modules/hono/dist/router/smart-router/router.js new file mode 100644 index 000000000..1b19adbe1 --- /dev/null +++ b/node_modules/hono/dist/router/smart-router/router.js @@ -0,0 +1,58 @@ +// src/router/smart-router/router.ts +import { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from "../../router.js"; +var SmartRouter = class { + name = "SmartRouter"; + #routers = []; + #routes = []; + constructor(init) { + this.#routers = init.routers; + } + add(method, path, handler) { + if (!this.#routes) { + throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); + } + this.#routes.push([method, path, handler]); + } + match(method, path) { + if (!this.#routes) { + throw new Error("Fatal error"); + } + const routers = this.#routers; + const routes = this.#routes; + const len = routers.length; + let i = 0; + let res; + for (; i < len; i++) { + const router = routers[i]; + try { + for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) { + router.add(...routes[i2]); + } + res = router.match(method, path); + } catch (e) { + if (e instanceof UnsupportedPathError) { + continue; + } + throw e; + } + this.match = router.match.bind(router); + this.#routers = [router]; + this.#routes = void 0; + break; + } + if (i === len) { + throw new Error("Fatal error"); + } + this.name = `SmartRouter + ${this.activeRouter.name}`; + return res; + } + get activeRouter() { + if (this.#routes || this.#routers.length !== 1) { + throw new Error("No active router has been determined yet."); + } + return this.#routers[0]; + } +}; +export { + SmartRouter +}; diff --git a/node_modules/hono/dist/router/trie-router/index.js b/node_modules/hono/dist/router/trie-router/index.js new file mode 100644 index 000000000..c680d1066 --- /dev/null +++ b/node_modules/hono/dist/router/trie-router/index.js @@ -0,0 +1,5 @@ +// src/router/trie-router/index.ts +import { TrieRouter } from "./router.js"; +export { + TrieRouter +}; diff --git a/node_modules/hono/dist/router/trie-router/node.js b/node_modules/hono/dist/router/trie-router/node.js new file mode 100644 index 000000000..a34c96d66 --- /dev/null +++ b/node_modules/hono/dist/router/trie-router/node.js @@ -0,0 +1,162 @@ +// src/router/trie-router/node.ts +import { METHOD_NAME_ALL } from "../../router.js"; +import { getPattern, splitPath, splitRoutingPath } from "../../utils/url.js"; +var emptyParams = /* @__PURE__ */ Object.create(null); +var Node = class _Node { + #methods; + #children; + #patterns; + #order = 0; + #params = emptyParams; + constructor(method, handler, children) { + this.#children = children || /* @__PURE__ */ Object.create(null); + this.#methods = []; + if (method && handler) { + const m = /* @__PURE__ */ Object.create(null); + m[method] = { handler, possibleKeys: [], score: 0 }; + this.#methods = [m]; + } + this.#patterns = []; + } + insert(method, path, handler) { + this.#order = ++this.#order; + let curNode = this; + const parts = splitRoutingPath(path); + const possibleKeys = []; + for (let i = 0, len = parts.length; i < len; i++) { + const p = parts[i]; + const nextP = parts[i + 1]; + const pattern = getPattern(p, nextP); + const key = Array.isArray(pattern) ? pattern[0] : p; + if (key in curNode.#children) { + curNode = curNode.#children[key]; + if (pattern) { + possibleKeys.push(pattern[1]); + } + continue; + } + curNode.#children[key] = new _Node(); + if (pattern) { + curNode.#patterns.push(pattern); + possibleKeys.push(pattern[1]); + } + curNode = curNode.#children[key]; + } + curNode.#methods.push({ + [method]: { + handler, + possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i), + score: this.#order + } + }); + return curNode; + } + #getHandlerSets(node, method, nodeParams, params) { + const handlerSets = []; + for (let i = 0, len = node.#methods.length; i < len; i++) { + const m = node.#methods[i]; + const handlerSet = m[method] || m[METHOD_NAME_ALL]; + const processedSet = {}; + if (handlerSet !== void 0) { + handlerSet.params = /* @__PURE__ */ Object.create(null); + handlerSets.push(handlerSet); + if (nodeParams !== emptyParams || params && params !== emptyParams) { + for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) { + const key = handlerSet.possibleKeys[i2]; + const processed = processedSet[handlerSet.score]; + handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key]; + processedSet[handlerSet.score] = true; + } + } + } + } + return handlerSets; + } + search(method, path) { + const handlerSets = []; + this.#params = emptyParams; + const curNode = this; + let curNodes = [curNode]; + const parts = splitPath(path); + const curNodesQueue = []; + for (let i = 0, len = parts.length; i < len; i++) { + const part = parts[i]; + const isLast = i === len - 1; + const tempNodes = []; + for (let j = 0, len2 = curNodes.length; j < len2; j++) { + const node = curNodes[j]; + const nextNode = node.#children[part]; + if (nextNode) { + nextNode.#params = node.#params; + if (isLast) { + if (nextNode.#children["*"]) { + handlerSets.push( + ...this.#getHandlerSets(nextNode.#children["*"], method, node.#params) + ); + } + handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params)); + } else { + tempNodes.push(nextNode); + } + } + for (let k = 0, len3 = node.#patterns.length; k < len3; k++) { + const pattern = node.#patterns[k]; + const params = node.#params === emptyParams ? {} : { ...node.#params }; + if (pattern === "*") { + const astNode = node.#children["*"]; + if (astNode) { + handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params)); + astNode.#params = params; + tempNodes.push(astNode); + } + continue; + } + const [key, name, matcher] = pattern; + if (!part && !(matcher instanceof RegExp)) { + continue; + } + const child = node.#children[key]; + const restPathString = parts.slice(i).join("/"); + if (matcher instanceof RegExp) { + const m = matcher.exec(restPathString); + if (m) { + params[name] = m[0]; + handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params)); + if (Object.keys(child.#children).length) { + child.#params = params; + const componentCount = m[0].match(/\//)?.length ?? 0; + const targetCurNodes = curNodesQueue[componentCount] ||= []; + targetCurNodes.push(child); + } + continue; + } + } + if (matcher === true || matcher.test(part)) { + params[name] = part; + if (isLast) { + handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params)); + if (child.#children["*"]) { + handlerSets.push( + ...this.#getHandlerSets(child.#children["*"], method, params, node.#params) + ); + } + } else { + child.#params = params; + tempNodes.push(child); + } + } + } + } + curNodes = tempNodes.concat(curNodesQueue.shift() ?? []); + } + if (handlerSets.length > 1) { + handlerSets.sort((a, b) => { + return a.score - b.score; + }); + } + return [handlerSets.map(({ handler, params }) => [handler, params])]; + } +}; +export { + Node +}; diff --git a/node_modules/hono/dist/router/trie-router/router.js b/node_modules/hono/dist/router/trie-router/router.js new file mode 100644 index 000000000..40fd29df0 --- /dev/null +++ b/node_modules/hono/dist/router/trie-router/router.js @@ -0,0 +1,26 @@ +// src/router/trie-router/router.ts +import { checkOptionalParameter } from "../../utils/url.js"; +import { Node } from "./node.js"; +var TrieRouter = class { + name = "TrieRouter"; + #node; + constructor() { + this.#node = new Node(); + } + add(method, path, handler) { + const results = checkOptionalParameter(path); + if (results) { + for (let i = 0, len = results.length; i < len; i++) { + this.#node.insert(method, results[i], handler); + } + return; + } + this.#node.insert(method, path, handler); + } + match(method, path) { + return this.#node.search(method, path); + } +}; +export { + TrieRouter +}; diff --git a/node_modules/hono/dist/types.js b/node_modules/hono/dist/types.js new file mode 100644 index 000000000..863d10445 --- /dev/null +++ b/node_modules/hono/dist/types.js @@ -0,0 +1,6 @@ +// src/types.ts +var FetchEventLike = class { +}; +export { + FetchEventLike +}; diff --git a/node_modules/hono/dist/types/adapter/aws-lambda/handler.d.ts b/node_modules/hono/dist/types/adapter/aws-lambda/handler.d.ts new file mode 100644 index 000000000..2adfa9b9b --- /dev/null +++ b/node_modules/hono/dist/types/adapter/aws-lambda/handler.d.ts @@ -0,0 +1,184 @@ +import type { Hono } from '../../hono'; +import type { Env, Schema } from '../../types'; +import type { ALBRequestContext, ApiGatewayRequestContext, ApiGatewayRequestContextV2, Handler, LambdaContext, LatticeRequestContextV2 } from './types'; +export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent | LatticeProxyEventV2; +export interface LatticeProxyEventV2 { + version: string; + path: string; + method: string; + headers: Record; + queryStringParameters: Record; + body: string | null; + isBase64Encoded: boolean; + requestContext: LatticeRequestContextV2; +} +export interface APIGatewayProxyEventV2 { + version: string; + routeKey: string; + headers: Record; + multiValueHeaders?: undefined; + cookies?: string[]; + rawPath: string; + rawQueryString: string; + body: string | null; + isBase64Encoded: boolean; + requestContext: ApiGatewayRequestContextV2; + queryStringParameters?: { + [name: string]: string | undefined; + }; + pathParameters?: { + [name: string]: string | undefined; + }; + stageVariables?: { + [name: string]: string | undefined; + }; +} +export interface APIGatewayProxyEvent { + version: string; + httpMethod: string; + headers: Record; + multiValueHeaders?: { + [headerKey: string]: string[]; + }; + path: string; + body: string | null; + isBase64Encoded: boolean; + queryStringParameters?: Record; + requestContext: ApiGatewayRequestContext; + resource: string; + multiValueQueryStringParameters?: { + [parameterKey: string]: string[]; + }; + pathParameters?: Record; + stageVariables?: Record; +} +export interface ALBProxyEvent { + httpMethod: string; + headers?: Record; + multiValueHeaders?: Record; + path: string; + body: string | null; + isBase64Encoded: boolean; + queryStringParameters?: Record; + multiValueQueryStringParameters?: { + [parameterKey: string]: string[]; + }; + requestContext: ALBRequestContext; +} +type WithHeaders = { + headers: Record; + multiValueHeaders?: undefined; +}; +type WithMultiValueHeaders = { + headers?: undefined; + multiValueHeaders: Record; +}; +export type APIGatewayProxyResult = { + statusCode: number; + statusDescription?: string; + body: string; + cookies?: string[]; + isBase64Encoded: boolean; +} & (WithHeaders | WithMultiValueHeaders); +export declare const streamHandle: (app: Hono) => Handler; +type HandleOptions = { + isContentTypeBinary: ((contentType: string) => boolean) | undefined; +}; +/** + * Converts a Hono application to an AWS Lambda handler. + * + * Accepts events from API Gateway (v1 and v2), Application Load Balancer (ALB), + * and Lambda Function URLs. + * + * @param app - The Hono application instance + * @param options - Optional configuration + * @param options.isContentTypeBinary - A function to determine if the content type is binary. + * If not provided, the default function will be used. + * @returns Lambda handler function + * + * @example + * ```js + * import { Hono } from 'hono' + * import { handle } from 'hono/aws-lambda' + * + * const app = new Hono() + * + * app.get('/', (c) => c.text('Hello from Lambda')) + * app.get('/json', (c) => c.json({ message: 'Hello JSON' })) + * + * export const handler = handle(app) + * ``` + * + * @example + * ```js + * // With custom binary content type detection + * import { handle, defaultIsContentTypeBinary } from 'hono/aws-lambda' + * export const handler = handle(app, { + * isContentTypeBinary: (contentType) => { + * if (defaultIsContentTypeBinary(contentType)) { + * // default logic same as prior to v4.8.4 + * return true + * } + * return contentType.startsWith('image/') || contentType === 'application/pdf' + * } + * }) + * ``` + */ +export declare const handle: (app: Hono, { isContentTypeBinary }?: HandleOptions) => ((event: L, lambdaContext?: LambdaContext) => Promise; +} ? WithMultiValueHeaders : WithHeaders)>); +export declare abstract class EventProcessor { + protected abstract getPath(event: E): string; + protected abstract getMethod(event: E): string; + protected abstract getQueryString(event: E): string; + protected abstract getHeaders(event: E): Headers; + protected abstract getCookies(event: E, headers: Headers): void; + protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void; + protected getHeaderValue(headers: E['headers'], key: string): string | undefined; + protected getDomainName(event: E): string | undefined; + createRequest(event: E): Request; + createResult(event: E, res: Response, options: Pick): Promise; + setCookies(event: E, res: Response, result: APIGatewayProxyResult): void; +} +export declare class EventV2Processor extends EventProcessor { + protected getPath(event: APIGatewayProxyEventV2): string; + protected getMethod(event: APIGatewayProxyEventV2): string; + protected getQueryString(event: APIGatewayProxyEventV2): string; + protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void; + protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void; + protected getHeaders(event: APIGatewayProxyEventV2): Headers; +} +export declare class EventV1Processor extends EventProcessor { + protected getPath(event: APIGatewayProxyEvent): string; + protected getMethod(event: APIGatewayProxyEvent): string; + protected getQueryString(event: APIGatewayProxyEvent): string; + protected getCookies(event: APIGatewayProxyEvent, headers: Headers): void; + protected getHeaders(event: APIGatewayProxyEvent): Headers; + protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void; +} +export declare class ALBProcessor extends EventProcessor { + protected getHeaders(event: ALBProxyEvent): Headers; + protected getPath(event: ALBProxyEvent): string; + protected getMethod(event: ALBProxyEvent): string; + protected getQueryString(event: ALBProxyEvent): string; + protected getCookies(event: ALBProxyEvent, headers: Headers): void; + protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void; +} +export declare class LatticeV2Processor extends EventProcessor { + protected getPath(event: LatticeProxyEventV2): string; + protected getMethod(event: LatticeProxyEventV2): string; + protected getQueryString(): string; + protected getHeaders(event: LatticeProxyEventV2): Headers; + protected getCookies(): void; + protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void; +} +export declare const getProcessor: (event: LambdaEvent) => EventProcessor; +/** + * Check if the given content type is binary. + * This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler(). + * @param contentType The content type to check. + * @returns True if the content type is binary, false otherwise. + */ +export declare const defaultIsContentTypeBinary: (contentType: string) => boolean; +export declare const isContentEncodingBinary: (contentEncoding: string | null) => boolean; +export {}; diff --git a/node_modules/hono/dist/types/adapter/aws-lambda/index.d.ts b/node_modules/hono/dist/types/adapter/aws-lambda/index.d.ts new file mode 100644 index 000000000..5a43c2c14 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/aws-lambda/index.d.ts @@ -0,0 +1,7 @@ +/** + * @module + * AWS Lambda Adapter for Hono. + */ +export { handle, streamHandle, defaultIsContentTypeBinary } from './handler'; +export type { APIGatewayProxyResult, LambdaEvent } from './handler'; +export type { ApiGatewayRequestContext, ApiGatewayRequestContextV2, ALBRequestContext, LambdaContext, } from './types'; diff --git a/node_modules/hono/dist/types/adapter/aws-lambda/types.d.ts b/node_modules/hono/dist/types/adapter/aws-lambda/types.d.ts new file mode 100644 index 000000000..22bb1c1cb --- /dev/null +++ b/node_modules/hono/dist/types/adapter/aws-lambda/types.d.ts @@ -0,0 +1,144 @@ +export interface CognitoIdentity { + cognitoIdentityId: string; + cognitoIdentityPoolId: string; +} +export interface ClientContext { + client: ClientContextClient; + Custom?: any; + env: ClientContextEnv; +} +export interface ClientContextClient { + installationId: string; + appTitle: string; + appVersionName: string; + appVersionCode: string; + appPackageName: string; +} +export interface ClientContextEnv { + platformVersion: string; + platform: string; + make: string; + model: string; + locale: string; +} +/** + * {@link Handler} context parameter. + * See {@link https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html AWS documentation}. + */ +export interface LambdaContext { + callbackWaitsForEmptyEventLoop: boolean; + functionName: string; + functionVersion: string; + invokedFunctionArn: string; + memoryLimitInMB: string; + awsRequestId: string; + logGroupName: string; + logStreamName: string; + identity?: CognitoIdentity | undefined; + clientContext?: ClientContext | undefined; + getRemainingTimeInMillis(): number; +} +type Callback = (error?: Error | string | null, result?: TResult) => void; +export type Handler = (event: TEvent, context: LambdaContext, callback: Callback) => void | Promise; +interface ClientCert { + clientCertPem: string; + subjectDN: string; + issuerDN: string; + serialNumber: string; + validity: { + notBefore: string; + notAfter: string; + }; +} +interface Identity { + accessKey?: string; + accountId?: string; + caller?: string; + cognitoAuthenticationProvider?: string; + cognitoAuthenticationType?: string; + cognitoIdentityId?: string; + cognitoIdentityPoolId?: string; + principalOrgId?: string; + sourceIp: string; + user?: string; + userAgent: string; + userArn?: string; + clientCert?: ClientCert; +} +export interface ApiGatewayRequestContext { + accountId: string; + apiId: string; + authorizer: { + claims?: unknown; + scopes?: unknown; + }; + domainName: string; + domainPrefix: string; + extendedRequestId: string; + httpMethod: string; + identity: Identity; + path: string; + protocol: string; + requestId: string; + requestTime: string; + requestTimeEpoch: number; + resourceId?: string; + resourcePath: string; + stage: string; +} +interface Authorizer { + iam?: { + accessKey: string; + accountId: string; + callerId: string; + cognitoIdentity: null; + principalOrgId: null; + userArn: string; + userId: string; + }; +} +export interface ApiGatewayRequestContextV2 { + accountId: string; + apiId: string; + authentication: null; + authorizer: Authorizer; + domainName: string; + domainPrefix: string; + http: { + method: string; + path: string; + protocol: string; + sourceIp: string; + userAgent: string; + }; + requestId: string; + routeKey: string; + stage: string; + time: string; + timeEpoch: number; +} +export interface ALBRequestContext { + elb: { + targetGroupArn: string; + }; +} +export interface LatticeRequestContextV2 { + serviceNetworkArn: string; + serviceArn: string; + targetGroupArn: string; + region: string; + timeEpoch: string; + identity: { + sourceVpcArn?: string; + type?: string; + principal?: string; + principalOrgID?: string; + sessionName?: string; + x509IssuerOu?: string; + x509SanDns?: string; + x509SanNameCn?: string; + x509SanUri?: string; + x509SubjectCn?: string; + }; +} +export {}; diff --git a/node_modules/hono/dist/types/adapter/bun/conninfo.d.ts b/node_modules/hono/dist/types/adapter/bun/conninfo.d.ts new file mode 100644 index 000000000..1a7cf118b --- /dev/null +++ b/node_modules/hono/dist/types/adapter/bun/conninfo.d.ts @@ -0,0 +1,7 @@ +import type { GetConnInfo } from '../../helper/conninfo'; +/** + * Get ConnInfo with Bun + * @param c Context + * @returns ConnInfo + */ +export declare const getConnInfo: GetConnInfo; diff --git a/node_modules/hono/dist/types/adapter/bun/index.d.ts b/node_modules/hono/dist/types/adapter/bun/index.d.ts new file mode 100644 index 000000000..39cd249be --- /dev/null +++ b/node_modules/hono/dist/types/adapter/bun/index.d.ts @@ -0,0 +1,9 @@ +/** + * @module + * Bun Adapter for Hono. + */ +export { serveStatic } from './serve-static'; +export { bunFileSystemModule, toSSG } from './ssg'; +export { createBunWebSocket, upgradeWebSocket, websocket } from './websocket'; +export type { BunWebSocketData, BunWebSocketHandler } from './websocket'; +export { getConnInfo } from './conninfo'; diff --git a/node_modules/hono/dist/types/adapter/bun/serve-static.d.ts b/node_modules/hono/dist/types/adapter/bun/serve-static.d.ts new file mode 100644 index 000000000..e79742d57 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/bun/serve-static.d.ts @@ -0,0 +1,3 @@ +import type { ServeStaticOptions } from '../../middleware/serve-static'; +import type { Env, MiddlewareHandler } from '../../types'; +export declare const serveStatic: (options: ServeStaticOptions) => MiddlewareHandler; diff --git a/node_modules/hono/dist/types/adapter/bun/server.d.ts b/node_modules/hono/dist/types/adapter/bun/server.d.ts new file mode 100644 index 000000000..a6f7f0b56 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/bun/server.d.ts @@ -0,0 +1,24 @@ +/** + * Getting Bun Server Object for Bun adapters + * @module + */ +import type { Context } from '../../context'; +/** + * Bun Server Object + */ +export interface BunServer { + requestIP?: (req: Request) => { + address: string; + family: string; + port: number; + } | null; + upgrade(req: Request, options?: { + data: T; + }): boolean; +} +/** + * Get Bun Server Object from Context + * @param c Context + * @returns Bun Server + */ +export declare const getBunServer: (c: Context) => BunServer | undefined; diff --git a/node_modules/hono/dist/types/adapter/bun/ssg.d.ts b/node_modules/hono/dist/types/adapter/bun/ssg.d.ts new file mode 100644 index 000000000..8db4e65a5 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/bun/ssg.d.ts @@ -0,0 +1,13 @@ +import type { FileSystemModule, ToSSGAdaptorInterface } from '../../helper/ssg'; +/** + * @experimental + * `bunFileSystemModule` is an experimental feature. + * The API might be changed. + */ +export declare const bunFileSystemModule: FileSystemModule; +/** + * @experimental + * `toSSG` is an experimental feature. + * The API might be changed. + */ +export declare const toSSG: ToSSGAdaptorInterface; diff --git a/node_modules/hono/dist/types/adapter/bun/websocket.d.ts b/node_modules/hono/dist/types/adapter/bun/websocket.d.ts new file mode 100644 index 000000000..9c6e2fb3d --- /dev/null +++ b/node_modules/hono/dist/types/adapter/bun/websocket.d.ts @@ -0,0 +1,39 @@ +import type { UpgradeWebSocket, WSEvents } from '../../helper/websocket'; +import { WSContext } from '../../helper/websocket'; +/** + * @internal + */ +export interface BunServerWebSocket { + send(data: string | ArrayBuffer | Uint8Array, compress?: boolean): void; + close(code?: number, reason?: string): void; + data: T; + readyState: 0 | 1 | 2 | 3; +} +export interface BunWebSocketHandler { + open(ws: BunServerWebSocket): void; + close(ws: BunServerWebSocket, code?: number, reason?: string): void; + message(ws: BunServerWebSocket, message: string | { + buffer: ArrayBufferLike; + }): void; +} +interface CreateWebSocket { + upgradeWebSocket: UpgradeWebSocket; + websocket: BunWebSocketHandler; +} +export interface BunWebSocketData { + events: WSEvents; + url: URL; + protocol: string; +} +/** + * @internal + */ +export declare const createWSContext: (ws: BunServerWebSocket) => WSContext; +export declare const upgradeWebSocket: UpgradeWebSocket; +export declare const websocket: BunWebSocketHandler; +/** + * @deprecated Import `upgradeWebSocket` and `websocket` directly from `hono/bun` instead. + * @returns A function to create a Bun WebSocket handler. + */ +export declare const createBunWebSocket: () => CreateWebSocket; +export {}; diff --git a/node_modules/hono/dist/types/adapter/cloudflare-pages/handler.d.ts b/node_modules/hono/dist/types/adapter/cloudflare-pages/handler.d.ts new file mode 100644 index 000000000..c78b00e5a --- /dev/null +++ b/node_modules/hono/dist/types/adapter/cloudflare-pages/handler.d.ts @@ -0,0 +1,33 @@ +import type { Hono } from '../../hono'; +import type { BlankSchema, Env, Input, MiddlewareHandler, Schema } from '../../types'; +type Params

= Record; +export type EventContext> = { + request: Request; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + props: any; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +declare type PagesFunction = Record> = (context: EventContext) => Response | Promise; +export declare const handle: (app: Hono) => PagesFunction; +export declare function handleMiddleware(middleware: MiddlewareHandler): PagesFunction; +/** + * + * @description `serveStatic()` is for advanced mode: + * https://developers.cloudflare.com/pages/platform/functions/advanced-mode/#set-up-a-function + * + */ +export declare const serveStatic: () => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/adapter/cloudflare-pages/index.d.ts b/node_modules/hono/dist/types/adapter/cloudflare-pages/index.d.ts new file mode 100644 index 000000000..4a7ff17b7 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/cloudflare-pages/index.d.ts @@ -0,0 +1,6 @@ +/** + * @module + * Cloudflare Pages Adapter for Hono. + */ +export { handle, handleMiddleware, serveStatic } from './handler'; +export type { EventContext } from './handler'; diff --git a/node_modules/hono/dist/types/adapter/cloudflare-workers/conninfo.d.ts b/node_modules/hono/dist/types/adapter/cloudflare-workers/conninfo.d.ts new file mode 100644 index 000000000..da71f88f1 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/cloudflare-workers/conninfo.d.ts @@ -0,0 +1,2 @@ +import type { GetConnInfo } from '../../helper/conninfo'; +export declare const getConnInfo: GetConnInfo; diff --git a/node_modules/hono/dist/types/adapter/cloudflare-workers/index.d.ts b/node_modules/hono/dist/types/adapter/cloudflare-workers/index.d.ts new file mode 100644 index 000000000..c2ca01b4e --- /dev/null +++ b/node_modules/hono/dist/types/adapter/cloudflare-workers/index.d.ts @@ -0,0 +1,7 @@ +/** + * @module + * Cloudflare Workers Adapter for Hono. + */ +export { serveStatic } from './serve-static-module'; +export { upgradeWebSocket } from './websocket'; +export { getConnInfo } from './conninfo'; diff --git a/node_modules/hono/dist/types/adapter/cloudflare-workers/serve-static-module.d.ts b/node_modules/hono/dist/types/adapter/cloudflare-workers/serve-static-module.d.ts new file mode 100644 index 000000000..59fbd2a5a --- /dev/null +++ b/node_modules/hono/dist/types/adapter/cloudflare-workers/serve-static-module.d.ts @@ -0,0 +1,4 @@ +import type { Env, MiddlewareHandler } from '../../types'; +import type { ServeStaticOptions } from './serve-static'; +declare const module: (options: Omit, "namespace">) => MiddlewareHandler; +export { module as serveStatic }; diff --git a/node_modules/hono/dist/types/adapter/cloudflare-workers/serve-static.d.ts b/node_modules/hono/dist/types/adapter/cloudflare-workers/serve-static.d.ts new file mode 100644 index 000000000..a8d166daa --- /dev/null +++ b/node_modules/hono/dist/types/adapter/cloudflare-workers/serve-static.d.ts @@ -0,0 +1,16 @@ +import type { ServeStaticOptions as BaseServeStaticOptions } from '../../middleware/serve-static'; +import type { Env, MiddlewareHandler } from '../../types'; +export type ServeStaticOptions = BaseServeStaticOptions & { + namespace?: unknown; + manifest: object | string; +}; +/** + * @deprecated + * `serveStatic` in the Cloudflare Workers adapter is deprecated. + * You can serve static files directly using Cloudflare Static Assets. + * @see https://developers.cloudflare.com/workers/static-assets/ + * Cloudflare Static Assets is currently in open beta. If this doesn't work for you, + * please consider using Cloudflare Pages. You can start to create the Cloudflare Pages + * application with the `npm create hono@latest` command. + */ +export declare const serveStatic: (options: ServeStaticOptions) => MiddlewareHandler; diff --git a/node_modules/hono/dist/types/adapter/cloudflare-workers/utils.d.ts b/node_modules/hono/dist/types/adapter/cloudflare-workers/utils.d.ts new file mode 100644 index 000000000..d406c1852 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/cloudflare-workers/utils.d.ts @@ -0,0 +1,5 @@ +export type KVAssetOptions = { + manifest?: object | string; + namespace?: unknown; +}; +export declare const getContentFromKVAsset: (path: string, options?: KVAssetOptions) => Promise; diff --git a/node_modules/hono/dist/types/adapter/cloudflare-workers/websocket.d.ts b/node_modules/hono/dist/types/adapter/cloudflare-workers/websocket.d.ts new file mode 100644 index 000000000..be356742f --- /dev/null +++ b/node_modules/hono/dist/types/adapter/cloudflare-workers/websocket.d.ts @@ -0,0 +1,2 @@ +import type { UpgradeWebSocket, WSEvents } from '../../helper/websocket'; +export declare const upgradeWebSocket: UpgradeWebSocket, 'onOpen'>>; diff --git a/node_modules/hono/dist/types/adapter/deno/conninfo.d.ts b/node_modules/hono/dist/types/adapter/deno/conninfo.d.ts new file mode 100644 index 000000000..d274def50 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/deno/conninfo.d.ts @@ -0,0 +1,7 @@ +import type { GetConnInfo } from '../../helper/conninfo'; +/** + * Get conninfo with Deno + * @param c Context + * @returns ConnInfo + */ +export declare const getConnInfo: GetConnInfo; diff --git a/node_modules/hono/dist/types/adapter/deno/index.d.ts b/node_modules/hono/dist/types/adapter/deno/index.d.ts new file mode 100644 index 000000000..d360f6dc6 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/deno/index.d.ts @@ -0,0 +1,8 @@ +/** + * @module + * Deno Adapter for Hono. + */ +export { serveStatic } from './serve-static'; +export { toSSG, denoFileSystemModule } from './ssg'; +export { upgradeWebSocket } from './websocket'; +export { getConnInfo } from './conninfo'; diff --git a/node_modules/hono/dist/types/adapter/deno/serve-static.d.ts b/node_modules/hono/dist/types/adapter/deno/serve-static.d.ts new file mode 100644 index 000000000..e79742d57 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/deno/serve-static.d.ts @@ -0,0 +1,3 @@ +import type { ServeStaticOptions } from '../../middleware/serve-static'; +import type { Env, MiddlewareHandler } from '../../types'; +export declare const serveStatic: (options: ServeStaticOptions) => MiddlewareHandler; diff --git a/node_modules/hono/dist/types/adapter/deno/ssg.d.ts b/node_modules/hono/dist/types/adapter/deno/ssg.d.ts new file mode 100644 index 000000000..293e1f94b --- /dev/null +++ b/node_modules/hono/dist/types/adapter/deno/ssg.d.ts @@ -0,0 +1,13 @@ +import type { FileSystemModule, ToSSGAdaptorInterface } from '../../helper/ssg/index'; +/** + * @experimental + * `denoFileSystemModule` is an experimental feature. + * The API might be changed. + */ +export declare const denoFileSystemModule: FileSystemModule; +/** + * @experimental + * `toSSG` is an experimental feature. + * The API might be changed. + */ +export declare const toSSG: ToSSGAdaptorInterface; diff --git a/node_modules/hono/dist/types/adapter/deno/websocket.d.ts b/node_modules/hono/dist/types/adapter/deno/websocket.d.ts new file mode 100644 index 000000000..f391ccbbf --- /dev/null +++ b/node_modules/hono/dist/types/adapter/deno/websocket.d.ts @@ -0,0 +1,2 @@ +import type { UpgradeWebSocket } from '../../helper/websocket'; +export declare const upgradeWebSocket: UpgradeWebSocket; diff --git a/node_modules/hono/dist/types/adapter/lambda-edge/conninfo.d.ts b/node_modules/hono/dist/types/adapter/lambda-edge/conninfo.d.ts new file mode 100644 index 000000000..da71f88f1 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/lambda-edge/conninfo.d.ts @@ -0,0 +1,2 @@ +import type { GetConnInfo } from '../../helper/conninfo'; +export declare const getConnInfo: GetConnInfo; diff --git a/node_modules/hono/dist/types/adapter/lambda-edge/handler.d.ts b/node_modules/hono/dist/types/adapter/lambda-edge/handler.d.ts new file mode 100644 index 000000000..67800f815 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/lambda-edge/handler.d.ts @@ -0,0 +1,87 @@ +import type { Hono } from '../../hono'; +interface CloudFrontHeader { + key: string; + value: string; +} +interface CloudFrontHeaders { + [name: string]: CloudFrontHeader[]; +} +interface CloudFrontCustomOrigin { + customHeaders: CloudFrontHeaders; + domainName: string; + keepaliveTimeout: number; + path: string; + port: number; + protocol: string; + readTimeout: number; + sslProtocols: string[]; +} +interface CloudFrontS3Origin { + authMethod: 'origin-access-identity' | 'none'; + customHeaders: CloudFrontHeaders; + domainName: string; + path: string; + region: string; +} +type CloudFrontOrigin = { + s3: CloudFrontS3Origin; + custom?: never; +} | { + custom: CloudFrontCustomOrigin; + s3?: never; +}; +export interface CloudFrontRequest { + clientIp: string; + headers: CloudFrontHeaders; + method: string; + querystring: string; + uri: string; + body?: { + inputTruncated: boolean; + action: string; + encoding: string; + data: string; + }; + origin?: CloudFrontOrigin; +} +export interface CloudFrontResponse { + headers: CloudFrontHeaders; + status: string; + statusDescription?: string; +} +export interface CloudFrontConfig { + distributionDomainName: string; + distributionId: string; + eventType: string; + requestId: string; +} +interface CloudFrontEvent { + cf: { + config: CloudFrontConfig; + request: CloudFrontRequest; + response?: CloudFrontResponse; + }; +} +export interface CloudFrontEdgeEvent { + Records: CloudFrontEvent[]; +} +type CloudFrontContext = {}; +export interface Callback { + (err: Error | null, result?: CloudFrontRequest | CloudFrontResult): void; +} +interface CloudFrontResult { + status: string; + statusDescription?: string; + headers?: { + [header: string]: { + key: string; + value: string; + }[]; + }; + body?: string; + bodyEncoding?: 'text' | 'base64'; +} +export declare const handle: (app: Hono) => ((event: CloudFrontEdgeEvent, context?: CloudFrontContext, callback?: Callback) => Promise); +export declare const createBody: (method: string, requestBody: CloudFrontRequest["body"]) => string | Uint8Array | undefined; +export declare const isContentTypeBinary: (contentType: string) => boolean; +export {}; diff --git a/node_modules/hono/dist/types/adapter/lambda-edge/index.d.ts b/node_modules/hono/dist/types/adapter/lambda-edge/index.d.ts new file mode 100644 index 000000000..8889c4197 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/lambda-edge/index.d.ts @@ -0,0 +1,7 @@ +/** + * @module + * Lambda@Edge Adapter for Hono. + */ +export { handle } from './handler'; +export { getConnInfo } from './conninfo'; +export type { Callback, CloudFrontConfig, CloudFrontRequest, CloudFrontResponse, CloudFrontEdgeEvent, } from './handler'; diff --git a/node_modules/hono/dist/types/adapter/netlify/handler.d.ts b/node_modules/hono/dist/types/adapter/netlify/handler.d.ts new file mode 100644 index 000000000..6f49216d7 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/netlify/handler.d.ts @@ -0,0 +1,2 @@ +import type { Hono } from '../../hono'; +export declare const handle: (app: Hono) => ((req: Request, context: any) => Response | Promise); diff --git a/node_modules/hono/dist/types/adapter/netlify/index.d.ts b/node_modules/hono/dist/types/adapter/netlify/index.d.ts new file mode 100644 index 000000000..cd2b35c6e --- /dev/null +++ b/node_modules/hono/dist/types/adapter/netlify/index.d.ts @@ -0,0 +1,5 @@ +/** + * @module + * Netlify Adapter for Hono. + */ +export * from './mod'; diff --git a/node_modules/hono/dist/types/adapter/netlify/mod.d.ts b/node_modules/hono/dist/types/adapter/netlify/mod.d.ts new file mode 100644 index 000000000..a7583a3f2 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/netlify/mod.d.ts @@ -0,0 +1 @@ +export { handle } from './handler'; diff --git a/node_modules/hono/dist/types/adapter/service-worker/handler.d.ts b/node_modules/hono/dist/types/adapter/service-worker/handler.d.ts new file mode 100644 index 000000000..b2c1c4f43 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/service-worker/handler.d.ts @@ -0,0 +1,16 @@ +/** + * Handler for Service Worker + * @module + */ +import type { Hono } from '../../hono'; +import type { Env, Schema } from '../../types'; +import type { FetchEvent } from './types'; +type Handler = (evt: FetchEvent) => void; +export type HandleOptions = { + fetch?: typeof fetch; +}; +/** + * Adapter for Service Worker + */ +export declare const handle: (app: Hono, opts?: HandleOptions) => Handler; +export {}; diff --git a/node_modules/hono/dist/types/adapter/service-worker/index.d.ts b/node_modules/hono/dist/types/adapter/service-worker/index.d.ts new file mode 100644 index 000000000..a89b3c786 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/service-worker/index.d.ts @@ -0,0 +1,28 @@ +/** + * Service Worker Adapter for Hono. + * @module + */ +import type { Hono } from '../../hono'; +import type { Env, Schema } from '../../types'; +import { handle } from './handler'; +import type { HandleOptions } from './handler'; +/** + * Registers a Hono app to handle fetch events in a service worker. + * This sets up `addEventListener('fetch', handle(app, options))` for the provided app. + * + * @param app - The Hono application instance + * @param options - Options for handling requests (fetch defaults to undefined) + * @example + * ```ts + * import { Hono } from 'hono' + * import { fire } from 'hono/service-worker' + * + * const app = new Hono() + * + * app.get('/', (c) => c.text('Hi')) + * + * fire(app) + * ``` + */ +declare const fire: (app: Hono, options?: HandleOptions) => void; +export { handle, fire }; diff --git a/node_modules/hono/dist/types/adapter/service-worker/types.d.ts b/node_modules/hono/dist/types/adapter/service-worker/types.d.ts new file mode 100644 index 000000000..66298f496 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/service-worker/types.d.ts @@ -0,0 +1,12 @@ +interface ExtendableEvent extends Event { + waitUntil(f: Promise): void; +} +export interface FetchEvent extends ExtendableEvent { + readonly clientId: string; + readonly handled: Promise; + readonly preloadResponse: Promise; + readonly request: Request; + readonly resultingClientId: string; + respondWith(r: Response | PromiseLike): void; +} +export {}; diff --git a/node_modules/hono/dist/types/adapter/vercel/conninfo.d.ts b/node_modules/hono/dist/types/adapter/vercel/conninfo.d.ts new file mode 100644 index 000000000..da71f88f1 --- /dev/null +++ b/node_modules/hono/dist/types/adapter/vercel/conninfo.d.ts @@ -0,0 +1,2 @@ +import type { GetConnInfo } from '../../helper/conninfo'; +export declare const getConnInfo: GetConnInfo; diff --git a/node_modules/hono/dist/types/adapter/vercel/handler.d.ts b/node_modules/hono/dist/types/adapter/vercel/handler.d.ts new file mode 100644 index 000000000..73bb38dca --- /dev/null +++ b/node_modules/hono/dist/types/adapter/vercel/handler.d.ts @@ -0,0 +1,2 @@ +import type { Hono } from '../../hono'; +export declare const handle: (app: Hono) => (req: Request) => Response | Promise; diff --git a/node_modules/hono/dist/types/adapter/vercel/index.d.ts b/node_modules/hono/dist/types/adapter/vercel/index.d.ts new file mode 100644 index 000000000..8645b763c --- /dev/null +++ b/node_modules/hono/dist/types/adapter/vercel/index.d.ts @@ -0,0 +1,6 @@ +/** + * @module + * Vercel Adapter for Hono. + */ +export { handle } from './handler'; +export { getConnInfo } from './conninfo'; diff --git a/node_modules/hono/dist/types/client/client.d.ts b/node_modules/hono/dist/types/client/client.d.ts new file mode 100644 index 000000000..9a161b65c --- /dev/null +++ b/node_modules/hono/dist/types/client/client.d.ts @@ -0,0 +1,4 @@ +import type { Hono } from '../hono'; +import type { UnionToIntersection } from '../utils/types'; +import type { Client, ClientRequestOptions } from './types'; +export declare const hc: , Prefix extends string = string>(baseUrl: Prefix, options?: ClientRequestOptions) => UnionToIntersection>; diff --git a/node_modules/hono/dist/types/client/fetch-result-please.d.ts b/node_modules/hono/dist/types/client/fetch-result-please.d.ts new file mode 100644 index 000000000..f9558e07e --- /dev/null +++ b/node_modules/hono/dist/types/client/fetch-result-please.d.ts @@ -0,0 +1,35 @@ +/** + * @description This file is a modified version of `fetch-result-please` (`ofetch`), minimalized and adapted to Hono's custom needs. + * + * @link https://www.npmjs.com/package/fetch-result-please + */ +/** + * Smartly parses and return the consumable result from a fetch `Response`. + * + * Throwing a structured error if the response is not `ok`. ({@link DetailedError}) + */ +export declare function fetchRP(fetchRes: Response | Promise): Promise; +export declare class DetailedError extends Error { + /** + * Additional `message` that will be logged AND returned to client + */ + detail?: any; + /** + * Additional `code` that will be logged AND returned to client + */ + code?: any; + /** + * Additional value that will be logged AND NOT returned to client + */ + log?: any; + /** + * Optionally set the status code to return, in a web server context + */ + statusCode?: any; + constructor(message: string, options?: { + detail?: any; + code?: any; + statusCode?: number; + log?: any; + }); +} diff --git a/node_modules/hono/dist/types/client/index.d.ts b/node_modules/hono/dist/types/client/index.d.ts new file mode 100644 index 000000000..7530b6cc7 --- /dev/null +++ b/node_modules/hono/dist/types/client/index.d.ts @@ -0,0 +1,7 @@ +/** + * @module + * The HTTP Client for Hono. + */ +export { hc } from './client'; +export { parseResponse, DetailedError } from './utils'; +export type { InferResponseType, InferRequestType, Fetch, ClientRequestOptions, ClientRequest, ClientResponse, } from './types'; diff --git a/node_modules/hono/dist/types/client/types.d.ts b/node_modules/hono/dist/types/client/types.d.ts new file mode 100644 index 000000000..7b31394d5 --- /dev/null +++ b/node_modules/hono/dist/types/client/types.d.ts @@ -0,0 +1,168 @@ +import type { Hono } from '../hono'; +import type { HonoBase } from '../hono-base'; +import type { METHODS, METHOD_NAME_ALL_LOWERCASE } from '../router'; +import type { Endpoint, ResponseFormat, Schema } from '../types'; +import type { StatusCode, SuccessStatusCode } from '../utils/http-status'; +import type { HasRequiredKeys } from '../utils/types'; +/** + * Type representing the '$all' method name + */ +type MethodNameAll = `$${typeof METHOD_NAME_ALL_LOWERCASE}`; +/** + * Type representing all standard HTTP methods prefixed with '$' + * e.g., '$get' | '$post' | '$put' | '$delete' | '$options' | '$patch' + */ +type StandardMethods = `$${(typeof METHODS)[number]}`; +/** + * Expands '$all' into all standard HTTP methods. + * If the schema contains '$all', it creates a type where all standard HTTP methods + * point to the same endpoint definition as '$all', while removing '$all' itself. + */ +type ExpandAllMethod = MethodNameAll extends keyof S ? { + [M in StandardMethods]: S[MethodNameAll]; +} & Omit : S; +type HonoRequest = (typeof Hono.prototype)['request']; +export type BuildSearchParamsFn = (query: Record) => URLSearchParams; +export type ClientRequestOptions = { + fetch?: typeof fetch | HonoRequest; + webSocket?: (...args: ConstructorParameters) => WebSocket; + /** + * Standard `RequestInit`, caution that this take highest priority + * and could be used to overwrite things that Hono sets for you, like `body | method | headers`. + * + * If you want to add some headers, use in `headers` instead of `init` + */ + init?: RequestInit; + /** + * Custom function to serialize query parameters into URLSearchParams. + * By default, arrays are serialized as multiple parameters with the same key (e.g., `key=a&key=b`). + * You can provide a custom function to change this behavior, for example to use bracket notation (e.g., `key[]=a&key[]=b`). + * + * @example + * ```ts + * const client = hc('http://localhost', { + * buildSearchParams: (query) => { + * return new URLSearchParams(qs.stringify(query)) + * } + * }) + * ``` + */ + buildSearchParams?: BuildSearchParamsFn; +} & (keyof T extends never ? { + headers?: Record | (() => Record | Promise>); +} : { + headers: T | (() => T | Promise); +}); +export type ClientRequest = { + [M in keyof ExpandAllMethod]: ExpandAllMethod[M] extends Endpoint & { + input: infer R; + } ? R extends object ? HasRequiredKeys extends true ? (args: R, options?: ClientRequestOptions) => Promise[M]>> : (args?: R, options?: ClientRequestOptions) => Promise[M]>> : never : never; +} & { + $url: (arg?: Arg) => HonoURL; +} & (S['$get'] extends { + outputFormat: 'ws'; +} ? S['$get'] extends { + input: infer I; +} ? { + $ws: (args?: I) => WebSocket; +} : {} : {}); +type ClientResponseOfEndpoint = T extends { + output: infer O; + outputFormat: infer F; + status: infer S; +} ? ClientResponse : never; +export interface ClientResponse extends globalThis.Response { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + ok: U extends SuccessStatusCode ? true : U extends Exclude ? false : boolean; + status: U; + statusText: string; + headers: Headers; + url: string; + redirect(url: string, status: number): Response; + clone(): Response; + json(): F extends 'text' ? Promise : F extends 'json' ? Promise : Promise; + text(): F extends 'text' ? (T extends string ? Promise : Promise) : Promise; + blob(): Promise; + formData(): Promise; + arrayBuffer(): Promise; +} +type BuildSearch = Arg extends { + [K in Key]: infer Query; +} ? IsEmptyObject extends true ? '' : `?${string}` : ''; +type BuildPathname

= Arg extends { + param: infer Param; +} ? `${ApplyParam, Param>}` : `/${TrimStartSlash

}`; +type BuildTypedURL = TypedURL<`${Protocol}:`, Host, Port, BuildPathname, BuildSearch>; +type HonoURL = IsLiteral extends true ? TrimEndSlash extends `${infer Protocol}://${infer Rest}` ? Rest extends `${infer Hostname}/${infer P}` ? ParseHostName extends [infer Host extends string, infer Port extends string] ? BuildTypedURL : never : ParseHostName extends [infer Host extends string, infer Port extends string] ? BuildTypedURL : never : URL : URL; +type ParseHostName = T extends `${infer Host}:${infer Port}` ? [Host, Port] : [T, '']; +type TrimStartSlash = T extends `/${infer R}` ? TrimStartSlash : T; +type TrimEndSlash = T extends `${infer R}/` ? TrimEndSlash : T; +type IsLiteral = [T] extends [never] ? false : string extends T ? false : true; +type ApplyParam = Path extends `${infer Head}/${infer Rest}` ? Head extends `:${infer Param}` ? P extends Record ? IsLiteral extends true ? ApplyParam : ApplyParam : ApplyParam : ApplyParam : Path extends `:${infer Param}` ? P extends Record ? IsLiteral extends true ? `${Result}/${Value & string}` : `${Result}/${Path}` : `${Result}/${Path}` : `${Result}/${Path}`; +type IsEmptyObject = keyof T extends never ? true : false; +export interface TypedURL extends URL { + protocol: Protocol; + hostname: Hostname; + port: Port; + host: Port extends '' ? Hostname : `${Hostname}:${Port}`; + origin: `${Protocol}//${Hostname}${Port extends '' ? '' : `:${Port}`}`; + pathname: Pathname; + search: Search; + href: `${Protocol}//${Hostname}${Port extends '' ? '' : `:${Port}`}${Pathname}${Search}`; +} +export interface Response extends ClientResponse { +} +export type Fetch = (args?: InferRequestType, opt?: ClientRequestOptions) => Promise>>; +type InferEndpointType = T extends (args: infer R, options: any | undefined) => Promise ? U extends ClientResponse ? { + input: NonNullable; + output: O; + outputFormat: F; + status: S; +} extends Endpoint ? { + input: NonNullable; + output: O; + outputFormat: F; + status: S; +} : never : never : never; +export type InferResponseType = InferResponseTypeFromEndpoint, U>; +type InferResponseTypeFromEndpoint = T extends { + output: infer O; + status: infer S; +} ? S extends U ? O : never : never; +export type InferRequestType = T extends (args: infer R, options: any | undefined) => Promise> ? NonNullable : never; +export type InferRequestOptionsType = T extends (args: any, options: infer R) => Promise> ? NonNullable : never; +/** + * Filter a ClientResponse type so it only includes responses of specific status codes. + */ +export type FilterClientResponseByStatusCode, U extends number = StatusCode> = T extends ClientResponse ? RC extends U ? ClientResponse : never : never; +type PathToChain = Path extends `/${infer P}` ? PathToChain : Path extends `${infer P}/${infer R}` ? { + [K in P]: PathToChain; +} : { + [K in Path extends '' ? 'index' : Path]: ClientRequest ? E[Original] : never>; +}; +export type Client = T extends HonoBase ? S extends Record ? K extends string ? PathToChain : never : never : never; +export type Callback = (opts: CallbackOptions) => unknown; +interface CallbackOptions { + path: string[]; + args: any[]; +} +export type ObjectType = { + [key: string]: T; +}; +export {}; diff --git a/node_modules/hono/dist/types/client/utils.d.ts b/node_modules/hono/dist/types/client/utils.d.ts new file mode 100644 index 000000000..496020bca --- /dev/null +++ b/node_modules/hono/dist/types/client/utils.d.ts @@ -0,0 +1,18 @@ +import type { ClientErrorStatusCode, ContentfulStatusCode, ServerErrorStatusCode } from '../utils/http-status'; +import { DetailedError } from './fetch-result-please'; +import type { ClientResponse, FilterClientResponseByStatusCode } from './types'; +export { DetailedError }; +export declare const mergePath: (base: string, path: string) => string; +export declare const replaceUrlParam: (urlString: string, params: Record) => string; +export declare const buildSearchParams: (query: Record) => URLSearchParams; +export declare const replaceUrlProtocol: (urlString: string, protocol: "ws" | "http") => string; +export declare const removeIndexString: (urlString: string) => string; +export declare function deepMerge(target: T, source: Record): T; +/** + * Shortcut to get a consumable response from `hc`'s fetch calls (Response), with types inference. + * + * Smartly parse the response data, throwing a structured error if the response is not `ok`. ({@link DetailedError}) + * + * @example const result = await parseResponse(client.posts.$get()) + */ +export declare function parseResponse>(fetchRes: T | Promise): Promise> extends never ? undefined : FilterClientResponseByStatusCode> extends ClientResponse ? RF extends 'json' ? RT : RT extends string ? RT : string : undefined>; diff --git a/node_modules/hono/dist/types/compose.d.ts b/node_modules/hono/dist/types/compose.d.ts new file mode 100644 index 000000000..937905e76 --- /dev/null +++ b/node_modules/hono/dist/types/compose.d.ts @@ -0,0 +1,14 @@ +import type { Context } from './context'; +import type { Env, ErrorHandler, Next, NotFoundHandler } from './types'; +/** + * Compose middleware functions into a single function based on `koa-compose` package. + * + * @template E - The environment type. + * + * @param {[[Function, unknown], unknown][] | [[Function]][]} middleware - An array of middleware functions and their corresponding parameters. + * @param {ErrorHandler} [onError] - An optional error handler function. + * @param {NotFoundHandler} [onNotFound] - An optional not-found handler function. + * + * @returns {(context: Context, next?: Next) => Promise} - A composed middleware function. + */ +export declare const compose: (middleware: [[Function, unknown], unknown][] | [[Function]][], onError?: ErrorHandler, onNotFound?: NotFoundHandler) => ((context: Context, next?: Next) => Promise); diff --git a/node_modules/hono/dist/types/context.d.ts b/node_modules/hono/dist/types/context.d.ts new file mode 100644 index 000000000..6ad1223c3 --- /dev/null +++ b/node_modules/hono/dist/types/context.d.ts @@ -0,0 +1,451 @@ +import { HonoRequest } from './request'; +import type { Result } from './router'; +import type { Env, FetchEventLike, H, Input, NotFoundHandler, RouterRoute, TypedResponse } from './types'; +import type { ResponseHeader } from './utils/headers'; +import type { ContentfulStatusCode, RedirectStatusCode, StatusCode } from './utils/http-status'; +import type { BaseMime } from './utils/mime'; +import type { InvalidJSONValue, IsAny, JSONParsed, JSONValue } from './utils/types'; +type HeaderRecord = Record<'Content-Type', BaseMime> | Record | Record; +/** + * Data type can be a string, ArrayBuffer, Uint8Array (buffer), or ReadableStream. + */ +export type Data = string | ArrayBuffer | ReadableStream | Uint8Array; +/** + * Interface for the execution context in a web worker or similar environment. + */ +export interface ExecutionContext { + /** + * Extends the lifetime of the event callback until the promise is settled. + * + * @param promise - A promise to wait for. + */ + waitUntil(promise: Promise): void; + /** + * Allows the event to be passed through to subsequent event listeners. + */ + passThroughOnException(): void; + /** + * For compatibility with Wrangler 4.x. + */ + props: any; +} +/** + * Interface for context variable mapping. + */ +export interface ContextVariableMap { +} +/** + * Interface for context renderer. + */ +export interface ContextRenderer { +} +/** + * Interface representing a renderer for content. + * + * @interface DefaultRenderer + * @param {string | Promise} content - The content to be rendered, which can be either a string or a Promise resolving to a string. + * @returns {Response | Promise} - The response after rendering the content, which can be either a Response or a Promise resolving to a Response. + */ +interface DefaultRenderer { + (content: string | Promise): Response | Promise; +} +/** + * Renderer type which can either be a ContextRenderer or DefaultRenderer. + */ +export type Renderer = ContextRenderer extends Function ? ContextRenderer : DefaultRenderer; +/** + * Extracts the props for the renderer. + */ +export type PropsForRenderer = [...Required>] extends [unknown, infer Props] ? Props : unknown; +export type Layout> = (props: T) => any; +/** + * Interface for getting context variables. + * + * @template E - Environment type. + */ +interface Get { + (key: Key): E['Variables'][Key]; + (key: Key): ContextVariableMap[Key]; +} +/** + * Interface for setting context variables. + * + * @template E - Environment type. + */ +interface Set { + (key: Key, value: E['Variables'][Key]): void; + (key: Key, value: ContextVariableMap[Key]): void; +} +/** + * Interface for creating a new response. + */ +interface NewResponse { + (data: Data | null, status?: StatusCode, headers?: HeaderRecord): Response; + (data: Data | null, init?: ResponseOrInit): Response; +} +/** + * Interface for responding with a body. + */ +interface BodyRespond { + (data: T, status?: U, headers?: HeaderRecord): Response & TypedResponse; + (data: T, init?: ResponseOrInit): Response & TypedResponse; + (data: T, status?: U, headers?: HeaderRecord): Response & TypedResponse; + (data: T, init?: ResponseOrInit): Response & TypedResponse; +} +/** + * Interface for responding with text. + * + * @interface TextRespond + * @template T - The type of the text content. + * @template U - The type of the status code. + * + * @param {T} text - The text content to be included in the response. + * @param {U} [status] - An optional status code for the response. + * @param {HeaderRecord} [headers] - An optional record of headers to include in the response. + * + * @returns {Response & TypedResponse} - The response after rendering the text content, typed with the provided text and status code types. + */ +interface TextRespond { + (text: T, status?: U, headers?: HeaderRecord): Response & TypedResponse; + (text: T, init?: ResponseOrInit): Response & TypedResponse; +} +/** + * Interface for responding with JSON. + * + * @interface JSONRespond + * @template T - The type of the JSON value or simplified unknown type. + * @template U - The type of the status code. + * + * @param {T} object - The JSON object to be included in the response. + * @param {U} [status] - An optional status code for the response. + * @param {HeaderRecord} [headers] - An optional record of headers to include in the response. + * + * @returns {JSONRespondReturn} - The response after rendering the JSON object, typed with the provided object and status code types. + */ +interface JSONRespond { + (object: T, status?: U, headers?: HeaderRecord): JSONRespondReturn; + (object: T, init?: ResponseOrInit): JSONRespondReturn; +} +/** + * @template T - The type of the JSON value or simplified unknown type. + * @template U - The type of the status code. + * + * @returns {Response & TypedResponse, U, 'json'>} - The response after rendering the JSON object, typed with the provided object and status code types. + */ +type JSONRespondReturn = Response & TypedResponse, U, 'json'>; +/** + * Interface representing a function that responds with HTML content. + * + * @param html - The HTML content to respond with, which can be a string or a Promise that resolves to a string. + * @param status - (Optional) The HTTP status code for the response. + * @param headers - (Optional) A record of headers to include in the response. + * @param init - (Optional) The response initialization object. + * + * @returns A Response object or a Promise that resolves to a Response object. + */ +interface HTMLRespond { + >(html: T, status?: ContentfulStatusCode, headers?: HeaderRecord): T extends string ? Response : Promise; + >(html: T, init?: ResponseOrInit): T extends string ? Response : Promise; +} +/** + * Options for configuring the context. + * + * @template E - Environment type. + */ +type ContextOptions = { + /** + * Bindings for the environment. + */ + env: E['Bindings']; + /** + * Execution context for the request. + */ + executionCtx?: FetchEventLike | ExecutionContext | undefined; + /** + * Handler for not found responses. + */ + notFoundHandler?: NotFoundHandler; + matchResult?: Result<[H, RouterRoute]>; + path?: string; +}; +interface SetHeadersOptions { + append?: boolean; +} +interface SetHeaders { + (name: 'Content-Type', value?: BaseMime, options?: SetHeadersOptions): void; + (name: ResponseHeader, value?: string, options?: SetHeadersOptions): void; + (name: string, value?: string, options?: SetHeadersOptions): void; +} +type ResponseHeadersInit = [string, string][] | Record<'Content-Type', BaseMime> | Record | Record | Headers; +interface ResponseInit { + headers?: ResponseHeadersInit; + status?: T; + statusText?: string; +} +type ResponseOrInit = ResponseInit | Response; +export declare const TEXT_PLAIN = "text/plain; charset=UTF-8"; +export declare class Context { + + /** + * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers. + * + * @see {@link https://hono.dev/docs/api/context#env} + * + * @example + * ```ts + * // Environment object for Cloudflare Workers + * app.get('*', async c => { + * const counter = c.env.COUNTER + * }) + * ``` + */ + env: E['Bindings']; + finalized: boolean; + /** + * `.error` can get the error object from the middleware if the Handler throws an error. + * + * @see {@link https://hono.dev/docs/api/context#error} + * + * @example + * ```ts + * app.use('*', async (c, next) => { + * await next() + * if (c.error) { + * // do something... + * } + * }) + * ``` + */ + error: Error | undefined; + /** + * Creates an instance of the Context class. + * + * @param req - The Request object. + * @param options - Optional configuration options for the context. + */ + constructor(req: Request, options?: ContextOptions); + /** + * `.req` is the instance of {@link HonoRequest}. + */ + get req(): HonoRequest; + /** + * @see {@link https://hono.dev/docs/api/context#event} + * The FetchEvent associated with the current request. + * + * @throws Will throw an error if the context does not have a FetchEvent. + */ + get event(): FetchEventLike; + /** + * @see {@link https://hono.dev/docs/api/context#executionctx} + * The ExecutionContext associated with the current request. + * + * @throws Will throw an error if the context does not have an ExecutionContext. + */ + get executionCtx(): ExecutionContext; + /** + * @see {@link https://hono.dev/docs/api/context#res} + * The Response object for the current request. + */ + get res(): Response; + /** + * Sets the Response object for the current request. + * + * @param _res - The Response object to set. + */ + set res(_res: Response | undefined); + /** + * `.render()` can create a response within a layout. + * + * @see {@link https://hono.dev/docs/api/context#render-setrenderer} + * + * @example + * ```ts + * app.get('/', (c) => { + * return c.render('Hello!') + * }) + * ``` + */ + render: Renderer; + /** + * Sets the layout for the response. + * + * @param layout - The layout to set. + * @returns The layout function. + */ + setLayout: (layout: Layout) => Layout; + /** + * Gets the current layout for the response. + * + * @returns The current layout function. + */ + getLayout: () => Layout | undefined; + /** + * `.setRenderer()` can set the layout in the custom middleware. + * + * @see {@link https://hono.dev/docs/api/context#render-setrenderer} + * + * @example + * ```tsx + * app.use('*', async (c, next) => { + * c.setRenderer((content) => { + * return c.html( + * + * + *

{content}

+ * + * + * ) + * }) + * await next() + * }) + * ``` + */ + setRenderer: (renderer: Renderer) => void; + /** + * `.header()` can set headers. + * + * @see {@link https://hono.dev/docs/api/context#header} + * + * @example + * ```ts + * app.get('/welcome', (c) => { + * // Set headers + * c.header('X-Message', 'Hello!') + * c.header('Content-Type', 'text/plain') + * + * return c.body('Thank you for coming') + * }) + * ``` + */ + header: SetHeaders; + status: (status: StatusCode) => void; + /** + * `.set()` can set the value specified by the key. + * + * @see {@link https://hono.dev/docs/api/context#set-get} + * + * @example + * ```ts + * app.use('*', async (c, next) => { + * c.set('message', 'Hono is hot!!') + * await next() + * }) + * ``` + */ + set: Set extends true ? { + Variables: ContextVariableMap & Record; + } : E>; + /** + * `.get()` can use the value specified by the key. + * + * @see {@link https://hono.dev/docs/api/context#set-get} + * + * @example + * ```ts + * app.get('/', (c) => { + * const message = c.get('message') + * return c.text(`The message is "${message}"`) + * }) + * ``` + */ + get: Get extends true ? { + Variables: ContextVariableMap & Record; + } : E>; + /** + * `.var` can access the value of a variable. + * + * @see {@link https://hono.dev/docs/api/context#var} + * + * @example + * ```ts + * const result = c.var.client.oneMethod() + * ``` + */ + get var(): Readonly extends true ? Record : E['Variables'])>; + newResponse: NewResponse; + /** + * `.body()` can return the HTTP response. + * You can set headers with `.header()` and set HTTP status code with `.status`. + * This can also be set in `.text()`, `.json()` and so on. + * + * @see {@link https://hono.dev/docs/api/context#body} + * + * @example + * ```ts + * app.get('/welcome', (c) => { + * // Set headers + * c.header('X-Message', 'Hello!') + * c.header('Content-Type', 'text/plain') + * // Set HTTP status code + * c.status(201) + * + * // Return the response body + * return c.body('Thank you for coming') + * }) + * ``` + */ + body: BodyRespond; + /** + * `.text()` can render text as `Content-Type:text/plain`. + * + * @see {@link https://hono.dev/docs/api/context#text} + * + * @example + * ```ts + * app.get('/say', (c) => { + * return c.text('Hello!') + * }) + * ``` + */ + text: TextRespond; + /** + * `.json()` can render JSON as `Content-Type:application/json`. + * + * @see {@link https://hono.dev/docs/api/context#json} + * + * @example + * ```ts + * app.get('/api', (c) => { + * return c.json({ message: 'Hello!' }) + * }) + * ``` + */ + json: JSONRespond; + html: HTMLRespond; + /** + * `.redirect()` can Redirect, default status code is 302. + * + * @see {@link https://hono.dev/docs/api/context#redirect} + * + * @example + * ```ts + * app.get('/redirect', (c) => { + * return c.redirect('/') + * }) + * app.get('/redirect-permanently', (c) => { + * return c.redirect('/', 301) + * }) + * ``` + */ + redirect: (location: string | URL, status?: T) => Response & TypedResponse; + /** + * `.notFound()` can return the Not Found Response. + * + * @see {@link https://hono.dev/docs/api/context#notfound} + * + * @example + * ```ts + * app.get('/notfound', (c) => { + * return c.notFound() + * }) + * ``` + */ + notFound: () => ReturnType; +} +export {}; diff --git a/node_modules/hono/dist/types/helper/accepts/accepts.d.ts b/node_modules/hono/dist/types/helper/accepts/accepts.d.ts new file mode 100644 index 000000000..55cbee14a --- /dev/null +++ b/node_modules/hono/dist/types/helper/accepts/accepts.d.ts @@ -0,0 +1,30 @@ +import type { Context } from '../../context'; +import type { AcceptHeader } from '../../utils/headers'; +export interface Accept { + type: string; + params: Record; + q: number; +} +export interface acceptsConfig { + header: AcceptHeader; + supports: string[]; + default: string; +} +export interface acceptsOptions extends acceptsConfig { + match?: (accepts: Accept[], config: acceptsConfig) => string; +} +export declare const defaultMatch: (accepts: Accept[], config: acceptsConfig) => string; +/** + * Match the accept header with the given options. + * @example + * ```ts + * app.get('/users', (c) => { + * const lang = accepts(c, { + * header: 'Accept-Language', + * supports: ['en', 'zh'], + * default: 'en', + * }) + * }) + * ``` + */ +export declare const accepts: (c: Context, options: acceptsOptions) => string; diff --git a/node_modules/hono/dist/types/helper/accepts/index.d.ts b/node_modules/hono/dist/types/helper/accepts/index.d.ts new file mode 100644 index 000000000..946d23e39 --- /dev/null +++ b/node_modules/hono/dist/types/helper/accepts/index.d.ts @@ -0,0 +1,5 @@ +/** + * @module + * Accepts Helper for Hono. + */ +export { accepts } from './accepts'; diff --git a/node_modules/hono/dist/types/helper/adapter/index.d.ts b/node_modules/hono/dist/types/helper/adapter/index.d.ts new file mode 100644 index 000000000..838391ac4 --- /dev/null +++ b/node_modules/hono/dist/types/helper/adapter/index.d.ts @@ -0,0 +1,12 @@ +/** + * @module + * Adapter Helper for Hono. + */ +import type { Context } from '../../context'; +export type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'other'; +export declare const env: , C extends Context = Context<{ + Bindings: T; +}>>(c: T extends Record ? Context : C, runtime?: Runtime) => T & C["env"]; +export declare const knownUserAgents: Partial>; +export declare const getRuntimeKey: () => Runtime; +export declare const checkUserAgentEquals: (platform: string) => boolean; diff --git a/node_modules/hono/dist/types/helper/conninfo/index.d.ts b/node_modules/hono/dist/types/helper/conninfo/index.d.ts new file mode 100644 index 000000000..876fb1df6 --- /dev/null +++ b/node_modules/hono/dist/types/helper/conninfo/index.d.ts @@ -0,0 +1,5 @@ +/** + * @module + * ConnInfo Helper for Hono. + */ +export type { AddressType, NetAddrInfo, ConnInfo, GetConnInfo } from './types'; diff --git a/node_modules/hono/dist/types/helper/conninfo/types.d.ts b/node_modules/hono/dist/types/helper/conninfo/types.d.ts new file mode 100644 index 000000000..466af764b --- /dev/null +++ b/node_modules/hono/dist/types/helper/conninfo/types.d.ts @@ -0,0 +1,36 @@ +import type { Context } from '../../context'; +export type AddressType = 'IPv6' | 'IPv4' | undefined; +export type NetAddrInfo = { + /** + * Transport protocol type + */ + transport?: 'tcp' | 'udp'; + /** + * Transport port number + */ + port?: number; + address?: string; + addressType?: AddressType; +} & ({ + /** + * Host name such as IP Addr + */ + address: string; + /** + * Host name type + */ + addressType: AddressType; +} | {}); +/** + * HTTP Connection information + */ +export interface ConnInfo { + /** + * Remote information + */ + remote: NetAddrInfo; +} +/** + * Helper type + */ +export type GetConnInfo = (c: Context) => ConnInfo; diff --git a/node_modules/hono/dist/types/helper/cookie/index.d.ts b/node_modules/hono/dist/types/helper/cookie/index.d.ts new file mode 100644 index 000000000..cc421b9a7 --- /dev/null +++ b/node_modules/hono/dist/types/helper/cookie/index.d.ts @@ -0,0 +1,24 @@ +/** + * @module + * Cookie Helper for Hono. + */ +import type { Context } from '../../context'; +import type { Cookie, CookieOptions, CookiePrefixOptions, SignedCookie } from '../../utils/cookie'; +interface GetCookie { + (c: Context, key: string): string | undefined; + (c: Context): Cookie; + (c: Context, key: string, prefixOptions?: CookiePrefixOptions): string | undefined; +} +interface GetSignedCookie { + (c: Context, secret: string | BufferSource, key: string): Promise; + (c: Context, secret: string | BufferSource): Promise; + (c: Context, secret: string | BufferSource, key: string, prefixOptions?: CookiePrefixOptions): Promise; +} +export declare const getCookie: GetCookie; +export declare const getSignedCookie: GetSignedCookie; +export declare const generateCookie: (name: string, value: string, opt?: CookieOptions) => string; +export declare const setCookie: (c: Context, name: string, value: string, opt?: CookieOptions) => void; +export declare const generateSignedCookie: (name: string, value: string, secret: string | BufferSource, opt?: CookieOptions) => Promise; +export declare const setSignedCookie: (c: Context, name: string, value: string, secret: string | BufferSource, opt?: CookieOptions) => Promise; +export declare const deleteCookie: (c: Context, name: string, opt?: CookieOptions) => string | undefined; +export {}; diff --git a/node_modules/hono/dist/types/helper/css/common.d.ts b/node_modules/hono/dist/types/helper/css/common.d.ts new file mode 100644 index 000000000..a71ff809e --- /dev/null +++ b/node_modules/hono/dist/types/helper/css/common.d.ts @@ -0,0 +1,42 @@ +export declare const PSEUDO_GLOBAL_SELECTOR = ":-hono-global"; +export declare const isPseudoGlobalSelectorRe: RegExp; +export declare const DEFAULT_STYLE_ID = "hono-css"; +export declare const SELECTOR: unique symbol; +export declare const CLASS_NAME: unique symbol; +export declare const STYLE_STRING: unique symbol; +export declare const SELECTORS: unique symbol; +export declare const EXTERNAL_CLASS_NAMES: unique symbol; +declare const CSS_ESCAPED: unique symbol; +export interface CssClassName { + [SELECTOR]: string; + [CLASS_NAME]: string; + [STYLE_STRING]: string; + [SELECTORS]: CssClassName[]; + [EXTERNAL_CLASS_NAMES]: string[]; +} +export declare const IS_CSS_ESCAPED: unique symbol; +interface CssEscapedString { + [CSS_ESCAPED]: string; +} +/** + * @experimental + * `rawCssString` is an experimental feature. + * The API might be changed. + */ +export declare const rawCssString: (value: string) => CssEscapedString; +export declare const minify: (css: string) => string; +type CssVariableBasicType = CssClassName | CssEscapedString | string | number | boolean | null | undefined; +type CssVariableAsyncType = Promise; +type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]; +export type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType; +export declare const buildStyleString: (strings: TemplateStringsArray, values: CssVariableType[]) => [string, string, CssClassName[], string[]]; +export declare const cssCommon: (strings: TemplateStringsArray, values: CssVariableType[]) => CssClassName; +export declare const cxCommon: (args: (string | boolean | null | undefined | CssClassName)[]) => (string | boolean | null | undefined | CssClassName)[]; +export declare const keyframesCommon: (strings: TemplateStringsArray, ...values: CssVariableType[]) => CssClassName; +type ViewTransitionType = { + (strings: TemplateStringsArray, values: CssVariableType[]): CssClassName; + (content: CssClassName): CssClassName; + (): CssClassName; +}; +export declare const viewTransitionCommon: ViewTransitionType; +export {}; diff --git a/node_modules/hono/dist/types/helper/css/index.d.ts b/node_modules/hono/dist/types/helper/css/index.d.ts new file mode 100644 index 000000000..9a74aaecd --- /dev/null +++ b/node_modules/hono/dist/types/helper/css/index.d.ts @@ -0,0 +1,73 @@ +/** + * @module + * css Helper for Hono. + */ +import type { HtmlEscapedString } from '../../utils/html'; +import type { CssClassName as CssClassNameCommon, CssVariableType } from './common'; +export { rawCssString } from './common'; +type CssClassName = HtmlEscapedString & CssClassNameCommon; +interface CssType { + (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise; +} +interface CxType { + (...args: (CssClassName | Promise | string | boolean | null | undefined)[]): Promise; +} +interface KeyframesType { + (strings: TemplateStringsArray, ...values: CssVariableType[]): CssClassNameCommon; +} +interface ViewTransitionType { + (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise; + (content: Promise): Promise; + (): Promise; +} +interface StyleType { + (args?: { + children?: Promise; + nonce?: string; + }): HtmlEscapedString; +} +/** + * @experimental + * `createCssContext` is an experimental feature. + * The API might be changed. + */ +export declare const createCssContext: ({ id }: { + id: Readonly; +}) => DefaultContextType; +interface DefaultContextType { + css: CssType; + cx: CxType; + keyframes: KeyframesType; + viewTransition: ViewTransitionType; + Style: StyleType; +} +/** + * @experimental + * `css` is an experimental feature. + * The API might be changed. + */ +export declare const css: CssType; +/** + * @experimental + * `cx` is an experimental feature. + * The API might be changed. + */ +export declare const cx: CxType; +/** + * @experimental + * `keyframes` is an experimental feature. + * The API might be changed. + */ +export declare const keyframes: KeyframesType; +/** + * @experimental + * `viewTransition` is an experimental feature. + * The API might be changed. + */ +export declare const viewTransition: ViewTransitionType; +/** + * @experimental + * `Style` is an experimental feature. + * The API might be changed. + */ +export declare const Style: StyleType; diff --git a/node_modules/hono/dist/types/helper/dev/index.d.ts b/node_modules/hono/dist/types/helper/dev/index.d.ts new file mode 100644 index 000000000..28eb4086d --- /dev/null +++ b/node_modules/hono/dist/types/helper/dev/index.d.ts @@ -0,0 +1,20 @@ +/** + * @module + * Dev Helper for Hono. + */ +import type { Hono } from '../../hono'; +import type { Env } from '../../types'; +interface ShowRoutesOptions { + verbose?: boolean; + colorize?: boolean; +} +interface RouteData { + path: string; + method: string; + name: string; + isMiddleware: boolean; +} +export declare const inspectRoutes: (hono: Hono) => RouteData[]; +export declare const showRoutes: (hono: Hono, opts?: ShowRoutesOptions) => void; +export declare const getRouterName: (app: Hono) => string; +export {}; diff --git a/node_modules/hono/dist/types/helper/factory/index.d.ts b/node_modules/hono/dist/types/helper/factory/index.d.ts new file mode 100644 index 000000000..f14b48aa6 --- /dev/null +++ b/node_modules/hono/dist/types/helper/factory/index.d.ts @@ -0,0 +1,82 @@ +/** + * @module + * Factory Helper for Hono. + */ +import { Hono } from '../../hono'; +import type { HonoOptions } from '../../hono-base'; +import type { Env, H, HandlerResponse, Input, IntersectNonAnyTypes, MiddlewareHandler } from '../../types'; +type InitApp = (app: Hono) => void; +export interface CreateHandlersInterface { + = any, E2 extends Env = E>(handler1: H): [H]; + = any, R2 extends HandlerResponse = any, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>>(handler1: H, handler2: H): [H, H]; + = any, R2 extends HandlerResponse = any, R3 extends HandlerResponse = any, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>>(handler1: H, handler2: H, handler3: H): [H, H, H]; + = any, R2 extends HandlerResponse = any, R3 extends HandlerResponse = any, R4 extends HandlerResponse = any, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>>(handler1: H, handler2: H, handler3: H, handler4: H): [H, H, H, H]; + = any, R2 extends HandlerResponse = any, R3 extends HandlerResponse = any, R4 extends HandlerResponse = any, R5 extends HandlerResponse = any, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>>(handler1: H, handler2: H, handler3: H, handler4: H, handler5: H): [H, H, H, H, H]; + = any, R2 extends HandlerResponse = any, R3 extends HandlerResponse = any, R4 extends HandlerResponse = any, R5 extends HandlerResponse = any, R6 extends HandlerResponse = any, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>>(handler1: H, handler2: H, handler3: H, handler4: H, handler5: H, handler6: H): [ + H, + H, + H, + H, + H, + H + ]; + = any, R2 extends HandlerResponse = any, R3 extends HandlerResponse = any, R4 extends HandlerResponse = any, R5 extends HandlerResponse = any, R6 extends HandlerResponse = any, R7 extends HandlerResponse = any, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>>(handler1: H, handler2: H, handler3: H, handler4: H, handler5: H, handler6: H, handler7: H): [ + H, + H, + H, + H, + H, + H, + H + ]; + = any, R2 extends HandlerResponse = any, R3 extends HandlerResponse = any, R4 extends HandlerResponse = any, R5 extends HandlerResponse = any, R6 extends HandlerResponse = any, R7 extends HandlerResponse = any, R8 extends HandlerResponse = any, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>>(handler1: H, handler2: H, handler3: H, handler4: H, handler5: H, handler6: H, handler7: H, handler8: H): [ + H, + H, + H, + H, + H, + H, + H, + H + ]; + = any, R2 extends HandlerResponse = any, R3 extends HandlerResponse = any, R4 extends HandlerResponse = any, R5 extends HandlerResponse = any, R6 extends HandlerResponse = any, R7 extends HandlerResponse = any, R8 extends HandlerResponse = any, R9 extends HandlerResponse = any, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>>(handler1: H, handler2: H, handler3: H, handler4: H, handler5: H, handler6: H, handler7: H, handler8: H, handler9: H): [ + H, + H, + H, + H, + H, + H, + H, + H, + H + ]; + = any, R2 extends HandlerResponse = any, R3 extends HandlerResponse = any, R4 extends HandlerResponse = any, R5 extends HandlerResponse = any, R6 extends HandlerResponse = any, R7 extends HandlerResponse = any, R8 extends HandlerResponse = any, R9 extends HandlerResponse = any, R10 extends HandlerResponse = any, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>, E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>>(handler1: H, handler2: H, handler3: H, handler4: H, handler5: H, handler6: H, handler7: H, handler8: H, handler9: H, handler10: H): [ + H, + H, + H, + H, + H, + H, + H, + H, + H, + H + ]; +} +export declare class Factory { + + private initApp?; + constructor(init?: { + initApp?: InitApp; + defaultAppOptions?: HonoOptions; + }); + createApp: (options?: HonoOptions) => Hono; + createMiddleware: | void = void>(middleware: MiddlewareHandler) => MiddlewareHandler; + createHandlers: CreateHandlersInterface; +} +export declare const createFactory: (init?: { + initApp?: InitApp; + defaultAppOptions?: HonoOptions; +}) => Factory; +export declare const createMiddleware: | void = void>(middleware: MiddlewareHandler) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/helper/html/index.d.ts b/node_modules/hono/dist/types/helper/html/index.d.ts new file mode 100644 index 000000000..ce17eac4a --- /dev/null +++ b/node_modules/hono/dist/types/helper/html/index.d.ts @@ -0,0 +1,8 @@ +/** + * @module + * html Helper for Hono. + */ +import { raw } from '../../utils/html'; +import type { HtmlEscapedString } from '../../utils/html'; +export { raw }; +export declare const html: (strings: TemplateStringsArray, ...values: unknown[]) => HtmlEscapedString | Promise; diff --git a/node_modules/hono/dist/types/helper/proxy/index.d.ts b/node_modules/hono/dist/types/helper/proxy/index.d.ts new file mode 100644 index 000000000..4a5b334ed --- /dev/null +++ b/node_modules/hono/dist/types/helper/proxy/index.d.ts @@ -0,0 +1,72 @@ +/** + * @module + * Proxy Helper for Hono. + */ +import type { RequestHeader } from '../../utils/headers'; +interface ProxyRequestInit extends Omit { + raw?: Request; + headers?: HeadersInit | [string, string][] | Record | Record; + customFetch?: (request: Request) => Promise; + /** + * Enable strict RFC 9110 compliance for Connection header processing. + * + * - `false` (default): Ignores Connection header to prevent potential + * Hop-by-Hop Header Injection attacks. Recommended for untrusted clients. + * - `true`: Processes Connection header per RFC 9110 and removes listed headers. + * Only use in trusted environments. + * + * @default false + * @see https://datatracker.ietf.org/doc/html/rfc9110#section-7.6.1 + */ + strictConnectionProcessing?: boolean; +} +interface ProxyFetch { + (input: string | URL | Request, init?: ProxyRequestInit): Promise; +} +/** + * Fetch API wrapper for proxy. + * The parameters and return value are the same as for `fetch` (except for the proxy-specific options). + * + * The “Accept-Encoding” header is replaced with an encoding that the current runtime can handle. + * Unnecessary response headers are deleted and a Response object is returned that can be returned + * as is as a response from the handler. + * + * @example + * ```ts + * app.get('/proxy/:path', (c) => { + * return proxy(`http://${originServer}/${c.req.param('path')}`, { + * headers: { + * ...c.req.header(), // optional, specify only when forwarding all the request data (including credentials) is necessary. + * 'X-Forwarded-For': '127.0.0.1', + * 'X-Forwarded-Host': c.req.header('host'), + * Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization') + * }, + * }).then((res) => { + * res.headers.delete('Set-Cookie') + * return res + * }) + * }) + * + * app.all('/proxy/:path', (c) => { + * return proxy(`http://${originServer}/${c.req.param('path')}`, { + * ...c.req, // optional, specify only when forwarding all the request data (including credentials) is necessary. + * headers: { + * ...c.req.header(), + * 'X-Forwarded-For': '127.0.0.1', + * 'X-Forwarded-Host': c.req.header('host'), + * Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization') + * }, + * }) + * }) + * + * // Strict RFC compliance mode (use only in trusted environments) + * app.get('/internal-proxy/:path', (c) => { + * return proxy(`http://${internalServer}/${c.req.param('path')}`, { + * ...c.req, + * strictConnectionProcessing: true, + * }) + * }) + * ``` + */ +export declare const proxy: ProxyFetch; +export {}; diff --git a/node_modules/hono/dist/types/helper/route/index.d.ts b/node_modules/hono/dist/types/helper/route/index.d.ts new file mode 100644 index 000000000..f5af1e639 --- /dev/null +++ b/node_modules/hono/dist/types/helper/route/index.d.ts @@ -0,0 +1,75 @@ +import type { Context } from '../../context'; +import type { RouterRoute } from '../../types'; +/** + * Get matched routes in the handler + * + * @param {Context} c - The context object + * @returns An array of matched routes + * + * @example + * ```ts + * import { matchedRoutes } from 'hono/route' + * + * app.use('*', async function logger(c, next) { + * await next() + * matchedRoutes(c).forEach(({ handler, method, path }, i) => { + * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]') + * console.log( + * method, + * ' ', + * path, + * ' '.repeat(Math.max(10 - path.length, 0)), + * name, + * i === c.req.routeIndex ? '<- respond from here' : '' + * ) + * }) + * }) + * ``` + */ +export declare const matchedRoutes: (c: Context) => RouterRoute[]; +/** + * Get the route path registered within the handler + * + * @param {Context} c - The context object + * @param {number} index - The index of the root from which to retrieve the path, similar to Array.prototype.at(), where a negative number is the index counted from the end of the matching root. Defaults to the current root index. + * @returns The route path registered within the handler + * + * @example + * ```ts + * import { routePath } from 'hono/route' + * + * app.use('*', (c, next) => { + * console.log(routePath(c)) // '*' + * console.log(routePath(c, -1)) // '/posts/:id' + * return next() + * }) + * + * app.get('/posts/:id', (c) => { + * return c.text(routePath(c)) // '/posts/:id' + * }) + * ``` + */ +export declare const routePath: (c: Context, index?: number) => string; +/** + * Get the basePath of the as-is route specified by routing. + * + * @param {Context} c - The context object + * @param {number} index - The index of the root from which to retrieve the path, similar to Array.prototype.at(), where a negative number is the index counted from the end of the matching root. Defaults to the current root index. + * @returns The basePath of the as-is route specified by routing. + * + * @example + * ```ts + * import { baseRoutePath } from 'hono/route' + * + * const app = new Hono() + * + * const subApp = new Hono() + * subApp.get('/posts/:id', (c) => { + * return c.text(baseRoutePath(c)) // '/:sub' + * }) + * + * app.route('/:sub', subApp) + * ``` + */ +export declare const baseRoutePath: (c: Context, index?: number) => string; +export declare const basePath: (c: Context, index?: number) => string; diff --git a/node_modules/hono/dist/types/helper/ssg/index.d.ts b/node_modules/hono/dist/types/helper/ssg/index.d.ts new file mode 100644 index 000000000..4e1241782 --- /dev/null +++ b/node_modules/hono/dist/types/helper/ssg/index.d.ts @@ -0,0 +1,6 @@ +/** + * @module + * SSG Helper for Hono. + */ +export * from './ssg'; +export { X_HONO_DISABLE_SSG_HEADER_KEY, ssgParams, isSSGContext, disableSSG, onlySSG, } from './middleware'; diff --git a/node_modules/hono/dist/types/helper/ssg/middleware.d.ts b/node_modules/hono/dist/types/helper/ssg/middleware.d.ts new file mode 100644 index 000000000..791ee402e --- /dev/null +++ b/node_modules/hono/dist/types/helper/ssg/middleware.d.ts @@ -0,0 +1,44 @@ +import type { Context } from '../../context'; +import type { Env, MiddlewareHandler } from '../../types'; +export declare const SSG_CONTEXT = "HONO_SSG_CONTEXT"; +export declare const X_HONO_DISABLE_SSG_HEADER_KEY = "x-hono-disable-ssg"; +/** + * @deprecated + * Use `X_HONO_DISABLE_SSG_HEADER_KEY` instead. + * This constant will be removed in the next minor version. + */ +export declare const SSG_DISABLED_RESPONSE: Response; +interface SSGParam { + [key: string]: string; +} +export type SSGParams = SSGParam[]; +interface SSGParamsMiddleware { + (generateParams: (c: Context) => SSGParams | Promise): MiddlewareHandler; + (params: SSGParams): MiddlewareHandler; +} +export type AddedSSGDataRequest = Request & { + ssgParams?: SSGParams; +}; +/** + * Define SSG Route + */ +export declare const ssgParams: SSGParamsMiddleware; +/** + * @experimental + * `isSSGContext` is an experimental feature. + * The API might be changed. + */ +export declare const isSSGContext: (c: Context) => boolean; +/** + * @experimental + * `disableSSG` is an experimental feature. + * The API might be changed. + */ +export declare const disableSSG: () => MiddlewareHandler; +/** + * @experimental + * `onlySSG` is an experimental feature. + * The API might be changed. + */ +export declare const onlySSG: () => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/helper/ssg/ssg.d.ts b/node_modules/hono/dist/types/helper/ssg/ssg.d.ts new file mode 100644 index 000000000..026cde266 --- /dev/null +++ b/node_modules/hono/dist/types/helper/ssg/ssg.d.ts @@ -0,0 +1,99 @@ +import type { Hono } from '../../hono'; +import type { Env, Schema } from '../../types'; +export declare const DEFAULT_OUTPUT_DIR = "./static"; +/** + * @experimental + * `FileSystemModule` is an experimental feature. + * The API might be changed. + */ +export interface FileSystemModule { + writeFile(path: string, data: string | Uint8Array): Promise; + mkdir(path: string, options: { + recursive: boolean; + }): Promise; +} +/** + * @experimental + * `ToSSGResult` is an experimental feature. + * The API might be changed. + */ +export interface ToSSGResult { + success: boolean; + files: string[]; + error?: Error; +} +export declare const defaultExtensionMap: Record; +export type BeforeRequestHook = (req: Request) => Request | false | Promise; +export type AfterResponseHook = (res: Response) => Response | false | Promise; +export type AfterGenerateHook = (result: ToSSGResult, fsModule: FileSystemModule, options?: ToSSGOptions) => void | Promise; +export declare const combineBeforeRequestHooks: (hooks: BeforeRequestHook | BeforeRequestHook[]) => BeforeRequestHook; +export declare const combineAfterResponseHooks: (hooks: AfterResponseHook | AfterResponseHook[]) => AfterResponseHook; +export declare const combineAfterGenerateHooks: (hooks: AfterGenerateHook | AfterGenerateHook[], fsModule: FileSystemModule, options?: ToSSGOptions) => AfterGenerateHook; +export interface SSGPlugin { + beforeRequestHook?: BeforeRequestHook | BeforeRequestHook[]; + afterResponseHook?: AfterResponseHook | AfterResponseHook[]; + afterGenerateHook?: AfterGenerateHook | AfterGenerateHook[]; +} +export interface ToSSGOptions { + dir?: string; + /** + * @deprecated Use plugins[].beforeRequestHook instead. + */ + beforeRequestHook?: BeforeRequestHook | BeforeRequestHook[]; + /** + * @deprecated Use plugins[].afterResponseHook instead. + */ + afterResponseHook?: AfterResponseHook | AfterResponseHook[]; + /** + * @deprecated Use plugins[].afterGenerateHook instead. + */ + afterGenerateHook?: AfterGenerateHook | AfterGenerateHook[]; + concurrency?: number; + extensionMap?: Record; + plugins?: SSGPlugin[]; +} +/** + * @experimental + * `fetchRoutesContent` is an experimental feature. + * The API might be changed. + */ +export declare const fetchRoutesContent: (app: Hono, beforeRequestHook?: BeforeRequestHook, afterResponseHook?: AfterResponseHook, concurrency?: number) => Generator> | undefined>>; +export declare const saveContentToFile: (data: Promise<{ + routePath: string; + content: string | ArrayBuffer; + mimeType: string; +} | undefined>, fsModule: FileSystemModule, outDir: string, extensionMap?: Record) => Promise; +/** + * @experimental + * `ToSSGInterface` is an experimental feature. + * The API might be changed. + */ +export interface ToSSGInterface { + (app: Hono, fsModule: FileSystemModule, options?: ToSSGOptions): Promise; +} +/** + * @experimental + * `ToSSGAdaptorInterface` is an experimental feature. + * The API might be changed. + */ +export interface ToSSGAdaptorInterface { + (app: Hono, options?: ToSSGOptions): Promise; +} +/** + * The default plugin that defines the recommended behavior. + * + * @experimental + * `defaultPlugin` is an experimental feature. + * The API might be changed. + */ +export declare const defaultPlugin: SSGPlugin; +/** + * @experimental + * `toSSG` is an experimental feature. + * The API might be changed. + */ +export declare const toSSG: ToSSGInterface; diff --git a/node_modules/hono/dist/types/helper/ssg/utils.d.ts b/node_modules/hono/dist/types/helper/ssg/utils.d.ts new file mode 100644 index 000000000..9553bf4ec --- /dev/null +++ b/node_modules/hono/dist/types/helper/ssg/utils.d.ts @@ -0,0 +1,15 @@ +import type { Hono } from '../../hono'; +import type { Env } from '../../types'; +/** + * Get dirname + * @param path File Path + * @returns Parent dir path + */ +export declare const dirname: (path: string) => string; +export declare const joinPaths: (...paths: string[]) => string; +interface FilterStaticGenerateRouteData { + path: string; +} +export declare const filterStaticGenerateRoutes: (hono: Hono) => FilterStaticGenerateRouteData[]; +export declare const isDynamicRoute: (path: string) => boolean; +export {}; diff --git a/node_modules/hono/dist/types/helper/streaming/index.d.ts b/node_modules/hono/dist/types/helper/streaming/index.d.ts new file mode 100644 index 000000000..c89d67ef5 --- /dev/null +++ b/node_modules/hono/dist/types/helper/streaming/index.d.ts @@ -0,0 +1,8 @@ +/** + * @module + * Streaming Helper for Hono. + */ +export { stream } from './stream'; +export type { SSEMessage } from './sse'; +export { streamSSE, SSEStreamingApi } from './sse'; +export { streamText } from './text'; diff --git a/node_modules/hono/dist/types/helper/streaming/sse.d.ts b/node_modules/hono/dist/types/helper/streaming/sse.d.ts new file mode 100644 index 000000000..c4cf6595b --- /dev/null +++ b/node_modules/hono/dist/types/helper/streaming/sse.d.ts @@ -0,0 +1,13 @@ +import type { Context } from '../../context'; +import { StreamingApi } from '../../utils/stream'; +export interface SSEMessage { + data: string | Promise; + event?: string; + id?: string; + retry?: number; +} +export declare class SSEStreamingApi extends StreamingApi { + constructor(writable: WritableStream, readable: ReadableStream); + writeSSE(message: SSEMessage): Promise; +} +export declare const streamSSE: (c: Context, cb: (stream: SSEStreamingApi) => Promise, onError?: (e: Error, stream: SSEStreamingApi) => Promise) => Response; diff --git a/node_modules/hono/dist/types/helper/streaming/stream.d.ts b/node_modules/hono/dist/types/helper/streaming/stream.d.ts new file mode 100644 index 000000000..2c34ef8ec --- /dev/null +++ b/node_modules/hono/dist/types/helper/streaming/stream.d.ts @@ -0,0 +1,3 @@ +import type { Context } from '../../context'; +import { StreamingApi } from '../../utils/stream'; +export declare const stream: (c: Context, cb: (stream: StreamingApi) => Promise, onError?: (e: Error, stream: StreamingApi) => Promise) => Response; diff --git a/node_modules/hono/dist/types/helper/streaming/text.d.ts b/node_modules/hono/dist/types/helper/streaming/text.d.ts new file mode 100644 index 000000000..39934dcdb --- /dev/null +++ b/node_modules/hono/dist/types/helper/streaming/text.d.ts @@ -0,0 +1,3 @@ +import type { Context } from '../../context'; +import type { StreamingApi } from '../../utils/stream'; +export declare const streamText: (c: Context, cb: (stream: StreamingApi) => Promise, onError?: (e: Error, stream: StreamingApi) => Promise) => Response; diff --git a/node_modules/hono/dist/types/helper/streaming/utils.d.ts b/node_modules/hono/dist/types/helper/streaming/utils.d.ts new file mode 100644 index 000000000..8ae4c7689 --- /dev/null +++ b/node_modules/hono/dist/types/helper/streaming/utils.d.ts @@ -0,0 +1 @@ +export declare let isOldBunVersion: () => boolean; diff --git a/node_modules/hono/dist/types/helper/testing/index.d.ts b/node_modules/hono/dist/types/helper/testing/index.d.ts new file mode 100644 index 000000000..208d3102e --- /dev/null +++ b/node_modules/hono/dist/types/helper/testing/index.d.ts @@ -0,0 +1,12 @@ +/** + * @module + * Testing Helper for Hono. + */ +import type { Client, ClientRequestOptions } from '../../client/types'; +import type { ExecutionContext } from '../../context'; +import type { Hono } from '../../hono'; +import type { Schema } from '../../types'; +import type { UnionToIntersection } from '../../utils/types'; +type ExtractEnv = T extends Hono ? E : never; +export declare const testClient: >(app: T, Env?: ExtractEnv["Bindings"] | {}, executionCtx?: ExecutionContext, options?: Omit) => UnionToIntersection>; +export {}; diff --git a/node_modules/hono/dist/types/helper/websocket/index.d.ts b/node_modules/hono/dist/types/helper/websocket/index.d.ts new file mode 100644 index 000000000..0d7ebbb94 --- /dev/null +++ b/node_modules/hono/dist/types/helper/websocket/index.d.ts @@ -0,0 +1,69 @@ +/** + * @module + * WebSocket Helper for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler, TypedResponse } from '../../types'; +import type { StatusCode } from '../../utils/http-status'; +/** + * WebSocket Event Listeners type + */ +export interface WSEvents { + onOpen?: (evt: Event, ws: WSContext) => void; + onMessage?: (evt: MessageEvent, ws: WSContext) => void; + onClose?: (evt: CloseEvent, ws: WSContext) => void; + onError?: (evt: Event, ws: WSContext) => void; +} +/** + * Upgrade WebSocket Type + */ +export interface UpgradeWebSocket> { + (createEvents: (c: Context) => _WSEvents | Promise<_WSEvents>, options?: U): MiddlewareHandler; + (c: Context, events: _WSEvents, options?: U): Promise>; +} +/** + * ReadyState for WebSocket + */ +export type WSReadyState = 0 | 1 | 2 | 3; +/** + * An argument for WSContext class + */ +export interface WSContextInit { + send(data: string | ArrayBuffer | Uint8Array, options: SendOptions): void; + close(code?: number, reason?: string): void; + raw?: T; + readyState: WSReadyState; + url?: string | URL | null; + protocol?: string | null; +} +/** + * Options for sending message + */ +export interface SendOptions { + compress?: boolean; +} +/** + * A context for controlling WebSockets + */ +export declare class WSContext { + + constructor(init: WSContextInit); + send(source: string | ArrayBuffer | Uint8Array, options?: SendOptions): void; + raw?: T; + binaryType: BinaryType; + get readyState(): WSReadyState; + url: URL | null; + protocol: string | null; + close(code?: number, reason?: string): void; +} +export type WSMessageReceive = string | Blob | ArrayBufferLike; +export declare const createWSMessageEvent: (source: WSMessageReceive) => MessageEvent; +export interface WebSocketHelperDefineContext { +} +export type WebSocketHelperDefineHandler = (c: Context, events: WSEvents, options?: U) => Promise | Response | void; +/** + * Create a WebSocket adapter/helper + */ +export declare const defineWebSocketHelper: (handler: WebSocketHelperDefineHandler) => UpgradeWebSocket; diff --git a/node_modules/hono/dist/types/hono-base.d.ts b/node_modules/hono/dist/types/hono-base.d.ts new file mode 100644 index 000000000..1f01271b0 --- /dev/null +++ b/node_modules/hono/dist/types/hono-base.d.ts @@ -0,0 +1,220 @@ +/** + * @module + * This module is the base module for the Hono object. + */ +import { Context } from './context'; +import type { ExecutionContext } from './context'; +import type { Router } from './router'; +import type { Env, ErrorHandler, H, HandlerInterface, MergePath, MergeSchemaPath, MiddlewareHandlerInterface, NotFoundHandler, OnHandlerInterface, RouterRoute, Schema } from './types'; +type GetPath = (request: Request, options?: { + env?: E['Bindings']; +}) => string; +export type HonoOptions = { + /** + * `strict` option specifies whether to distinguish whether the last path is a directory or not. + * + * @see {@link https://hono.dev/docs/api/hono#strict-mode} + * + * @default true + */ + strict?: boolean; + /** + * `router` option specifies which router to use. + * + * @see {@link https://hono.dev/docs/api/hono#router-option} + * + * @example + * ```ts + * const app = new Hono({ router: new RegExpRouter() }) + * ``` + */ + router?: Router<[H, RouterRoute]>; + /** + * `getPath` can handle the host header value. + * + * @see {@link https://hono.dev/docs/api/routing#routing-with-host-header-value} + * + * @example + * ```ts + * const app = new Hono({ + * getPath: (req) => + * '/' + req.headers.get('host') + req.url.replace(/^https?:\/\/[^/]+(\/[^?]*)/, '$1'), + * }) + * + * app.get('/www1.example.com/hello', () => c.text('hello www1')) + * + * // A following request will match the route: + * // new Request('http://www1.example.com/hello', { + * // headers: { host: 'www1.example.com' }, + * // }) + * ``` + */ + getPath?: GetPath; +}; +type MountOptionHandler = (c: Context) => unknown; +type MountReplaceRequest = (originalRequest: Request) => Request; +type MountOptions = MountOptionHandler | { + optionHandler?: MountOptionHandler; + replaceRequest?: MountReplaceRequest | false; +}; +declare class Hono { + + get: HandlerInterface; + post: HandlerInterface; + put: HandlerInterface; + delete: HandlerInterface; + options: HandlerInterface; + patch: HandlerInterface; + all: HandlerInterface; + on: OnHandlerInterface; + use: MiddlewareHandlerInterface; + router: Router<[H, RouterRoute]>; + readonly getPath: GetPath; + private _basePath; + routes: RouterRoute[]; + constructor(options?: HonoOptions); + private errorHandler; + /** + * `.route()` allows grouping other Hono instance in routes. + * + * @see {@link https://hono.dev/docs/api/routing#grouping} + * + * @param {string} path - base Path + * @param {Hono} app - other Hono instance + * @returns {Hono} routed Hono instance + * + * @example + * ```ts + * const app = new Hono() + * const app2 = new Hono() + * + * app2.get("/user", (c) => c.text("user")) + * app.route("/api", app2) // GET /api/user + * ``` + */ + route(path: SubPath, app: Hono): Hono> | S, BasePath, CurrentPath>; + /** + * `.basePath()` allows base paths to be specified. + * + * @see {@link https://hono.dev/docs/api/routing#base-path} + * + * @param {string} path - base Path + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * const api = new Hono().basePath('/api') + * ``` + */ + basePath(path: SubPath): Hono, MergePath>; + /** + * `.onError()` handles an error and returns a customized Response. + * + * @see {@link https://hono.dev/docs/api/hono#error-handling} + * + * @param {ErrorHandler} handler - request Handler for error + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * app.onError((err, c) => { + * console.error(`${err}`) + * return c.text('Custom Error Message', 500) + * }) + * ``` + */ + onError: (handler: ErrorHandler) => Hono; + /** + * `.notFound()` allows you to customize a Not Found Response. + * + * @see {@link https://hono.dev/docs/api/hono#not-found} + * + * @param {NotFoundHandler} handler - request handler for not-found + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * app.notFound((c) => { + * return c.text('Custom 404 Message', 404) + * }) + * ``` + */ + notFound: (handler: NotFoundHandler) => Hono; + /** + * `.mount()` allows you to mount applications built with other frameworks into your Hono application. + * + * @see {@link https://hono.dev/docs/api/hono#mount} + * + * @param {string} path - base Path + * @param {Function} applicationHandler - other Request Handler + * @param {MountOptions} [options] - options of `.mount()` + * @returns {Hono} mounted Hono instance + * + * @example + * ```ts + * import { Router as IttyRouter } from 'itty-router' + * import { Hono } from 'hono' + * // Create itty-router application + * const ittyRouter = IttyRouter() + * // GET /itty-router/hello + * ittyRouter.get('/hello', () => new Response('Hello from itty-router')) + * + * const app = new Hono() + * app.mount('/itty-router', ittyRouter.handle) + * ``` + * + * @example + * ```ts + * const app = new Hono() + * // Send the request to another application without modification. + * app.mount('/app', anotherApp, { + * replaceRequest: (req) => req, + * }) + * ``` + */ + mount(path: string, applicationHandler: (request: Request, ...args: any) => Response | Promise, options?: MountOptions): Hono; + /** + * `.fetch()` will be entry point of your app. + * + * @see {@link https://hono.dev/docs/api/hono#fetch} + * + * @param {Request} request - request Object of request + * @param {Env} Env - env Object + * @param {ExecutionContext} - context of execution + * @returns {Response | Promise} response of request + * + */ + fetch: (request: Request, Env?: E['Bindings'] | {}, executionCtx?: ExecutionContext) => Response | Promise; + /** + * `.request()` is a useful method for testing. + * You can pass a URL or pathname to send a GET request. + * app will return a Response object. + * ```ts + * test('GET /hello is ok', async () => { + * const res = await app.request('/hello') + * expect(res.status).toBe(200) + * }) + * ``` + * @see https://hono.dev/docs/api/hono#request + */ + request: (input: RequestInfo | URL, requestInit?: RequestInit, Env?: E["Bindings"] | {}, executionCtx?: ExecutionContext) => Response | Promise; + /** + * `.fire()` automatically adds a global fetch event listener. + * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers. + * @deprecated + * Use `fire` from `hono/service-worker` instead. + * ```ts + * import { Hono } from 'hono' + * import { fire } from 'hono/service-worker' + * + * const app = new Hono() + * // ... + * fire(app) + * ``` + * @see https://hono.dev/docs/api/hono#fire + * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API + * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/ + */ + fire: () => void; +} +export { Hono as HonoBase }; diff --git a/node_modules/hono/dist/types/hono.d.ts b/node_modules/hono/dist/types/hono.d.ts new file mode 100644 index 000000000..caeb4dcf4 --- /dev/null +++ b/node_modules/hono/dist/types/hono.d.ts @@ -0,0 +1,19 @@ +import { HonoBase } from './hono-base'; +import type { HonoOptions } from './hono-base'; +import type { BlankEnv, BlankSchema, Env, Schema } from './types'; +/** + * The Hono class extends the functionality of the HonoBase class. + * It sets up routing and allows for custom options to be passed. + * + * @template E - The environment type. + * @template S - The schema type. + * @template BasePath - The base path type. + */ +export declare class Hono extends HonoBase { + /** + * Creates an instance of the Hono class. + * + * @param options - Optional configuration options for the Hono instance. + */ + constructor(options?: HonoOptions); +} diff --git a/node_modules/hono/dist/types/http-exception.d.ts b/node_modules/hono/dist/types/http-exception.d.ts new file mode 100644 index 000000000..8b90ccaba --- /dev/null +++ b/node_modules/hono/dist/types/http-exception.d.ts @@ -0,0 +1,59 @@ +/** + * @module + * This module provides the `HTTPException` class. + */ +import type { ContentfulStatusCode } from './utils/http-status'; +/** + * Options for creating an `HTTPException`. + * @property res - Optional response object to use. + * @property message - Optional custom error message. + * @property cause - Optional cause of the error. + */ +type HTTPExceptionOptions = { + res?: Response; + message?: string; + cause?: unknown; +}; +/** + * `HTTPException` must be used when a fatal error such as authentication failure occurs. + * + * @see {@link https://hono.dev/docs/api/exception} + * + * @param {StatusCode} status - status code of HTTPException + * @param {HTTPExceptionOptions} options - options of HTTPException + * @param {HTTPExceptionOptions["res"]} options.res - response of options of HTTPException + * @param {HTTPExceptionOptions["message"]} options.message - message of options of HTTPException + * @param {HTTPExceptionOptions["cause"]} options.cause - cause of options of HTTPException + * + * @example + * ```ts + * import { HTTPException } from 'hono/http-exception' + * + * // ... + * + * app.post('/auth', async (c, next) => { + * // authentication + * if (authorized === false) { + * throw new HTTPException(401, { message: 'Custom error message' }) + * } + * await next() + * }) + * ``` + */ +export declare class HTTPException extends Error { + readonly res?: Response; + readonly status: ContentfulStatusCode; + /** + * Creates an instance of `HTTPException`. + * @param status - HTTP status code for the exception. Defaults to 500. + * @param options - Additional options for the exception. + */ + constructor(status?: ContentfulStatusCode, options?: HTTPExceptionOptions); + /** + * Returns the response object associated with the exception. + * If a response object is not provided, a new response is created with the error message and status code. + * @returns The response object. + */ + getResponse(): Response; +} +export {}; diff --git a/node_modules/hono/dist/types/index.d.ts b/node_modules/hono/dist/types/index.d.ts new file mode 100644 index 000000000..2e861bf6d --- /dev/null +++ b/node_modules/hono/dist/types/index.d.ts @@ -0,0 +1,36 @@ +/** + * @module + * + * Hono - Web Framework built on Web Standards + * + * @example + * ```ts + * import { Hono } from 'hono' + * const app = new Hono() + * + * app.get('/', (c) => c.text('Hono!')) + * + * export default app + * ``` + */ +import { Hono } from './hono'; +/** + * Types for environment variables, error handlers, handlers, middleware handlers, and more. + */ +export type { Env, ErrorHandler, Handler, MiddlewareHandler, Next, NotFoundResponse, NotFoundHandler, ValidationTargets, Input, Schema, ToSchema, TypedResponse, } from './types'; +/** + * Types for context, context variable map, context renderer, and execution context. + */ +export type { Context, ContextVariableMap, ContextRenderer, ExecutionContext } from './context'; +/** + * Type for HonoRequest. + */ +export type { HonoRequest } from './request'; +/** + * Types for inferring request and response types and client request options. + */ +export type { InferRequestType, InferResponseType, ClientRequestOptions } from './client'; +/** + * Hono framework for building web applications. + */ +export { Hono }; diff --git a/node_modules/hono/dist/types/jsx/base.d.ts b/node_modules/hono/dist/types/jsx/base.d.ts new file mode 100644 index 000000000..488d5c4ae --- /dev/null +++ b/node_modules/hono/dist/types/jsx/base.d.ts @@ -0,0 +1,58 @@ +import type { HtmlEscaped, HtmlEscapedString, StringBufferWithCallbacks } from '../utils/html'; +import { DOM_MEMO } from './constants'; +import type { Context } from './context'; +import type { JSX as HonoJSX, IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements'; +export type Props = Record; +export type FC

= { + (props: P): HtmlEscapedString | Promise | null; + defaultProps?: Partial

| undefined; + displayName?: string | undefined; +}; +export type DOMAttributes = HonoJSX.HTMLAttributes; +export declare namespace JSX { + type Element = HtmlEscapedString | Promise; + interface ElementChildrenAttribute { + children: Child; + } + interface IntrinsicElements extends IntrinsicElementsDefined { + [tagName: string]: Props; + } + interface IntrinsicAttributes { + key?: string | number | bigint | null | undefined; + } +} +export declare const getNameSpaceContext: () => Context | undefined; +export declare const booleanAttributes: string[]; +type LocalContexts = [Context, unknown][]; +export type Child = string | Promise | number | JSXNode | null | undefined | boolean | Child[]; +export declare class JSXNode implements HtmlEscaped { + tag: string | Function; + props: Props; + key?: string; + children: Child[]; + isEscaped: true; + localContexts?: LocalContexts; + constructor(tag: string | Function, props: Props, children: Child[]); + get type(): string | Function; + get ref(): any; + toString(): string | Promise; + toStringToBuffer(buffer: StringBufferWithCallbacks): void; +} +export declare class JSXFragmentNode extends JSXNode { + toStringToBuffer(buffer: StringBufferWithCallbacks): void; +} +export declare const jsx: (tag: string | Function, props: Props | null, ...children: (string | number | HtmlEscapedString)[]) => JSXNode; +export declare const jsxFn: (tag: string | Function, props: Props, children: (string | number | HtmlEscapedString)[]) => JSXNode; +export declare const shallowEqual: (a: Props, b: Props) => boolean; +export type MemorableFC = FC & { + [DOM_MEMO]: (prevProps: Readonly, nextProps: Readonly) => boolean; +}; +export declare const memo: (component: FC, propsAreEqual?: (prevProps: Readonly, nextProps: Readonly) => boolean) => FC; +export declare const Fragment: ({ children, }: { + key?: string; + children?: Child | HtmlEscapedString; +}) => HtmlEscapedString; +export declare const isValidElement: (element: unknown) => element is JSXNode; +export declare const cloneElement: (element: T, props: Partial, ...children: Child[]) => T; +export declare const reactAPICompatVersion = "19.0.0-hono-jsx"; +export {}; diff --git a/node_modules/hono/dist/types/jsx/children.d.ts b/node_modules/hono/dist/types/jsx/children.d.ts new file mode 100644 index 000000000..7e13b2793 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/children.d.ts @@ -0,0 +1,9 @@ +import type { Child } from './base'; +export declare const toArray: (children: Child) => Child[]; +export declare const Children: { + map: (children: Child[], fn: (child: Child, index: number) => Child) => Child[]; + forEach: (children: Child[], fn: (child: Child, index: number) => void) => void; + count: (children: Child[]) => number; + only: (_children: Child[]) => Child; + toArray: (children: Child) => Child[]; +}; diff --git a/node_modules/hono/dist/types/jsx/components.d.ts b/node_modules/hono/dist/types/jsx/components.d.ts new file mode 100644 index 000000000..ede9201f7 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/components.d.ts @@ -0,0 +1,15 @@ +import type { HtmlEscapedString } from '../utils/html'; +import type { Child, FC, PropsWithChildren } from './'; +export declare const childrenToString: (children: Child[]) => Promise; +export type ErrorHandler = (error: Error) => void; +export type FallbackRender = (error: Error) => Child; +/** + * @experimental + * `ErrorBoundary` is an experimental feature. + * The API might be changed. + */ +export declare const ErrorBoundary: FC>; diff --git a/node_modules/hono/dist/types/jsx/constants.d.ts b/node_modules/hono/dist/types/jsx/constants.d.ts new file mode 100644 index 000000000..27b96060a --- /dev/null +++ b/node_modules/hono/dist/types/jsx/constants.d.ts @@ -0,0 +1,6 @@ +export declare const DOM_RENDERER: unique symbol; +export declare const DOM_ERROR_HANDLER: unique symbol; +export declare const DOM_STASH: unique symbol; +export declare const DOM_INTERNAL_TAG: unique symbol; +export declare const DOM_MEMO: unique symbol; +export declare const PERMALINK: unique symbol; diff --git a/node_modules/hono/dist/types/jsx/context.d.ts b/node_modules/hono/dist/types/jsx/context.d.ts new file mode 100644 index 000000000..64ac66c98 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/context.d.ts @@ -0,0 +1,12 @@ +import type { FC, PropsWithChildren } from './'; +export interface Context extends FC> { + values: T[]; + Provider: FC>; +} +export declare const globalContexts: Context[]; +export declare const createContext: (defaultValue: T) => Context; +export declare const useContext: (context: Context) => T; diff --git a/node_modules/hono/dist/types/jsx/dom/client.d.ts b/node_modules/hono/dist/types/jsx/dom/client.d.ts new file mode 100644 index 000000000..a30e3e416 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/dom/client.d.ts @@ -0,0 +1,31 @@ +/** + * @module + * This module provides APIs for `hono/jsx/dom/client`, which is compatible with `react-dom/client`. + */ +import type { Child } from '../base'; +export interface Root { + render(children: Child): void; + unmount(): void; +} +export type RootOptions = Record; +/** + * Create a root object for rendering + * @param element Render target + * @param options Options for createRoot (not supported yet) + * @returns Root object has `render` and `unmount` methods + */ +export declare const createRoot: (element: HTMLElement | DocumentFragment, options?: RootOptions) => Root; +/** + * Create a root object and hydrate app to the target element. + * In hono/jsx/dom, hydrate is equivalent to render. + * @param element Render target + * @param reactNode A JSXNode to render + * @param options Options for createRoot (not supported yet) + * @returns Root object has `render` and `unmount` methods + */ +export declare const hydrateRoot: (element: HTMLElement | DocumentFragment, reactNode: Child, options?: RootOptions) => Root; +declare const _default: { + createRoot: (element: HTMLElement | DocumentFragment, options?: RootOptions) => Root; + hydrateRoot: (element: HTMLElement | DocumentFragment, reactNode: Child, options?: RootOptions) => Root; +}; +export default _default; diff --git a/node_modules/hono/dist/types/jsx/dom/components.d.ts b/node_modules/hono/dist/types/jsx/dom/components.d.ts new file mode 100644 index 000000000..54beaef44 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/dom/components.d.ts @@ -0,0 +1,10 @@ +import type { Child, FC, PropsWithChildren } from '../'; +import type { ErrorHandler, FallbackRender } from '../components'; +export declare const ErrorBoundary: FC>; +export declare const Suspense: FC>; diff --git a/node_modules/hono/dist/types/jsx/dom/context.d.ts b/node_modules/hono/dist/types/jsx/dom/context.d.ts new file mode 100644 index 000000000..ba9b54b8a --- /dev/null +++ b/node_modules/hono/dist/types/jsx/dom/context.d.ts @@ -0,0 +1,3 @@ +import type { Context } from '../context'; +export declare const createContextProviderFunction: (values: T[]) => Function; +export declare const createContext: (defaultValue: T) => Context; diff --git a/node_modules/hono/dist/types/jsx/dom/css.d.ts b/node_modules/hono/dist/types/jsx/dom/css.d.ts new file mode 100644 index 000000000..cf6ea2208 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/dom/css.d.ts @@ -0,0 +1,77 @@ +/** + * @module + * This module provides APIs that enable `hono/jsx/dom` to support. + */ +import type { FC, PropsWithChildren } from '../'; +import type { CssClassName, CssVariableType } from '../../helper/css/common'; +export { rawCssString } from '../../helper/css/common'; +interface CreateCssJsxDomObjectsType { + (args: { + id: Readonly; + }): readonly [ + { + toString(this: CssClassName): string; + }, + FC> + ]; +} +export declare const createCssJsxDomObjects: CreateCssJsxDomObjectsType; +interface CssType { + (strings: TemplateStringsArray, ...values: CssVariableType[]): string; +} +interface CxType { + (...args: (string | boolean | null | undefined)[]): string; +} +interface KeyframesType { + (strings: TemplateStringsArray, ...values: CssVariableType[]): CssClassName; +} +interface ViewTransitionType { + (strings: TemplateStringsArray, ...values: CssVariableType[]): string; + (content: string): string; + (): string; +} +interface DefaultContextType { + css: CssType; + cx: CxType; + keyframes: KeyframesType; + viewTransition: ViewTransitionType; + Style: FC>; +} +/** + * @experimental + * `createCssContext` is an experimental feature. + * The API might be changed. + */ +export declare const createCssContext: ({ id }: { + id: Readonly; +}) => DefaultContextType; +/** + * @experimental + * `css` is an experimental feature. + * The API might be changed. + */ +export declare const css: CssType; +/** + * @experimental + * `cx` is an experimental feature. + * The API might be changed. + */ +export declare const cx: CxType; +/** + * @experimental + * `keyframes` is an experimental feature. + * The API might be changed. + */ +export declare const keyframes: KeyframesType; +/** + * @experimental + * `viewTransition` is an experimental feature. + * The API might be changed. + */ +export declare const viewTransition: ViewTransitionType; +/** + * @experimental + * `Style` is an experimental feature. + * The API might be changed. + */ +export declare const Style: FC>; diff --git a/node_modules/hono/dist/types/jsx/dom/hooks/index.d.ts b/node_modules/hono/dist/types/jsx/dom/hooks/index.d.ts new file mode 100644 index 000000000..eca26aedc --- /dev/null +++ b/node_modules/hono/dist/types/jsx/dom/hooks/index.d.ts @@ -0,0 +1,39 @@ +/** + * Provide hooks used only in jsx/dom + */ +import type { Context } from '../../context'; +type FormStatus = { + pending: false; + data: null; + method: null; + action: null; +} | { + pending: true; + data: FormData; + method: 'get' | 'post'; + action: string | ((formData: FormData) => void | Promise); +}; +export declare const FormContext: Context; +export declare const registerAction: (action: Promise) => void; +/** + * This hook returns the current form status + * @returns FormStatus + */ +export declare const useFormStatus: () => FormStatus; +/** + * This hook returns the current state and a function to update the state optimistically + * The current state is updated optimistically and then reverted to the original state when all actions are resolved + * @param state + * @param updateState + * @returns [T, (action: N) => void] + */ +export declare const useOptimistic: (state: T, updateState: (currentState: T, action: N) => T) => [T, (action: N) => void]; +/** + * This hook returns the current state and a function to update the state by form action + * @param fn + * @param initialState + * @param permalink + * @returns [T, (data: FormData) => void] + */ +export declare const useActionState: (fn: Function, initialState: T, permalink?: string) => [T, Function]; +export {}; diff --git a/node_modules/hono/dist/types/jsx/dom/index.d.ts b/node_modules/hono/dist/types/jsx/dom/index.d.ts new file mode 100644 index 000000000..a3cfe595d --- /dev/null +++ b/node_modules/hono/dist/types/jsx/dom/index.d.ts @@ -0,0 +1,88 @@ +/** + * @module + * This module provides APIs for `hono/jsx/dom`. + */ +import { isValidElement, reactAPICompatVersion } from '../base'; +import type { Child, DOMAttributes, JSX, JSXNode, Props, FC } from '../base'; +import { Children } from '../children'; +import { useContext } from '../context'; +import { createRef, forwardRef, startTransition, startViewTransition, use, useCallback, useDebugValue, useDeferredValue, useEffect, useId, useImperativeHandle, useInsertionEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, useTransition, useViewTransition } from '../hooks'; +import { ErrorBoundary, Suspense } from './components'; +import { createContext } from './context'; +import { useActionState, useFormStatus, useOptimistic } from './hooks'; +import { Fragment } from './jsx-runtime'; +import { createPortal, flushSync } from './render'; +export { render } from './render'; +declare const createElement: (tag: string | ((props: Props) => JSXNode), props: Props | null, ...children: Child[]) => JSXNode; +declare const cloneElement: (element: T, props: Props, ...children: Child[]) => T; +declare const memo: (component: FC, propsAreEqual?: (prevProps: Readonly, nextProps: Readonly) => boolean) => FC; +export { reactAPICompatVersion as version, createElement as jsx, useState, useEffect, useRef, useCallback, use, startTransition, useTransition, useDeferredValue, startViewTransition, useViewTransition, useMemo, useLayoutEffect, useInsertionEffect, useReducer, useId, useDebugValue, createRef, forwardRef, useImperativeHandle, useSyncExternalStore, useFormStatus, useActionState, useOptimistic, Suspense, ErrorBoundary, createContext, useContext, memo, isValidElement, createElement, cloneElement, Children, Fragment, Fragment as StrictMode, DOMAttributes, flushSync, createPortal, }; +declare const _default: { + version: string; + useState: { + (initialState: T | (() => T)): [T, (newState: T | ((currentState: T) => T)) => void]; + (): [T | undefined, (newState: T | ((currentState: T | undefined) => T | undefined) | undefined) => void]; + }; + useEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => void; + useRef: (initialValue: T | null) => import("..").RefObject; + useCallback: (callback: T, deps: readonly unknown[]) => T; + use: (promise: Promise) => T; + startTransition: (callback: () => void) => void; + useTransition: () => [boolean, (callback: () => void | Promise) => void]; + useDeferredValue: (value: T, initialValue?: T) => T; + startViewTransition: (callback: () => void) => void; + useViewTransition: () => [boolean, (callback: () => void) => void]; + useMemo: (factory: () => T, deps: readonly unknown[]) => T; + useLayoutEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => void; + useInsertionEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => void; + useReducer: (reducer: (state: T, action: A) => T, initialArg: T, init?: (initialState: T) => T) => [T, (action: A) => void]; + useId: () => string; + useDebugValue: (_value: unknown, _formatter?: (value: unknown) => string) => void; + createRef: () => import("..").RefObject; + forwardRef: (Component: (props: P, ref?: import("..").RefObject) => JSX.Element) => ((props: P & { + ref?: import("..").RefObject; + }) => JSX.Element); + useImperativeHandle: (ref: import("..").RefObject, createHandle: () => T, deps: readonly unknown[]) => void; + useSyncExternalStore: (subscribe: (callback: () => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T) => T; + useFormStatus: () => { + pending: false; + data: null; + method: null; + action: null; + } | { + pending: true; + data: FormData; + method: "get" | "post"; + action: string | ((formData: FormData) => void | Promise); + }; + useActionState: (fn: Function, initialState: T, permalink?: string) => [T, Function]; + useOptimistic: (state: T, updateState: (currentState: T, action: N) => T) => [T, (action: N) => void]; + Suspense: FC>; + ErrorBoundary: FC>; + createContext: (defaultValue: T) => import("..").Context; + useContext: (context: import("..").Context) => T; + memo: (component: FC, propsAreEqual?: (prevProps: Readonly, nextProps: Readonly) => boolean) => FC; + isValidElement: (element: unknown) => element is JSXNode; + createElement: (tag: string | ((props: Props) => JSXNode), props: Props | null, ...children: Child[]) => JSXNode; + cloneElement: (element: T, props: Props, ...children: Child[]) => T; + Children: { + map: (children: Child[], fn: (child: Child, index: number) => Child) => Child[]; + forEach: (children: Child[], fn: (child: Child, index: number) => void) => void; + count: (children: Child[]) => number; + only: (_children: Child[]) => Child; + toArray: (children: Child) => Child[]; + }; + Fragment: (props: Record) => JSXNode; + StrictMode: (props: Record) => JSXNode; + flushSync: (callback: () => void) => void; + createPortal: (children: Child, container: HTMLElement, key?: string) => Child; +}; +export default _default; +export type { Context } from '../context'; +export type * from '../types'; diff --git a/node_modules/hono/dist/types/jsx/dom/intrinsic-element/components.d.ts b/node_modules/hono/dist/types/jsx/dom/intrinsic-element/components.d.ts new file mode 100644 index 000000000..53f879ad8 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/dom/intrinsic-element/components.d.ts @@ -0,0 +1,16 @@ +import type { IntrinsicElements } from '../../intrinsic-elements'; +import type { FC, PropsWithChildren, RefObject } from '../../types'; +export declare const clearCache: () => void; +export declare const composeRef: (ref: RefObject | Function | undefined, cb: (e: T) => void | (() => void)) => ((e: T) => () => void); +export declare const title: FC; +export declare const script: FC>; +export declare const style: FC>; +export declare const link: FC>; +export declare const meta: FC; +export declare const form: FC | ((e: HTMLFormElement | null) => void | (() => void)); +}>>; +export declare const input: FC>; +export declare const button: FC>; diff --git a/node_modules/hono/dist/types/jsx/dom/jsx-dev-runtime.d.ts b/node_modules/hono/dist/types/jsx/dom/jsx-dev-runtime.d.ts new file mode 100644 index 000000000..2316d31b7 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/dom/jsx-dev-runtime.d.ts @@ -0,0 +1,8 @@ +/** + * @module + * This module provides the `hono/jsx/dom` dev runtime. + */ +import type { JSXNode, Props } from '../base'; +export type { JSX } from '../base'; +export declare const jsxDEV: (tag: string | Function, props: Props, key?: string) => JSXNode; +export declare const Fragment: (props: Record) => JSXNode; diff --git a/node_modules/hono/dist/types/jsx/dom/jsx-runtime.d.ts b/node_modules/hono/dist/types/jsx/dom/jsx-runtime.d.ts new file mode 100644 index 000000000..884ccb99a --- /dev/null +++ b/node_modules/hono/dist/types/jsx/dom/jsx-runtime.d.ts @@ -0,0 +1,7 @@ +/** + * @module + * This module provides the `hono/jsx/dom` runtime. + */ +export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime'; +export { jsxDEV as jsxs } from './jsx-dev-runtime'; +export type { JSX } from './jsx-dev-runtime'; diff --git a/node_modules/hono/dist/types/jsx/dom/render.d.ts b/node_modules/hono/dist/types/jsx/dom/render.d.ts new file mode 100644 index 000000000..5b12d554f --- /dev/null +++ b/node_modules/hono/dist/types/jsx/dom/render.d.ts @@ -0,0 +1,73 @@ +import type { Child, FC, JSXNode, Props } from '../base'; +import { DOM_RENDERER, DOM_STASH } from '../constants'; +import type { Context as JSXContext } from '../context'; +export type HasRenderToDom = FC & { + [DOM_RENDERER]: FC; +}; +export type ErrorHandler = (error: any, retry: () => void) => Child | undefined; +type Container = HTMLElement | DocumentFragment; +type LocalJSXContexts = [JSXContext, unknown][] | undefined; +type SupportedElement = HTMLElement | SVGElement | MathMLElement; +export type PreserveNodeType = 1 | 2; +export type NodeObject = { + pP: Props | undefined; + nN: Node | undefined; + vC: Node[]; + pC?: Node[]; + vR: Node[]; + n?: string; + f?: boolean; + s?: boolean; + c: Container | undefined; + e: SupportedElement | Text | undefined; + p?: PreserveNodeType; + a?: boolean; + o?: NodeObject; + [DOM_STASH]: [ + number, + any[][], + LocalJSXContexts, + [ + Context, + Function, + NodeObject + ] + ] | [number, any[][]]; +} & JSXNode; +type NodeString = { + t: string; + d: boolean; + s?: boolean; +} & { + e?: Text; + vC: undefined; + nN: undefined; + p?: true; + key: undefined; + tag: undefined; +}; +export type Node = NodeString | NodeObject; +export type PendingType = 0 | 1 | 2; +export type UpdateHook = (context: Context, node: Node, cb: (context: Context) => void) => Promise; +export type Context = [ + PendingType, + boolean, + UpdateHook, + boolean, + boolean, + [ + Context, + Function, + NodeObject + ][] +] | [PendingType, boolean, UpdateHook, boolean] | [PendingType, boolean, UpdateHook] | [PendingType, boolean] | [PendingType] | []; +export declare const buildDataStack: [Context, Node][]; +export declare const getNameSpaceContext: () => JSXContext | undefined; +export declare const build: (context: Context, node: NodeObject, children?: Child[]) => void; +export declare const buildNode: (node: Child) => Node | undefined; +export declare const update: (context: Context, node: NodeObject) => Promise; +export declare const renderNode: (node: NodeObject, container: Container) => void; +export declare const render: (jsxNode: Child, container: Container) => void; +export declare const flushSync: (callback: () => void) => void; +export declare const createPortal: (children: Child, container: HTMLElement, key?: string) => Child; +export {}; diff --git a/node_modules/hono/dist/types/jsx/dom/server.d.ts b/node_modules/hono/dist/types/jsx/dom/server.d.ts new file mode 100644 index 000000000..7de82ccf0 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/dom/server.d.ts @@ -0,0 +1,106 @@ +/** + * @module + * This module provides APIs for `hono/jsx/server`, which is compatible with `react-dom/server`. + */ +import type { Child } from '../base'; +import version from './'; +export interface RenderToStringOptions { + identifierPrefix?: string; +} +/** + * Render JSX element to string. + * @param element JSX element to render. + * @param options Options for rendering. + * @returns Rendered string. + */ +declare const renderToString: (element: Child, options?: RenderToStringOptions) => string; +export interface RenderToReadableStreamOptions { + identifierPrefix?: string; + namespaceURI?: string; + nonce?: string; + bootstrapScriptContent?: string; + bootstrapScripts?: string[]; + bootstrapModules?: string[]; + progressiveChunkSize?: number; + signal?: AbortSignal; + onError?: (error: unknown) => string | void; +} +/** + * Render JSX element to readable stream. + * @param element JSX element to render. + * @param options Options for rendering. + * @returns Rendered readable stream. + */ +declare const renderToReadableStream: (element: Child, options?: RenderToReadableStreamOptions) => Promise>; +export { renderToString, renderToReadableStream, version }; +declare const _default: { + renderToString: (element: Child, options?: RenderToStringOptions) => string; + renderToReadableStream: (element: Child, options?: RenderToReadableStreamOptions) => Promise>; + version: { + version: string; + useState: { + (initialState: T | (() => T)): [T, (newState: T | ((currentState: T) => T)) => void]; + (): [T | undefined, (newState: T | ((currentState: T | undefined) => T | undefined) | undefined) => void]; + }; + useEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => void; + useRef: (initialValue: T | null) => import("..").RefObject; + useCallback: (callback: T, deps: readonly unknown[]) => T; + use: (promise: Promise) => T; + startTransition: (callback: () => void) => void; + useTransition: () => [boolean, (callback: () => void | Promise) => void]; + useDeferredValue: (value: T, initialValue?: T) => T; + startViewTransition: (callback: () => void) => void; + useViewTransition: () => [boolean, (callback: () => void) => void]; + useMemo: (factory: () => T, deps: readonly unknown[]) => T; + useLayoutEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => void; + useInsertionEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => void; + useReducer: (reducer: (state: T, action: A) => T, initialArg: T, init?: (initialState: T) => T) => [T, (action: A) => void]; + useId: () => string; + useDebugValue: (_value: unknown, _formatter?: (value: unknown) => string) => void; + createRef: () => import("..").RefObject; + forwardRef: (Component: (props: P, ref?: import("..").RefObject) => import("./jsx-dev-runtime").JSX.Element) => ((props: P & { + ref?: import("..").RefObject; + }) => import("./jsx-dev-runtime").JSX.Element); + useImperativeHandle: (ref: import("..").RefObject, createHandle: () => T, deps: readonly unknown[]) => void; + useSyncExternalStore: (subscribe: (callback: () => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T) => T; + useFormStatus: () => { + pending: false; + data: null; + method: null; + action: null; + } | { + pending: true; + data: FormData; + method: "get" | "post"; + action: string | ((formData: FormData) => void | Promise); + }; + useActionState: (fn: Function, initialState: T, permalink?: string) => [T, Function]; + useOptimistic: (state: T, updateState: (currentState: T, action: N) => T) => [T, (action: N) => void]; + Suspense: import("..").FC>; + ErrorBoundary: import("..").FC>; + createContext: (defaultValue: T) => import("..").Context; + useContext: (context: import("..").Context) => T; + memo: (component: import("..").FC, propsAreEqual?: (prevProps: Readonly, nextProps: Readonly) => boolean) => import("..").FC; + isValidElement: (element: unknown) => element is import("..").JSXNode; + createElement: (tag: string | ((props: import("../base").Props) => import("..").JSXNode), props: import("../base").Props | null, ...children: Child[]) => import("..").JSXNode; + cloneElement: (element: T, props: import("../base").Props, ...children: Child[]) => T; + Children: { + map: (children: Child[], fn: (child: Child, index: number) => Child) => Child[]; + forEach: (children: Child[], fn: (child: Child, index: number) => void) => void; + count: (children: Child[]) => number; + only: (_children: Child[]) => Child; + toArray: (children: Child) => Child[]; + }; + Fragment: (props: Record) => import("..").JSXNode; + StrictMode: (props: Record) => import("..").JSXNode; + flushSync: (callback: () => void) => void; + createPortal: (children: Child, container: HTMLElement, key?: string) => Child; + }; +}; +export default _default; diff --git a/node_modules/hono/dist/types/jsx/dom/utils.d.ts b/node_modules/hono/dist/types/jsx/dom/utils.d.ts new file mode 100644 index 000000000..b1d29f6a4 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/dom/utils.d.ts @@ -0,0 +1 @@ +export declare const setInternalTagFlag: (fn: Function) => Function; diff --git a/node_modules/hono/dist/types/jsx/hooks/index.d.ts b/node_modules/hono/dist/types/jsx/hooks/index.d.ts new file mode 100644 index 000000000..929e31525 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/hooks/index.d.ts @@ -0,0 +1,45 @@ +import type { JSX } from '../base'; +type UpdateStateFunction = (newState: T | ((currentState: T) => T)) => void; +export declare const STASH_EFFECT = 1; +export type EffectData = [ + readonly unknown[] | undefined, + // deps + (() => void | (() => void)) | undefined, + // layout effect + (() => void) | undefined, + // cleanup + (() => void) | undefined, + // effect + (() => void) | undefined +]; +export declare const startViewTransition: (callback: () => void) => void; +export declare const useViewTransition: () => [boolean, (callback: () => void) => void]; +export declare const startTransition: (callback: () => void) => void; +export declare const useTransition: () => [boolean, (callback: () => void | Promise) => void]; +type UseDeferredValue = (value: T, initialValue?: T) => T; +export declare const useDeferredValue: UseDeferredValue; +type UseStateType = { + (initialState: T | (() => T)): [T, UpdateStateFunction]; + (): [T | undefined, UpdateStateFunction]; +}; +export declare const useState: UseStateType; +export declare const useReducer: (reducer: (state: T, action: A) => T, initialArg: T, init?: (initialState: T) => T) => [T, (action: A) => void]; +export declare const useEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => void; +export declare const useLayoutEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => void; +export declare const useInsertionEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => void; +export declare const useCallback: (callback: T, deps: readonly unknown[]) => T; +export type RefObject = { + current: T | null; +}; +export declare const useRef: (initialValue: T | null) => RefObject; +export declare const use: (promise: Promise) => T; +export declare const useMemo: (factory: () => T, deps: readonly unknown[]) => T; +export declare const useId: () => string; +export declare const useDebugValue: (_value: unknown, _formatter?: (value: unknown) => string) => void; +export declare const createRef: () => RefObject; +export declare const forwardRef: (Component: (props: P, ref?: RefObject) => JSX.Element) => ((props: P & { + ref?: RefObject; +}) => JSX.Element); +export declare const useImperativeHandle: (ref: RefObject, createHandle: () => T, deps: readonly unknown[]) => void; +export declare const useSyncExternalStore: (subscribe: (callback: () => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T) => T; +export {}; diff --git a/node_modules/hono/dist/types/jsx/index.d.ts b/node_modules/hono/dist/types/jsx/index.d.ts new file mode 100644 index 000000000..63d20b6fd --- /dev/null +++ b/node_modules/hono/dist/types/jsx/index.d.ts @@ -0,0 +1,75 @@ +/** + * @module + * JSX for Hono. + */ +import { Fragment, cloneElement, isValidElement, jsx, memo, reactAPICompatVersion } from './base'; +import type { DOMAttributes } from './base'; +import { Children } from './children'; +import { ErrorBoundary } from './components'; +import { createContext, useContext } from './context'; +import { useActionState, useOptimistic } from './dom/hooks'; +import { createRef, forwardRef, startTransition, startViewTransition, use, useCallback, useDebugValue, useDeferredValue, useEffect, useId, useImperativeHandle, useInsertionEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, useTransition, useViewTransition } from './hooks'; +import { Suspense } from './streaming'; +export { reactAPICompatVersion as version, jsx, memo, Fragment, Fragment as StrictMode, isValidElement, jsx as createElement, cloneElement, ErrorBoundary, createContext, useContext, useState, useEffect, useRef, useCallback, useReducer, useId, useDebugValue, use, startTransition, useTransition, useDeferredValue, startViewTransition, useViewTransition, useMemo, useLayoutEffect, useInsertionEffect, createRef, forwardRef, useImperativeHandle, useSyncExternalStore, useActionState, useOptimistic, Suspense, Children, DOMAttributes, }; +declare const _default: { + version: string; + memo: (component: import("./base").FC, propsAreEqual?: (prevProps: Readonly, nextProps: Readonly) => boolean) => import("./base").FC; + Fragment: ({ children, }: { + key?: string; + children?: import("./base").Child | import("../utils/html").HtmlEscapedString; + }) => import("../utils/html").HtmlEscapedString; + StrictMode: ({ children, }: { + key?: string; + children?: import("./base").Child | import("../utils/html").HtmlEscapedString; + }) => import("../utils/html").HtmlEscapedString; + isValidElement: (element: unknown) => element is import("./base").JSXNode; + createElement: (tag: string | Function, props: import("./base").Props | null, ...children: (string | number | import("../utils/html").HtmlEscapedString)[]) => import("./base").JSXNode; + cloneElement: (element: T, props: Partial, ...children: import("./base").Child[]) => T; + ErrorBoundary: import("./base").FC>; + createContext: (defaultValue: T) => import("./context").Context; + useContext: (context: import("./context").Context) => T; + useState: { + (initialState: T | (() => T)): [T, (newState: T | ((currentState: T) => T)) => void]; + (): [T | undefined, (newState: T | ((currentState: T | undefined) => T | undefined) | undefined) => void]; + }; + useEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => void; + useRef: (initialValue: T | null) => import("./hooks").RefObject; + useCallback: (callback: T, deps: readonly unknown[]) => T; + useReducer: (reducer: (state: T, action: A) => T, initialArg: T, init?: (initialState: T) => T) => [T, (action: A) => void]; + useId: () => string; + useDebugValue: (_value: unknown, _formatter?: (value: unknown) => string) => void; + use: (promise: Promise) => T; + startTransition: (callback: () => void) => void; + useTransition: () => [boolean, (callback: () => void | Promise) => void]; + useDeferredValue: (value: T, initialValue?: T) => T; + startViewTransition: (callback: () => void) => void; + useViewTransition: () => [boolean, (callback: () => void) => void]; + useMemo: (factory: () => T, deps: readonly unknown[]) => T; + useLayoutEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => void; + useInsertionEffect: (effect: () => void | (() => void), deps?: readonly unknown[]) => void; + createRef: () => import("./hooks").RefObject; + forwardRef: (Component: (props: P, ref?: import("./hooks").RefObject) => import("./base").JSX.Element) => ((props: P & { + ref?: import("./hooks").RefObject; + }) => import("./base").JSX.Element); + useImperativeHandle: (ref: import("./hooks").RefObject, createHandle: () => T, deps: readonly unknown[]) => void; + useSyncExternalStore: (subscribe: (callback: () => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T) => T; + useActionState: (fn: Function, initialState: T, permalink?: string) => [T, Function]; + useOptimistic: (state: T, updateState: (currentState: T, action: N) => T) => [T, (action: N) => void]; + Suspense: import("./base").FC>; + Children: { + map: (children: import("./base").Child[], fn: (child: import("./base").Child, index: number) => import("./base").Child) => import("./base").Child[]; + forEach: (children: import("./base").Child[], fn: (child: import("./base").Child, index: number) => void) => void; + count: (children: import("./base").Child[]) => number; + only: (_children: import("./base").Child[]) => import("./base").Child; + toArray: (children: import("./base").Child) => import("./base").Child[]; + }; +}; +export default _default; +export type * from './types'; +export type { JSX } from './intrinsic-elements'; diff --git a/node_modules/hono/dist/types/jsx/intrinsic-element/common.d.ts b/node_modules/hono/dist/types/jsx/intrinsic-element/common.d.ts new file mode 100644 index 000000000..b095aa65f --- /dev/null +++ b/node_modules/hono/dist/types/jsx/intrinsic-element/common.d.ts @@ -0,0 +1,3 @@ +export declare const deDupeKeyMap: Record; +export declare const domRenderers: Record; +export declare const dataPrecedenceAttr = "data-precedence"; diff --git a/node_modules/hono/dist/types/jsx/intrinsic-element/components.d.ts b/node_modules/hono/dist/types/jsx/intrinsic-element/components.d.ts new file mode 100644 index 000000000..77d084998 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/intrinsic-element/components.d.ts @@ -0,0 +1,13 @@ +import type { IntrinsicElements } from '../intrinsic-elements'; +import type { FC, PropsWithChildren } from '../types'; +export declare const title: FC; +export declare const script: FC>; +export declare const style: FC>; +export declare const link: FC>; +export declare const meta: FC; +export declare const form: FC>; +export declare const input: (props: PropsWithChildren) => unknown; +export declare const button: (props: PropsWithChildren) => unknown; diff --git a/node_modules/hono/dist/types/jsx/intrinsic-elements.d.ts b/node_modules/hono/dist/types/jsx/intrinsic-elements.d.ts new file mode 100644 index 000000000..f35b34f36 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/intrinsic-elements.d.ts @@ -0,0 +1,722 @@ +import type { BaseMime } from '../utils/mime'; +import type { StringLiteralUnion } from '../utils/types'; +/** + * This code is based on React. + * https://github.com/facebook/react + * MIT License + * Copyright (c) Meta Platforms, Inc. and affiliates. + */ +export declare namespace JSX { + export type CrossOrigin = 'anonymous' | 'use-credentials' | '' | undefined; + export interface CSSProperties { + [propertyKey: string]: unknown; + } + type AnyAttributes = { + [attributeName: string]: any; + }; + interface JSXAttributes { + dangerouslySetInnerHTML?: { + __html: string; + }; + } + interface EventAttributes { + onScroll?: (event: Event) => void; + onScrollCapture?: (event: Event) => void; + onScrollEnd?: (event: Event) => void; + onScrollEndCapture?: (event: Event) => void; + onWheel?: (event: WheelEvent) => void; + onWheelCapture?: (event: WheelEvent) => void; + onAnimationCancel?: (event: AnimationEvent) => void; + onAnimationCancelCapture?: (event: AnimationEvent) => void; + onAnimationEnd?: (event: AnimationEvent) => void; + onAnimationEndCapture?: (event: AnimationEvent) => void; + onAnimationIteration?: (event: AnimationEvent) => void; + onAnimationIterationCapture?: (event: AnimationEvent) => void; + onAnimationStart?: (event: AnimationEvent) => void; + onAnimationStartCapture?: (event: AnimationEvent) => void; + onCopy?: (event: ClipboardEvent) => void; + onCopyCapture?: (event: ClipboardEvent) => void; + onCut?: (event: ClipboardEvent) => void; + onCutCapture?: (event: ClipboardEvent) => void; + onPaste?: (event: ClipboardEvent) => void; + onPasteCapture?: (event: ClipboardEvent) => void; + onCompositionEnd?: (event: CompositionEvent) => void; + onCompositionEndCapture?: (event: CompositionEvent) => void; + onCompositionStart?: (event: CompositionEvent) => void; + onCompositionStartCapture?: (event: CompositionEvent) => void; + onCompositionUpdate?: (event: CompositionEvent) => void; + onCompositionUpdateCapture?: (event: CompositionEvent) => void; + onBlur?: (event: FocusEvent) => void; + onBlurCapture?: (event: FocusEvent) => void; + onFocus?: (event: FocusEvent) => void; + onFocusCapture?: (event: FocusEvent) => void; + onFocusIn?: (event: FocusEvent) => void; + onFocusInCapture?: (event: FocusEvent) => void; + onFocusOut?: (event: FocusEvent) => void; + onFocusOutCapture?: (event: FocusEvent) => void; + onFullscreenChange?: (event: Event) => void; + onFullscreenChangeCapture?: (event: Event) => void; + onFullscreenError?: (event: Event) => void; + onFullscreenErrorCapture?: (event: Event) => void; + onKeyDown?: (event: KeyboardEvent) => void; + onKeyDownCapture?: (event: KeyboardEvent) => void; + onKeyPress?: (event: KeyboardEvent) => void; + onKeyPressCapture?: (event: KeyboardEvent) => void; + onKeyUp?: (event: KeyboardEvent) => void; + onKeyUpCapture?: (event: KeyboardEvent) => void; + onAuxClick?: (event: MouseEvent) => void; + onAuxClickCapture?: (event: MouseEvent) => void; + onClick?: (event: MouseEvent) => void; + onClickCapture?: (event: MouseEvent) => void; + onContextMenu?: (event: MouseEvent) => void; + onContextMenuCapture?: (event: MouseEvent) => void; + onDoubleClick?: (event: MouseEvent) => void; + onDoubleClickCapture?: (event: MouseEvent) => void; + onMouseDown?: (event: MouseEvent) => void; + onMouseDownCapture?: (event: MouseEvent) => void; + onMouseEnter?: (event: MouseEvent) => void; + onMouseEnterCapture?: (event: MouseEvent) => void; + onMouseLeave?: (event: MouseEvent) => void; + onMouseLeaveCapture?: (event: MouseEvent) => void; + onMouseMove?: (event: MouseEvent) => void; + onMouseMoveCapture?: (event: MouseEvent) => void; + onMouseOut?: (event: MouseEvent) => void; + onMouseOutCapture?: (event: MouseEvent) => void; + onMouseOver?: (event: MouseEvent) => void; + onMouseOverCapture?: (event: MouseEvent) => void; + onMouseUp?: (event: MouseEvent) => void; + onMouseUpCapture?: (event: MouseEvent) => void; + onMouseWheel?: (event: WheelEvent) => void; + onMouseWheelCapture?: (event: WheelEvent) => void; + onGotPointerCapture?: (event: PointerEvent) => void; + onGotPointerCaptureCapture?: (event: PointerEvent) => void; + onLostPointerCapture?: (event: PointerEvent) => void; + onLostPointerCaptureCapture?: (event: PointerEvent) => void; + onPointerCancel?: (event: PointerEvent) => void; + onPointerCancelCapture?: (event: PointerEvent) => void; + onPointerDown?: (event: PointerEvent) => void; + onPointerDownCapture?: (event: PointerEvent) => void; + onPointerEnter?: (event: PointerEvent) => void; + onPointerEnterCapture?: (event: PointerEvent) => void; + onPointerLeave?: (event: PointerEvent) => void; + onPointerLeaveCapture?: (event: PointerEvent) => void; + onPointerMove?: (event: PointerEvent) => void; + onPointerMoveCapture?: (event: PointerEvent) => void; + onPointerOut?: (event: PointerEvent) => void; + onPointerOutCapture?: (event: PointerEvent) => void; + onPointerOver?: (event: PointerEvent) => void; + onPointerOverCapture?: (event: PointerEvent) => void; + onPointerUp?: (event: PointerEvent) => void; + onPointerUpCapture?: (event: PointerEvent) => void; + onTouchCancel?: (event: TouchEvent) => void; + onTouchCancelCapture?: (event: TouchEvent) => void; + onTouchEnd?: (event: TouchEvent) => void; + onTouchEndCapture?: (event: TouchEvent) => void; + onTouchMove?: (event: TouchEvent) => void; + onTouchMoveCapture?: (event: TouchEvent) => void; + onTouchStart?: (event: TouchEvent) => void; + onTouchStartCapture?: (event: TouchEvent) => void; + onTransitionCancel?: (event: TransitionEvent) => void; + onTransitionCancelCapture?: (event: TransitionEvent) => void; + onTransitionEnd?: (event: TransitionEvent) => void; + onTransitionEndCapture?: (event: TransitionEvent) => void; + onTransitionRun?: (event: TransitionEvent) => void; + onTransitionRunCapture?: (event: TransitionEvent) => void; + onTransitionStart?: (event: TransitionEvent) => void; + onTransitionStartCapture?: (event: TransitionEvent) => void; + onFormData?: (event: FormDataEvent) => void; + onFormDataCapture?: (event: FormDataEvent) => void; + onReset?: (event: Event) => void; + onResetCapture?: (event: Event) => void; + onSubmit?: (event: Event) => void; + onSubmitCapture?: (event: Event) => void; + onInvalid?: (event: Event) => void; + onInvalidCapture?: (event: Event) => void; + onSelect?: (event: Event) => void; + onSelectCapture?: (event: Event) => void; + onSelectChange?: (event: Event) => void; + onSelectChangeCapture?: (event: Event) => void; + onInput?: (event: InputEvent) => void; + onInputCapture?: (event: InputEvent) => void; + onBeforeInput?: (event: InputEvent) => void; + onBeforeInputCapture?: (event: InputEvent) => void; + onChange?: (event: Event) => void; + onChangeCapture?: (event: Event) => void; + } + export interface HTMLAttributes extends JSXAttributes, EventAttributes, AnyAttributes { + accesskey?: string | undefined; + autocapitalize?: 'off' | 'none' | 'on' | 'sentences' | 'words' | 'characters' | undefined; + autofocus?: boolean | undefined; + class?: string | Promise | undefined; + contenteditable?: boolean | 'inherit' | 'plaintext-only' | undefined; + contextmenu?: string | undefined; + dir?: string | undefined; + draggable?: 'true' | 'false' | boolean | undefined; + enterkeyhint?: 'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send' | undefined; + hidden?: boolean | undefined; + id?: string | undefined; + inert?: boolean | undefined; + inputmode?: 'none' | 'text' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search' | undefined; + is?: string | undefined; + itemid?: string | undefined; + itemprop?: string | undefined; + itemref?: string | undefined; + itemscope?: boolean | undefined; + itemtype?: string | undefined; + lang?: string | undefined; + nonce?: string | undefined; + placeholder?: string | undefined; + /** @see https://developer.mozilla.org/en-US/docs/Web/API/Popover_API */ + popover?: boolean | 'auto' | 'manual' | undefined; + slot?: string | undefined; + spellcheck?: boolean | undefined; + style?: CSSProperties | string | undefined; + tabindex?: number | undefined; + title?: string | undefined; + translate?: 'yes' | 'no' | undefined; + itemProp?: string | undefined; + } + type HTMLAttributeReferrerPolicy = '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url'; + type HTMLAttributeAnchorTarget = StringLiteralUnion<'_self' | '_blank' | '_parent' | '_top'>; + interface AnchorHTMLAttributes extends HTMLAttributes { + download?: string | boolean | undefined; + href?: string | undefined; + hreflang?: string | undefined; + media?: string | undefined; + ping?: string | undefined; + target?: HTMLAttributeAnchorTarget | undefined; + type?: StringLiteralUnion | undefined; + referrerpolicy?: HTMLAttributeReferrerPolicy | undefined; + } + interface AudioHTMLAttributes extends MediaHTMLAttributes { + } + interface AreaHTMLAttributes extends HTMLAttributes { + alt?: string | undefined; + coords?: string | undefined; + download?: string | boolean | undefined; + href?: string | undefined; + hreflang?: string | undefined; + media?: string | undefined; + referrerpolicy?: HTMLAttributeReferrerPolicy | undefined; + shape?: string | undefined; + target?: HTMLAttributeAnchorTarget | undefined; + } + interface BaseHTMLAttributes extends HTMLAttributes { + href?: string | undefined; + target?: HTMLAttributeAnchorTarget | undefined; + } + interface BlockquoteHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + } + /** @see https://developer.mozilla.org/en-US/docs/Web/API/Popover_API */ + type HTMLAttributePopoverTargetAction = 'show' | 'hide' | 'toggle'; + interface ButtonHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + form?: string | undefined; + formenctype?: HTMLAttributeFormEnctype | undefined; + formmethod?: HTMLAttributeFormMethod | undefined; + formnovalidate?: boolean | undefined; + formtarget?: HTMLAttributeAnchorTarget | undefined; + name?: string | undefined; + type?: 'submit' | 'reset' | 'button' | undefined; + value?: string | ReadonlyArray | number | undefined; + popovertarget?: string | undefined; + popovertargetaction?: HTMLAttributePopoverTargetAction | undefined; + formAction?: string | Function | undefined; + } + interface CanvasHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + width?: number | string | undefined; + } + interface ColHTMLAttributes extends HTMLAttributes { + span?: number | undefined; + width?: number | string | undefined; + } + interface ColgroupHTMLAttributes extends HTMLAttributes { + span?: number | undefined; + } + interface DataHTMLAttributes extends HTMLAttributes { + value?: string | ReadonlyArray | number | undefined; + } + interface DetailsHTMLAttributes extends HTMLAttributes { + open?: boolean | undefined; + } + interface DelHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + dateTime?: string | undefined; + } + interface DialogHTMLAttributes extends HTMLAttributes { + open?: boolean | undefined; + } + interface EmbedHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + src?: string | undefined; + type?: StringLiteralUnion | undefined; + width?: number | string | undefined; + } + interface FieldsetHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + form?: string | undefined; + name?: string | undefined; + } + /** @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#method */ + type HTMLAttributeFormMethod = 'get' | 'post' | 'dialog'; + /** @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#enctype */ + type HTMLAttributeFormEnctype = 'application/x-www-form-urlencoded' | 'multipart/form-data' | 'text/plain'; + /** @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#autocomplete */ + type HTMLAttributeFormAutocomplete = 'on' | 'off'; + interface FormHTMLAttributes extends HTMLAttributes { + 'accept-charset'?: StringLiteralUnion<'utf-8'> | undefined; + autocomplete?: HTMLAttributeFormAutocomplete | undefined; + enctype?: HTMLAttributeFormEnctype | undefined; + method?: HTMLAttributeFormMethod | undefined; + name?: string | undefined; + novalidate?: boolean | undefined; + target?: HTMLAttributeAnchorTarget | undefined; + action?: string | Function | undefined; + } + interface HtmlHTMLAttributes extends HTMLAttributes { + manifest?: string | undefined; + } + interface IframeHTMLAttributes extends HTMLAttributes { + allow?: string | undefined; + allowfullscreen?: boolean | undefined; + height?: number | string | undefined; + loading?: 'eager' | 'lazy' | undefined; + name?: string | undefined; + referrerpolicy?: HTMLAttributeReferrerPolicy | undefined; + sandbox?: string | undefined; + seamless?: boolean | undefined; + src?: string | undefined; + srcdoc?: string | undefined; + width?: number | string | undefined; + } + interface ImgHTMLAttributes extends HTMLAttributes { + alt?: string | undefined; + crossorigin?: CrossOrigin; + decoding?: 'async' | 'auto' | 'sync' | undefined; + height?: number | string | undefined; + loading?: 'eager' | 'lazy' | undefined; + referrerpolicy?: HTMLAttributeReferrerPolicy | undefined; + sizes?: string | undefined; + src?: string | undefined; + srcset?: string | undefined; + usemap?: string | undefined; + width?: number | string | undefined; + } + interface InsHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + datetime?: string | undefined; + } + type HTMLInputTypeAttribute = StringLiteralUnion<'button' | 'checkbox' | 'color' | 'date' | 'datetime-local' | 'email' | 'file' | 'hidden' | 'image' | 'month' | 'number' | 'password' | 'radio' | 'range' | 'reset' | 'search' | 'submit' | 'tel' | 'text' | 'time' | 'url' | 'week'>; + type AutoFillAddressKind = 'billing' | 'shipping'; + type AutoFillBase = '' | 'off' | 'on'; + type AutoFillContactField = 'email' | 'tel' | 'tel-area-code' | 'tel-country-code' | 'tel-extension' | 'tel-local' | 'tel-local-prefix' | 'tel-local-suffix' | 'tel-national'; + type AutoFillContactKind = 'home' | 'mobile' | 'work'; + type AutoFillCredentialField = 'webauthn'; + type AutoFillNormalField = 'additional-name' | 'address-level1' | 'address-level2' | 'address-level3' | 'address-level4' | 'address-line1' | 'address-line2' | 'address-line3' | 'bday-day' | 'bday-month' | 'bday-year' | 'cc-csc' | 'cc-exp' | 'cc-exp-month' | 'cc-exp-year' | 'cc-family-name' | 'cc-given-name' | 'cc-name' | 'cc-number' | 'cc-type' | 'country' | 'country-name' | 'current-password' | 'family-name' | 'given-name' | 'honorific-prefix' | 'honorific-suffix' | 'name' | 'new-password' | 'one-time-code' | 'organization' | 'postal-code' | 'street-address' | 'transaction-amount' | 'transaction-currency' | 'username'; + type OptionalPrefixToken = `${T} ` | ''; + type OptionalPostfixToken = ` ${T}` | ''; + type AutoFillField = AutoFillNormalField | `${OptionalPrefixToken}${AutoFillContactField}`; + type AutoFillSection = `section-${string}`; + type AutoFill = AutoFillBase | `${OptionalPrefixToken}${OptionalPrefixToken}${AutoFillField}${OptionalPostfixToken}`; + interface InputHTMLAttributes extends HTMLAttributes { + accept?: string | undefined; + alt?: string | undefined; + autocomplete?: StringLiteralUnion | undefined; + capture?: boolean | 'user' | 'environment' | undefined; + checked?: boolean | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + formenctype?: HTMLAttributeFormEnctype | undefined; + formmethod?: HTMLAttributeFormMethod | undefined; + formnovalidate?: boolean | undefined; + formtarget?: HTMLAttributeAnchorTarget | undefined; + height?: number | string | undefined; + list?: string | undefined; + max?: number | string | undefined; + maxlength?: number | undefined; + min?: number | string | undefined; + minlength?: number | undefined; + multiple?: boolean | undefined; + name?: string | undefined; + pattern?: string | undefined; + placeholder?: string | undefined; + readonly?: boolean | undefined; + required?: boolean | undefined; + size?: number | undefined; + src?: string | undefined; + step?: number | string | undefined; + type?: HTMLInputTypeAttribute | undefined; + value?: string | ReadonlyArray | number | undefined; + width?: number | string | undefined; + popovertarget?: string | undefined; + popovertargetaction?: HTMLAttributePopoverTargetAction | undefined; + formAction?: string | Function | undefined; + } + interface KeygenHTMLAttributes extends HTMLAttributes { + challenge?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + keytype?: string | undefined; + name?: string | undefined; + } + interface LabelHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + for?: string | undefined; + } + interface LiHTMLAttributes extends HTMLAttributes { + value?: string | ReadonlyArray | number | undefined; + } + interface LinkHTMLAttributes extends HTMLAttributes { + as?: string | undefined; + crossorigin?: CrossOrigin; + href?: string | undefined; + hreflang?: string | undefined; + integrity?: string | undefined; + media?: string | undefined; + imagesrcset?: string | undefined; + imagesizes?: string | undefined; + referrerpolicy?: HTMLAttributeReferrerPolicy | undefined; + sizes?: string | undefined; + type?: StringLiteralUnion | undefined; + charSet?: string | undefined; + rel?: string | undefined; + precedence?: string | undefined; + title?: string | undefined; + disabled?: boolean | undefined; + onError?: ((event: Event) => void) | undefined; + onLoad?: ((event: Event) => void) | undefined; + blocking?: 'render' | undefined; + } + interface MapHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + } + interface MenuHTMLAttributes extends HTMLAttributes { + type?: string | undefined; + } + interface MediaHTMLAttributes extends HTMLAttributes { + autoplay?: boolean | undefined; + controls?: boolean | undefined; + controlslist?: string | undefined; + crossorigin?: CrossOrigin; + loop?: boolean | undefined; + mediagroup?: string | undefined; + muted?: boolean | undefined; + playsinline?: boolean | undefined; + preload?: string | undefined; + src?: string | undefined; + } + /** + * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#http-equiv + */ + type MetaHttpEquiv = 'content-security-policy' | 'content-type' | 'default-style' | 'x-ua-compatible' | 'refresh'; + /** + * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name + */ + type MetaName = 'application-name' | 'author' | 'description' | 'generator' | 'keywords' | 'referrer' | 'theme-color' | 'color-scheme' | 'viewport' | 'creator' | 'googlebot' | 'publisher' | 'robots'; + /** + * @see https://ogp.me/ + */ + type MetaProperty = 'og:title' | 'og:type' | 'og:image' | 'og:url' | 'og:audio' | 'og:description' | 'og:determiner' | 'og:locale' | 'og:locale:alternate' | 'og:site_name' | 'og:video' | 'og:image:url' | 'og:image:secure_url' | 'og:image:type' | 'og:image:width' | 'og:image:height' | 'og:image:alt'; + interface MetaHTMLAttributes extends HTMLAttributes { + charset?: StringLiteralUnion<'utf-8'> | undefined; + 'http-equiv'?: StringLiteralUnion | undefined; + name?: StringLiteralUnion | undefined; + media?: string | undefined; + content?: string | undefined; + property?: StringLiteralUnion | undefined; + httpEquiv?: StringLiteralUnion | undefined; + } + interface MeterHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + high?: number | undefined; + low?: number | undefined; + max?: number | string | undefined; + min?: number | string | undefined; + optimum?: number | undefined; + value?: string | ReadonlyArray | number | undefined; + } + interface QuoteHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + } + interface ObjectHTMLAttributes extends HTMLAttributes { + data?: string | undefined; + form?: string | undefined; + height?: number | string | undefined; + name?: string | undefined; + type?: StringLiteralUnion | undefined; + usemap?: string | undefined; + width?: number | string | undefined; + } + interface OlHTMLAttributes extends HTMLAttributes { + reversed?: boolean | undefined; + start?: number | undefined; + type?: '1' | 'a' | 'A' | 'i' | 'I' | undefined; + } + interface OptgroupHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + label?: string | undefined; + } + interface OptionHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + label?: string | undefined; + selected?: boolean | undefined; + value?: string | ReadonlyArray | number | undefined; + } + interface OutputHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + for?: string | undefined; + name?: string | undefined; + } + interface ParamHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + value?: string | ReadonlyArray | number | undefined; + } + interface ProgressHTMLAttributes extends HTMLAttributes { + max?: number | string | undefined; + value?: string | ReadonlyArray | number | undefined; + } + interface SlotHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + } + interface ScriptHTMLAttributes extends HTMLAttributes { + async?: boolean | undefined; + crossorigin?: CrossOrigin; + defer?: boolean | undefined; + integrity?: string | undefined; + nomodule?: boolean | undefined; + referrerpolicy?: HTMLAttributeReferrerPolicy | undefined; + src?: string | undefined; + /** + * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type + */ + type?: StringLiteralUnion<'' | 'text/javascript' | 'importmap' | 'module'> | undefined; + crossOrigin?: CrossOrigin; + fetchPriority?: string | undefined; + noModule?: boolean | undefined; + referrer?: HTMLAttributeReferrerPolicy | undefined; + onError?: ((event: Event) => void) | undefined; + onLoad?: ((event: Event) => void) | undefined; + blocking?: 'render' | undefined; + } + interface SelectHTMLAttributes extends HTMLAttributes { + autocomplete?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + multiple?: boolean | undefined; + name?: string | undefined; + required?: boolean | undefined; + size?: number | undefined; + value?: string | ReadonlyArray | number | undefined; + } + type MediaMime = BaseMime & (`image/${string}` | `audio/${string}` | `video/${string}`); + interface SourceHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + media?: string | undefined; + sizes?: string | undefined; + src?: string | undefined; + srcset?: string | undefined; + type?: StringLiteralUnion | undefined; + width?: number | string | undefined; + } + interface StyleHTMLAttributes extends HTMLAttributes { + media?: string | undefined; + scoped?: boolean | undefined; + /** + * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style#type + */ + type?: '' | 'text/css' | undefined; + href?: string | undefined; + precedence?: string | undefined; + title?: string | undefined; + disabled?: boolean | undefined; + blocking?: 'render' | undefined; + } + interface TableHTMLAttributes extends HTMLAttributes { + align?: 'left' | 'center' | 'right' | undefined; + bgcolor?: string | undefined; + border?: number | undefined; + cellpadding?: number | string | undefined; + cellspacing?: number | string | undefined; + frame?: boolean | undefined; + rules?: 'none' | 'groups' | 'rows' | 'columns' | 'all' | undefined; + summary?: string | undefined; + width?: number | string | undefined; + } + interface TextareaHTMLAttributes extends HTMLAttributes { + autocomplete?: string | undefined; + cols?: number | undefined; + dirname?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + maxlength?: number | undefined; + minlength?: number | undefined; + name?: string | undefined; + placeholder?: string | undefined; + readonly?: boolean | undefined; + required?: boolean | undefined; + rows?: number | undefined; + value?: string | ReadonlyArray | number | undefined; + wrap?: string | undefined; + } + interface TdHTMLAttributes extends HTMLAttributes { + align?: 'left' | 'center' | 'right' | 'justify' | 'char' | undefined; + colspan?: number | undefined; + headers?: string | undefined; + rowspan?: number | undefined; + scope?: string | undefined; + abbr?: string | undefined; + height?: number | string | undefined; + width?: number | string | undefined; + valign?: 'top' | 'middle' | 'bottom' | 'baseline' | undefined; + } + interface ThHTMLAttributes extends HTMLAttributes { + align?: 'left' | 'center' | 'right' | 'justify' | 'char' | undefined; + colspan?: number | undefined; + headers?: string | undefined; + rowspan?: number | undefined; + scope?: 'row' | 'col' | 'rowgroup' | 'colgroup' | string | undefined; + abbr?: string | undefined; + } + interface TimeHTMLAttributes extends HTMLAttributes { + datetime?: string | undefined; + } + interface TrackHTMLAttributes extends HTMLAttributes { + default?: boolean | undefined; + kind?: string | undefined; + label?: string | undefined; + src?: string | undefined; + srclang?: string | undefined; + } + interface VideoHTMLAttributes extends MediaHTMLAttributes { + height?: number | string | undefined; + playsinline?: boolean | undefined; + poster?: string | undefined; + width?: number | string | undefined; + disablePictureInPicture?: boolean | undefined; + disableRemotePlayback?: boolean | undefined; + } + export interface IntrinsicElements { + a: AnchorHTMLAttributes; + abbr: HTMLAttributes; + address: HTMLAttributes; + area: AreaHTMLAttributes; + article: HTMLAttributes; + aside: HTMLAttributes; + audio: AudioHTMLAttributes; + b: HTMLAttributes; + base: BaseHTMLAttributes; + bdi: HTMLAttributes; + bdo: HTMLAttributes; + big: HTMLAttributes; + blockquote: BlockquoteHTMLAttributes; + body: HTMLAttributes; + br: HTMLAttributes; + button: ButtonHTMLAttributes; + canvas: CanvasHTMLAttributes; + caption: HTMLAttributes; + center: HTMLAttributes; + cite: HTMLAttributes; + code: HTMLAttributes; + col: ColHTMLAttributes; + colgroup: ColgroupHTMLAttributes; + data: DataHTMLAttributes; + datalist: HTMLAttributes; + dd: HTMLAttributes; + del: DelHTMLAttributes; + details: DetailsHTMLAttributes; + dfn: HTMLAttributes; + dialog: DialogHTMLAttributes; + div: HTMLAttributes; + dl: HTMLAttributes; + dt: HTMLAttributes; + em: HTMLAttributes; + embed: EmbedHTMLAttributes; + fieldset: FieldsetHTMLAttributes; + figcaption: HTMLAttributes; + figure: HTMLAttributes; + footer: HTMLAttributes; + form: FormHTMLAttributes; + h1: HTMLAttributes; + h2: HTMLAttributes; + h3: HTMLAttributes; + h4: HTMLAttributes; + h5: HTMLAttributes; + h6: HTMLAttributes; + head: HTMLAttributes; + header: HTMLAttributes; + hgroup: HTMLAttributes; + hr: HTMLAttributes; + html: HtmlHTMLAttributes; + i: HTMLAttributes; + iframe: IframeHTMLAttributes; + img: ImgHTMLAttributes; + input: InputHTMLAttributes; + ins: InsHTMLAttributes; + kbd: HTMLAttributes; + keygen: KeygenHTMLAttributes; + label: LabelHTMLAttributes; + legend: HTMLAttributes; + li: LiHTMLAttributes; + link: LinkHTMLAttributes; + main: HTMLAttributes; + map: MapHTMLAttributes; + mark: HTMLAttributes; + menu: MenuHTMLAttributes; + menuitem: HTMLAttributes; + meta: MetaHTMLAttributes; + meter: MeterHTMLAttributes; + nav: HTMLAttributes; + noscript: HTMLAttributes; + object: ObjectHTMLAttributes; + ol: OlHTMLAttributes; + optgroup: OptgroupHTMLAttributes; + option: OptionHTMLAttributes; + output: OutputHTMLAttributes; + p: HTMLAttributes; + param: ParamHTMLAttributes; + picture: HTMLAttributes; + pre: HTMLAttributes; + progress: ProgressHTMLAttributes; + q: QuoteHTMLAttributes; + rp: HTMLAttributes; + rt: HTMLAttributes; + ruby: HTMLAttributes; + s: HTMLAttributes; + samp: HTMLAttributes; + search: HTMLAttributes; + slot: SlotHTMLAttributes; + script: ScriptHTMLAttributes; + section: HTMLAttributes; + select: SelectHTMLAttributes; + small: HTMLAttributes; + source: SourceHTMLAttributes; + span: HTMLAttributes; + strong: HTMLAttributes; + style: StyleHTMLAttributes; + sub: HTMLAttributes; + summary: HTMLAttributes; + sup: HTMLAttributes; + table: TableHTMLAttributes; + template: HTMLAttributes; + tbody: HTMLAttributes; + td: TdHTMLAttributes; + textarea: TextareaHTMLAttributes; + tfoot: HTMLAttributes; + th: ThHTMLAttributes; + thead: HTMLAttributes; + time: TimeHTMLAttributes; + title: HTMLAttributes; + tr: HTMLAttributes; + track: TrackHTMLAttributes; + u: HTMLAttributes; + ul: HTMLAttributes; + var: HTMLAttributes; + video: VideoHTMLAttributes; + wbr: HTMLAttributes; + } + export {}; +} +export interface IntrinsicElements extends JSX.IntrinsicElements { +} diff --git a/node_modules/hono/dist/types/jsx/jsx-dev-runtime.d.ts b/node_modules/hono/dist/types/jsx/jsx-dev-runtime.d.ts new file mode 100644 index 000000000..aa11518ad --- /dev/null +++ b/node_modules/hono/dist/types/jsx/jsx-dev-runtime.d.ts @@ -0,0 +1,8 @@ +/** + * @module + * This module provides Hono's JSX dev runtime. + */ +import type { JSXNode } from './base'; +export { Fragment } from './base'; +export type { JSX } from './base'; +export declare function jsxDEV(tag: string | Function, props: Record, key?: string): JSXNode; diff --git a/node_modules/hono/dist/types/jsx/jsx-runtime.d.ts b/node_modules/hono/dist/types/jsx/jsx-runtime.d.ts new file mode 100644 index 000000000..41ab6691a --- /dev/null +++ b/node_modules/hono/dist/types/jsx/jsx-runtime.d.ts @@ -0,0 +1,12 @@ +/** + * @module + * This module provides Hono's JSX runtime. + */ +export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime'; +export { jsxDEV as jsxs } from './jsx-dev-runtime'; +export type { JSX } from './jsx-dev-runtime'; +import { html } from '../helper/html'; +import type { HtmlEscapedString } from '../utils/html'; +export { html as jsxTemplate }; +export declare const jsxAttr: (key: string, v: string | Promise | Record) => HtmlEscapedString | Promise; +export declare const jsxEscape: (value: string) => string; diff --git a/node_modules/hono/dist/types/jsx/streaming.d.ts b/node_modules/hono/dist/types/jsx/streaming.d.ts new file mode 100644 index 000000000..6c85baeed --- /dev/null +++ b/node_modules/hono/dist/types/jsx/streaming.d.ts @@ -0,0 +1,36 @@ +/** + * @module + * This module enables JSX to supports streaming Response. + */ +import type { HtmlEscapedString } from '../utils/html'; +import { JSXNode } from './base'; +import type { FC, PropsWithChildren, Context as JSXContext } from './'; +/** + * Used to specify nonce for scripts generated by `Suspense` and `ErrorBoundary`. + * + * @example + * ```tsx + * + * Loading...

}> + * + * + * + * ``` + */ +export declare const StreamingContext: JSXContext<{ + scriptNonce: string; +} | null>; +/** + * @experimental + * `Suspense` is an experimental feature. + * The API might be changed. + */ +export declare const Suspense: FC>; +/** + * @experimental + * `renderToReadableStream()` is an experimental feature. + * The API might be changed. + */ +export declare const renderToReadableStream: (content: HtmlEscapedString | JSXNode | Promise, onError?: (e: unknown) => string | void) => ReadableStream; diff --git a/node_modules/hono/dist/types/jsx/types.d.ts b/node_modules/hono/dist/types/jsx/types.d.ts new file mode 100644 index 000000000..2251ba7ae --- /dev/null +++ b/node_modules/hono/dist/types/jsx/types.d.ts @@ -0,0 +1,35 @@ +/** + * All types exported from "hono/jsx" are in this file. + */ +import type { Child, JSXNode } from './base'; +import type { JSX } from './intrinsic-elements'; +export type { Child, JSXNode, FC } from './base'; +export type { RefObject } from './hooks'; +export type { Context } from './context'; +export type PropsWithChildren

= P & { + children?: Child | undefined; +}; +export type CSSProperties = JSX.CSSProperties; +/** + * React types + */ +type ReactElement

= JSXNode & { + type: T; + props: P; + key: string | null; +}; +type ReactNode = ReactElement | string | number | boolean | null | undefined; +type ComponentClass

= unknown; +export type { ReactElement, ReactNode, ComponentClass }; +export type Event = globalThis.Event; +export type MouseEvent = globalThis.MouseEvent; +export type KeyboardEvent = globalThis.KeyboardEvent; +export type FocusEvent = globalThis.FocusEvent; +export type ClipboardEvent = globalThis.ClipboardEvent; +export type InputEvent = globalThis.InputEvent; +export type PointerEvent = globalThis.PointerEvent; +export type TouchEvent = globalThis.TouchEvent; +export type WheelEvent = globalThis.WheelEvent; +export type AnimationEvent = globalThis.AnimationEvent; +export type TransitionEvent = globalThis.TransitionEvent; +export type DragEvent = globalThis.DragEvent; diff --git a/node_modules/hono/dist/types/jsx/utils.d.ts b/node_modules/hono/dist/types/jsx/utils.d.ts new file mode 100644 index 000000000..8dd469a17 --- /dev/null +++ b/node_modules/hono/dist/types/jsx/utils.d.ts @@ -0,0 +1,2 @@ +export declare const normalizeIntrinsicElementKey: (key: string) => string; +export declare const styleObjectForEach: (style: Record, fn: (key: string, value: string | null) => void) => void; diff --git a/node_modules/hono/dist/types/middleware/basic-auth/index.d.ts b/node_modules/hono/dist/types/middleware/basic-auth/index.d.ts new file mode 100644 index 000000000..80cb79382 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/basic-auth/index.d.ts @@ -0,0 +1,56 @@ +/** + * @module + * Basic Auth Middleware for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler } from '../../types'; +type MessageFunction = (c: Context) => string | object | Promise; +type BasicAuthOptions = { + username: string; + password: string; + realm?: string; + hashFunction?: Function; + invalidUserMessage?: string | object | MessageFunction; +} | { + verifyUser: (username: string, password: string, c: Context) => boolean | Promise; + realm?: string; + hashFunction?: Function; + invalidUserMessage?: string | object | MessageFunction; +}; +/** + * Basic Auth Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/basic-auth} + * + * @param {BasicAuthOptions} options - The options for the basic authentication middleware. + * @param {string} options.username - The username for authentication. + * @param {string} options.password - The password for authentication. + * @param {string} [options.realm="Secure Area"] - The realm attribute for the WWW-Authenticate header. + * @param {Function} [options.hashFunction] - The hash function used for secure comparison. + * @param {Function} [options.verifyUser] - The function to verify user credentials. + * @param {string | object | MessageFunction} [options.invalidUserMessage="Unauthorized"] - The invalid user message. + * @returns {MiddlewareHandler} The middleware handler function. + * @throws {HTTPException} If neither "username and password" nor "verifyUser" options are provided. + * + * @example + * ```ts + * const app = new Hono() + * + * app.use( + * '/auth/*', + * basicAuth({ + * username: 'hono', + * password: 'ahotproject', + * }) + * ) + * + * app.get('/auth/page', (c) => { + * return c.text('You are authorized') + * }) + * ``` + */ +export declare const basicAuth: (options: BasicAuthOptions, ...users: { + username: string; + password: string; +}[]) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/bearer-auth/index.d.ts b/node_modules/hono/dist/types/middleware/bearer-auth/index.d.ts new file mode 100644 index 000000000..61645851a --- /dev/null +++ b/node_modules/hono/dist/types/middleware/bearer-auth/index.d.ts @@ -0,0 +1,91 @@ +/** + * @module + * Bearer Auth Middleware for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler } from '../../types'; +type MessageFunction = (c: Context) => string | object | Promise; +type CustomizedErrorResponseOptions = { + wwwAuthenticateHeader?: string | object | MessageFunction; + message?: string | object | MessageFunction; +}; +type BearerAuthOptions = { + token: string | string[]; + realm?: string; + prefix?: string; + headerName?: string; + hashFunction?: Function; + /** + * @deprecated Use noAuthenticationHeader.message instead + */ + noAuthenticationHeaderMessage?: string | object | MessageFunction; + noAuthenticationHeader?: CustomizedErrorResponseOptions; + /** + * @deprecated Use invalidAuthenticationHeader.message instead + */ + invalidAuthenticationHeaderMessage?: string | object | MessageFunction; + invalidAuthenticationHeader?: CustomizedErrorResponseOptions; + /** + * @deprecated Use invalidToken.message instead + */ + invalidTokenMessage?: string | object | MessageFunction; + invalidToken?: CustomizedErrorResponseOptions; +} | { + realm?: string; + prefix?: string; + headerName?: string; + verifyToken: (token: string, c: Context) => boolean | Promise; + hashFunction?: Function; + /** + * @deprecated Use noAuthenticationHeader.message instead + */ + noAuthenticationHeaderMessage?: string | object | MessageFunction; + noAuthenticationHeader?: CustomizedErrorResponseOptions; + /** + * @deprecated Use invalidAuthenticationHeader.message instead + */ + invalidAuthenticationHeaderMessage?: string | object | MessageFunction; + invalidAuthenticationHeader?: CustomizedErrorResponseOptions; + /** + * @deprecated Use invalidToken.message instead + */ + invalidTokenMessage?: string | object | MessageFunction; + invalidToken?: CustomizedErrorResponseOptions; +}; +/** + * Bearer Auth Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/bearer-auth} + * + * @param {BearerAuthOptions} options - The options for the bearer authentication middleware. + * @param {string | string[]} [options.token] - The string or array of strings to validate the incoming bearer token against. + * @param {Function} [options.verifyToken] - The function to verify the token. + * @param {string} [options.realm=""] - The domain name of the realm, as part of the returned WWW-Authenticate challenge header. + * @param {string} [options.prefix="Bearer"] - The prefix (or known as `schema`) for the Authorization header value. If set to the empty string, no prefix is expected. + * @param {string} [options.headerName=Authorization] - The header name. + * @param {Function} [options.hashFunction] - A function to handle hashing for safe comparison of authentication tokens. + * @param {string | object | MessageFunction} [options.noAuthenticationHeader.message="Unauthorized"] - The no authentication header message. + * @param {string | object | MessageFunction} [options.noAuthenticationHeader.wwwAuthenticateHeader="Bearer realm=\"\""] - The response header value for the WWW-Authenticate header when no authentication header is provided. + * @param {string | object | MessageFunction} [options.invalidAuthenticationHeader.message="Bad Request"] - The invalid authentication header message. + * @param {string | object | MessageFunction} [options.invalidAuthenticationHeader.wwwAuthenticateHeader="Bearer error=\"invalid_request\""] - The response header value for the WWW-Authenticate header when authentication header is invalid. + * @param {string | object | MessageFunction} [options.invalidToken.message="Unauthorized"] - The invalid token message. + * @param {string | object | MessageFunction} [options.invalidToken.wwwAuthenticateHeader="Bearer error=\"invalid_token\""] - The response header value for the WWW-Authenticate header when token is invalid. + * @returns {MiddlewareHandler} The middleware handler function. + * @throws {Error} If neither "token" nor "verifyToken" options are provided. + * @throws {HTTPException} If authentication fails, with 401 status code for missing or invalid token, or 400 status code for invalid request. + * + * @example + * ```ts + * const app = new Hono() + * + * const token = 'honoishot' + * + * app.use('/api/*', bearerAuth({ token })) + * + * app.get('/api/page', (c) => { + * return c.json({ message: 'You are authorized' }) + * }) + * ``` + */ +export declare const bearerAuth: (options: BearerAuthOptions) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/body-limit/index.d.ts b/node_modules/hono/dist/types/middleware/body-limit/index.d.ts new file mode 100644 index 000000000..754e9eca2 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/body-limit/index.d.ts @@ -0,0 +1,45 @@ +/** + * @module + * Body Limit Middleware for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler } from '../../types'; +type OnError = (c: Context) => Response | Promise; +type BodyLimitOptions = { + maxSize: number; + onError?: OnError; +}; +/** + * Body Limit Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/body-limit} + * + * @param {BodyLimitOptions} options - The options for the body limit middleware. + * @param {number} options.maxSize - The maximum body size allowed. + * @param {OnError} [options.onError] - The error handler to be invoked if the specified body size is exceeded. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * app.post( + * '/upload', + * bodyLimit({ + * maxSize: 50 * 1024, // 50kb + * onError: (c) => { + * return c.text('overflow :(', 413) + * }, + * }), + * async (c) => { + * const body = await c.req.parseBody() + * if (body['file'] instanceof File) { + * console.log(`Got file sized: ${body['file'].size}`) + * } + * return c.text('pass :)') + * } + * ) + * ``` + */ +export declare const bodyLimit: (options: BodyLimitOptions) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/cache/index.d.ts b/node_modules/hono/dist/types/middleware/cache/index.d.ts new file mode 100644 index 000000000..5d0372759 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/cache/index.d.ts @@ -0,0 +1,41 @@ +/** + * @module + * Cache Middleware for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler } from '../../types'; +import type { StatusCode } from '../../utils/http-status'; +/** + * Cache Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/cache} + * + * @param {Object} options - The options for the cache middleware. + * @param {string | Function} options.cacheName - The name of the cache. Can be used to store multiple caches with different identifiers. + * @param {boolean} [options.wait=false] - A boolean indicating if Hono should wait for the Promise of the `cache.put` function to resolve before continuing with the request. Required to be true for the Deno environment. + * @param {string} [options.cacheControl] - A string of directives for the `Cache-Control` header. + * @param {string | string[]} [options.vary] - Sets the `Vary` header in the response. If the original response header already contains a `Vary` header, the values are merged, removing any duplicates. + * @param {Function} [options.keyGenerator] - Generates keys for every request in the `cacheName` store. This can be used to cache data based on request parameters or context parameters. + * @param {number[]} [options.cacheableStatusCodes=[200]] - An array of status codes that can be cached. + * @returns {MiddlewareHandler} The middleware handler function. + * @throws {Error} If the `vary` option includes "*". + * + * @example + * ```ts + * app.get( + * '*', + * cache({ + * cacheName: 'my-app', + * cacheControl: 'max-age=3600', + * }) + * ) + * ``` + */ +export declare const cache: (options: { + cacheName: string | ((c: Context) => Promise | string); + wait?: boolean; + cacheControl?: string; + vary?: string | string[]; + keyGenerator?: (c: Context) => Promise | string; + cacheableStatusCodes?: StatusCode[]; +}) => MiddlewareHandler; diff --git a/node_modules/hono/dist/types/middleware/combine/index.d.ts b/node_modules/hono/dist/types/middleware/combine/index.d.ts new file mode 100644 index 000000000..57e53dc2f --- /dev/null +++ b/node_modules/hono/dist/types/middleware/combine/index.d.ts @@ -0,0 +1,85 @@ +/** + * @module + * Combine Middleware for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler } from '../../types'; +type Condition = (c: Context) => boolean; +/** + * Create a composed middleware that runs the first middleware that returns true. + * + * @param middleware - An array of MiddlewareHandler or Condition functions. + * Middleware is applied in the order it is passed, and if any middleware exits without returning + * an exception first, subsequent middleware will not be executed. + * You can also pass a condition function that returns a boolean value. If returns true + * the evaluation will be halted, and rest of the middleware will not be executed. + * @returns A composed middleware. + * + * @example + * ```ts + * import { some } from 'hono/combine' + * import { bearerAuth } from 'hono/bearer-auth' + * import { myRateLimit } from '@/rate-limit' + * + * // If client has a valid token, then skip rate limiting. + * // Otherwise, apply rate limiting. + * app.use('/api/*', some( + * bearerAuth({ token }), + * myRateLimit({ limit: 100 }), + * )); + * ``` + */ +export declare const some: (...middleware: (MiddlewareHandler | Condition)[]) => MiddlewareHandler; +/** + * Create a composed middleware that runs all middleware and throws an error if any of them fail. + * + * @param middleware - An array of MiddlewareHandler or Condition functions. + * Middleware is applied in the order it is passed, and if any middleware throws an error, + * subsequent middleware will not be executed. + * You can also pass a condition function that returns a boolean value. If returns false + * the evaluation will be halted, and rest of the middleware will not be executed. + * @returns A composed middleware. + * + * @example + * ```ts + * import { some, every } from 'hono/combine' + * import { bearerAuth } from 'hono/bearer-auth' + * import { myCheckLocalNetwork } from '@/check-local-network' + * import { myRateLimit } from '@/rate-limit' + * + * // If client is in local network, then skip authentication and rate limiting. + * // Otherwise, apply authentication and rate limiting. + * app.use('/api/*', some( + * myCheckLocalNetwork(), + * every( + * bearerAuth({ token }), + * myRateLimit({ limit: 100 }), + * ), + * )); + * ``` + */ +export declare const every: (...middleware: (MiddlewareHandler | Condition)[]) => MiddlewareHandler; +/** + * Create a composed middleware that runs all middleware except when the condition is met. + * + * @param condition - A string or Condition function. + * If there are multiple targets to match any of them, they can be passed as an array. + * If a string is passed, it will be treated as a path pattern to match. + * If a Condition function is passed, it will be evaluated against the request context. + * @param middleware - A composed middleware + * + * @example + * ```ts + * import { except } from 'hono/combine' + * import { bearerAuth } from 'hono/bearer-auth + * + * // If client is accessing public API, then skip authentication. + * // Otherwise, require a valid token. + * app.use('/api/*', except( + * '/api/public/*', + * bearerAuth({ token }), + * )); + * ``` + */ +export declare const except: (condition: string | Condition | (string | Condition)[], ...middleware: MiddlewareHandler[]) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/compress/index.d.ts b/node_modules/hono/dist/types/middleware/compress/index.d.ts new file mode 100644 index 000000000..aa8f93759 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/compress/index.d.ts @@ -0,0 +1,29 @@ +/** + * @module + * Compress Middleware for Hono. + */ +import type { MiddlewareHandler } from '../../types'; +declare const ENCODING_TYPES: readonly ["gzip", "deflate"]; +interface CompressionOptions { + encoding?: (typeof ENCODING_TYPES)[number]; + threshold?: number; +} +/** + * Compress Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/compress} + * + * @param {CompressionOptions} [options] - The options for the compress middleware. + * @param {'gzip' | 'deflate'} [options.encoding] - The compression scheme to allow for response compression. Either 'gzip' or 'deflate'. If not defined, both are allowed and will be used based on the Accept-Encoding header. 'gzip' is prioritized if this option is not provided and the client provides both in the Accept-Encoding header. + * @param {number} [options.threshold=1024] - The minimum size in bytes to compress. Defaults to 1024 bytes. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * app.use(compress()) + * ``` + */ +export declare const compress: (options?: CompressionOptions) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/context-storage/index.d.ts b/node_modules/hono/dist/types/middleware/context-storage/index.d.ts new file mode 100644 index 000000000..6e6301bb7 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/context-storage/index.d.ts @@ -0,0 +1,40 @@ +/** + * @module + * Context Storage Middleware for Hono. + */ +import type { Context } from '../../context'; +import type { Env, MiddlewareHandler } from '../../types'; +/** + * Context Storage Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/context-storage} + * + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * type Env = { + * Variables: { + * message: string + * } + * } + * + * const app = new Hono() + * + * app.use(contextStorage()) + * + * app.use(async (c, next) => { + * c.set('message', 'Hono is hot!!) + * await next() + * }) + * + * app.get('/', async (c) => { c.text(getMessage()) }) + * + * const getMessage = () => { + * return getContext().var.message + * } + * ``` + */ +export declare const contextStorage: () => MiddlewareHandler; +export declare const tryGetContext: () => Context | undefined; +export declare const getContext: () => Context; diff --git a/node_modules/hono/dist/types/middleware/cors/index.d.ts b/node_modules/hono/dist/types/middleware/cors/index.d.ts new file mode 100644 index 000000000..c23fb3ed1 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/cors/index.d.ts @@ -0,0 +1,55 @@ +/** + * @module + * CORS Middleware for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler } from '../../types'; +type CORSOptions = { + origin: string | string[] | ((origin: string, c: Context) => Promise | string | undefined | null); + allowMethods?: string[] | ((origin: string, c: Context) => Promise | string[]); + allowHeaders?: string[]; + maxAge?: number; + credentials?: boolean; + exposeHeaders?: string[]; +}; +/** + * CORS Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/cors} + * + * @param {CORSOptions} [options] - The options for the CORS middleware. + * @param {string | string[] | ((origin: string, c: Context) => Promise | string | undefined | null)} [options.origin='*'] - The value of "Access-Control-Allow-Origin" CORS header. + * @param {string[] | ((origin: string, c: Context) => Promise | string[])} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']] - The value of "Access-Control-Allow-Methods" CORS header. + * @param {string[]} [options.allowHeaders=[]] - The value of "Access-Control-Allow-Headers" CORS header. + * @param {number} [options.maxAge] - The value of "Access-Control-Max-Age" CORS header. + * @param {boolean} [options.credentials] - The value of "Access-Control-Allow-Credentials" CORS header. + * @param {string[]} [options.exposeHeaders=[]] - The value of "Access-Control-Expose-Headers" CORS header. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * app.use('/api/*', cors()) + * app.use( + * '/api2/*', + * cors({ + * origin: 'http://example.com', + * allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'], + * allowMethods: ['POST', 'GET', 'OPTIONS'], + * exposeHeaders: ['Content-Length', 'X-Kuma-Revision'], + * maxAge: 600, + * credentials: true, + * }) + * ) + * + * app.all('/api/abc', (c) => { + * return c.json({ success: true }) + * }) + * app.all('/api2/abc', (c) => { + * return c.json({ success: true }) + * }) + * ``` + */ +export declare const cors: (options?: CORSOptions) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/csrf/index.d.ts b/node_modules/hono/dist/types/middleware/csrf/index.d.ts new file mode 100644 index 000000000..fc478548a --- /dev/null +++ b/node_modules/hono/dist/types/middleware/csrf/index.d.ts @@ -0,0 +1,78 @@ +/** + * @module + * CSRF Protection Middleware for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler } from '../../types'; +type IsAllowedOriginHandler = (origin: string, context: Context) => boolean | Promise; +declare const secFetchSiteValues: readonly ["same-origin", "same-site", "none", "cross-site"]; +type SecFetchSite = (typeof secFetchSiteValues)[number]; +type IsAllowedSecFetchSiteHandler = (secFetchSite: SecFetchSite, context: Context) => boolean | Promise; +interface CSRFOptions { + origin?: string | string[] | IsAllowedOriginHandler; + secFetchSite?: SecFetchSite | SecFetchSite[] | IsAllowedSecFetchSiteHandler; +} +/** + * CSRF Protection Middleware for Hono. + * + * Protects against Cross-Site Request Forgery attacks by validating request origins + * and sec-fetch-site headers. The request is allowed if either validation passes. + * + * @see {@link https://hono.dev/docs/middleware/builtin/csrf} + * + * @param {CSRFOptions} [options] - The options for the CSRF protection middleware. + * @param {string|string[]|(origin: string, context: Context) => boolean} [options.origin] - + * Allowed origins for requests. + * - string: Single allowed origin (e.g., 'https://example.com') + * - string[]: Multiple allowed origins + * - function: Custom validation logic + * - Default: Only same origin as the request URL + * @param {string|string[]|(secFetchSite: string, context: Context) => boolean} [options.secFetchSite] - + * Sec-Fetch-Site header validation. Standard values include 'same-origin', 'same-site', 'cross-site', 'none'. + * - string: Single allowed value (e.g., 'same-origin') + * - string[]: Multiple allowed values (e.g., ['same-origin', 'same-site']) + * - function: Custom validation with access to context + * - Default: Only allows 'same-origin' + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * // Default: both origin and sec-fetch-site validation + * app.use('*', csrf()) + * + * // Allow specific origins + * app.use('*', csrf({ origin: 'https://example.com' })) + * app.use('*', csrf({ origin: ['https://app.com', 'https://api.com'] })) + * + * // Allow specific sec-fetch-site values + * app.use('*', csrf({ secFetchSite: 'same-origin' })) + * app.use('*', csrf({ secFetchSite: ['same-origin', 'same-site'] })) + * + * // Dynamic sec-fetch-site validation + * app.use('*', csrf({ + * secFetchSite: (secFetchSite, c) => { + * // Always allow same-origin + * if (secFetchSite === 'same-origin') return true + * // Allow cross-site for webhook endpoints + * if (secFetchSite === 'cross-site' && c.req.path.startsWith('/webhook/')) { + * return true + * } + * return false + * } + * })) + * + * // Dynamic origin validation + * app.use('*', csrf({ + * origin: (origin, c) => { + * // Allow same origin + * if (origin === new URL(c.req.url).origin) return true + * // Allow specific trusted domains + * return ['https://app.example.com', 'https://admin.example.com'].includes(origin) + * } + * })) + * ``` + */ +export declare const csrf: (options?: CSRFOptions) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/etag/digest.d.ts b/node_modules/hono/dist/types/middleware/etag/digest.d.ts new file mode 100644 index 000000000..dcc773a99 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/etag/digest.d.ts @@ -0,0 +1 @@ +export declare const generateDigest: (stream: ReadableStream> | null, generator: (body: Uint8Array) => ArrayBuffer | Promise) => Promise; diff --git a/node_modules/hono/dist/types/middleware/etag/index.d.ts b/node_modules/hono/dist/types/middleware/etag/index.d.ts new file mode 100644 index 000000000..415d028bb --- /dev/null +++ b/node_modules/hono/dist/types/middleware/etag/index.d.ts @@ -0,0 +1,42 @@ +/** + * @module + * ETag Middleware for Hono. + */ +import type { MiddlewareHandler } from '../../types'; +type ETagOptions = { + retainedHeaders?: string[]; + weak?: boolean; + generateDigest?: (body: Uint8Array) => ArrayBuffer | Promise; +}; +/** + * Default headers to pass through on 304 responses. From the spec: + * > The response must not contain a body and must include the headers that + * > would have been sent in an equivalent 200 OK response: Cache-Control, + * > Content-Location, Date, ETag, Expires, and Vary. + */ +export declare const RETAINED_304_HEADERS: string[]; +/** + * ETag Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/etag} + * + * @param {ETagOptions} [options] - The options for the ETag middleware. + * @param {boolean} [options.weak=false] - Define using or not using a weak validation. If true is set, then `W/` is added to the prefix of the value. + * @param {string[]} [options.retainedHeaders=RETAINED_304_HEADERS] - The headers that you want to retain in the 304 Response. + * @param {function(Uint8Array): ArrayBuffer | Promise} [options.generateDigest] - + * A custom digest generation function. By default, it uses 'SHA-1' + * This function is called with the response body as a `Uint8Array` and should return a hash as an `ArrayBuffer` or a Promise of one. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * app.use('/etag/*', etag()) + * app.get('/etag/abc', (c) => { + * return c.text('Hono is hot') + * }) + * ``` + */ +export declare const etag: (options?: ETagOptions) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/ip-restriction/index.d.ts b/node_modules/hono/dist/types/middleware/ip-restriction/index.d.ts new file mode 100644 index 000000000..a21aa0b57 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/ip-restriction/index.d.ts @@ -0,0 +1,31 @@ +/** + * IP Restriction Middleware for Hono + * @module + */ +import type { Context, MiddlewareHandler } from '../..'; +import type { AddressType, GetConnInfo } from '../../helper/conninfo'; +/** + * Function to get IP Address + */ +type GetIPAddr = GetConnInfo | ((c: Context) => string); +export type IPRestrictionRule = string | ((addr: { + addr: string; + type: AddressType; +}) => boolean); +/** + * Rules for IP Restriction Middleware + */ +export interface IPRestrictionRules { + denyList?: IPRestrictionRule[]; + allowList?: IPRestrictionRule[]; +} +/** + * IP Restriction Middleware + * + * @param getIP function to get IP Address + */ +export declare const ipRestriction: (getIP: GetIPAddr, { denyList, allowList }: IPRestrictionRules, onError?: (remote: { + addr: string; + type: AddressType; +}, c: Context) => Response | Promise) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/jsx-renderer/index.d.ts b/node_modules/hono/dist/types/middleware/jsx-renderer/index.d.ts new file mode 100644 index 000000000..f5bfc57f3 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/jsx-renderer/index.d.ts @@ -0,0 +1,77 @@ +/** + * @module + * JSX Renderer Middleware for Hono. + */ +import type { Context, PropsForRenderer } from '../../context'; +import type { FC, Context as JSXContext, PropsWithChildren } from '../../jsx'; +import type { Env, Input, MiddlewareHandler } from '../../types'; +import type { HtmlEscapedString } from '../../utils/html'; +export declare const RequestContext: JSXContext | null>; +type RendererOptions = { + docType?: boolean | string; + stream?: boolean | Record; +}; +type ComponentWithChildren = (props: PropsWithChildren, c: Context) => HtmlEscapedString | Promise; +/** + * JSX Renderer Middleware for hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/jsx-renderer} + * + * @param {ComponentWithChildren} [component] - The component to render, which can accept children and props. + * @param {RendererOptions} [options] - The options for the JSX renderer middleware. + * @param {boolean | string} [options.docType=true] - The DOCTYPE to be added at the beginning of the HTML. If set to false, no DOCTYPE will be added. + * @param {boolean | Record} [options.stream=false] - If set to true, enables streaming response with default headers. If a record is provided, custom headers will be used. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * app.get( + * '/page/*', + * jsxRenderer(({ children }) => { + * return ( + * + * + *

Menu
+ *
{children}
+ * + * + * ) + * }) + * ) + * + * app.get('/page/about', (c) => { + * return c.render(

About me!

) + * }) + * ``` + */ +export declare const jsxRenderer: (component?: ComponentWithChildren, options?: RendererOptions) => MiddlewareHandler; +/** + * useRequestContext for Hono. + * + * @template E - The environment type. + * @template P - The parameter type. + * @template I - The input type. + * @returns {Context} An instance of Context. + * + * @example + * ```ts + * const RequestUrlBadge: FC = () => { + * const c = useRequestContext() + * return {c.req.url} + * } + * + * app.get('/page/info', (c) => { + * return c.render( + *
+ * You are accessing: + *
+ * ) + * }) + * ``` + */ +export declare const useRequestContext: () => Context; +export {}; diff --git a/node_modules/hono/dist/types/middleware/jwk/index.d.ts b/node_modules/hono/dist/types/middleware/jwk/index.d.ts new file mode 100644 index 000000000..ff7158d27 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/jwk/index.d.ts @@ -0,0 +1 @@ +export { jwk } from './jwk'; diff --git a/node_modules/hono/dist/types/middleware/jwk/jwk.d.ts b/node_modules/hono/dist/types/middleware/jwk/jwk.d.ts new file mode 100644 index 000000000..e0b3dc396 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/jwk/jwk.d.ts @@ -0,0 +1,54 @@ +/** + * @module + * JWK Auth Middleware for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler } from '../../types'; +import type { CookiePrefixOptions } from '../../utils/cookie'; +import '../../context'; +import type { AsymmetricAlgorithm } from '../../utils/jwt/jwa'; +import type { HonoJsonWebKey } from '../../utils/jwt/jws'; +import type { VerifyOptions } from '../../utils/jwt/jwt'; +/** + * JWK Auth Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/jwk} + * + * @param {object} options - The options for the JWK middleware. + * @param {HonoJsonWebKey[] | ((ctx: Context) => Promise | HonoJsonWebKey[])} [options.keys] - The public keys used for JWK verification, or a function that returns them. + * @param {string | ((ctx: Context) => Promise | string)} [options.jwks_uri] - If set to a URI string or a function that returns a URI string, attempt to fetch JWKs from it. The response must be a JSON object containing a `keys` array, which will be merged with the `keys` option. + * @param {boolean} [options.allow_anon] - If set to `true`, the middleware allows requests without a token to proceed without authentication. + * @param {string} [options.cookie] - If set, the middleware attempts to retrieve the token from a cookie with these options (optionally signed) only if no token is found in the header. + * @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'. + * @param {AsymmetricAlgorithm[]} options.alg - An array of allowed asymmetric algorithms for JWT verification. Only tokens signed with these algorithms will be accepted. + * @param {RequestInit} [init] - Optional init options for the `fetch` request when retrieving JWKS from a URI. + * @param {VerifyOptions} [options.verification] - Additional options for JWK payload verification. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * app.use("/auth/*", jwk({ + * jwks_uri: (c) => `https://${c.env.authServer}/.well-known/jwks.json`, + * headerName: 'x-custom-auth-header', // Optional, default is 'Authorization' + * })) + * + * app.get('/auth/page', (c) => { + * return c.text('You are authorized') + * }) + * ``` + */ +export declare const jwk: (options: { + keys?: HonoJsonWebKey[] | ((ctx: Context) => Promise | HonoJsonWebKey[]); + jwks_uri?: string | ((ctx: Context) => Promise | string); + allow_anon?: boolean; + cookie?: string | { + key: string; + secret?: string | BufferSource; + prefixOptions?: CookiePrefixOptions; + }; + headerName?: string; + alg: AsymmetricAlgorithm[]; + verification?: VerifyOptions; +}, init?: RequestInit) => MiddlewareHandler; diff --git a/node_modules/hono/dist/types/middleware/jwt/index.d.ts b/node_modules/hono/dist/types/middleware/jwt/index.d.ts new file mode 100644 index 000000000..40ab4bc85 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/jwt/index.d.ts @@ -0,0 +1,8 @@ +import type { JwtVariables } from './jwt'; +export type { JwtVariables }; +export { jwt, verifyWithJwks, verify, decode, sign } from './jwt'; +export { AlgorithmTypes } from '../../utils/jwt/jwa'; +declare module '../..' { + interface ContextVariableMap extends JwtVariables { + } +} diff --git a/node_modules/hono/dist/types/middleware/jwt/jwt.d.ts b/node_modules/hono/dist/types/middleware/jwt/jwt.d.ts new file mode 100644 index 000000000..aabbd2bf1 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/jwt/jwt.d.ts @@ -0,0 +1,67 @@ +/** + * @module + * JWT Auth Middleware for Hono. + */ +import type { MiddlewareHandler } from '../../types'; +import type { CookiePrefixOptions } from '../../utils/cookie'; +import '../../context'; +import type { SignatureAlgorithm } from '../../utils/jwt/jwa'; +import type { SignatureKey } from '../../utils/jwt/jws'; +import type { VerifyOptions } from '../../utils/jwt/jwt'; +export type JwtVariables = { + jwtPayload: T; +}; +/** + * JWT Auth Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/jwt} + * + * @param {object} options - The options for the JWT middleware. + * @param {SignatureKey} [options.secret] - A value of your secret key. + * @param {string} [options.cookie] - If this value is set, then the value is retrieved from the cookie header using that value as a key, which is then validated as a token. + * @param {SignatureAlgorithm} options.alg - An algorithm type that is used for verifying (required). Available types are `HS256` | `HS384` | `HS512` | `RS256` | `RS384` | `RS512` | `PS256` | `PS384` | `PS512` | `ES256` | `ES384` | `ES512` | `EdDSA`. + * @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'. + * @param {VerifyOptions} [options.verification] - Additional options for JWT payload verification. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * app.use( + * '/auth/*', + * jwt({ + * secret: 'it-is-very-secret', + * alg: 'HS256', + * headerName: 'x-custom-auth-header', // Optional, default is 'Authorization' + * }) + * ) + * + * app.get('/auth/page', (c) => { + * return c.text('You are authorized') + * }) + * ``` + */ +export declare const jwt: (options: { + secret: SignatureKey; + cookie?: string | { + key: string; + secret?: string | BufferSource; + prefixOptions?: CookiePrefixOptions; + }; + alg: SignatureAlgorithm; + headerName?: string; + verification?: VerifyOptions; +}) => MiddlewareHandler; +export declare const verifyWithJwks: (token: string, options: { + keys?: import("../../utils/jwt/jws").HonoJsonWebKey[]; + jwks_uri?: string; + verification?: VerifyOptions; + allowedAlgorithms: readonly import("../../utils/jwt/jwa").AsymmetricAlgorithm[]; +}, init?: RequestInit) => Promise; +export declare const verify: (token: string, publicKey: SignatureKey, algOrOptions: SignatureAlgorithm | import("../../utils/jwt/jwt").VerifyOptionsWithAlg) => Promise; +export declare const decode: (token: string) => { + header: import("../../utils/jwt/jwt").TokenHeader; + payload: import("../../utils/jwt/types").JWTPayload; +}; +export declare const sign: (payload: import("../../utils/jwt/types").JWTPayload, privateKey: SignatureKey, alg?: SignatureAlgorithm) => Promise; diff --git a/node_modules/hono/dist/types/middleware/language/index.d.ts b/node_modules/hono/dist/types/middleware/language/index.d.ts new file mode 100644 index 000000000..51cc2ee43 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/language/index.d.ts @@ -0,0 +1,7 @@ +import type { LanguageVariables, DetectorOptions, DetectorType, CacheType } from './language'; +export type { LanguageVariables, DetectorOptions, DetectorType, CacheType }; +export { languageDetector, detectFromCookie, detectFromHeader, detectFromPath, detectFromQuery, } from './language'; +declare module '../..' { + interface ContextVariableMap extends LanguageVariables { + } +} diff --git a/node_modules/hono/dist/types/middleware/language/language.d.ts b/node_modules/hono/dist/types/middleware/language/language.d.ts new file mode 100644 index 000000000..d4be43bb7 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/language/language.d.ts @@ -0,0 +1,102 @@ +/** + * @module + * Language module for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler } from '../../types'; +export type DetectorType = 'path' | 'querystring' | 'cookie' | 'header'; +export type CacheType = 'cookie'; +export interface DetectorOptions { + /** Order of language detection strategies */ + order: DetectorType[]; + /** Query parameter name for language */ + lookupQueryString: string; + /** Cookie name for language */ + lookupCookie: string; + /** Index in URL path where language code appears */ + lookupFromPathIndex: number; + /** Header key for language detection */ + lookupFromHeaderKey: string; + /** Caching strategies */ + caches: CacheType[] | false; + /** Cookie configuration options */ + cookieOptions?: { + domain?: string; + path?: string; + sameSite?: 'Strict' | 'Lax' | 'None'; + secure?: boolean; + maxAge?: number; + httpOnly?: boolean; + }; + /** Whether to ignore case in language codes */ + ignoreCase: boolean; + /** Default language if none detected */ + fallbackLanguage: string; + /** List of supported language codes */ + supportedLanguages: string[]; + /** Optional function to transform detected language codes */ + convertDetectedLanguage?: (lang: string) => string; + /** Enable debug logging */ + debug?: boolean; +} +export interface LanguageVariables { + language: string; +} +export declare const DEFAULT_OPTIONS: DetectorOptions; +/** + * Parse Accept-Language header values with quality scores + * @param header Accept-Language header string + * @returns Array of parsed languages with quality scores + */ +export declare function parseAcceptLanguage(header: string): Array<{ + lang: string; + q: number; +}>; +/** + * Validate and normalize language codes + * @param lang Language code to normalize + * @param options Detector options + * @returns Normalized language code or undefined + */ +export declare const normalizeLanguage: (lang: string | null | undefined, options: DetectorOptions) => string | undefined; +/** + * Detects language from query parameter + */ +export declare const detectFromQuery: (c: Context, options: DetectorOptions) => string | undefined; +/** + * Detects language from cookie + */ +export declare const detectFromCookie: (c: Context, options: DetectorOptions) => string | undefined; +/** + * Detects language from Accept-Language header + */ +export declare function detectFromHeader(c: Context, options: DetectorOptions): string | undefined; +/** + * Detects language from URL path + */ +export declare function detectFromPath(c: Context, options: DetectorOptions): string | undefined; +/** + * Collection of all language detection strategies + */ +export declare const detectors: { + readonly querystring: (c: Context, options: DetectorOptions) => string | undefined; + readonly cookie: (c: Context, options: DetectorOptions) => string | undefined; + readonly header: typeof detectFromHeader; + readonly path: typeof detectFromPath; +}; +/** Type for detector functions */ +export type DetectorFunction = (c: Context, options: DetectorOptions) => string | undefined; +/** Type-safe detector map */ +export type Detectors = Record; +/** + * Validate detector options + * @param options Detector options to validate + * @throws Error if options are invalid + */ +export declare function validateOptions(options: DetectorOptions): void; +/** + * Language detector middleware factory + * @param userOptions Configuration options for the language detector + * @returns Hono middleware function + */ +export declare const languageDetector: (userOptions: Partial) => MiddlewareHandler; diff --git a/node_modules/hono/dist/types/middleware/logger/index.d.ts b/node_modules/hono/dist/types/middleware/logger/index.d.ts new file mode 100644 index 000000000..a36100ef9 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/logger/index.d.ts @@ -0,0 +1,24 @@ +/** + * @module + * Logger Middleware for Hono. + */ +import type { MiddlewareHandler } from '../../types'; +type PrintFunc = (str: string, ...rest: string[]) => void; +/** + * Logger Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/logger} + * + * @param {PrintFunc} [fn=console.log] - Optional function for customized logging behavior. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * app.use(logger()) + * app.get('/', (c) => c.text('Hello Hono!')) + * ``` + */ +export declare const logger: (fn?: PrintFunc) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/method-override/index.d.ts b/node_modules/hono/dist/types/middleware/method-override/index.d.ts new file mode 100644 index 000000000..0217975e6 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/method-override/index.d.ts @@ -0,0 +1,48 @@ +/** + * @module + * Method Override Middleware for Hono. + */ +import type { Hono } from '../../hono'; +import type { MiddlewareHandler } from '../../types'; +type MethodOverrideOptions = { + app: Hono; +} & ({ + form?: string; + header?: never; + query?: never; +} | { + form?: never; + header: string; + query?: never; +} | { + form?: never; + header?: never; + query: string; +}); +/** + * Method Override Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/method-override} + * + * @param {MethodOverrideOptions} options - The options for the method override middleware. + * @param {Hono} options.app - The instance of Hono is used in your application. + * @param {string} [options.form=_method] - Form key with a value containing the method name. + * @param {string} [options.header] - Header name with a value containing the method name. + * @param {string} [options.query] - Query parameter key with a value containing the method name. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * // If no options are specified, the value of `_method` in the form, + * // e.g. DELETE, is used as the method. + * app.use('/posts', methodOverride({ app })) + * + * app.delete('/posts', (c) => { + * // .... + * }) + * ``` + */ +export declare const methodOverride: (options: MethodOverrideOptions) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/powered-by/index.d.ts b/node_modules/hono/dist/types/middleware/powered-by/index.d.ts new file mode 100644 index 000000000..909197093 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/powered-by/index.d.ts @@ -0,0 +1,29 @@ +/** + * @module + * Powered By Middleware for Hono. + */ +import type { MiddlewareHandler } from '../../types'; +type PoweredByOptions = { + /** + * The value for X-Powered-By header. + * @default Hono + */ + serverName?: string; +}; +/** + * Powered By Middleware for Hono. + * + * @param options - The options for the Powered By Middleware. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * import { poweredBy } from 'hono/powered-by' + * + * const app = new Hono() + * + * app.use(poweredBy()) // With options: poweredBy({ serverName: "My Server" }) + * ``` + */ +export declare const poweredBy: (options?: PoweredByOptions) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/pretty-json/index.d.ts b/node_modules/hono/dist/types/middleware/pretty-json/index.d.ts new file mode 100644 index 000000000..256d4ce6d --- /dev/null +++ b/node_modules/hono/dist/types/middleware/pretty-json/index.d.ts @@ -0,0 +1,42 @@ +/** + * @module + * Pretty JSON Middleware for Hono. + */ +import type { MiddlewareHandler } from '../../types'; +interface PrettyOptions { + /** + * Number of spaces for indentation. + * @default 2 + */ + space?: number; + /** + * Query conditions for when to Pretty. + * @default 'pretty' + */ + query?: string; + /** + * Force prettification of JSON responses regardless of query parameters. + * @default false + */ + force?: boolean; +} +/** + * Pretty JSON Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/pretty-json} + * + * @param options - The options for the pretty JSON middleware. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * app.use(prettyJSON()) // With options: prettyJSON({ space: 4 }) + * app.get('/', (c) => { + * return c.json({ message: 'Hono!' }) + * }) + * ``` + */ +export declare const prettyJSON: (options?: PrettyOptions) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/request-id/index.d.ts b/node_modules/hono/dist/types/middleware/request-id/index.d.ts new file mode 100644 index 000000000..dc895b9a8 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/request-id/index.d.ts @@ -0,0 +1,7 @@ +import type { RequestIdVariables } from './request-id'; +export type { RequestIdVariables }; +export { requestId } from './request-id'; +declare module '../..' { + interface ContextVariableMap extends RequestIdVariables { + } +} diff --git a/node_modules/hono/dist/types/middleware/request-id/request-id.d.ts b/node_modules/hono/dist/types/middleware/request-id/request-id.d.ts new file mode 100644 index 000000000..dd1fdea4c --- /dev/null +++ b/node_modules/hono/dist/types/middleware/request-id/request-id.d.ts @@ -0,0 +1,37 @@ +/** + * @module + * Request ID Middleware for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler } from '../../types'; +export type RequestIdVariables = { + requestId: string; +}; +export type RequestIdOptions = { + limitLength?: number; + headerName?: string; + generator?: (c: Context) => string; +}; +/** + * Request ID Middleware for Hono. + * + * @param {object} options - Options for Request ID middleware. + * @param {number} [options.limitLength=255] - The maximum length of request id. + * @param {string} [options.headerName=X-Request-Id] - The header name used in request id. + * @param {generator} [options.generator=() => crypto.randomUUID()] - The request id generation function. + * + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * type Variables = RequestIdVariables + * const app = new Hono<{Variables: Variables}>() + * + * app.use(requestId()) + * app.get('/', (c) => { + * console.log(c.get('requestId')) // Debug + * return c.text('Hello World!') + * }) + * ``` + */ +export declare const requestId: ({ limitLength, headerName, generator, }?: RequestIdOptions) => MiddlewareHandler; diff --git a/node_modules/hono/dist/types/middleware/secure-headers/index.d.ts b/node_modules/hono/dist/types/middleware/secure-headers/index.d.ts new file mode 100644 index 000000000..6e351a866 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/secure-headers/index.d.ts @@ -0,0 +1,8 @@ +export type { ContentSecurityPolicyOptionHandler } from './secure-headers'; +export { NONCE, secureHeaders } from './secure-headers'; +import type { SecureHeadersVariables } from './secure-headers'; +export type { SecureHeadersVariables }; +declare module '../..' { + interface ContextVariableMap extends SecureHeadersVariables { + } +} diff --git a/node_modules/hono/dist/types/middleware/secure-headers/permissions-policy.d.ts b/node_modules/hono/dist/types/middleware/secure-headers/permissions-policy.d.ts new file mode 100644 index 000000000..1a4c40ea9 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/secure-headers/permissions-policy.d.ts @@ -0,0 +1,14 @@ +export type PermissionsPolicyDirective = StandardizedFeatures | ProposedFeatures | ExperimentalFeatures; +/** + * These features have been declared in a published version of the respective specification. + */ +type StandardizedFeatures = 'accelerometer' | 'ambientLightSensor' | 'attributionReporting' | 'autoplay' | 'battery' | 'bluetooth' | 'camera' | 'chUa' | 'chUaArch' | 'chUaBitness' | 'chUaFullVersion' | 'chUaFullVersionList' | 'chUaMobile' | 'chUaModel' | 'chUaPlatform' | 'chUaPlatformVersion' | 'chUaWow64' | 'computePressure' | 'crossOriginIsolated' | 'directSockets' | 'displayCapture' | 'encryptedMedia' | 'executionWhileNotRendered' | 'executionWhileOutOfViewport' | 'fullscreen' | 'geolocation' | 'gyroscope' | 'hid' | 'identityCredentialsGet' | 'idleDetection' | 'keyboardMap' | 'magnetometer' | 'microphone' | 'midi' | 'navigationOverride' | 'payment' | 'pictureInPicture' | 'publickeyCredentialsGet' | 'screenWakeLock' | 'serial' | 'storageAccess' | 'syncXhr' | 'usb' | 'webShare' | 'windowManagement' | 'xrSpatialTracking'; +/** + * These features have been proposed, but the definitions have not yet been integrated into their respective specs. + */ +type ProposedFeatures = 'clipboardRead' | 'clipboardWrite' | 'gamepad' | 'sharedAutofill' | 'speakerSelection'; +/** + * These features generally have an explainer only, but may be available for experimentation by web developers. + */ +type ExperimentalFeatures = 'allScreensCapture' | 'browsingTopics' | 'capturedSurfaceControl' | 'conversionMeasurement' | 'digitalCredentialsGet' | 'focusWithoutUserActivation' | 'joinAdInterestGroup' | 'localFonts' | 'runAdAuction' | 'smartCard' | 'syncScript' | 'trustTokenRedemption' | 'unload' | 'verticalScroll'; +export {}; diff --git a/node_modules/hono/dist/types/middleware/secure-headers/secure-headers.d.ts b/node_modules/hono/dist/types/middleware/secure-headers/secure-headers.d.ts new file mode 100644 index 000000000..a632b52f3 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/secure-headers/secure-headers.d.ts @@ -0,0 +1,109 @@ +/** + * @module + * Secure Headers Middleware for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler } from '../../types'; +import type { PermissionsPolicyDirective } from './permissions-policy'; +export type SecureHeadersVariables = { + secureHeadersNonce?: string; +}; +export type ContentSecurityPolicyOptionHandler = (ctx: Context, directive: string) => string; +type ContentSecurityPolicyOptionValue = (string | ContentSecurityPolicyOptionHandler)[]; +interface ContentSecurityPolicyOptions { + defaultSrc?: ContentSecurityPolicyOptionValue; + baseUri?: ContentSecurityPolicyOptionValue; + childSrc?: ContentSecurityPolicyOptionValue; + connectSrc?: ContentSecurityPolicyOptionValue; + fontSrc?: ContentSecurityPolicyOptionValue; + formAction?: ContentSecurityPolicyOptionValue; + frameAncestors?: ContentSecurityPolicyOptionValue; + frameSrc?: ContentSecurityPolicyOptionValue; + imgSrc?: ContentSecurityPolicyOptionValue; + manifestSrc?: ContentSecurityPolicyOptionValue; + mediaSrc?: ContentSecurityPolicyOptionValue; + objectSrc?: ContentSecurityPolicyOptionValue; + reportTo?: string; + reportUri?: string | string[]; + sandbox?: ContentSecurityPolicyOptionValue; + scriptSrc?: ContentSecurityPolicyOptionValue; + scriptSrcAttr?: ContentSecurityPolicyOptionValue; + scriptSrcElem?: ContentSecurityPolicyOptionValue; + styleSrc?: ContentSecurityPolicyOptionValue; + styleSrcAttr?: ContentSecurityPolicyOptionValue; + styleSrcElem?: ContentSecurityPolicyOptionValue; + upgradeInsecureRequests?: ContentSecurityPolicyOptionValue; + workerSrc?: ContentSecurityPolicyOptionValue; + requireTrustedTypesFor?: ContentSecurityPolicyOptionValue; + trustedTypes?: ContentSecurityPolicyOptionValue; +} +interface ReportToOptions { + group: string; + max_age: number; + endpoints: ReportToEndpoint[]; +} +interface ReportToEndpoint { + url: string; +} +interface ReportingEndpointOptions { + name: string; + url: string; +} +type PermissionsPolicyValue = '*' | 'self' | 'src' | 'none' | string; +type PermissionsPolicyOptions = Partial>; +type overridableHeader = boolean | string; +interface SecureHeadersOptions { + contentSecurityPolicy?: ContentSecurityPolicyOptions; + contentSecurityPolicyReportOnly?: ContentSecurityPolicyOptions; + crossOriginEmbedderPolicy?: overridableHeader; + crossOriginResourcePolicy?: overridableHeader; + crossOriginOpenerPolicy?: overridableHeader; + originAgentCluster?: overridableHeader; + referrerPolicy?: overridableHeader; + reportingEndpoints?: ReportingEndpointOptions[]; + reportTo?: ReportToOptions[]; + strictTransportSecurity?: overridableHeader; + xContentTypeOptions?: overridableHeader; + xDnsPrefetchControl?: overridableHeader; + xDownloadOptions?: overridableHeader; + xFrameOptions?: overridableHeader; + xPermittedCrossDomainPolicies?: overridableHeader; + xXssProtection?: overridableHeader; + removePoweredBy?: boolean; + permissionsPolicy?: PermissionsPolicyOptions; +} +export declare const NONCE: ContentSecurityPolicyOptionHandler; +/** + * Secure Headers Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/secure-headers} + * + * @param {Partial} [customOptions] - The options for the secure headers middleware. + * @param {ContentSecurityPolicyOptions} [customOptions.contentSecurityPolicy] - Settings for the Content-Security-Policy header. + * @param {ContentSecurityPolicyOptions} [customOptions.contentSecurityPolicyReportOnly] - Settings for the Content-Security-Policy-Report-Only header. + * @param {overridableHeader} [customOptions.crossOriginEmbedderPolicy=false] - Settings for the Cross-Origin-Embedder-Policy header. + * @param {overridableHeader} [customOptions.crossOriginResourcePolicy=true] - Settings for the Cross-Origin-Resource-Policy header. + * @param {overridableHeader} [customOptions.crossOriginOpenerPolicy=true] - Settings for the Cross-Origin-Opener-Policy header. + * @param {overridableHeader} [customOptions.originAgentCluster=true] - Settings for the Origin-Agent-Cluster header. + * @param {overridableHeader} [customOptions.referrerPolicy=true] - Settings for the Referrer-Policy header. + * @param {ReportingEndpointOptions[]} [customOptions.reportingEndpoints] - Settings for the Reporting-Endpoints header. + * @param {ReportToOptions[]} [customOptions.reportTo] - Settings for the Report-To header. + * @param {overridableHeader} [customOptions.strictTransportSecurity=true] - Settings for the Strict-Transport-Security header. + * @param {overridableHeader} [customOptions.xContentTypeOptions=true] - Settings for the X-Content-Type-Options header. + * @param {overridableHeader} [customOptions.xDnsPrefetchControl=true] - Settings for the X-DNS-Prefetch-Control header. + * @param {overridableHeader} [customOptions.xDownloadOptions=true] - Settings for the X-Download-Options header. + * @param {overridableHeader} [customOptions.xFrameOptions=true] - Settings for the X-Frame-Options header. + * @param {overridableHeader} [customOptions.xPermittedCrossDomainPolicies=true] - Settings for the X-Permitted-Cross-Domain-Policies header. + * @param {overridableHeader} [customOptions.xXssProtection=true] - Settings for the X-XSS-Protection header. + * @param {boolean} [customOptions.removePoweredBy=true] - Settings for remove X-Powered-By header. + * @param {PermissionsPolicyOptions} [customOptions.permissionsPolicy] - Settings for the Permissions-Policy header. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * app.use(secureHeaders()) + * ``` + */ +export declare const secureHeaders: (customOptions?: SecureHeadersOptions) => MiddlewareHandler; +export {}; diff --git a/node_modules/hono/dist/types/middleware/serve-static/index.d.ts b/node_modules/hono/dist/types/middleware/serve-static/index.d.ts new file mode 100644 index 000000000..f8fd60628 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/serve-static/index.d.ts @@ -0,0 +1,31 @@ +/** + * @module + * Serve Static Middleware for Hono. + */ +import type { Context, Data } from '../../context'; +import type { Env, MiddlewareHandler } from '../../types'; +export type ServeStaticOptions = { + root?: string; + path?: string; + precompressed?: boolean; + mimes?: Record; + rewriteRequestPath?: (path: string) => string; + onFound?: (path: string, c: Context) => void | Promise; + onNotFound?: (path: string, c: Context) => void | Promise; +}; +/** + * This middleware is not directly used by the user. Create a wrapper specifying `getContent()` by the environment such as Deno or Bun. + */ +export declare const serveStatic: (options: ServeStaticOptions & { + getContent: (path: string, c: Context) => Promise; + /** + * + * `join` option according to the runtime. Example `import { join } from 'node:path`. If not specified, it will fall back to the default join function.` + */ + join?: (...paths: string[]) => string; + /** + * @deprecated Currently, `pathResolve` is no longer used. + */ + pathResolve?: (path: string) => string; + isDir?: (path: string) => boolean | undefined | Promise; +}) => MiddlewareHandler; diff --git a/node_modules/hono/dist/types/middleware/serve-static/path.d.ts b/node_modules/hono/dist/types/middleware/serve-static/path.d.ts new file mode 100644 index 000000000..4d2e95e9d --- /dev/null +++ b/node_modules/hono/dist/types/middleware/serve-static/path.d.ts @@ -0,0 +1,5 @@ +/** + * `defaultJoin` does not support Windows paths and always uses `/` separators. + * If you need Windows path support, please use `join` exported from `node:path` etc. instead. + */ +export declare const defaultJoin: (...paths: string[]) => string; diff --git a/node_modules/hono/dist/types/middleware/timeout/index.d.ts b/node_modules/hono/dist/types/middleware/timeout/index.d.ts new file mode 100644 index 000000000..28d533f90 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/timeout/index.d.ts @@ -0,0 +1,31 @@ +/** + * @module + * Timeout Middleware for Hono. + */ +import type { Context } from '../../context'; +import { HTTPException } from '../../http-exception'; +import type { MiddlewareHandler } from '../../types'; +export type HTTPExceptionFunction = (context: Context) => HTTPException; +/** + * Timeout Middleware for Hono. + * + * @param {number} duration - The timeout duration in milliseconds. + * @param {HTTPExceptionFunction | HTTPException} [exception=defaultTimeoutException] - The exception to throw when the timeout occurs. Can be a function that returns an HTTPException or an HTTPException object. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * app.use( + * '/long-request', + * timeout(5000) // Set timeout to 5 seconds + * ) + * + * app.get('/long-request', async (c) => { + * await someLongRunningFunction() + * return c.text('Completed within time limit') + * }) + * ``` + */ +export declare const timeout: (duration: number, exception?: HTTPExceptionFunction | HTTPException) => MiddlewareHandler; diff --git a/node_modules/hono/dist/types/middleware/timing/index.d.ts b/node_modules/hono/dist/types/middleware/timing/index.d.ts new file mode 100644 index 000000000..a627bc6db --- /dev/null +++ b/node_modules/hono/dist/types/middleware/timing/index.d.ts @@ -0,0 +1,7 @@ +import type { TimingVariables } from './timing'; +export { TimingVariables }; +export { timing, setMetric, startTime, endTime, wrapTime } from './timing'; +declare module '../..' { + interface ContextVariableMap extends TimingVariables { + } +} diff --git a/node_modules/hono/dist/types/middleware/timing/timing.d.ts b/node_modules/hono/dist/types/middleware/timing/timing.d.ts new file mode 100644 index 000000000..b4d217035 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/timing/timing.d.ts @@ -0,0 +1,129 @@ +/** + * @module + * Server-Timing Middleware for Hono. + */ +import type { Context } from '../../context'; +import type { MiddlewareHandler } from '../../types'; +import '../../context'; +export type TimingVariables = { + metric?: { + headers: string[]; + timers: Map; + }; +}; +interface Timer { + description?: string; + start: number; +} +interface TimingOptions { + total?: boolean; + enabled?: boolean | ((c: Context) => boolean); + totalDescription?: string; + autoEnd?: boolean; + crossOrigin?: boolean | string | ((c: Context) => boolean | string); +} +/** + * Server-Timing Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/timing} + * + * @param {TimingOptions} [config] - The options for the timing middleware. + * @param {boolean} [config.total=true] - Show the total response time. + * @param {boolean | ((c: Context) => boolean)} [config.enabled=true] - Whether timings should be added to the headers or not. + * @param {string} [config.totalDescription=Total Response Time] - Description for the total response time. + * @param {boolean} [config.autoEnd=true] - If `startTime()` should end automatically at the end of the request. + * @param {boolean | string | ((c: Context) => boolean | string)} [config.crossOrigin=false] - The origin this timings header should be readable. + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * // add the middleware to your router + * app.use(timing()); + * + * app.get('/', async (c) => { + * // add custom metrics + * setMetric(c, 'region', 'europe-west3') + * + * // add custom metrics with timing, must be in milliseconds + * setMetric(c, 'custom', 23.8, 'My custom Metric') + * + * // start a new timer + * startTime(c, 'db'); + * + * const data = await db.findMany(...); + * + * // end the timer + * endTime(c, 'db'); + * + * return c.json({ response: data }); + * }); + * ``` + */ +export declare const timing: (config?: TimingOptions) => MiddlewareHandler; +interface SetMetric { + (c: Context, name: string, value: number, description?: string, precision?: number): void; + (c: Context, name: string, description?: string): void; +} +/** + * Set a metric for the timing middleware. + * + * @param {Context} c - The context of the request. + * @param {string} name - The name of the metric. + * @param {number | string} [valueDescription] - The value or description of the metric. + * @param {string} [description] - The description of the metric. + * @param {number} [precision] - The precision of the metric value. + * + * @example + * ```ts + * setMetric(c, 'region', 'europe-west3') + * setMetric(c, 'custom', 23.8, 'My custom Metric') + * ``` + */ +export declare const setMetric: SetMetric; +/** + * Start a timer for the timing middleware. + * + * @param {Context} c - The context of the request. + * @param {string} name - The name of the timer. + * @param {string} [description] - The description of the timer. + * + * @example + * ```ts + * startTime(c, 'db') + * ``` + */ +export declare const startTime: (c: Context, name: string, description?: string) => void; +/** + * End a timer for the timing middleware. + * + * @param {Context} c - The context of the request. + * @param {string} name - The name of the timer. + * @param {number} [precision] - The precision of the timer value. + * + * @example + * ```ts + * endTime(c, 'db') + * ``` + */ +export declare const endTime: (c: Context, name: string, precision?: number) => void; +/** + * Wrap a Promise to capture its duration. + * @param {Context} c - The context of the request. + * @param {string} name - The name of the timer. + * @param {Promise} callable - The Promise to time. + * @param {string} [description] - The description of the timer. + * @param {number} [precision] - The precision of the timer value. + * + * @example + * ```ts + * // Instead of this: + * const data = await db.findMany(...); + * + * // do this: + * const data = await wrapTime(c, 'query', db.findMany(...)); + * ``` + * */ +export declare function wrapTime(c: Context, name: string, callable: Promise, description?: string, precision?: number): Promise; +export {}; diff --git a/node_modules/hono/dist/types/middleware/trailing-slash/index.d.ts b/node_modules/hono/dist/types/middleware/trailing-slash/index.d.ts new file mode 100644 index 000000000..9b1d12d07 --- /dev/null +++ b/node_modules/hono/dist/types/middleware/trailing-slash/index.d.ts @@ -0,0 +1,37 @@ +/** + * @module + * Trailing Slash Middleware for Hono. + */ +import type { MiddlewareHandler } from '../../types'; +/** + * Trailing Slash Middleware for Hono. + * + * @see {@link https://hono.dev/docs/middleware/builtin/trailing-slash} + * + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * app.use(trimTrailingSlash()) + * app.get('/about/me/', (c) => c.text('With Trailing Slash')) + * ``` + */ +export declare const trimTrailingSlash: () => MiddlewareHandler; +/** + * Append trailing slash middleware for Hono. + * Append a trailing slash to the URL if it doesn't have one. For example, `/path/to/page` will be redirected to `/path/to/page/`. + * + * @see {@link https://hono.dev/docs/middleware/builtin/trailing-slash} + * + * @returns {MiddlewareHandler} The middleware handler function. + * + * @example + * ```ts + * const app = new Hono() + * + * app.use(appendTrailingSlash()) + * ``` + */ +export declare const appendTrailingSlash: () => MiddlewareHandler; diff --git a/node_modules/hono/dist/types/package.json b/node_modules/hono/dist/types/package.json new file mode 100644 index 000000000..5bbefffba --- /dev/null +++ b/node_modules/hono/dist/types/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/hono/dist/types/preset/quick.d.ts b/node_modules/hono/dist/types/preset/quick.d.ts new file mode 100644 index 000000000..d53dea3a3 --- /dev/null +++ b/node_modules/hono/dist/types/preset/quick.d.ts @@ -0,0 +1,10 @@ +/** + * @module + * The preset that uses `LinearRouter`. + */ +import { HonoBase } from '../hono-base'; +import type { HonoOptions } from '../hono-base'; +import type { BlankEnv, BlankSchema, Env, Schema } from '../types'; +export declare class Hono extends HonoBase { + constructor(options?: HonoOptions); +} diff --git a/node_modules/hono/dist/types/preset/tiny.d.ts b/node_modules/hono/dist/types/preset/tiny.d.ts new file mode 100644 index 000000000..4f75f7258 --- /dev/null +++ b/node_modules/hono/dist/types/preset/tiny.d.ts @@ -0,0 +1,10 @@ +/** + * @module + * The preset that uses `PatternRouter`. + */ +import { HonoBase } from '../hono-base'; +import type { HonoOptions } from '../hono-base'; +import type { BlankEnv, BlankSchema, Env, Schema } from '../types'; +export declare class Hono extends HonoBase { + constructor(options?: HonoOptions); +} diff --git a/node_modules/hono/dist/types/request.d.ts b/node_modules/hono/dist/types/request.d.ts new file mode 100644 index 000000000..fa1342514 --- /dev/null +++ b/node_modules/hono/dist/types/request.d.ts @@ -0,0 +1,313 @@ +import { GET_MATCH_RESULT } from './request/constants'; +import type { Result } from './router'; +import type { Input, InputToDataByTarget, ParamKeyToRecord, ParamKeys, RemoveQuestion, RouterRoute, ValidationTargets } from './types'; +import type { BodyData, ParseBodyOptions } from './utils/body'; +import type { CustomHeader, RequestHeader } from './utils/headers'; +import type { Simplify, UnionToIntersection } from './utils/types'; +type Body = { + json: any; + text: string; + arrayBuffer: ArrayBuffer; + blob: Blob; + formData: FormData; +}; +type BodyCache = Partial; +export declare class HonoRequest

{ + + [GET_MATCH_RESULT]: Result<[unknown, RouterRoute]>; + /** + * `.raw` can get the raw Request object. + * + * @see {@link https://hono.dev/docs/api/request#raw} + * + * @example + * ```ts + * // For Cloudflare Workers + * app.post('/', async (c) => { + * const metadata = c.req.raw.cf?.hostMetadata? + * ... + * }) + * ``` + */ + raw: Request; + routeIndex: number; + /** + * `.path` can get the pathname of the request. + * + * @see {@link https://hono.dev/docs/api/request#path} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const pathname = c.req.path // `/about/me` + * }) + * ``` + */ + path: string; + bodyCache: BodyCache; + constructor(request: Request, path?: string, matchResult?: Result<[unknown, RouterRoute]>); + /** + * `.req.param()` gets the path parameters. + * + * @see {@link https://hono.dev/docs/api/routing#path-parameter} + * + * @example + * ```ts + * const name = c.req.param('name') + * // or all parameters at once + * const { id, comment_id } = c.req.param() + * ``` + */ + param = ParamKeys

>(key: P2 extends `${infer _}?` ? never : P2): string; + param> = RemoveQuestion>>(key: P2): string | undefined; + param(key: string): string | undefined; + param(): Simplify>>>; + /** + * `.query()` can get querystring parameters. + * + * @see {@link https://hono.dev/docs/api/request#query} + * + * @example + * ```ts + * // Query params + * app.get('/search', (c) => { + * const query = c.req.query('q') + * }) + * + * // Get all params at once + * app.get('/search', (c) => { + * const { q, limit, offset } = c.req.query() + * }) + * ``` + */ + query(key: string): string | undefined; + query(): Record; + /** + * `.queries()` can get multiple querystring parameter values, e.g. /search?tags=A&tags=B + * + * @see {@link https://hono.dev/docs/api/request#queries} + * + * @example + * ```ts + * app.get('/search', (c) => { + * // tags will be string[] + * const tags = c.req.queries('tags') + * }) + * ``` + */ + queries(key: string): string[] | undefined; + queries(): Record; + /** + * `.header()` can get the request header value. + * + * @see {@link https://hono.dev/docs/api/request#header} + * + * @example + * ```ts + * app.get('/', (c) => { + * const userAgent = c.req.header('User-Agent') + * }) + * ``` + */ + header(name: RequestHeader): string | undefined; + header(name: string): string | undefined; + header(): Record; + /** + * `.parseBody()` can parse Request body of type `multipart/form-data` or `application/x-www-form-urlencoded` + * + * @see {@link https://hono.dev/docs/api/request#parsebody} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.parseBody() + * }) + * ``` + */ + parseBody, T extends BodyData>(options?: Options): Promise; + parseBody(options?: Partial): Promise; + /** + * `.json()` can parse Request body of type `application/json` + * + * @see {@link https://hono.dev/docs/api/request#json} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.json() + * }) + * ``` + */ + json(): Promise; + /** + * `.text()` can parse Request body of type `text/plain` + * + * @see {@link https://hono.dev/docs/api/request#text} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.text() + * }) + * ``` + */ + text(): Promise; + /** + * `.arrayBuffer()` parse Request body as an `ArrayBuffer` + * + * @see {@link https://hono.dev/docs/api/request#arraybuffer} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.arrayBuffer() + * }) + * ``` + */ + arrayBuffer(): Promise; + /** + * Parses the request body as a `Blob`. + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.blob(); + * }); + * ``` + * @see https://hono.dev/docs/api/request#blob + */ + blob(): Promise; + /** + * Parses the request body as `FormData`. + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.formData(); + * }); + * ``` + * @see https://hono.dev/docs/api/request#formdata + */ + formData(): Promise; + /** + * Adds validated data to the request. + * + * @param target - The target of the validation. + * @param data - The validated data to add. + */ + addValidatedData(target: keyof ValidationTargets, data: {}): void; + /** + * Gets validated data from the request. + * + * @param target - The target of the validation. + * @returns The validated data. + * + * @see https://hono.dev/docs/api/request#valid + */ + valid(target: T): InputToDataByTarget; + /** + * `.url()` can get the request url strings. + * + * @see {@link https://hono.dev/docs/api/request#url} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const url = c.req.url // `http://localhost:8787/about/me` + * ... + * }) + * ``` + */ + get url(): string; + /** + * `.method()` can get the method name of the request. + * + * @see {@link https://hono.dev/docs/api/request#method} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const method = c.req.method // `GET` + * }) + * ``` + */ + get method(): string; + /** + * `.matchedRoutes()` can return a matched route in the handler + * + * @deprecated + * + * Use matchedRoutes helper defined in "hono/route" instead. + * + * @see {@link https://hono.dev/docs/api/request#matchedroutes} + * + * @example + * ```ts + * app.use('*', async function logger(c, next) { + * await next() + * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => { + * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]') + * console.log( + * method, + * ' ', + * path, + * ' '.repeat(Math.max(10 - path.length, 0)), + * name, + * i === c.req.routeIndex ? '<- respond from here' : '' + * ) + * }) + * }) + * ``` + */ + get matchedRoutes(): RouterRoute[]; + /** + * `routePath()` can retrieve the path registered within the handler + * + * @deprecated + * + * Use routePath helper defined in "hono/route" instead. + * + * @see {@link https://hono.dev/docs/api/request#routepath} + * + * @example + * ```ts + * app.get('/posts/:id', (c) => { + * return c.json({ path: c.req.routePath }) + * }) + * ``` + */ + get routePath(): string; +} +/** + * Clones a HonoRequest's underlying raw Request object. + * + * This utility handles both consumed and unconsumed request bodies: + * - If the request body hasn't been consumed, it uses the native `clone()` method + * - If the request body has been consumed, it reconstructs a new Request using cached body data + * + * This is particularly useful when you need to: + * - Process the same request body multiple times + * - Pass requests to external services after validation + * + * @param req - The HonoRequest object to clone + * @returns A Promise that resolves to a new Request object with the same properties + * @throws {HTTPException} If the request body was consumed directly via `req.raw` + * without using HonoRequest methods (e.g., `req.json()`, `req.text()`), making it + * impossible to reconstruct the body from cache + * + * @example + * ```ts + * // Clone after consuming the body (e.g., after validation) + * app.post('/forward', + * validator('json', (data) => data), + * async (c) => { + * const validated = c.req.valid('json') + * // Body has been consumed, but cloneRawRequest still works + * const clonedReq = await cloneRawRequest(c.req) + * return fetch('http://backend-service.com', clonedReq) + * } + * ) + * ``` + */ +export declare const cloneRawRequest: (req: HonoRequest) => Promise; +export {}; diff --git a/node_modules/hono/dist/types/request/constants.d.ts b/node_modules/hono/dist/types/request/constants.d.ts new file mode 100644 index 000000000..3d95e12d0 --- /dev/null +++ b/node_modules/hono/dist/types/request/constants.d.ts @@ -0,0 +1 @@ +export declare const GET_MATCH_RESULT: symbol; diff --git a/node_modules/hono/dist/types/router.d.ts b/node_modules/hono/dist/types/router.d.ts new file mode 100644 index 000000000..abe9f0307 --- /dev/null +++ b/node_modules/hono/dist/types/router.d.ts @@ -0,0 +1,97 @@ +/** + * @module + * This module provides types definitions and variables for the routers. + */ +/** + * Constant representing all HTTP methods in uppercase. + */ +export declare const METHOD_NAME_ALL: "ALL"; +/** + * Constant representing all HTTP methods in lowercase. + */ +export declare const METHOD_NAME_ALL_LOWERCASE: "all"; +/** + * Array of supported HTTP methods. + */ +export declare const METHODS: readonly ["get", "post", "put", "delete", "options", "patch"]; +/** + * Error message indicating that a route cannot be added because the matcher is already built. + */ +export declare const MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built."; +/** + * Interface representing a router. + * + * @template T - The type of the handler. + */ +export interface Router { + /** + * The name of the router. + */ + name: string; + /** + * Adds a route to the router. + * + * @param method - The HTTP method (e.g., 'get', 'post'). + * @param path - The path for the route. + * @param handler - The handler for the route. + */ + add(method: string, path: string, handler: T): void; + /** + * Matches a route based on the given method and path. + * + * @param method - The HTTP method (e.g., 'get', 'post'). + * @param path - The path to match. + * @returns The result of the match. + */ + match(method: string, path: string): Result; +} +/** + * Type representing a map of parameter indices. + */ +export type ParamIndexMap = Record; +/** + * Type representing a stash of parameters. + */ +export type ParamStash = string[]; +/** + * Type representing a map of parameters. + */ +export type Params = Record; +/** + * Type representing the result of a route match. + * + * The result can be in one of two formats: + * 1. An array of handlers with their corresponding parameter index maps, followed by a parameter stash. + * 2. An array of handlers with their corresponding parameter maps. + * + * Example: + * + * [[handler, paramIndexMap][], paramArray] + * ```typescript + * [ + * [ + * [middlewareA, {}], // '*' + * [funcA, {'id': 0}], // '/user/:id/*' + * [funcB, {'id': 0, 'action': 1}], // '/user/:id/:action' + * ], + * ['123', 'abc'] + * ] + * ``` + * + * [[handler, params][]] + * ```typescript + * [ + * [ + * [middlewareA, {}], // '*' + * [funcA, {'id': '123'}], // '/user/:id/*' + * [funcB, {'id': '123', 'action': 'abc'}], // '/user/:id/:action' + * ] + * ] + * ``` + */ +export type Result = [[T, ParamIndexMap][], ParamStash] | [[T, Params][]]; +/** + * Error class representing an unsupported path error. + */ +export declare class UnsupportedPathError extends Error { +} diff --git a/node_modules/hono/dist/types/router/linear-router/index.d.ts b/node_modules/hono/dist/types/router/linear-router/index.d.ts new file mode 100644 index 000000000..899f66e11 --- /dev/null +++ b/node_modules/hono/dist/types/router/linear-router/index.d.ts @@ -0,0 +1,5 @@ +/** + * @module + * LinearRouter for Hono. + */ +export { LinearRouter } from './router'; diff --git a/node_modules/hono/dist/types/router/linear-router/router.d.ts b/node_modules/hono/dist/types/router/linear-router/router.d.ts new file mode 100644 index 000000000..45d563a15 --- /dev/null +++ b/node_modules/hono/dist/types/router/linear-router/router.d.ts @@ -0,0 +1,7 @@ +import type { Result, Router } from '../../router'; +export declare class LinearRouter implements Router { + + name: string; + add(method: string, path: string, handler: T): void; + match(method: string, path: string): Result; +} diff --git a/node_modules/hono/dist/types/router/pattern-router/index.d.ts b/node_modules/hono/dist/types/router/pattern-router/index.d.ts new file mode 100644 index 000000000..26f9f235e --- /dev/null +++ b/node_modules/hono/dist/types/router/pattern-router/index.d.ts @@ -0,0 +1,5 @@ +/** + * @module + * PatternRouter for Hono. + */ +export { PatternRouter } from './router'; diff --git a/node_modules/hono/dist/types/router/pattern-router/router.d.ts b/node_modules/hono/dist/types/router/pattern-router/router.d.ts new file mode 100644 index 000000000..299811dd5 --- /dev/null +++ b/node_modules/hono/dist/types/router/pattern-router/router.d.ts @@ -0,0 +1,7 @@ +import type { Result, Router } from '../../router'; +export declare class PatternRouter implements Router { + + name: string; + add(method: string, path: string, handler: T): void; + match(method: string, path: string): Result; +} diff --git a/node_modules/hono/dist/types/router/reg-exp-router/index.d.ts b/node_modules/hono/dist/types/router/reg-exp-router/index.d.ts new file mode 100644 index 000000000..25c2363ca --- /dev/null +++ b/node_modules/hono/dist/types/router/reg-exp-router/index.d.ts @@ -0,0 +1,6 @@ +/** + * @module + * RegExpRouter for Hono. + */ +export { RegExpRouter } from './router'; +export { PreparedRegExpRouter, buildInitParams, serializeInitParams } from './prepared-router'; diff --git a/node_modules/hono/dist/types/router/reg-exp-router/matcher.d.ts b/node_modules/hono/dist/types/router/reg-exp-router/matcher.d.ts new file mode 100644 index 000000000..721ec4bd7 --- /dev/null +++ b/node_modules/hono/dist/types/router/reg-exp-router/matcher.d.ts @@ -0,0 +1,7 @@ +import type { ParamIndexMap, Result, Router } from '../../router'; +export type HandlerData = [T, ParamIndexMap][]; +export type StaticMap = Record>; +export type Matcher = [RegExp, HandlerData[], StaticMap]; +export type MatcherMap = Record | null>; +export declare const emptyParam: string[]; +export declare function match, T>(this: R, method: string, path: string): Result; diff --git a/node_modules/hono/dist/types/router/reg-exp-router/node.d.ts b/node_modules/hono/dist/types/router/reg-exp-router/node.d.ts new file mode 100644 index 000000000..76f1c5343 --- /dev/null +++ b/node_modules/hono/dist/types/router/reg-exp-router/node.d.ts @@ -0,0 +1,10 @@ +export declare const PATH_ERROR: unique symbol; +export type ParamAssocArray = [string, number][]; +export interface Context { + varIndex: number; +} +export declare class Node { + + insert(tokens: readonly string[], index: number, paramMap: ParamAssocArray, context: Context, pathErrorCheckOnly: boolean): void; + buildRegExpStr(): string; +} diff --git a/node_modules/hono/dist/types/router/reg-exp-router/prepared-router.d.ts b/node_modules/hono/dist/types/router/reg-exp-router/prepared-router.d.ts new file mode 100644 index 000000000..de9f39e92 --- /dev/null +++ b/node_modules/hono/dist/types/router/reg-exp-router/prepared-router.d.ts @@ -0,0 +1,17 @@ +import type { ParamIndexMap, Router } from '../../router'; +import type { MatcherMap } from './matcher'; +import { match } from './matcher'; +type RelocateMap = Record; +export declare class PreparedRegExpRouter implements Router { + + name: string; + constructor(matchers: MatcherMap, relocateMap: RelocateMap); + add(method: string, path: string, handler: T): void; + protected buildAllMatchers(): MatcherMap; + match: typeof match, T>; +} +export declare const buildInitParams: (params: { + paths: string[]; +}) => ConstructorParameters; +export declare const serializeInitParams: (params: ConstructorParameters) => string; +export {}; diff --git a/node_modules/hono/dist/types/router/reg-exp-router/router.d.ts b/node_modules/hono/dist/types/router/reg-exp-router/router.d.ts new file mode 100644 index 000000000..fda1ebb2f --- /dev/null +++ b/node_modules/hono/dist/types/router/reg-exp-router/router.d.ts @@ -0,0 +1,11 @@ +import type { Router } from '../../router'; +import type { MatcherMap } from './matcher'; +import { match } from './matcher'; +export declare class RegExpRouter implements Router { + + name: string; + constructor(); + add(method: string, path: string, handler: T): void; + match: typeof match, T>; + protected buildAllMatchers(): MatcherMap; +} diff --git a/node_modules/hono/dist/types/router/reg-exp-router/trie.d.ts b/node_modules/hono/dist/types/router/reg-exp-router/trie.d.ts new file mode 100644 index 000000000..a1f1a8060 --- /dev/null +++ b/node_modules/hono/dist/types/router/reg-exp-router/trie.d.ts @@ -0,0 +1,7 @@ +import type { ParamAssocArray } from './node'; +export type ReplacementMap = number[]; +export declare class Trie { + + insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamAssocArray; + buildRegExp(): [RegExp, ReplacementMap, ReplacementMap]; +} diff --git a/node_modules/hono/dist/types/router/smart-router/index.d.ts b/node_modules/hono/dist/types/router/smart-router/index.d.ts new file mode 100644 index 000000000..e7801b8e4 --- /dev/null +++ b/node_modules/hono/dist/types/router/smart-router/index.d.ts @@ -0,0 +1,5 @@ +/** + * @module + * SmartRouter for Hono. + */ +export { SmartRouter } from './router'; diff --git a/node_modules/hono/dist/types/router/smart-router/router.d.ts b/node_modules/hono/dist/types/router/smart-router/router.d.ts new file mode 100644 index 000000000..94a4de31a --- /dev/null +++ b/node_modules/hono/dist/types/router/smart-router/router.d.ts @@ -0,0 +1,11 @@ +import type { Result, Router } from '../../router'; +export declare class SmartRouter implements Router { + + name: string; + constructor(init: { + routers: Router[]; + }); + add(method: string, path: string, handler: T): void; + match(method: string, path: string): Result; + get activeRouter(): Router; +} diff --git a/node_modules/hono/dist/types/router/trie-router/index.d.ts b/node_modules/hono/dist/types/router/trie-router/index.d.ts new file mode 100644 index 000000000..44ace76e7 --- /dev/null +++ b/node_modules/hono/dist/types/router/trie-router/index.d.ts @@ -0,0 +1,5 @@ +/** + * @module + * TrieRouter for Hono. + */ +export { TrieRouter } from './router'; diff --git a/node_modules/hono/dist/types/router/trie-router/node.d.ts b/node_modules/hono/dist/types/router/trie-router/node.d.ts new file mode 100644 index 000000000..81b9cc51e --- /dev/null +++ b/node_modules/hono/dist/types/router/trie-router/node.d.ts @@ -0,0 +1,7 @@ +import type { Params } from '../../router'; +export declare class Node { + + constructor(method?: string, handler?: T, children?: Record>); + insert(method: string, path: string, handler: T): Node; + search(method: string, path: string): [[T, Params][]]; +} diff --git a/node_modules/hono/dist/types/router/trie-router/router.d.ts b/node_modules/hono/dist/types/router/trie-router/router.d.ts new file mode 100644 index 000000000..50990dbbe --- /dev/null +++ b/node_modules/hono/dist/types/router/trie-router/router.d.ts @@ -0,0 +1,8 @@ +import type { Result, Router } from '../../router'; +export declare class TrieRouter implements Router { + + name: string; + constructor(); + add(method: string, path: string, handler: T): void; + match(method: string, path: string): Result; +} diff --git a/node_modules/hono/dist/types/types.d.ts b/node_modules/hono/dist/types/types.d.ts new file mode 100644 index 000000000..856f412f9 --- /dev/null +++ b/node_modules/hono/dist/types/types.d.ts @@ -0,0 +1,573 @@ +/** + * @module + * This module contains some type definitions for the Hono modules. + */ +import type { Context } from './context'; +import type { HonoBase } from './hono-base'; +import type { CustomHeader, RequestHeader } from './utils/headers'; +import type { StatusCode } from './utils/http-status'; +import type { IfAnyThenEmptyObject, IsAny, JSONValue, RemoveBlankRecord, Simplify, UnionToIntersection } from './utils/types'; +export type Bindings = object; +export type Variables = object; +export type BlankEnv = {}; +export type Env = { + Bindings?: Bindings; + Variables?: Variables; +}; +export type Next = () => Promise; +export type ExtractInput = I extends Input ? unknown extends I['in'] ? {} : I['in'] : I; +export type Input = { + in?: {}; + out?: {}; + outputFormat?: ResponseFormat; +}; +export type BlankSchema = {}; +export type BlankInput = {}; +export interface RouterRoute { + basePath: string; + path: string; + method: string; + handler: H; +} +export type HandlerResponse = Response | TypedResponse | Promise> | Promise; +export type Handler = any> = (c: Context, next: Next) => R; +export type MiddlewareHandler = Response> = (c: Context, next: Next) => Promise; +export type H = any> = Handler | MiddlewareHandler; +/** + * You can extend this interface to define a custom `c.notFound()` Response type. + * + * @example + * declare module 'hono' { + * interface NotFoundResponse extends Response, TypedResponse {} + * } + */ +export interface NotFoundResponse { +} +export type NotFoundHandler = (c: Context) => NotFoundResponse extends Response ? NotFoundResponse | Promise : Response | Promise; +export interface HTTPResponseError extends Error { + getResponse: () => Response; +} +export type ErrorHandler = (err: Error | HTTPResponseError, c: Context) => Response | Promise; +export interface HandlerInterface { +

= any, E2 extends Env = E>(handler: H): HonoBase, S & ToSchema>, BasePath, CurrentPath>; +

= any, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, M1 extends H = H>(...handlers: [H & M1, H]): HonoBase, S & ToSchema | MergeMiddlewareResponse>, BasePath, CurrentPath>; +

, R extends HandlerResponse = any, I extends Input = BlankInput, E2 extends Env = E>(path: P, handler: H): HonoBase, S, M, P, I, BasePath>, BasePath, MergePath>; +

= any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, M1 extends H = H, M2 extends H = H>(...handlers: [H & M1, H & M2, H]): HonoBase, S & ToSchema | MergeMiddlewareResponse | MergeMiddlewareResponse>, BasePath, CurrentPath>; +

, R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, M1 extends H = H>(path: P, ...handlers: [H & M1, H]): HonoBase | MergeMiddlewareResponse, S, M, P, I2, BasePath>, BasePath, MergePath>; +

= any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, M1 extends H = H, M2 extends H = H, M3 extends H = H>(...handlers: [H & M1, H & M2, H & M3, H]): HonoBase, S & ToSchema | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse>, BasePath, CurrentPath>; +

, R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, M1 extends H = H, M2 extends H = H>(path: P, ...handlers: [H & M1, H & M2, H]): HonoBase | MergeMiddlewareResponse | MergeMiddlewareResponse, S, M, P, I3, BasePath>, BasePath, MergePath>; +

= any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, M1 extends H = H, M2 extends H = H, M3 extends H = H, M4 extends H = H>(...handlers: [ + H & M1, + H & M2, + H & M3, + H & M4, + H + ]): HonoBase, S & ToSchema | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse>, BasePath, CurrentPath>; +

, R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, M1 extends H = H, M2 extends H = H, M3 extends H = H>(path: P, ...handlers: [ + H & M1, + H & M2, + H & M3, + H + ]): HonoBase | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse, S, M, P, I4, BasePath>, BasePath, MergePath>; +

= any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, M1 extends H = H, M2 extends H = H, M3 extends H = H, M4 extends H = H, M5 extends H = H>(...handlers: [ + H & M1, + H & M2, + H & M3, + H & M4, + H & M5, + H + ]): HonoBase, S & ToSchema | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse>, BasePath, CurrentPath>; +

, R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, M1 extends H = H, M2 extends H = H, M3 extends H = H, M4 extends H = H>(path: P, ...handlers: [ + H & M1, + H & M2, + H & M3, + H & M4, + H + ]): HonoBase | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse, S, M, P, I5, BasePath>, BasePath, MergePath>; +

= any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, M1 extends H = H, M2 extends H = H, M3 extends H = H, M4 extends H = H, M5 extends H = H, M6 extends H = H>(...handlers: [ + H & M1, + H & M2, + H & M3, + H & M4, + H & M5, + H & M6, + H + ]): HonoBase, S & ToSchema | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse>, BasePath, CurrentPath>; +

, R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, M1 extends H = H, M2 extends H = H, M3 extends H = H, M4 extends H = H, M5 extends H = H>(path: P, ...handlers: [ + H & M1, + H & M2, + H & M3, + H & M4, + H & M5, + H + ]): HonoBase | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse, S, M, P, I6, BasePath>, BasePath, MergePath>; +

= any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, M1 extends H = H, M2 extends H = H, M3 extends H = H, M4 extends H = H, M5 extends H = H, M6 extends H = H, M7 extends H = H>(...handlers: [ + H & M1, + H & M2, + H & M3, + H & M4, + H & M5, + H & M6, + H & M7, + H + ]): HonoBase, S & ToSchema | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse>, BasePath, CurrentPath>; +

, R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, M1 extends H = H, M2 extends H = H, M3 extends H = H, M4 extends H = H, M5 extends H = H, M6 extends H = H>(path: P, ...handlers: [ + H & M1, + H & M2, + H & M3, + H & M4, + H & M5, + H & M6, + H + ]): HonoBase | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse, S, M, P, I7, BasePath>, BasePath, MergePath>; +

= any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7, I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>, M1 extends H = H, M2 extends H = H, M3 extends H = H, M4 extends H = H, M5 extends H = H, M6 extends H = H, M7 extends H = H, M8 extends H = H>(...handlers: [ + H & M1, + H & M2, + H & M3, + H & M4, + H & M5, + H & M6, + H & M7, + H & M8, + H + ]): HonoBase, S & ToSchema | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse>, BasePath, CurrentPath>; +

, R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, M1 extends H = H, M2 extends H = H, M3 extends H = H, M4 extends H = H, M5 extends H = H, M6 extends H = H, M7 extends H = H>(path: P, ...handlers: [ + H & M1, + H & M2, + H & M3, + H & M4, + H & M5, + H & M6, + H & M7, + H + ]): HonoBase | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse, S, M, P, I8, BasePath>, BasePath, MergePath>; +

= any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7, I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8, I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>, E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>, M1 extends H = H, M2 extends H = H, M3 extends H = H, M4 extends H = H, M5 extends H = H, M6 extends H = H, M7 extends H = H, M8 extends H = H, M9 extends H = H>(...handlers: [ + H & M1, + H & M2, + H & M3, + H & M4, + H & M5, + H & M6, + H & M7, + H & M8, + H & M9, + H + ]): HonoBase, S & ToSchema | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse>, BasePath, CurrentPath>; +

, R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7, I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>, M1 extends H = H, M2 extends H = H, M3 extends H = H, M4 extends H = H, M5 extends H = H, M6 extends H = H, M7 extends H = H, M8 extends H = H>(path: P, ...handlers: [ + H & M1, + H & M2, + H & M3, + H & M4, + H & M5, + H & M6, + H & M7, + H & M8, + H + ]): HonoBase | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse, S, M, P, I9, BasePath>, BasePath, MergePath>; +

, R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7, I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8, I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>, E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>, M1 extends H = H, M2 extends H = H, M3 extends H = H, M4 extends H = H, M5 extends H = H, M6 extends H = H, M7 extends H = H, M8 extends H = H, M9 extends H = H>(path: P, ...handlers: [ + H & M1, + H & M2, + H & M3, + H & M4, + H & M5, + H & M6, + H & M7, + H & M8, + H & M9, + H + ]): HonoBase | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse, S, M, P, I10, BasePath>, BasePath, MergePath>; +

= any>(...handlers: H[]): HonoBase>, BasePath, CurrentPath>; +

= any>(path: P, ...handlers: [H, I, R>, ...H, I, R>[]]): HonoBase, I, MergeTypedResponse>, BasePath, MergePath>; +

= any, I extends Input = BlankInput>(path: P): HonoBase, I, MergeTypedResponse>, BasePath, MergePath>; +} +export interface MiddlewareHandlerInterface { + (...handlers: MiddlewareHandler>[]): HonoBase, S, BasePath, MergePath>; + (handler: MiddlewareHandler>): HonoBase, S, BasePath, MergePath>; + , P extends string = MergePath>(...handlers: [MiddlewareHandler, MiddlewareHandler]): HonoBase, S, BasePath, P>; +

, E2 extends Env = E>(path: P, handler: MiddlewareHandler): HonoBase, S, BasePath, MergedPath>; + , E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, P extends string = MergePath>(...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, P>; +

, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>>(path: P, ...handlers: [MiddlewareHandler, MiddlewareHandler]): HonoBase, S, BasePath, MergedPath>; + , E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, P extends string = MergePath>(...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, P>; +

, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>>(path: P, ...handlers: [MiddlewareHandler, MiddlewareHandler, MiddlewareHandler]): HonoBase, S, BasePath, MergedPath>; + , E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, P extends string = MergePath>(...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, P>; +

, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>>(path: P, ...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, MergedPath>; + , E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, P extends string = MergePath>(...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, P>; +

, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>>(path: P, ...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, MergedPath>; + , E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, P extends string = MergePath>(...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, P>; +

, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>>(path: P, ...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, MergedPath>; + , E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, P extends string = MergePath>(...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, P>; +

, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>>(path: P, ...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, MergedPath>; + , E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>, P extends string = MergePath>(...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, P>; +

, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>>(path: P, ...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, MergedPath>; + , E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>, E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>, P extends string = MergePath>(...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, P>; +

, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>>(path: P, ...handlers: [ + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler, + MiddlewareHandler + ]): HonoBase, S, BasePath, MergedPath>; +

(path: P, ...handlers: MiddlewareHandler>[]): HonoBase>; +} +export interface OnHandlerInterface { + , R extends HandlerResponse = any, I extends Input = BlankInput, E2 extends Env = E>(method: M, path: P, handler: H): HonoBase, S & ToSchema, I, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>>(method: M, path: P, ...handlers: [H, H]): HonoBase, S & ToSchema, I2, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>>(method: M, path: P, ...handlers: [H, H, H]): HonoBase, S & ToSchema, I3, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>>(method: M, path: P, ...handlers: [ + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I4, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>>(method: M, path: P, ...handlers: [ + H, + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I5, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>>(method: M, path: P, ...handlers: [ + H, + H, + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I6, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>>(method: M, path: P, ...handlers: [ + H, + H, + H, + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I7, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>>(method: M, path: P, ...handlers: [ + H, + H, + H, + H, + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I8, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7, I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>>(method: M, path: P, ...handlers: [ + H, + H, + H, + H, + H, + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I9, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7, I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8, I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>, E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>>(method: M, path: P, ...handlers: [ + H, + H, + H, + H, + H, + H, + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I10, MergeTypedResponse>>, BasePath, MergePath>; + = any, I extends Input = BlankInput>(method: M, path: P, ...handlers: [H, I, R>, ...H, I, R>[]]): HonoBase, I, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, E2 extends Env = E>(methods: M[], path: P, handler: H): HonoBase, S & ToSchema, I, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>>(methods: M[], path: P, ...handlers: [H, H]): HonoBase, S & ToSchema, I2, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>>(methods: M[], path: P, ...handlers: [H, H, H]): HonoBase, S & ToSchema, I3, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>>(methods: M[], path: P, ...handlers: [ + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I4, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>>(methods: M[], path: P, ...handlers: [ + H, + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I5, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>>(methods: M[], path: P, ...handlers: [ + H, + H, + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I6, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>>(methods: M[], path: P, ...handlers: [ + H, + H, + H, + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I7, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>>(methods: M[], path: P, ...handlers: [ + H, + H, + H, + H, + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I8, MergeTypedResponse>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7, I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>>(methods: M[], path: P, ...handlers: [ + H, + H, + H, + H, + H, + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I9, MergeTypedResponse>>, BasePath, MergePath>; + , R extends HandlerResponse = any, I extends Input = BlankInput, I2 extends Input = I, I3 extends Input = I & I2, I4 extends Input = I & I2 & I3, I5 extends Input = I & I2 & I3 & I4, I6 extends Input = I & I2 & I3 & I4 & I5, I7 extends Input = I & I2 & I3 & I4 & I5 & I6, I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7, I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8, I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9, E2 extends Env = E, E3 extends Env = IntersectNonAnyTypes<[E, E2]>, E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>, E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>, E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>, E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>, E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>, E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>, E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>, E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>>(methods: M[], path: P, ...handlers: [ + H, + H, + H, + H, + H, + H, + H, + H, + H, + H + ]): HonoBase, S & ToSchema, I10, MergeTypedResponse>>, BasePath, MergePath>; + = any, I extends Input = BlankInput>(methods: M[], path: P, ...handlers: [H, I, R>, ...H, I, R>[]]): HonoBase, I, MergeTypedResponse>, BasePath, MergePath>; + = any, E2 extends Env = E>(methods: M | M[], paths: Ps, ...handlers: H, I, R>[]): HonoBase, I, MergeTypedResponse>, BasePath, Ps extends [...string[], infer LastPath extends string] ? MergePath : never>; +} +type ToSchemaOutput = RorO extends TypedResponse ? { + output: unknown extends T ? {} : T; + outputFormat: I extends { + outputFormat: string; + } ? I['outputFormat'] : F; + status: U; +} : { + output: unknown extends RorO ? {} : RorO; + outputFormat: unknown extends RorO ? 'json' : I extends { + outputFormat: string; + } ? I['outputFormat'] : 'json'; + status: StatusCode; +}; +export type ToSchema = IsAny extends true ? { + [K in P]: { + [K2 in M as AddDollar]: { + input: AddParam, P>; + output: {}; + outputFormat: ResponseFormat; + status: StatusCode; + }; + }; +} : [RorO] extends [never] ? {} : [RorO] extends [Promise] ? {} : { + [K in P]: { + [K2 in M as AddDollar]: Simplify<{ + input: AddParam, P>; + } & ToSchemaOutput>; + }; +}; +export type Schema = { + [Path: string]: { + [Method: `$${Lowercase}`]: Endpoint; + }; +}; +type AddSchemaIfHasResponse = [Merged] extends [Promise] ? S : S & ToSchema, I, Merged>; +export type Endpoint = { + input: any; + output: any; + outputFormat: ResponseFormat; + status: StatusCode; +}; +type ExtractParams = string extends Path ? Record : Path extends `${infer _Start}:${infer Param}/${infer Rest}` ? { + [K in Param | keyof ExtractParams<`/${Rest}`>]: string; +} : Path extends `${infer _Start}:${infer Param}` ? { + [K in Param]: string; +} : never; +type FlattenIfIntersect = T extends infer O ? { + [K in keyof O]: O[K]; +} : never; +export type MergeSchemaPath = { + [P in keyof OrigSchema as MergePath]: [OrigSchema[P]] extends [ + Record + ] ? { + [M in keyof OrigSchema[P]]: MergeEndpointParamsWithPath; + } : never; +}; +type MergeEndpointParamsWithPath = T extends unknown ? { + input: T['input'] extends { + param: infer _; + } ? ExtractParams extends never ? T['input'] : FlattenIfIntersect as K extends `${infer Prefix}{${infer _}}` ? Prefix : K]: string; + }; + }> : RemoveBlankRecord> extends never ? T['input'] : T['input'] & { + param: { + [K in keyof ExtractParams as K extends `${infer Prefix}{${infer _}}` ? Prefix : K]: string; + }; + }; + output: T['output']; + outputFormat: T['outputFormat']; + status: T['status']; +} : never; +export type AddParam = ParamKeys

extends never ? I : I extends { + param: infer _; +} ? I : I & { + param: UnionToIntersection>>; +}; +type AddDollar = `$${Lowercase}`; +export type MergePath = B extends '' ? MergePath : A extends '' ? B : A extends '/' ? B : A extends `${infer P}/` ? B extends `/${infer Q}` ? `${P}/${Q}` : `${P}/${B}` : B extends `/${infer Q}` ? Q extends '' ? A : `${A}/${Q}` : `${A}/${B}`; +export type KnownResponseFormat = 'json' | 'text' | 'redirect'; +export type ResponseFormat = KnownResponseFormat | string; +export type TypedResponse = { + _data: T; + _status: U; + _format: F; +}; +type MergeTypedResponse = T extends Promise ? T : T extends Promise ? T2 extends TypedResponse ? T2 : TypedResponse : T extends TypedResponse ? T : TypedResponse; +type ExtractTypedResponseOnly = T extends TypedResponse ? T : never; +type MergeMiddlewareResponse = T extends (c: any, next: any) => Promise ? Exclude extends never ? never : Exclude extends Response | TypedResponse ? ExtractTypedResponseOnly> : never : T extends (c: any, next: any) => infer R ? R extends Response | TypedResponse ? ExtractTypedResponseOnly : never : never; +export type FormValue = string | Blob; +export type ParsedFormValue = string | File; +export type ValidationTargets = { + json: any; + form: Record; + query: Record; + param: Record; + header: Record; + cookie: Record; +}; +type ParamKey = Component extends `:${infer NameWithPattern}` ? NameWithPattern extends `${infer Name}{${infer Rest}` ? Rest extends `${infer _Pattern}?` ? `${Name}?` : Name : NameWithPattern : never; +export type ParamKeys = Path extends `${infer Component}/${infer Rest}` ? ParamKey | ParamKeys : ParamKey; +export type ParamKeyToRecord = T extends `${infer R}?` ? Record : { + [K in T]: string; +}; +export type InputToDataByTarget = T extends { + [K in Target]: infer R; +} ? R : never; +export type RemoveQuestion = T extends `${infer R}?` ? R : T; +export type ExtractSchema = UnionToIntersection ? S : never>; +export type ExtractSchemaForStatusCode = { + [Path in keyof ExtractSchema]: { + [Method in keyof ExtractSchema[Path]]: Extract[Path][Method], { + status: Status; + }>; + }; +}; +export type ExtractHandlerResponse = T extends (c: any, next: any) => Promise ? Exclude extends never ? never : Exclude extends Response | TypedResponse ? Exclude : never : T extends (c: any, next: any) => infer R ? R extends Response | TypedResponse ? R : never : never; +type ProcessHead = IfAnyThenEmptyObject; +export type IntersectNonAnyTypes = T extends [infer Head, ...infer Rest] ? ProcessHead & IntersectNonAnyTypes : {}; +export declare abstract class FetchEventLike { + abstract readonly request: Request; + abstract respondWith(promise: Response | Promise): void; + abstract passThroughOnException(): void; + abstract waitUntil(promise: Promise): void; +} +export {}; diff --git a/node_modules/hono/dist/types/utils/accept.d.ts b/node_modules/hono/dist/types/utils/accept.d.ts new file mode 100644 index 000000000..75c37e89b --- /dev/null +++ b/node_modules/hono/dist/types/utils/accept.d.ts @@ -0,0 +1,11 @@ +export interface Accept { + type: string; + params: Record; + q: number; +} +/** + * Parse an Accept header into an array of objects with type, parameters, and quality score. + * @param acceptHeader The Accept header string + * @returns An array of parsed Accept values + */ +export declare const parseAccept: (acceptHeader: string) => Accept[]; diff --git a/node_modules/hono/dist/types/utils/basic-auth.d.ts b/node_modules/hono/dist/types/utils/basic-auth.d.ts new file mode 100644 index 000000000..4741a4eb1 --- /dev/null +++ b/node_modules/hono/dist/types/utils/basic-auth.d.ts @@ -0,0 +1,5 @@ +export type Auth = (req: Request) => { + username: string; + password: string; +} | undefined; +export declare const auth: Auth; diff --git a/node_modules/hono/dist/types/utils/body.d.ts b/node_modules/hono/dist/types/utils/body.d.ts new file mode 100644 index 000000000..5c37a1fa7 --- /dev/null +++ b/node_modules/hono/dist/types/utils/body.d.ts @@ -0,0 +1,79 @@ +/** + * @module + * Body utility. + */ +import { HonoRequest } from '../request'; +type BodyDataValueDot = { + [x: string]: string | File | BodyDataValueDot; +}; +type BodyDataValueDotAll = { + [x: string]: string | File | (string | File)[] | BodyDataValueDotAll; +}; +type SimplifyBodyData = { + [K in keyof T]: string | File | (string | File)[] | BodyDataValueDotAll extends T[K] ? string | File | (string | File)[] | BodyDataValueDotAll : string | File | BodyDataValueDot extends T[K] ? string | File | BodyDataValueDot : string | File | (string | File)[] extends T[K] ? string | File | (string | File)[] : string | File; +} & {}; +type BodyDataValueComponent = string | File | (T extends { + all: false; +} ? never : T extends { + all: true; +} | { + all: boolean; +} ? (string | File)[] : never); +type BodyDataValueObject = { + [key: string]: BodyDataValueComponent | BodyDataValueObject; +}; +type BodyDataValue = BodyDataValueComponent | (T extends { + dot: false; +} ? never : T extends { + dot: true; +} | { + dot: boolean; +} ? BodyDataValueObject : never); +export type BodyData = {}> = SimplifyBodyData>>; +export type ParseBodyOptions = { + /** + * Determines whether all fields with multiple values should be parsed as arrays. + * @default false + * @example + * const data = new FormData() + * data.append('file', 'aaa') + * data.append('file', 'bbb') + * data.append('message', 'hello') + * + * If all is false: + * parseBody should return { file: 'bbb', message: 'hello' } + * + * If all is true: + * parseBody should return { file: ['aaa', 'bbb'], message: 'hello' } + */ + all: boolean; + /** + * Determines whether all fields with dot notation should be parsed as nested objects. + * @default false + * @example + * const data = new FormData() + * data.append('obj.key1', 'value1') + * data.append('obj.key2', 'value2') + * + * If dot is false: + * parseBody should return { 'obj.key1': 'value1', 'obj.key2': 'value2' } + * + * If dot is true: + * parseBody should return { obj: { key1: 'value1', key2: 'value2' } } + */ + dot: boolean; +}; +/** + * Parses the body of a request based on the provided options. + * + * @template T - The type of the parsed body data. + * @param {HonoRequest | Request} request - The request object to parse. + * @param {Partial} [options] - Options for parsing the body. + * @returns {Promise} The parsed body data. + */ +interface ParseBody { + , T extends BodyData>(request: HonoRequest | Request, options?: Options): Promise; + (request: HonoRequest | Request, options?: Partial): Promise; +} +export declare const parseBody: ParseBody; +export {}; diff --git a/node_modules/hono/dist/types/utils/buffer.d.ts b/node_modules/hono/dist/types/utils/buffer.d.ts new file mode 100644 index 000000000..71396bc98 --- /dev/null +++ b/node_modules/hono/dist/types/utils/buffer.d.ts @@ -0,0 +1,8 @@ +/** + * @module + * Buffer utility. + */ +export declare const equal: (a: ArrayBuffer, b: ArrayBuffer) => boolean; +export declare const timingSafeEqual: (a: string | object | boolean, b: string | object | boolean, hashFunction?: Function) => Promise; +export declare const bufferToString: (buffer: ArrayBuffer) => string; +export declare const bufferToFormData: (arrayBuffer: ArrayBuffer, contentType: string) => Promise; diff --git a/node_modules/hono/dist/types/utils/color.d.ts b/node_modules/hono/dist/types/utils/color.d.ts new file mode 100644 index 000000000..f57d73980 --- /dev/null +++ b/node_modules/hono/dist/types/utils/color.d.ts @@ -0,0 +1,21 @@ +/** + * @module + * Color utility. + */ +/** + * Get whether color change on terminal is enabled or disabled. + * If `NO_COLOR` environment variable is set, this function returns `false`. + * Unlike getColorEnabledAsync(), this cannot check Cloudflare environment variables. + * @see {@link https://no-color.org/} + * + * @returns {boolean} + */ +export declare function getColorEnabled(): boolean; +/** + * Get whether color change on terminal is enabled or disabled. + * If `NO_COLOR` environment variable is set, this function returns `false`. + * @see {@link https://no-color.org/} + * + * @returns {boolean} + */ +export declare function getColorEnabledAsync(): Promise; diff --git a/node_modules/hono/dist/types/utils/compress.d.ts b/node_modules/hono/dist/types/utils/compress.d.ts new file mode 100644 index 000000000..01666b8ac --- /dev/null +++ b/node_modules/hono/dist/types/utils/compress.d.ts @@ -0,0 +1,8 @@ +/** + * @module + * Constants for compression. + */ +/** + * Match for compressible content type. + */ +export declare const COMPRESSIBLE_CONTENT_TYPE_REGEX: RegExp; diff --git a/node_modules/hono/dist/types/utils/concurrent.d.ts b/node_modules/hono/dist/types/utils/concurrent.d.ts new file mode 100644 index 000000000..24abe69e4 --- /dev/null +++ b/node_modules/hono/dist/types/utils/concurrent.d.ts @@ -0,0 +1,11 @@ +/** + * @module + * Concurrent utility. + */ +export interface Pool { + run(fn: () => T): Promise; +} +export declare const createPool: ({ concurrency, interval, }?: { + concurrency?: number; + interval?: number; +}) => Pool; diff --git a/node_modules/hono/dist/types/utils/constants.d.ts b/node_modules/hono/dist/types/utils/constants.d.ts new file mode 100644 index 000000000..733c0efe8 --- /dev/null +++ b/node_modules/hono/dist/types/utils/constants.d.ts @@ -0,0 +1,4 @@ +/** + * Constant used to mark a composed handler. + */ +export declare const COMPOSED_HANDLER = "__COMPOSED_HANDLER"; diff --git a/node_modules/hono/dist/types/utils/cookie.d.ts b/node_modules/hono/dist/types/utils/cookie.d.ts new file mode 100644 index 000000000..d6f75f964 --- /dev/null +++ b/node_modules/hono/dist/types/utils/cookie.d.ts @@ -0,0 +1,40 @@ +/** + * @module + * Cookie utility. + */ +export type Cookie = Record; +export type SignedCookie = Record; +type PartitionedCookieConstraint = { + partitioned: true; + secure: true; +} | { + partitioned?: boolean; + secure?: boolean; +}; +type SecureCookieConstraint = { + secure: true; +}; +type HostCookieConstraint = { + secure: true; + path: '/'; + domain?: undefined; +}; +export type CookieOptions = { + domain?: string; + expires?: Date; + httpOnly?: boolean; + maxAge?: number; + path?: string; + secure?: boolean; + sameSite?: 'Strict' | 'Lax' | 'None' | 'strict' | 'lax' | 'none'; + partitioned?: boolean; + priority?: 'Low' | 'Medium' | 'High' | 'low' | 'medium' | 'high'; + prefix?: CookiePrefixOptions; +} & PartitionedCookieConstraint; +export type CookiePrefixOptions = 'host' | 'secure'; +export type CookieConstraint = Name extends `__Secure-${string}` ? CookieOptions & SecureCookieConstraint : Name extends `__Host-${string}` ? CookieOptions & HostCookieConstraint : CookieOptions; +export declare const parse: (cookie: string, name?: string) => Cookie; +export declare const parseSigned: (cookie: string, secret: string | BufferSource, name?: string) => Promise; +export declare const serialize: (name: Name, value: string, opt?: CookieConstraint) => string; +export declare const serializeSigned: (name: string, value: string, secret: string | BufferSource, opt?: CookieOptions) => Promise; +export {}; diff --git a/node_modules/hono/dist/types/utils/crypto.d.ts b/node_modules/hono/dist/types/utils/crypto.d.ts new file mode 100644 index 000000000..597428602 --- /dev/null +++ b/node_modules/hono/dist/types/utils/crypto.d.ts @@ -0,0 +1,15 @@ +/** + * @module + * Crypto utility. + */ +import type { JSONValue } from './types'; +type Algorithm = { + name: string; + alias: string; +}; +type Data = string | boolean | number | JSONValue | ArrayBufferView | ArrayBuffer; +export declare const sha256: (data: Data) => Promise; +export declare const sha1: (data: Data) => Promise; +export declare const md5: (data: Data) => Promise; +export declare const createHash: (data: Data, algorithm: Algorithm) => Promise; +export {}; diff --git a/node_modules/hono/dist/types/utils/encode.d.ts b/node_modules/hono/dist/types/utils/encode.d.ts new file mode 100644 index 000000000..c60d6e79e --- /dev/null +++ b/node_modules/hono/dist/types/utils/encode.d.ts @@ -0,0 +1,8 @@ +/** + * @module + * Encode utility. + */ +export declare const decodeBase64Url: (str: string) => Uint8Array; +export declare const encodeBase64Url: (buf: ArrayBufferLike) => string; +export declare const encodeBase64: (buf: ArrayBufferLike) => string; +export declare const decodeBase64: (str: string) => Uint8Array; diff --git a/node_modules/hono/dist/types/utils/filepath.d.ts b/node_modules/hono/dist/types/utils/filepath.d.ts new file mode 100644 index 000000000..b26692540 --- /dev/null +++ b/node_modules/hono/dist/types/utils/filepath.d.ts @@ -0,0 +1,12 @@ +/** + * @module + * FilePath utility. + */ +type FilePathOptions = { + filename: string; + root?: string; + defaultDocument?: string; +}; +export declare const getFilePath: (options: FilePathOptions) => string | undefined; +export declare const getFilePathWithoutDefaultDocument: (options: Omit) => string | undefined; +export {}; diff --git a/node_modules/hono/dist/types/utils/handler.d.ts b/node_modules/hono/dist/types/utils/handler.d.ts new file mode 100644 index 000000000..6b593c5a6 --- /dev/null +++ b/node_modules/hono/dist/types/utils/handler.d.ts @@ -0,0 +1,6 @@ +/** + * @module + * Handler utility. + */ +export declare const isMiddleware: (handler: Function) => boolean; +export declare const findTargetHandler: (handler: Function) => Function; diff --git a/node_modules/hono/dist/types/utils/headers.d.ts b/node_modules/hono/dist/types/utils/headers.d.ts new file mode 100644 index 000000000..0c1bc9cec --- /dev/null +++ b/node_modules/hono/dist/types/utils/headers.d.ts @@ -0,0 +1,8 @@ +/** + * @module + * HTTP Headers utility. + */ +export type RequestHeader = 'A-IM' | 'Accept' | 'Accept-Additions' | 'Accept-CH' | 'Accept-Charset' | 'Accept-Datetime' | 'Accept-Encoding' | 'Accept-Features' | 'Accept-Language' | 'Accept-Patch' | 'Accept-Post' | 'Accept-Ranges' | 'Accept-Signature' | 'Access-Control' | 'Access-Control-Allow-Credentials' | 'Access-Control-Allow-Headers' | 'Access-Control-Allow-Methods' | 'Access-Control-Allow-Origin' | 'Access-Control-Expose-Headers' | 'Access-Control-Max-Age' | 'Access-Control-Request-Headers' | 'Access-Control-Request-Method' | 'Age' | 'Allow' | 'ALPN' | 'Alt-Svc' | 'Alt-Used' | 'Alternates' | 'AMP-Cache-Transform' | 'Apply-To-Redirect-Ref' | 'Authentication-Control' | 'Authentication-Info' | 'Authorization' | 'Available-Dictionary' | 'C-Ext' | 'C-Man' | 'C-Opt' | 'C-PEP' | 'C-PEP-Info' | 'Cache-Control' | 'Cache-Status' | 'Cal-Managed-ID' | 'CalDAV-Timezones' | 'Capsule-Protocol' | 'CDN-Cache-Control' | 'CDN-Loop' | 'Cert-Not-After' | 'Cert-Not-Before' | 'Clear-Site-Data' | 'Client-Cert' | 'Client-Cert-Chain' | 'Close' | 'CMCD-Object' | 'CMCD-Request' | 'CMCD-Session' | 'CMCD-Status' | 'CMSD-Dynamic' | 'CMSD-Static' | 'Concealed-Auth-Export' | 'Configuration-Context' | 'Connection' | 'Content-Base' | 'Content-Digest' | 'Content-Disposition' | 'Content-Encoding' | 'Content-ID' | 'Content-Language' | 'Content-Length' | 'Content-Location' | 'Content-MD5' | 'Content-Range' | 'Content-Script-Type' | 'Content-Security-Policy' | 'Content-Security-Policy-Report-Only' | 'Content-Style-Type' | 'Content-Type' | 'Content-Version' | 'Cookie' | 'Cookie2' | 'Cross-Origin-Embedder-Policy' | 'Cross-Origin-Embedder-Policy-Report-Only' | 'Cross-Origin-Opener-Policy' | 'Cross-Origin-Opener-Policy-Report-Only' | 'Cross-Origin-Resource-Policy' | 'CTA-Common-Access-Token' | 'DASL' | 'Date' | 'DAV' | 'Default-Style' | 'Delta-Base' | 'Deprecation' | 'Depth' | 'Derived-From' | 'Destination' | 'Differential-ID' | 'Dictionary-ID' | 'Digest' | 'DPoP' | 'DPoP-Nonce' | 'Early-Data' | 'EDIINT-Features' | 'ETag' | 'Expect' | 'Expect-CT' | 'Expires' | 'Ext' | 'Forwarded' | 'From' | 'GetProfile' | 'Hobareg' | 'Host' | 'HTTP2-Settings' | 'If' | 'If-Match' | 'If-Modified-Since' | 'If-None-Match' | 'If-Range' | 'If-Schedule-Tag-Match' | 'If-Unmodified-Since' | 'IM' | 'Include-Referred-Token-Binding-ID' | 'Isolation' | 'Keep-Alive' | 'Label' | 'Last-Event-ID' | 'Last-Modified' | 'Link' | 'Link-Template' | 'Location' | 'Lock-Token' | 'Man' | 'Max-Forwards' | 'Memento-Datetime' | 'Meter' | 'Method-Check' | 'Method-Check-Expires' | 'MIME-Version' | 'Negotiate' | 'NEL' | 'OData-EntityId' | 'OData-Isolation' | 'OData-MaxVersion' | 'OData-Version' | 'Opt' | 'Optional-WWW-Authenticate' | 'Ordering-Type' | 'Origin' | 'Origin-Agent-Cluster' | 'OSCORE' | 'OSLC-Core-Version' | 'Overwrite' | 'P3P' | 'PEP' | 'PEP-Info' | 'Permissions-Policy' | 'PICS-Label' | 'Ping-From' | 'Ping-To' | 'Position' | 'Pragma' | 'Prefer' | 'Preference-Applied' | 'Priority' | 'ProfileObject' | 'Protocol' | 'Protocol-Info' | 'Protocol-Query' | 'Protocol-Request' | 'Proxy-Authenticate' | 'Proxy-Authentication-Info' | 'Proxy-Authorization' | 'Proxy-Features' | 'Proxy-Instruction' | 'Proxy-Status' | 'Public' | 'Public-Key-Pins' | 'Public-Key-Pins-Report-Only' | 'Range' | 'Redirect-Ref' | 'Referer' | 'Referer-Root' | 'Referrer-Policy' | 'Refresh' | 'Repeatability-Client-ID' | 'Repeatability-First-Sent' | 'Repeatability-Request-ID' | 'Repeatability-Result' | 'Replay-Nonce' | 'Reporting-Endpoints' | 'Repr-Digest' | 'Retry-After' | 'Safe' | 'Schedule-Reply' | 'Schedule-Tag' | 'Sec-GPC' | 'Sec-Purpose' | 'Sec-Token-Binding' | 'Sec-WebSocket-Accept' | 'Sec-WebSocket-Extensions' | 'Sec-WebSocket-Key' | 'Sec-WebSocket-Protocol' | 'Sec-WebSocket-Version' | 'Security-Scheme' | 'Server' | 'Server-Timing' | 'Set-Cookie' | 'Set-Cookie2' | 'SetProfile' | 'Signature' | 'Signature-Input' | 'SLUG' | 'SoapAction' | 'Status-URI' | 'Strict-Transport-Security' | 'Sunset' | 'Surrogate-Capability' | 'Surrogate-Control' | 'TCN' | 'TE' | 'Timeout' | 'Timing-Allow-Origin' | 'Topic' | 'Traceparent' | 'Tracestate' | 'Trailer' | 'Transfer-Encoding' | 'TTL' | 'Upgrade' | 'Urgency' | 'URI' | 'Use-As-Dictionary' | 'User-Agent' | 'Variant-Vary' | 'Vary' | 'Via' | 'Want-Content-Digest' | 'Want-Digest' | 'Want-Repr-Digest' | 'Warning' | 'WWW-Authenticate' | 'X-Content-Type-Options' | 'X-Frame-Options'; +export type ResponseHeader = 'Access-Control-Allow-Credentials' | 'Access-Control-Allow-Headers' | 'Access-Control-Allow-Methods' | 'Access-Control-Allow-Origin' | 'Access-Control-Expose-Headers' | 'Access-Control-Max-Age' | 'Age' | 'Allow' | 'Cache-Control' | 'Clear-Site-Data' | 'Content-Disposition' | 'Content-Encoding' | 'Content-Language' | 'Content-Length' | 'Content-Location' | 'Content-Range' | 'Content-Security-Policy' | 'Content-Security-Policy-Report-Only' | 'Content-Type' | 'Cookie' | 'Cross-Origin-Embedder-Policy' | 'Cross-Origin-Opener-Policy' | 'Cross-Origin-Resource-Policy' | 'Date' | 'ETag' | 'Expires' | 'Last-Modified' | 'Location' | 'Permissions-Policy' | 'Pragma' | 'Retry-After' | 'Save-Data' | 'Sec-CH-Prefers-Color-Scheme' | 'Sec-CH-Prefers-Reduced-Motion' | 'Sec-CH-UA' | 'Sec-CH-UA-Arch' | 'Sec-CH-UA-Bitness' | 'Sec-CH-UA-Form-Factor' | 'Sec-CH-UA-Full-Version' | 'Sec-CH-UA-Full-Version-List' | 'Sec-CH-UA-Mobile' | 'Sec-CH-UA-Model' | 'Sec-CH-UA-Platform' | 'Sec-CH-UA-Platform-Version' | 'Sec-CH-UA-WoW64' | 'Sec-Fetch-Dest' | 'Sec-Fetch-Mode' | 'Sec-Fetch-Site' | 'Sec-Fetch-User' | 'Sec-GPC' | 'Server' | 'Server-Timing' | 'Service-Worker-Navigation-Preload' | 'Set-Cookie' | 'Strict-Transport-Security' | 'Timing-Allow-Origin' | 'Trailer' | 'Transfer-Encoding' | 'Upgrade' | 'Vary' | 'WWW-Authenticate' | 'Warning' | 'X-Content-Type-Options' | 'X-DNS-Prefetch-Control' | 'X-Frame-Options' | 'X-Permitted-Cross-Domain-Policies' | 'X-Powered-By' | 'X-Robots-Tag' | 'X-XSS-Protection'; +export type AcceptHeader = 'Accept' | 'Accept-Charset' | 'Accept-Encoding' | 'Accept-Language' | 'Accept-Patch' | 'Accept-Post' | 'Accept-Ranges'; +export type CustomHeader = string & {}; diff --git a/node_modules/hono/dist/types/utils/html.d.ts b/node_modules/hono/dist/types/utils/html.d.ts new file mode 100644 index 000000000..35475cb60 --- /dev/null +++ b/node_modules/hono/dist/types/utils/html.d.ts @@ -0,0 +1,44 @@ +/** + * @module + * HTML utility. + */ +export declare const HtmlEscapedCallbackPhase: { + readonly Stringify: 1; + readonly BeforeStream: 2; + readonly Stream: 3; +}; +type HtmlEscapedCallbackOpts = { + buffer?: [string]; + phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase]; + context: Readonly; +}; +export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise | undefined; +export type HtmlEscaped = { + isEscaped: true; + callbacks?: HtmlEscapedCallback[]; +}; +export type HtmlEscapedString = string & HtmlEscaped; +/** + * StringBuffer contains string and Promise alternately + * The length of the array will be odd, the odd numbered element will be a string, + * and the even numbered element will be a Promise. + * When concatenating into a single string, it must be processed from the tail. + * @example + * [ + * 'framework.', + * Promise.resolve('ultra fast'), + * 'a ', + * Promise.resolve('is '), + * 'Hono', + * ] + */ +export type StringBuffer = (string | Promise)[]; +export type StringBufferWithCallbacks = StringBuffer & { + callbacks: HtmlEscapedCallback[]; +}; +export declare const raw: (value: unknown, callbacks?: HtmlEscapedCallback[]) => HtmlEscapedString; +export declare const stringBufferToString: (buffer: StringBuffer, callbacks: HtmlEscapedCallback[] | undefined) => Promise; +export declare const escapeToBuffer: (str: string, buffer: StringBuffer) => void; +export declare const resolveCallbackSync: (str: string | HtmlEscapedString) => string; +export declare const resolveCallback: (str: string | HtmlEscapedString | Promise, phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase], preserveCallbacks: boolean, context: object, buffer?: [string]) => Promise; +export {}; diff --git a/node_modules/hono/dist/types/utils/http-status.d.ts b/node_modules/hono/dist/types/utils/http-status.d.ts new file mode 100644 index 000000000..f0cb67cc1 --- /dev/null +++ b/node_modules/hono/dist/types/utils/http-status.d.ts @@ -0,0 +1,32 @@ +/** + * @module + * HTTP Status utility. + */ +export type InfoStatusCode = 100 | 101 | 102 | 103; +export type SuccessStatusCode = 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 226; +export type DeprecatedStatusCode = 305 | 306; +export type RedirectStatusCode = 300 | 301 | 302 | 303 | 304 | DeprecatedStatusCode | 307 | 308; +export type ClientErrorStatusCode = 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451; +export type ServerErrorStatusCode = 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511; +/** + * `UnofficialStatusCode` can be used to specify an unofficial status code. + * @example + * + * ```ts + * app.get('/unknown', (c) => { + * return c.text("Unknown Error", 520 as UnofficialStatusCode) + * }) + * ``` + */ +export type UnofficialStatusCode = -1; +/** + * @deprecated + * Use `UnofficialStatusCode` instead. + */ +export type UnOfficalStatusCode = UnofficialStatusCode; +/** + * If you want to use an unofficial status, use `UnofficialStatusCode`. + */ +export type StatusCode = InfoStatusCode | SuccessStatusCode | RedirectStatusCode | ClientErrorStatusCode | ServerErrorStatusCode | UnofficialStatusCode; +export type ContentlessStatusCode = 101 | 204 | 205 | 304; +export type ContentfulStatusCode = Exclude; diff --git a/node_modules/hono/dist/types/utils/ipaddr.d.ts b/node_modules/hono/dist/types/utils/ipaddr.d.ts new file mode 100644 index 000000000..ae97e71dd --- /dev/null +++ b/node_modules/hono/dist/types/utils/ipaddr.d.ts @@ -0,0 +1,40 @@ +/** + * Utils for IP Addresses + * @module + */ +import type { AddressType } from '../helper/conninfo'; +/** + * Expand IPv6 Address + * @param ipV6 Shorten IPv6 Address + * @return expanded IPv6 Address + */ +export declare const expandIPv6: (ipV6: string) => string; +/** + * Distinct Remote Addr + * @param remoteAddr Remote Addr + */ +export declare const distinctRemoteAddr: (remoteAddr: string) => AddressType; +/** + * Convert IPv4 to Uint8Array + * @param ipv4 IPv4 Address + * @returns BigInt + */ +export declare const convertIPv4ToBinary: (ipv4: string) => bigint; +/** + * Convert IPv6 to Uint8Array + * @param ipv6 IPv6 Address + * @returns BigInt + */ +export declare const convertIPv6ToBinary: (ipv6: string) => bigint; +/** + * Convert a binary representation of an IPv4 address to a string. + * @param ipV4 binary IPv4 Address + * @return IPv4 Address in string + */ +export declare const convertIPv4BinaryToString: (ipV4: bigint) => string; +/** + * Convert a binary representation of an IPv6 address to a string. + * @param ipV6 binary IPv6 Address + * @return normalized IPv6 Address in string + */ +export declare const convertIPv6BinaryToString: (ipV6: bigint) => string; diff --git a/node_modules/hono/dist/types/utils/jwt/index.d.ts b/node_modules/hono/dist/types/utils/jwt/index.d.ts new file mode 100644 index 000000000..5d8931048 --- /dev/null +++ b/node_modules/hono/dist/types/utils/jwt/index.d.ts @@ -0,0 +1,18 @@ +/** + * @module + * JWT utility. + */ +export declare const Jwt: { + sign: (payload: import("./types").JWTPayload, privateKey: import("./jws").SignatureKey, alg?: import("./jwa").SignatureAlgorithm) => Promise; + verify: (token: string, publicKey: import("./jws").SignatureKey, algOrOptions: import("./jwa").SignatureAlgorithm | import("./jwt").VerifyOptionsWithAlg) => Promise; + decode: (token: string) => { + header: import("./jwt").TokenHeader; + payload: import("./types").JWTPayload; + }; + verifyWithJwks: (token: string, options: { + keys?: import("./jws").HonoJsonWebKey[]; + jwks_uri?: string; + verification?: import("./jwt").VerifyOptions; + allowedAlgorithms: readonly import("./jwa").AsymmetricAlgorithm[]; + }, init?: RequestInit) => Promise; +}; diff --git a/node_modules/hono/dist/types/utils/jwt/jwa.d.ts b/node_modules/hono/dist/types/utils/jwt/jwa.d.ts new file mode 100644 index 000000000..72b51f4bd --- /dev/null +++ b/node_modules/hono/dist/types/utils/jwt/jwa.d.ts @@ -0,0 +1,23 @@ +/** + * @module + * JSON Web Algorithms (JWA) + * https://datatracker.ietf.org/doc/html/rfc7518 + */ +export declare enum AlgorithmTypes { + HS256 = "HS256", + HS384 = "HS384", + HS512 = "HS512", + RS256 = "RS256", + RS384 = "RS384", + RS512 = "RS512", + PS256 = "PS256", + PS384 = "PS384", + PS512 = "PS512", + ES256 = "ES256", + ES384 = "ES384", + ES512 = "ES512", + EdDSA = "EdDSA" +} +export type SignatureAlgorithm = keyof typeof AlgorithmTypes; +export type SymmetricAlgorithm = 'HS256' | 'HS384' | 'HS512'; +export type AsymmetricAlgorithm = 'RS256' | 'RS384' | 'RS512' | 'PS256' | 'PS384' | 'PS512' | 'ES256' | 'ES384' | 'ES512' | 'EdDSA'; diff --git a/node_modules/hono/dist/types/utils/jwt/jws.d.ts b/node_modules/hono/dist/types/utils/jwt/jws.d.ts new file mode 100644 index 000000000..63605f67b --- /dev/null +++ b/node_modules/hono/dist/types/utils/jwt/jws.d.ts @@ -0,0 +1,12 @@ +/** + * @module + * JSON Web Signature (JWS) + * https://datatracker.ietf.org/doc/html/rfc7515 + */ +import type { SignatureAlgorithm } from './jwa'; +export interface HonoJsonWebKey extends JsonWebKey { + kid?: string; +} +export type SignatureKey = string | HonoJsonWebKey | CryptoKey; +export declare function signing(privateKey: SignatureKey, alg: SignatureAlgorithm, data: BufferSource): Promise; +export declare function verifying(publicKey: SignatureKey, alg: SignatureAlgorithm, signature: BufferSource, data: BufferSource): Promise; diff --git a/node_modules/hono/dist/types/utils/jwt/jwt.d.ts b/node_modules/hono/dist/types/utils/jwt/jwt.d.ts new file mode 100644 index 000000000..e8fed89b2 --- /dev/null +++ b/node_modules/hono/dist/types/utils/jwt/jwt.d.ts @@ -0,0 +1,43 @@ +/** + * @module + * JSON Web Token (JWT) + * https://datatracker.ietf.org/doc/html/rfc7519 + */ +import type { AsymmetricAlgorithm, SignatureAlgorithm } from './jwa'; +import type { HonoJsonWebKey, SignatureKey } from './jws'; +import type { JWTPayload } from './types'; +export interface TokenHeader { + alg: SignatureAlgorithm; + typ?: 'JWT'; + kid?: string; +} +export declare function isTokenHeader(obj: unknown): obj is TokenHeader; +export declare const sign: (payload: JWTPayload, privateKey: SignatureKey, alg?: SignatureAlgorithm) => Promise; +export type VerifyOptions = { + /** The expected issuer used for verifying the token */ + iss?: string | RegExp; + /** Verify the `nbf` claim (default: `true`) */ + nbf?: boolean; + /** Verify the `exp` claim (default: `true`) */ + exp?: boolean; + /** Verify the `iat` claim (default: `true`) */ + iat?: boolean; + /** Acceptable audience(s) for the token */ + aud?: string | string[] | RegExp; +}; +export type VerifyOptionsWithAlg = { + /** The algorithm used for decoding the token */ + alg: SignatureAlgorithm; +} & VerifyOptions; +export declare const verify: (token: string, publicKey: SignatureKey, algOrOptions: SignatureAlgorithm | VerifyOptionsWithAlg) => Promise; +export declare const verifyWithJwks: (token: string, options: { + keys?: HonoJsonWebKey[]; + jwks_uri?: string; + verification?: VerifyOptions; + allowedAlgorithms: readonly AsymmetricAlgorithm[]; +}, init?: RequestInit) => Promise; +export declare const decode: (token: string) => { + header: TokenHeader; + payload: JWTPayload; +}; +export declare const decodeHeader: (token: string) => TokenHeader; diff --git a/node_modules/hono/dist/types/utils/jwt/types.d.ts b/node_modules/hono/dist/types/utils/jwt/types.d.ts new file mode 100644 index 000000000..d5ccf8573 --- /dev/null +++ b/node_modules/hono/dist/types/utils/jwt/types.d.ts @@ -0,0 +1,86 @@ +/** + * @module + * Type definitions for JWT utilities. + */ +export declare class JwtAlgorithmNotImplemented extends Error { + constructor(alg: string); +} +export declare class JwtAlgorithmRequired extends Error { + constructor(); +} +export declare class JwtAlgorithmMismatch extends Error { + constructor(expected: string, actual: string); +} +export declare class JwtTokenInvalid extends Error { + constructor(token: string); +} +export declare class JwtTokenNotBefore extends Error { + constructor(token: string); +} +export declare class JwtTokenExpired extends Error { + constructor(token: string); +} +export declare class JwtTokenIssuedAt extends Error { + constructor(currentTimestamp: number, iat: number); +} +export declare class JwtTokenIssuer extends Error { + constructor(expected: string | RegExp, iss: string | null); +} +export declare class JwtHeaderInvalid extends Error { + constructor(header: object); +} +export declare class JwtHeaderRequiresKid extends Error { + constructor(header: object); +} +export declare class JwtSymmetricAlgorithmNotAllowed extends Error { + constructor(alg: string); +} +export declare class JwtAlgorithmNotAllowed extends Error { + constructor(alg: string, allowedAlgorithms: readonly string[]); +} +export declare class JwtTokenSignatureMismatched extends Error { + constructor(token: string); +} +export declare class JwtPayloadRequiresAud extends Error { + constructor(payload: object); +} +export declare class JwtTokenAudience extends Error { + constructor(expected: string | string[] | RegExp, aud: string | string[]); +} +export declare enum CryptoKeyUsage { + Encrypt = "encrypt", + Decrypt = "decrypt", + Sign = "sign", + Verify = "verify", + DeriveKey = "deriveKey", + DeriveBits = "deriveBits", + WrapKey = "wrapKey", + UnwrapKey = "unwrapKey" +} +/** + * JWT Payload + */ +export type JWTPayload = { + [key: string]: unknown; + /** + * The token is checked to ensure it has not expired. + */ + exp?: number; + /** + * The token is checked to ensure it is not being used before a specified time. + */ + nbf?: number; + /** + * The token is checked to ensure it is not issued in the future. + */ + iat?: number; + /** + * The token is checked to ensure it has been issued by a trusted issuer. + */ + iss?: string; + /** + * The token is checked to ensure it is intended for a specific audience. + */ + aud?: string | string[]; +}; +export type { HonoJsonWebKey } from './jws'; diff --git a/node_modules/hono/dist/types/utils/jwt/utf8.d.ts b/node_modules/hono/dist/types/utils/jwt/utf8.d.ts new file mode 100644 index 000000000..ff9fc1ce9 --- /dev/null +++ b/node_modules/hono/dist/types/utils/jwt/utf8.d.ts @@ -0,0 +1,6 @@ +/** + * @module + * Functions for encoding/decoding UTF8. + */ +export declare const utf8Encoder: TextEncoder; +export declare const utf8Decoder: TextDecoder; diff --git a/node_modules/hono/dist/types/utils/mime.d.ts b/node_modules/hono/dist/types/utils/mime.d.ts new file mode 100644 index 000000000..b83bcecb2 --- /dev/null +++ b/node_modules/hono/dist/types/utils/mime.d.ts @@ -0,0 +1,70 @@ +/** + * @module + * MIME utility. + */ +export declare const getMimeType: (filename: string, mimes?: Record) => string | undefined; +export declare const getExtension: (mimeType: string) => string | undefined; +export { baseMimes as mimes }; +/** + * Union types for BaseMime + */ +export type BaseMime = (typeof _baseMimes)[keyof typeof _baseMimes]; +declare const _baseMimes: { + readonly aac: "audio/aac"; + readonly avi: "video/x-msvideo"; + readonly avif: "image/avif"; + readonly av1: "video/av1"; + readonly bin: "application/octet-stream"; + readonly bmp: "image/bmp"; + readonly css: "text/css"; + readonly csv: "text/csv"; + readonly eot: "application/vnd.ms-fontobject"; + readonly epub: "application/epub+zip"; + readonly gif: "image/gif"; + readonly gz: "application/gzip"; + readonly htm: "text/html"; + readonly html: "text/html"; + readonly ico: "image/x-icon"; + readonly ics: "text/calendar"; + readonly jpeg: "image/jpeg"; + readonly jpg: "image/jpeg"; + readonly js: "text/javascript"; + readonly json: "application/json"; + readonly jsonld: "application/ld+json"; + readonly map: "application/json"; + readonly mid: "audio/x-midi"; + readonly midi: "audio/x-midi"; + readonly mjs: "text/javascript"; + readonly mp3: "audio/mpeg"; + readonly mp4: "video/mp4"; + readonly mpeg: "video/mpeg"; + readonly oga: "audio/ogg"; + readonly ogv: "video/ogg"; + readonly ogx: "application/ogg"; + readonly opus: "audio/opus"; + readonly otf: "font/otf"; + readonly pdf: "application/pdf"; + readonly png: "image/png"; + readonly rtf: "application/rtf"; + readonly svg: "image/svg+xml"; + readonly tif: "image/tiff"; + readonly tiff: "image/tiff"; + readonly ts: "video/mp2t"; + readonly ttf: "font/ttf"; + readonly txt: "text/plain"; + readonly wasm: "application/wasm"; + readonly webm: "video/webm"; + readonly weba: "audio/webm"; + readonly webmanifest: "application/manifest+json"; + readonly webp: "image/webp"; + readonly woff: "font/woff"; + readonly woff2: "font/woff2"; + readonly xhtml: "application/xhtml+xml"; + readonly xml: "application/xml"; + readonly zip: "application/zip"; + readonly '3gp': "video/3gpp"; + readonly '3g2': "video/3gpp2"; + readonly gltf: "model/gltf+json"; + readonly glb: "model/gltf-binary"; +}; +declare const baseMimes: Record; diff --git a/node_modules/hono/dist/types/utils/stream.d.ts b/node_modules/hono/dist/types/utils/stream.d.ts new file mode 100644 index 000000000..51c46e6e3 --- /dev/null +++ b/node_modules/hono/dist/types/utils/stream.d.ts @@ -0,0 +1,31 @@ +/** + * @module + * Stream utility. + */ +export declare class StreamingApi { + private writer; + private encoder; + private writable; + private abortSubscribers; + responseReadable: ReadableStream; + /** + * Whether the stream has been aborted. + */ + aborted: boolean; + /** + * Whether the stream has been closed normally. + */ + closed: boolean; + constructor(writable: WritableStream, _readable: ReadableStream); + write(input: Uint8Array | string): Promise; + writeln(input: string): Promise; + sleep(ms: number): Promise; + close(): Promise; + pipe(body: ReadableStream): Promise; + onAbort(listener: () => void | Promise): void; + /** + * Abort the stream. + * You can call this method when stream is aborted by external event. + */ + abort(): void; +} diff --git a/node_modules/hono/dist/types/utils/types.d.ts b/node_modules/hono/dist/types/utils/types.d.ts new file mode 100644 index 000000000..8dce20d92 --- /dev/null +++ b/node_modules/hono/dist/types/utils/types.d.ts @@ -0,0 +1,74 @@ +/** + * @module + * Types utility. + */ +export type Expect = T; +export type Equal = (() => T extends X ? 1 : 2) extends () => T extends Y ? 1 : 2 ? true : false; +export type NotEqual = true extends Equal ? false : true; +export type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; +export type RemoveBlankRecord = T extends Record ? (K extends string ? T : never) : never; +export type IfAnyThenEmptyObject = 0 extends 1 & T ? {} : T; +export type JSONPrimitive = string | boolean | number | null; +export type JSONArray = (JSONPrimitive | JSONObject | JSONArray)[]; +export type JSONObject = { + [key: string]: JSONPrimitive | JSONArray | JSONObject | object | InvalidJSONValue; +}; +export type InvalidJSONValue = undefined | symbol | ((...args: unknown[]) => unknown); +type InvalidToNull = T extends InvalidJSONValue ? null : T; +type IsInvalid = T extends InvalidJSONValue ? true : false; +/** + * symbol keys are omitted through `JSON.stringify` + */ +type OmitSymbolKeys = { + [K in keyof T as K extends symbol ? never : K]: T[K]; +}; +export type JSONValue = JSONObject | JSONArray | JSONPrimitive; +/** + * Convert a type to a JSON-compatible type. + * + * Non-JSON values such as `Date` implement `.toJSON()`, + * so they can be transformed to a value assignable to `JSONObject` + * + * `JSON.stringify()` throws a `TypeError` when it encounters a `bigint` value, + * unless a custom `replacer` function or `.toJSON()` method is provided. + * + * This behaviour can be controlled by the `TError` generic type parameter, + * which defaults to `bigint | ReadonlyArray`. + * You can set it to `never` to disable this check. + */ +export type JSONParsed> = T extends { + toJSON(): infer J; +} ? (() => J) extends () => JSONPrimitive ? J : (() => J) extends () => { + toJSON(): unknown; +} ? {} : JSONParsed : T extends JSONPrimitive ? T : T extends InvalidJSONValue ? never : T extends ReadonlyArray ? { + [K in keyof T]: JSONParsed, TError>; +} : T extends Set | Map | Record ? {} : T extends object ? T[keyof T] extends TError ? never : { + [K in keyof OmitSymbolKeys as IsInvalid extends true ? never : K]: boolean extends IsInvalid ? JSONParsed | undefined : JSONParsed; +} : T extends unknown ? T extends TError ? never : JSONValue : never; +/** + * Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability. + * @copyright from sindresorhus/type-fest + */ +export type Simplify = { + [KeyType in keyof T]: T[KeyType]; +} & {}; +/** + * A simple extension of Simplify that will deeply traverse array elements. + */ +export type SimplifyDeepArray = T extends any[] ? { + [E in keyof T]: SimplifyDeepArray; +} : Simplify; +export type InterfaceToType = T extends Function ? T : { + [K in keyof T]: InterfaceToType; +}; +export type RequiredKeysOf = Exclude<{ + [Key in keyof BaseType]: BaseType extends Record ? Key : never; +}[keyof BaseType], undefined>; +export type HasRequiredKeys = RequiredKeysOf extends never ? false : true; +export type IsAny = boolean extends (T extends never ? true : false) ? true : false; +/** + * String literal types with auto-completion + * @see https://github.com/Microsoft/TypeScript/issues/29729 + */ +export type StringLiteralUnion = T | (string & Record); +export {}; diff --git a/node_modules/hono/dist/types/utils/url.d.ts b/node_modules/hono/dist/types/utils/url.d.ts new file mode 100644 index 000000000..dc94f1e4b --- /dev/null +++ b/node_modules/hono/dist/types/utils/url.d.ts @@ -0,0 +1,29 @@ +/** + * @module + * URL utility. + */ +export type Pattern = readonly [string, string, RegExp | true] | '*'; +export declare const splitPath: (path: string) => string[]; +export declare const splitRoutingPath: (routePath: string) => string[]; +export declare const getPattern: (label: string, next?: string) => Pattern | null; +type Decoder = (str: string) => string; +export declare const tryDecode: (str: string, decoder: Decoder) => string; +export declare const getPath: (request: Request) => string; +export declare const getQueryStrings: (url: string) => string; +export declare const getPathNoStrict: (request: Request) => string; +/** + * Merge paths. + * @param {string[]} ...paths - The paths to merge. + * @returns {string} The merged path. + * @example + * mergePath('/api', '/users') // '/api/users' + * mergePath('/api/', '/users') // '/api/users' + * mergePath('/api', '/') // '/api' + * mergePath('/api/', '/') // '/api/' + */ +export declare const mergePath: (...paths: string[]) => string; +export declare const checkOptionalParameter: (path: string) => string[] | null; +export declare const getQueryParam: (url: string, key?: string) => string | undefined | Record; +export declare const getQueryParams: (url: string, key?: string) => string[] | undefined | Record; +export declare const decodeURIComponent_: typeof decodeURIComponent; +export {}; diff --git a/node_modules/hono/dist/types/validator/index.d.ts b/node_modules/hono/dist/types/validator/index.d.ts new file mode 100644 index 000000000..149b25557 --- /dev/null +++ b/node_modules/hono/dist/types/validator/index.d.ts @@ -0,0 +1,7 @@ +/** + * @module + * Validator for Hono. + */ +export { validator } from './validator'; +export type { ValidationFunction } from './validator'; +export type { InferInput } from './utils'; diff --git a/node_modules/hono/dist/types/validator/utils.d.ts b/node_modules/hono/dist/types/validator/utils.d.ts new file mode 100644 index 000000000..4fef73dde --- /dev/null +++ b/node_modules/hono/dist/types/validator/utils.d.ts @@ -0,0 +1,29 @@ +import type { FormValue, ParsedFormValue, ValidationTargets } from '../types'; +import type { UnionToIntersection } from '../utils/types'; +/** + * Checks if T is a literal union type (e.g., 'asc' | 'desc') + * that should be preserved in input types. + * Returns true for union literals, false for single literals or wide types. + */ +export type IsLiteralUnion = [Exclude] extends [Base] ? [Exclude] extends [UnionToIntersection>] ? false : true : false; +type IsOptionalUnion = [unknown] extends [T] ? false : undefined extends T ? true : false; +type SimplifyDeep = { + [K in keyof T]: T[K]; +} & {}; +type InferInputInner = SimplifyDeep<{ + [K in keyof Output]: IsLiteralUnion extends true ? Output[K] : IsOptionalUnion extends true ? Output[K] : Target extends 'form' ? T | T[] : Target extends 'query' ? string | string[] : Target extends 'param' ? string : Target extends 'header' ? string : Target extends 'cookie' ? string : unknown; +}>; +/** + * Utility type to infer input types for validation targets. + * Preserves literal union types (e.g., 'asc' | 'desc') while using + * the default ValidationTargets type for other values. + * + * @example + * ```ts + * // In @hono/zod-validator or similar: + * type Input = InferInput, 'query'> + * // { orderBy: 'asc' | 'desc', page: string | string[] } + * ``` + */ +export type InferInput = [Exclude] extends [never] ? {} : [Exclude] extends [object] ? undefined extends Output ? SimplifyDeep, Target, T>> | undefined : SimplifyDeep> : {}; +export {}; diff --git a/node_modules/hono/dist/types/validator/validator.d.ts b/node_modules/hono/dist/types/validator/validator.d.ts new file mode 100644 index 000000000..0a94947bf --- /dev/null +++ b/node_modules/hono/dist/types/validator/validator.d.ts @@ -0,0 +1,16 @@ +import type { Context } from '../context'; +import type { Env, MiddlewareHandler, TypedResponse, ValidationTargets, FormValue } from '../types'; +import type { InferInput } from './utils'; +type ValidationTargetKeysWithBody = 'form' | 'json'; +type ValidationTargetByMethod = M extends 'get' | 'head' ? Exclude : keyof ValidationTargets; +export type ValidationFunction = (value: InputType, c: Context) => OutputType | TypedResponse | Promise | Promise; +export type ExtractValidationResponse = VF extends (value: any, c: any) => infer R ? R extends Promise ? PR extends TypedResponse ? TypedResponse : PR extends Response ? PR : PR extends undefined ? never : never : R extends TypedResponse ? TypedResponse : R extends Response ? R : R extends undefined ? never : never : never; +export declare const validator: , P2 extends string = P, VF extends (value: unknown extends InputType ? ValidationTargets[U] : InputType, c: Context) => any = (value: unknown extends InputType ? ValidationTargets[U] : InputType, c: Context) => any, V extends { + in: { [K in U]: K extends "json" ? unknown extends InputType ? ExtractValidatorOutput : InputType : InferInput, K, FormValue>; }; + out: { [K in U]: ExtractValidatorOutput; }; +} = { + in: { [K in U]: K extends "json" ? unknown extends InputType ? ExtractValidatorOutput : InputType : InferInput, K, FormValue>; }; + out: { [K in U]: ExtractValidatorOutput; }; +}, E extends Env = any>(target: U, validationFunc: VF) => MiddlewareHandler>; +export type ExtractValidatorOutput = VF extends (value: any, c: any) => infer R ? R extends Promise ? PR extends Response | TypedResponse ? never : PR : R extends Response | TypedResponse ? never : R : never; +export {}; diff --git a/node_modules/hono/dist/utils/accept.js b/node_modules/hono/dist/utils/accept.js new file mode 100644 index 000000000..2d72f1fb1 --- /dev/null +++ b/node_modules/hono/dist/utils/accept.js @@ -0,0 +1,63 @@ +// src/utils/accept.ts +var parseAccept = (acceptHeader) => { + if (!acceptHeader) { + return []; + } + const acceptValues = acceptHeader.split(",").map((value, index) => ({ value, index })); + return acceptValues.map(parseAcceptValue).filter((item) => Boolean(item)).sort(sortByQualityAndIndex).map(({ type, params, q }) => ({ type, params, q })); +}; +var parseAcceptValueRegex = /;(?=(?:(?:[^"]*"){2})*[^"]*$)/; +var parseAcceptValue = ({ value, index }) => { + const parts = value.trim().split(parseAcceptValueRegex).map((s) => s.trim()); + const type = parts[0]; + if (!type) { + return null; + } + const params = parseParams(parts.slice(1)); + const q = parseQuality(params.q); + return { type, params, q, index }; +}; +var parseParams = (paramParts) => { + return paramParts.reduce((acc, param) => { + const [key, val] = param.split("=").map((s) => s.trim()); + if (key && val) { + acc[key] = val; + } + return acc; + }, {}); +}; +var parseQuality = (qVal) => { + if (qVal === void 0) { + return 1; + } + if (qVal === "") { + return 1; + } + if (qVal === "NaN") { + return 0; + } + const num = Number(qVal); + if (num === Infinity) { + return 1; + } + if (num === -Infinity) { + return 0; + } + if (Number.isNaN(num)) { + return 1; + } + if (num < 0 || num > 1) { + return 1; + } + return num; +}; +var sortByQualityAndIndex = (a, b) => { + const qDiff = b.q - a.q; + if (qDiff !== 0) { + return qDiff; + } + return a.index - b.index; +}; +export { + parseAccept +}; diff --git a/node_modules/hono/dist/utils/basic-auth.js b/node_modules/hono/dist/utils/basic-auth.js new file mode 100644 index 000000000..579a665cb --- /dev/null +++ b/node_modules/hono/dist/utils/basic-auth.js @@ -0,0 +1,23 @@ +// src/utils/basic-auth.ts +import { decodeBase64 } from "./encode.js"; +var CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/; +var USER_PASS_REGEXP = /^([^:]*):(.*)$/; +var utf8Decoder = new TextDecoder(); +var auth = (req) => { + const match = CREDENTIALS_REGEXP.exec(req.headers.get("Authorization") || ""); + if (!match) { + return void 0; + } + let userPass = void 0; + try { + userPass = USER_PASS_REGEXP.exec(utf8Decoder.decode(decodeBase64(match[1]))); + } catch { + } + if (!userPass) { + return void 0; + } + return { username: userPass[1], password: userPass[2] }; +}; +export { + auth +}; diff --git a/node_modules/hono/dist/utils/body.js b/node_modules/hono/dist/utils/body.js new file mode 100644 index 000000000..d63656212 --- /dev/null +++ b/node_modules/hono/dist/utils/body.js @@ -0,0 +1,72 @@ +// src/utils/body.ts +import { HonoRequest } from "../request.js"; +var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => { + const { all = false, dot = false } = options; + const headers = request instanceof HonoRequest ? request.raw.headers : request.headers; + const contentType = headers.get("Content-Type"); + if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) { + return parseFormData(request, { all, dot }); + } + return {}; +}; +async function parseFormData(request, options) { + const formData = await request.formData(); + if (formData) { + return convertFormDataToBodyData(formData, options); + } + return {}; +} +function convertFormDataToBodyData(formData, options) { + const form = /* @__PURE__ */ Object.create(null); + formData.forEach((value, key) => { + const shouldParseAllValues = options.all || key.endsWith("[]"); + if (!shouldParseAllValues) { + form[key] = value; + } else { + handleParsingAllValues(form, key, value); + } + }); + if (options.dot) { + Object.entries(form).forEach(([key, value]) => { + const shouldParseDotValues = key.includes("."); + if (shouldParseDotValues) { + handleParsingNestedValues(form, key, value); + delete form[key]; + } + }); + } + return form; +} +var handleParsingAllValues = (form, key, value) => { + if (form[key] !== void 0) { + if (Array.isArray(form[key])) { + ; + form[key].push(value); + } else { + form[key] = [form[key], value]; + } + } else { + if (!key.endsWith("[]")) { + form[key] = value; + } else { + form[key] = [value]; + } + } +}; +var handleParsingNestedValues = (form, key, value) => { + let nestedForm = form; + const keys = key.split("."); + keys.forEach((key2, index) => { + if (index === keys.length - 1) { + nestedForm[key2] = value; + } else { + if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) { + nestedForm[key2] = /* @__PURE__ */ Object.create(null); + } + nestedForm = nestedForm[key2]; + } + }); +}; +export { + parseBody +}; diff --git a/node_modules/hono/dist/utils/buffer.js b/node_modules/hono/dist/utils/buffer.js new file mode 100644 index 000000000..241b9c1a7 --- /dev/null +++ b/node_modules/hono/dist/utils/buffer.js @@ -0,0 +1,50 @@ +// src/utils/buffer.ts +import { sha256 } from "./crypto.js"; +var equal = (a, b) => { + if (a === b) { + return true; + } + if (a.byteLength !== b.byteLength) { + return false; + } + const va = new DataView(a); + const vb = new DataView(b); + let i = va.byteLength; + while (i--) { + if (va.getUint8(i) !== vb.getUint8(i)) { + return false; + } + } + return true; +}; +var timingSafeEqual = async (a, b, hashFunction) => { + if (!hashFunction) { + hashFunction = sha256; + } + const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]); + if (!sa || !sb) { + return false; + } + return sa === sb && a === b; +}; +var bufferToString = (buffer) => { + if (buffer instanceof ArrayBuffer) { + const enc = new TextDecoder("utf-8"); + return enc.decode(buffer); + } + return buffer; +}; +var bufferToFormData = (arrayBuffer, contentType) => { + const response = new Response(arrayBuffer, { + headers: { + "Content-Type": contentType + } + }); + return response.formData(); +}; +export { + bufferToFormData, + bufferToString, + equal, + timingSafeEqual +}; diff --git a/node_modules/hono/dist/utils/color.js b/node_modules/hono/dist/utils/color.js new file mode 100644 index 000000000..e8671957b --- /dev/null +++ b/node_modules/hono/dist/utils/color.js @@ -0,0 +1,25 @@ +// src/utils/color.ts +function getColorEnabled() { + const { process, Deno } = globalThis; + const isNoColor = typeof Deno?.noColor === "boolean" ? Deno.noColor : process !== void 0 ? ( + // eslint-disable-next-line no-unsafe-optional-chaining + "NO_COLOR" in process?.env + ) : false; + return !isNoColor; +} +async function getColorEnabledAsync() { + const { navigator } = globalThis; + const cfWorkers = "cloudflare:workers"; + const isNoColor = navigator !== void 0 && navigator.userAgent === "Cloudflare-Workers" ? await (async () => { + try { + return "NO_COLOR" in ((await import(cfWorkers)).env ?? {}); + } catch { + return false; + } + })() : !getColorEnabled(); + return !isNoColor; +} +export { + getColorEnabled, + getColorEnabledAsync +}; diff --git a/node_modules/hono/dist/utils/compress.js b/node_modules/hono/dist/utils/compress.js new file mode 100644 index 000000000..52b39b454 --- /dev/null +++ b/node_modules/hono/dist/utils/compress.js @@ -0,0 +1,5 @@ +// src/utils/compress.ts +var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i; +export { + COMPRESSIBLE_CONTENT_TYPE_REGEX +}; diff --git a/node_modules/hono/dist/utils/concurrent.js b/node_modules/hono/dist/utils/concurrent.js new file mode 100644 index 000000000..a9d4b6cc1 --- /dev/null +++ b/node_modules/hono/dist/utils/concurrent.js @@ -0,0 +1,39 @@ +// src/utils/concurrent.ts +var DEFAULT_CONCURRENCY = 1024; +var createPool = ({ + concurrency, + interval +} = {}) => { + concurrency ||= DEFAULT_CONCURRENCY; + if (concurrency === Infinity) { + return { + run: async (fn) => fn() + }; + } + const pool = /* @__PURE__ */ new Set(); + const run = async (fn, promise, resolve) => { + if (pool.size >= concurrency) { + promise ||= new Promise((r) => resolve = r); + setTimeout(() => run(fn, promise, resolve)); + return promise; + } + const marker = {}; + pool.add(marker); + const result = await fn(); + if (interval) { + setTimeout(() => pool.delete(marker), interval); + } else { + pool.delete(marker); + } + if (resolve) { + resolve(result); + return promise; + } else { + return result; + } + }; + return { run }; +}; +export { + createPool +}; diff --git a/node_modules/hono/dist/utils/constants.js b/node_modules/hono/dist/utils/constants.js new file mode 100644 index 000000000..1c6316593 --- /dev/null +++ b/node_modules/hono/dist/utils/constants.js @@ -0,0 +1,5 @@ +// src/utils/constants.ts +var COMPOSED_HANDLER = "__COMPOSED_HANDLER"; +export { + COMPOSED_HANDLER +}; diff --git a/node_modules/hono/dist/utils/cookie.js b/node_modules/hono/dist/utils/cookie.js new file mode 100644 index 000000000..c1281f450 --- /dev/null +++ b/node_modules/hono/dist/utils/cookie.js @@ -0,0 +1,147 @@ +// src/utils/cookie.ts +import { decodeURIComponent_, tryDecode } from "./url.js"; +var algorithm = { name: "HMAC", hash: "SHA-256" }; +var getCryptoKey = async (secret) => { + const secretBuf = typeof secret === "string" ? new TextEncoder().encode(secret) : secret; + return await crypto.subtle.importKey("raw", secretBuf, algorithm, false, ["sign", "verify"]); +}; +var makeSignature = async (value, secret) => { + const key = await getCryptoKey(secret); + const signature = await crypto.subtle.sign(algorithm.name, key, new TextEncoder().encode(value)); + return btoa(String.fromCharCode(...new Uint8Array(signature))); +}; +var verifySignature = async (base64Signature, value, secret) => { + try { + const signatureBinStr = atob(base64Signature); + const signature = new Uint8Array(signatureBinStr.length); + for (let i = 0, len = signatureBinStr.length; i < len; i++) { + signature[i] = signatureBinStr.charCodeAt(i); + } + return await crypto.subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value)); + } catch { + return false; + } +}; +var validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/; +var validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/; +var parse = (cookie, name) => { + if (name && cookie.indexOf(name) === -1) { + return {}; + } + const pairs = cookie.trim().split(";"); + const parsedCookie = {}; + for (let pairStr of pairs) { + pairStr = pairStr.trim(); + const valueStartPos = pairStr.indexOf("="); + if (valueStartPos === -1) { + continue; + } + const cookieName = pairStr.substring(0, valueStartPos).trim(); + if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName)) { + continue; + } + let cookieValue = pairStr.substring(valueStartPos + 1).trim(); + if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) { + cookieValue = cookieValue.slice(1, -1); + } + if (validCookieValueRegEx.test(cookieValue)) { + parsedCookie[cookieName] = cookieValue.indexOf("%") !== -1 ? tryDecode(cookieValue, decodeURIComponent_) : cookieValue; + if (name) { + break; + } + } + } + return parsedCookie; +}; +var parseSigned = async (cookie, secret, name) => { + const parsedCookie = {}; + const secretKey = await getCryptoKey(secret); + for (const [key, value] of Object.entries(parse(cookie, name))) { + const signatureStartPos = value.lastIndexOf("."); + if (signatureStartPos < 1) { + continue; + } + const signedValue = value.substring(0, signatureStartPos); + const signature = value.substring(signatureStartPos + 1); + if (signature.length !== 44 || !signature.endsWith("=")) { + continue; + } + const isVerified = await verifySignature(signature, signedValue, secretKey); + parsedCookie[key] = isVerified ? signedValue : false; + } + return parsedCookie; +}; +var _serialize = (name, value, opt = {}) => { + let cookie = `${name}=${value}`; + if (name.startsWith("__Secure-") && !opt.secure) { + throw new Error("__Secure- Cookie must have Secure attributes"); + } + if (name.startsWith("__Host-")) { + if (!opt.secure) { + throw new Error("__Host- Cookie must have Secure attributes"); + } + if (opt.path !== "/") { + throw new Error('__Host- Cookie must have Path attributes with "/"'); + } + if (opt.domain) { + throw new Error("__Host- Cookie must not have Domain attributes"); + } + } + if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) { + if (opt.maxAge > 3456e4) { + throw new Error( + "Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration." + ); + } + cookie += `; Max-Age=${opt.maxAge | 0}`; + } + if (opt.domain && opt.prefix !== "host") { + cookie += `; Domain=${opt.domain}`; + } + if (opt.path) { + cookie += `; Path=${opt.path}`; + } + if (opt.expires) { + if (opt.expires.getTime() - Date.now() > 3456e7) { + throw new Error( + "Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future." + ); + } + cookie += `; Expires=${opt.expires.toUTCString()}`; + } + if (opt.httpOnly) { + cookie += "; HttpOnly"; + } + if (opt.secure) { + cookie += "; Secure"; + } + if (opt.sameSite) { + cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`; + } + if (opt.priority) { + cookie += `; Priority=${opt.priority.charAt(0).toUpperCase() + opt.priority.slice(1)}`; + } + if (opt.partitioned) { + if (!opt.secure) { + throw new Error("Partitioned Cookie must have Secure attributes"); + } + cookie += "; Partitioned"; + } + return cookie; +}; +var serialize = (name, value, opt) => { + value = encodeURIComponent(value); + return _serialize(name, value, opt); +}; +var serializeSigned = async (name, value, secret, opt = {}) => { + const signature = await makeSignature(value, secret); + value = `${value}.${signature}`; + value = encodeURIComponent(value); + return _serialize(name, value, opt); +}; +export { + parse, + parseSigned, + serialize, + serializeSigned +}; diff --git a/node_modules/hono/dist/utils/crypto.js b/node_modules/hono/dist/utils/crypto.js new file mode 100644 index 000000000..36772c416 --- /dev/null +++ b/node_modules/hono/dist/utils/crypto.js @@ -0,0 +1,44 @@ +// src/utils/crypto.ts +var sha256 = async (data) => { + const algorithm = { name: "SHA-256", alias: "sha256" }; + const hash = await createHash(data, algorithm); + return hash; +}; +var sha1 = async (data) => { + const algorithm = { name: "SHA-1", alias: "sha1" }; + const hash = await createHash(data, algorithm); + return hash; +}; +var md5 = async (data) => { + const algorithm = { name: "MD5", alias: "md5" }; + const hash = await createHash(data, algorithm); + return hash; +}; +var createHash = async (data, algorithm) => { + let sourceBuffer; + if (ArrayBuffer.isView(data) || data instanceof ArrayBuffer) { + sourceBuffer = data; + } else { + if (typeof data === "object") { + data = JSON.stringify(data); + } + sourceBuffer = new TextEncoder().encode(String(data)); + } + if (crypto && crypto.subtle) { + const buffer = await crypto.subtle.digest( + { + name: algorithm.name + }, + sourceBuffer + ); + const hash = Array.prototype.map.call(new Uint8Array(buffer), (x) => ("00" + x.toString(16)).slice(-2)).join(""); + return hash; + } + return null; +}; +export { + createHash, + md5, + sha1, + sha256 +}; diff --git a/node_modules/hono/dist/utils/encode.js b/node_modules/hono/dist/utils/encode.js new file mode 100644 index 000000000..d4ce6a715 --- /dev/null +++ b/node_modules/hono/dist/utils/encode.js @@ -0,0 +1,29 @@ +// src/utils/encode.ts +var decodeBase64Url = (str) => { + return decodeBase64(str.replace(/_|-/g, (m) => ({ _: "/", "-": "+" })[m] ?? m)); +}; +var encodeBase64Url = (buf) => encodeBase64(buf).replace(/\/|\+/g, (m) => ({ "/": "_", "+": "-" })[m] ?? m); +var encodeBase64 = (buf) => { + let binary = ""; + const bytes = new Uint8Array(buf); + for (let i = 0, len = bytes.length; i < len; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); +}; +var decodeBase64 = (str) => { + const binary = atob(str); + const bytes = new Uint8Array(new ArrayBuffer(binary.length)); + const half = binary.length / 2; + for (let i = 0, j = binary.length - 1; i <= half; i++, j--) { + bytes[i] = binary.charCodeAt(i); + bytes[j] = binary.charCodeAt(j); + } + return bytes; +}; +export { + decodeBase64, + decodeBase64Url, + encodeBase64, + encodeBase64Url +}; diff --git a/node_modules/hono/dist/utils/filepath.js b/node_modules/hono/dist/utils/filepath.js new file mode 100644 index 000000000..7807be58e --- /dev/null +++ b/node_modules/hono/dist/utils/filepath.js @@ -0,0 +1,35 @@ +// src/utils/filepath.ts +var getFilePath = (options) => { + let filename = options.filename; + const defaultDocument = options.defaultDocument || "index.html"; + if (filename.endsWith("/")) { + filename = filename.concat(defaultDocument); + } else if (!filename.match(/\.[a-zA-Z0-9_-]+$/)) { + filename = filename.concat("/" + defaultDocument); + } + const path = getFilePathWithoutDefaultDocument({ + root: options.root, + filename + }); + return path; +}; +var getFilePathWithoutDefaultDocument = (options) => { + let root = options.root || ""; + let filename = options.filename; + if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) { + return; + } + filename = filename.replace(/^\.?[\/\\]/, ""); + filename = filename.replace(/\\/, "/"); + root = root.replace(/\/$/, ""); + let path = root ? root + "/" + filename : filename; + path = path.replace(/^\.?\//, ""); + if (root[0] !== "/" && path[0] === "/") { + return; + } + return path; +}; +export { + getFilePath, + getFilePathWithoutDefaultDocument +}; diff --git a/node_modules/hono/dist/utils/handler.js b/node_modules/hono/dist/utils/handler.js new file mode 100644 index 000000000..317ae6587 --- /dev/null +++ b/node_modules/hono/dist/utils/handler.js @@ -0,0 +1,13 @@ +// src/utils/handler.ts +import { COMPOSED_HANDLER } from "./constants.js"; +var isMiddleware = (handler) => handler.length > 1; +var findTargetHandler = (handler) => { + return handler[COMPOSED_HANDLER] ? ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + findTargetHandler(handler[COMPOSED_HANDLER]) + ) : handler; +}; +export { + findTargetHandler, + isMiddleware +}; diff --git a/node_modules/hono/dist/utils/headers.js b/node_modules/hono/dist/utils/headers.js new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/hono/dist/utils/html.js b/node_modules/hono/dist/utils/html.js new file mode 100644 index 000000000..79f77723d --- /dev/null +++ b/node_modules/hono/dist/utils/html.js @@ -0,0 +1,123 @@ +// src/utils/html.ts +var HtmlEscapedCallbackPhase = { + Stringify: 1, + BeforeStream: 2, + Stream: 3 +}; +var raw = (value, callbacks) => { + const escapedString = new String(value); + escapedString.isEscaped = true; + escapedString.callbacks = callbacks; + return escapedString; +}; +var escapeRe = /[&<>'"]/; +var stringBufferToString = async (buffer, callbacks) => { + let str = ""; + callbacks ||= []; + const resolvedBuffer = await Promise.all(buffer); + for (let i = resolvedBuffer.length - 1; ; i--) { + str += resolvedBuffer[i]; + i--; + if (i < 0) { + break; + } + let r = resolvedBuffer[i]; + if (typeof r === "object") { + callbacks.push(...r.callbacks || []); + } + const isEscaped = r.isEscaped; + r = await (typeof r === "object" ? r.toString() : r); + if (typeof r === "object") { + callbacks.push(...r.callbacks || []); + } + if (r.isEscaped ?? isEscaped) { + str += r; + } else { + const buf = [str]; + escapeToBuffer(r, buf); + str = buf[0]; + } + } + return raw(str, callbacks); +}; +var escapeToBuffer = (str, buffer) => { + const match = str.search(escapeRe); + if (match === -1) { + buffer[0] += str; + return; + } + let escape; + let index; + let lastIndex = 0; + for (index = match; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: + escape = """; + break; + case 39: + escape = "'"; + break; + case 38: + escape = "&"; + break; + case 60: + escape = "<"; + break; + case 62: + escape = ">"; + break; + default: + continue; + } + buffer[0] += str.substring(lastIndex, index) + escape; + lastIndex = index + 1; + } + buffer[0] += str.substring(lastIndex, index); +}; +var resolveCallbackSync = (str) => { + const callbacks = str.callbacks; + if (!callbacks?.length) { + return str; + } + const buffer = [str]; + const context = {}; + callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context })); + return buffer[0]; +}; +var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => { + if (typeof str === "object" && !(str instanceof String)) { + if (!(str instanceof Promise)) { + str = str.toString(); + } + if (str instanceof Promise) { + str = await str; + } + } + const callbacks = str.callbacks; + if (!callbacks?.length) { + return Promise.resolve(str); + } + if (buffer) { + buffer[0] += str; + } else { + buffer = [str]; + } + const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then( + (res) => Promise.all( + res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer)) + ).then(() => buffer[0]) + ); + if (preserveCallbacks) { + return raw(await resStr, callbacks); + } else { + return resStr; + } +}; +export { + HtmlEscapedCallbackPhase, + escapeToBuffer, + raw, + resolveCallback, + resolveCallbackSync, + stringBufferToString +}; diff --git a/node_modules/hono/dist/utils/http-status.js b/node_modules/hono/dist/utils/http-status.js new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/hono/dist/utils/ipaddr.js b/node_modules/hono/dist/utils/ipaddr.js new file mode 100644 index 000000000..c10df08b6 --- /dev/null +++ b/node_modules/hono/dist/utils/ipaddr.js @@ -0,0 +1,101 @@ +// src/utils/ipaddr.ts +var expandIPv6 = (ipV6) => { + const sections = ipV6.split(":"); + if (IPV4_REGEX.test(sections.at(-1))) { + sections.splice( + -1, + 1, + ...convertIPv6BinaryToString(convertIPv4ToBinary(sections.at(-1))).substring(2).split(":") + // => ['7f00', '0001'] + ); + } + for (let i = 0; i < sections.length; i++) { + const node = sections[i]; + if (node !== "") { + sections[i] = node.padStart(4, "0"); + } else { + sections[i + 1] === "" && sections.splice(i + 1, 1); + sections[i] = new Array(8 - sections.length + 1).fill("0000").join(":"); + } + } + return sections.join(":"); +}; +var IPV4_REGEX = /^[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}$/; +var distinctRemoteAddr = (remoteAddr) => { + if (IPV4_REGEX.test(remoteAddr)) { + return "IPv4"; + } + if (remoteAddr.includes(":")) { + return "IPv6"; + } +}; +var convertIPv4ToBinary = (ipv4) => { + const parts = ipv4.split("."); + let result = 0n; + for (let i = 0; i < 4; i++) { + result <<= 8n; + result += BigInt(parts[i]); + } + return result; +}; +var convertIPv6ToBinary = (ipv6) => { + const sections = expandIPv6(ipv6).split(":"); + let result = 0n; + for (let i = 0; i < 8; i++) { + result <<= 16n; + result += BigInt(parseInt(sections[i], 16)); + } + return result; +}; +var convertIPv4BinaryToString = (ipV4) => { + const sections = []; + for (let i = 0; i < 4; i++) { + sections.push(ipV4 >> BigInt(8 * (3 - i)) & 0xffn); + } + return sections.join("."); +}; +var convertIPv6BinaryToString = (ipV6) => { + if (ipV6 >> 32n === 0xffffn) { + return `::ffff:${convertIPv4BinaryToString(ipV6 & 0xffffffffn)}`; + } + const sections = []; + for (let i = 0; i < 8; i++) { + sections.push((ipV6 >> BigInt(16 * (7 - i)) & 0xffffn).toString(16)); + } + let currentZeroStart = -1; + let maxZeroStart = -1; + let maxZeroEnd = -1; + for (let i = 0; i < 8; i++) { + if (sections[i] === "0") { + if (currentZeroStart === -1) { + currentZeroStart = i; + } + } else { + if (currentZeroStart > -1) { + if (i - currentZeroStart > maxZeroEnd - maxZeroStart) { + maxZeroStart = currentZeroStart; + maxZeroEnd = i; + } + currentZeroStart = -1; + } + } + } + if (currentZeroStart > -1) { + if (8 - currentZeroStart > maxZeroEnd - maxZeroStart) { + maxZeroStart = currentZeroStart; + maxZeroEnd = 8; + } + } + if (maxZeroStart !== -1) { + sections.splice(maxZeroStart, maxZeroEnd - maxZeroStart, ":"); + } + return sections.join(":").replace(/:{2,}/g, "::"); +}; +export { + convertIPv4BinaryToString, + convertIPv4ToBinary, + convertIPv6BinaryToString, + convertIPv6ToBinary, + distinctRemoteAddr, + expandIPv6 +}; diff --git a/node_modules/hono/dist/utils/jwt/index.js b/node_modules/hono/dist/utils/jwt/index.js new file mode 100644 index 000000000..25467d1da --- /dev/null +++ b/node_modules/hono/dist/utils/jwt/index.js @@ -0,0 +1,6 @@ +// src/utils/jwt/index.ts +import { decode, sign, verify, verifyWithJwks } from "./jwt.js"; +var Jwt = { sign, verify, decode, verifyWithJwks }; +export { + Jwt +}; diff --git a/node_modules/hono/dist/utils/jwt/jwa.js b/node_modules/hono/dist/utils/jwt/jwa.js new file mode 100644 index 000000000..633119299 --- /dev/null +++ b/node_modules/hono/dist/utils/jwt/jwa.js @@ -0,0 +1,20 @@ +// src/utils/jwt/jwa.ts +var AlgorithmTypes = /* @__PURE__ */ ((AlgorithmTypes2) => { + AlgorithmTypes2["HS256"] = "HS256"; + AlgorithmTypes2["HS384"] = "HS384"; + AlgorithmTypes2["HS512"] = "HS512"; + AlgorithmTypes2["RS256"] = "RS256"; + AlgorithmTypes2["RS384"] = "RS384"; + AlgorithmTypes2["RS512"] = "RS512"; + AlgorithmTypes2["PS256"] = "PS256"; + AlgorithmTypes2["PS384"] = "PS384"; + AlgorithmTypes2["PS512"] = "PS512"; + AlgorithmTypes2["ES256"] = "ES256"; + AlgorithmTypes2["ES384"] = "ES384"; + AlgorithmTypes2["ES512"] = "ES512"; + AlgorithmTypes2["EdDSA"] = "EdDSA"; + return AlgorithmTypes2; +})(AlgorithmTypes || {}); +export { + AlgorithmTypes +}; diff --git a/node_modules/hono/dist/utils/jwt/jws.js b/node_modules/hono/dist/utils/jwt/jws.js new file mode 100644 index 000000000..2832b9c3d --- /dev/null +++ b/node_modules/hono/dist/utils/jwt/jws.js @@ -0,0 +1,192 @@ +// src/utils/jwt/jws.ts +import { getRuntimeKey } from "../../helper/adapter/index.js"; +import { decodeBase64 } from "../encode.js"; +import { CryptoKeyUsage, JwtAlgorithmNotImplemented } from "./types.js"; +import { utf8Encoder } from "./utf8.js"; +async function signing(privateKey, alg, data) { + const algorithm = getKeyAlgorithm(alg); + const cryptoKey = await importPrivateKey(privateKey, algorithm); + return await crypto.subtle.sign(algorithm, cryptoKey, data); +} +async function verifying(publicKey, alg, signature, data) { + const algorithm = getKeyAlgorithm(alg); + const cryptoKey = await importPublicKey(publicKey, algorithm); + return await crypto.subtle.verify(algorithm, cryptoKey, signature, data); +} +function pemToBinary(pem) { + return decodeBase64(pem.replace(/-+(BEGIN|END).*/g, "").replace(/\s/g, "")); +} +async function importPrivateKey(key, alg) { + if (!crypto.subtle || !crypto.subtle.importKey) { + throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it."); + } + if (isCryptoKey(key)) { + if (key.type !== "private" && key.type !== "secret") { + throw new Error( + `unexpected key type: CryptoKey.type is ${key.type}, expected private or secret` + ); + } + return key; + } + const usages = [CryptoKeyUsage.Sign]; + if (typeof key === "object") { + return await crypto.subtle.importKey("jwk", key, alg, false, usages); + } + if (key.includes("PRIVATE")) { + return await crypto.subtle.importKey("pkcs8", pemToBinary(key), alg, false, usages); + } + return await crypto.subtle.importKey("raw", utf8Encoder.encode(key), alg, false, usages); +} +async function importPublicKey(key, alg) { + if (!crypto.subtle || !crypto.subtle.importKey) { + throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it."); + } + if (isCryptoKey(key)) { + if (key.type === "public" || key.type === "secret") { + return key; + } + key = await exportPublicJwkFrom(key); + } + if (typeof key === "string" && key.includes("PRIVATE")) { + const privateKey = await crypto.subtle.importKey("pkcs8", pemToBinary(key), alg, true, [ + CryptoKeyUsage.Sign + ]); + key = await exportPublicJwkFrom(privateKey); + } + const usages = [CryptoKeyUsage.Verify]; + if (typeof key === "object") { + return await crypto.subtle.importKey("jwk", key, alg, false, usages); + } + if (key.includes("PUBLIC")) { + return await crypto.subtle.importKey("spki", pemToBinary(key), alg, false, usages); + } + return await crypto.subtle.importKey("raw", utf8Encoder.encode(key), alg, false, usages); +} +async function exportPublicJwkFrom(privateKey) { + if (privateKey.type !== "private") { + throw new Error(`unexpected key type: ${privateKey.type}`); + } + if (!privateKey.extractable) { + throw new Error("unexpected private key is unextractable"); + } + const jwk = await crypto.subtle.exportKey("jwk", privateKey); + const { kty } = jwk; + const { alg, e, n } = jwk; + const { crv, x, y } = jwk; + return { kty, alg, e, n, crv, x, y, key_ops: [CryptoKeyUsage.Verify] }; +} +function getKeyAlgorithm(name) { + switch (name) { + case "HS256": + return { + name: "HMAC", + hash: { + name: "SHA-256" + } + }; + case "HS384": + return { + name: "HMAC", + hash: { + name: "SHA-384" + } + }; + case "HS512": + return { + name: "HMAC", + hash: { + name: "SHA-512" + } + }; + case "RS256": + return { + name: "RSASSA-PKCS1-v1_5", + hash: { + name: "SHA-256" + } + }; + case "RS384": + return { + name: "RSASSA-PKCS1-v1_5", + hash: { + name: "SHA-384" + } + }; + case "RS512": + return { + name: "RSASSA-PKCS1-v1_5", + hash: { + name: "SHA-512" + } + }; + case "PS256": + return { + name: "RSA-PSS", + hash: { + name: "SHA-256" + }, + saltLength: 32 + // 256 >> 3 + }; + case "PS384": + return { + name: "RSA-PSS", + hash: { + name: "SHA-384" + }, + saltLength: 48 + // 384 >> 3 + }; + case "PS512": + return { + name: "RSA-PSS", + hash: { + name: "SHA-512" + }, + saltLength: 64 + // 512 >> 3, + }; + case "ES256": + return { + name: "ECDSA", + hash: { + name: "SHA-256" + }, + namedCurve: "P-256" + }; + case "ES384": + return { + name: "ECDSA", + hash: { + name: "SHA-384" + }, + namedCurve: "P-384" + }; + case "ES512": + return { + name: "ECDSA", + hash: { + name: "SHA-512" + }, + namedCurve: "P-521" + }; + case "EdDSA": + return { + name: "Ed25519", + namedCurve: "Ed25519" + }; + default: + throw new JwtAlgorithmNotImplemented(name); + } +} +function isCryptoKey(key) { + const runtime = getRuntimeKey(); + if (runtime === "node" && !!crypto.webcrypto) { + return key instanceof crypto.webcrypto.CryptoKey; + } + return key instanceof CryptoKey; +} +export { + signing, + verifying +}; diff --git a/node_modules/hono/dist/utils/jwt/jwt.js b/node_modules/hono/dist/utils/jwt/jwt.js new file mode 100644 index 000000000..e9d785243 --- /dev/null +++ b/node_modules/hono/dist/utils/jwt/jwt.js @@ -0,0 +1,197 @@ +// src/utils/jwt/jwt.ts +import { decodeBase64Url, encodeBase64Url } from "../../utils/encode.js"; +import { AlgorithmTypes } from "./jwa.js"; +import { signing, verifying } from "./jws.js"; +import { + JwtAlgorithmMismatch, + JwtAlgorithmNotAllowed, + JwtAlgorithmRequired, + JwtHeaderInvalid, + JwtHeaderRequiresKid, + JwtPayloadRequiresAud, + JwtSymmetricAlgorithmNotAllowed, + JwtTokenAudience, + JwtTokenExpired, + JwtTokenInvalid, + JwtTokenIssuedAt, + JwtTokenIssuer, + JwtTokenNotBefore, + JwtTokenSignatureMismatched +} from "./types.js"; +import { utf8Decoder, utf8Encoder } from "./utf8.js"; +var encodeJwtPart = (part) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(part)).buffer).replace(/=/g, ""); +var encodeSignaturePart = (buf) => encodeBase64Url(buf).replace(/=/g, ""); +var decodeJwtPart = (part) => JSON.parse(utf8Decoder.decode(decodeBase64Url(part))); +function isTokenHeader(obj) { + if (typeof obj === "object" && obj !== null) { + const objWithAlg = obj; + return "alg" in objWithAlg && Object.values(AlgorithmTypes).includes(objWithAlg.alg) && (!("typ" in objWithAlg) || objWithAlg.typ === "JWT"); + } + return false; +} +var sign = async (payload, privateKey, alg = "HS256") => { + const encodedPayload = encodeJwtPart(payload); + let encodedHeader; + if (typeof privateKey === "object" && "alg" in privateKey) { + alg = privateKey.alg; + encodedHeader = encodeJwtPart({ alg, typ: "JWT", kid: privateKey.kid }); + } else { + encodedHeader = encodeJwtPart({ alg, typ: "JWT" }); + } + const partialToken = `${encodedHeader}.${encodedPayload}`; + const signaturePart = await signing(privateKey, alg, utf8Encoder.encode(partialToken)); + const signature = encodeSignaturePart(signaturePart); + return `${partialToken}.${signature}`; +}; +var verify = async (token, publicKey, algOrOptions) => { + if (!algOrOptions) { + throw new JwtAlgorithmRequired(); + } + const { + alg, + iss, + nbf = true, + exp = true, + iat = true, + aud + } = typeof algOrOptions === "string" ? { alg: algOrOptions } : algOrOptions; + if (!alg) { + throw new JwtAlgorithmRequired(); + } + const tokenParts = token.split("."); + if (tokenParts.length !== 3) { + throw new JwtTokenInvalid(token); + } + const { header, payload } = decode(token); + if (!isTokenHeader(header)) { + throw new JwtHeaderInvalid(header); + } + if (header.alg !== alg) { + throw new JwtAlgorithmMismatch(alg, header.alg); + } + const now = Date.now() / 1e3 | 0; + if (nbf && payload.nbf && payload.nbf > now) { + throw new JwtTokenNotBefore(token); + } + if (exp && payload.exp && payload.exp <= now) { + throw new JwtTokenExpired(token); + } + if (iat && payload.iat && now < payload.iat) { + throw new JwtTokenIssuedAt(now, payload.iat); + } + if (iss) { + if (!payload.iss) { + throw new JwtTokenIssuer(iss, null); + } + if (typeof iss === "string" && payload.iss !== iss) { + throw new JwtTokenIssuer(iss, payload.iss); + } + if (iss instanceof RegExp && !iss.test(payload.iss)) { + throw new JwtTokenIssuer(iss, payload.iss); + } + } + if (aud) { + if (!payload.aud) { + throw new JwtPayloadRequiresAud(payload); + } + const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; + const matched = audiences.some( + (payloadAud) => aud instanceof RegExp ? aud.test(payloadAud) : typeof aud === "string" ? payloadAud === aud : Array.isArray(aud) && aud.includes(payloadAud) + ); + if (!matched) { + throw new JwtTokenAudience(aud, payload.aud); + } + } + const headerPayload = token.substring(0, token.lastIndexOf(".")); + const verified = await verifying( + publicKey, + alg, + decodeBase64Url(tokenParts[2]), + utf8Encoder.encode(headerPayload) + ); + if (!verified) { + throw new JwtTokenSignatureMismatched(token); + } + return payload; +}; +var symmetricAlgorithms = [ + AlgorithmTypes.HS256, + AlgorithmTypes.HS384, + AlgorithmTypes.HS512 +]; +var verifyWithJwks = async (token, options, init) => { + const verifyOpts = options.verification || {}; + const header = decodeHeader(token); + if (!isTokenHeader(header)) { + throw new JwtHeaderInvalid(header); + } + if (!header.kid) { + throw new JwtHeaderRequiresKid(header); + } + if (symmetricAlgorithms.includes(header.alg)) { + throw new JwtSymmetricAlgorithmNotAllowed(header.alg); + } + if (!options.allowedAlgorithms.includes(header.alg)) { + throw new JwtAlgorithmNotAllowed(header.alg, options.allowedAlgorithms); + } + if (options.jwks_uri) { + const response = await fetch(options.jwks_uri, init); + if (!response.ok) { + throw new Error(`failed to fetch JWKS from ${options.jwks_uri}`); + } + const data = await response.json(); + if (!data.keys) { + throw new Error('invalid JWKS response. "keys" field is missing'); + } + if (!Array.isArray(data.keys)) { + throw new Error('invalid JWKS response. "keys" field is not an array'); + } + if (options.keys) { + options.keys.push(...data.keys); + } else { + options.keys = data.keys; + } + } else if (!options.keys) { + throw new Error('verifyWithJwks requires options for either "keys" or "jwks_uri" or both'); + } + const matchingKey = options.keys.find((key) => key.kid === header.kid); + if (!matchingKey) { + throw new JwtTokenInvalid(token); + } + if (matchingKey.alg && matchingKey.alg !== header.alg) { + throw new JwtAlgorithmMismatch(matchingKey.alg, header.alg); + } + return await verify(token, matchingKey, { + alg: header.alg, + ...verifyOpts + }); +}; +var decode = (token) => { + try { + const [h, p] = token.split("."); + const header = decodeJwtPart(h); + const payload = decodeJwtPart(p); + return { + header, + payload + }; + } catch { + throw new JwtTokenInvalid(token); + } +}; +var decodeHeader = (token) => { + try { + const [h] = token.split("."); + return decodeJwtPart(h); + } catch { + throw new JwtTokenInvalid(token); + } +}; +export { + decode, + decodeHeader, + isTokenHeader, + sign, + verify, + verifyWithJwks +}; diff --git a/node_modules/hono/dist/utils/jwt/types.js b/node_modules/hono/dist/utils/jwt/types.js new file mode 100644 index 000000000..253427c78 --- /dev/null +++ b/node_modules/hono/dist/utils/jwt/types.js @@ -0,0 +1,124 @@ +// src/utils/jwt/types.ts +var JwtAlgorithmNotImplemented = class extends Error { + constructor(alg) { + super(`${alg} is not an implemented algorithm`); + this.name = "JwtAlgorithmNotImplemented"; + } +}; +var JwtAlgorithmRequired = class extends Error { + constructor() { + super('JWT verification requires "alg" option to be specified'); + this.name = "JwtAlgorithmRequired"; + } +}; +var JwtAlgorithmMismatch = class extends Error { + constructor(expected, actual) { + super(`JWT algorithm mismatch: expected "${expected}", got "${actual}"`); + this.name = "JwtAlgorithmMismatch"; + } +}; +var JwtTokenInvalid = class extends Error { + constructor(token) { + super(`invalid JWT token: ${token}`); + this.name = "JwtTokenInvalid"; + } +}; +var JwtTokenNotBefore = class extends Error { + constructor(token) { + super(`token (${token}) is being used before it's valid`); + this.name = "JwtTokenNotBefore"; + } +}; +var JwtTokenExpired = class extends Error { + constructor(token) { + super(`token (${token}) expired`); + this.name = "JwtTokenExpired"; + } +}; +var JwtTokenIssuedAt = class extends Error { + constructor(currentTimestamp, iat) { + super( + `Invalid "iat" claim, must be a valid number lower than "${currentTimestamp}" (iat: "${iat}")` + ); + this.name = "JwtTokenIssuedAt"; + } +}; +var JwtTokenIssuer = class extends Error { + constructor(expected, iss) { + super(`expected issuer "${expected}", got ${iss ? `"${iss}"` : "none"} `); + this.name = "JwtTokenIssuer"; + } +}; +var JwtHeaderInvalid = class extends Error { + constructor(header) { + super(`jwt header is invalid: ${JSON.stringify(header)}`); + this.name = "JwtHeaderInvalid"; + } +}; +var JwtHeaderRequiresKid = class extends Error { + constructor(header) { + super(`required "kid" in jwt header: ${JSON.stringify(header)}`); + this.name = "JwtHeaderRequiresKid"; + } +}; +var JwtSymmetricAlgorithmNotAllowed = class extends Error { + constructor(alg) { + super(`symmetric algorithm "${alg}" is not allowed for JWK verification`); + this.name = "JwtSymmetricAlgorithmNotAllowed"; + } +}; +var JwtAlgorithmNotAllowed = class extends Error { + constructor(alg, allowedAlgorithms) { + super(`algorithm "${alg}" is not in the allowed list: [${allowedAlgorithms.join(", ")}]`); + this.name = "JwtAlgorithmNotAllowed"; + } +}; +var JwtTokenSignatureMismatched = class extends Error { + constructor(token) { + super(`token(${token}) signature mismatched`); + this.name = "JwtTokenSignatureMismatched"; + } +}; +var JwtPayloadRequiresAud = class extends Error { + constructor(payload) { + super(`required "aud" in jwt payload: ${JSON.stringify(payload)}`); + this.name = "JwtPayloadRequiresAud"; + } +}; +var JwtTokenAudience = class extends Error { + constructor(expected, aud) { + super( + `expected audience "${Array.isArray(expected) ? expected.join(", ") : expected}", got "${aud}"` + ); + this.name = "JwtTokenAudience"; + } +}; +var CryptoKeyUsage = /* @__PURE__ */ ((CryptoKeyUsage2) => { + CryptoKeyUsage2["Encrypt"] = "encrypt"; + CryptoKeyUsage2["Decrypt"] = "decrypt"; + CryptoKeyUsage2["Sign"] = "sign"; + CryptoKeyUsage2["Verify"] = "verify"; + CryptoKeyUsage2["DeriveKey"] = "deriveKey"; + CryptoKeyUsage2["DeriveBits"] = "deriveBits"; + CryptoKeyUsage2["WrapKey"] = "wrapKey"; + CryptoKeyUsage2["UnwrapKey"] = "unwrapKey"; + return CryptoKeyUsage2; +})(CryptoKeyUsage || {}); +export { + CryptoKeyUsage, + JwtAlgorithmMismatch, + JwtAlgorithmNotAllowed, + JwtAlgorithmNotImplemented, + JwtAlgorithmRequired, + JwtHeaderInvalid, + JwtHeaderRequiresKid, + JwtPayloadRequiresAud, + JwtSymmetricAlgorithmNotAllowed, + JwtTokenAudience, + JwtTokenExpired, + JwtTokenInvalid, + JwtTokenIssuedAt, + JwtTokenIssuer, + JwtTokenNotBefore, + JwtTokenSignatureMismatched +}; diff --git a/node_modules/hono/dist/utils/jwt/utf8.js b/node_modules/hono/dist/utils/jwt/utf8.js new file mode 100644 index 000000000..3cd9f0eac --- /dev/null +++ b/node_modules/hono/dist/utils/jwt/utf8.js @@ -0,0 +1,7 @@ +// src/utils/jwt/utf8.ts +var utf8Encoder = new TextEncoder(); +var utf8Decoder = new TextDecoder(); +export { + utf8Decoder, + utf8Encoder +}; diff --git a/node_modules/hono/dist/utils/mime.js b/node_modules/hono/dist/utils/mime.js new file mode 100644 index 000000000..8d9985ec0 --- /dev/null +++ b/node_modules/hono/dist/utils/mime.js @@ -0,0 +1,84 @@ +// src/utils/mime.ts +var getMimeType = (filename, mimes = baseMimes) => { + const regexp = /\.([a-zA-Z0-9]+?)$/; + const match = filename.match(regexp); + if (!match) { + return; + } + let mimeType = mimes[match[1]]; + if (mimeType && mimeType.startsWith("text")) { + mimeType += "; charset=utf-8"; + } + return mimeType; +}; +var getExtension = (mimeType) => { + for (const ext in baseMimes) { + if (baseMimes[ext] === mimeType) { + return ext; + } + } +}; +var _baseMimes = { + aac: "audio/aac", + avi: "video/x-msvideo", + avif: "image/avif", + av1: "video/av1", + bin: "application/octet-stream", + bmp: "image/bmp", + css: "text/css", + csv: "text/csv", + eot: "application/vnd.ms-fontobject", + epub: "application/epub+zip", + gif: "image/gif", + gz: "application/gzip", + htm: "text/html", + html: "text/html", + ico: "image/x-icon", + ics: "text/calendar", + jpeg: "image/jpeg", + jpg: "image/jpeg", + js: "text/javascript", + json: "application/json", + jsonld: "application/ld+json", + map: "application/json", + mid: "audio/x-midi", + midi: "audio/x-midi", + mjs: "text/javascript", + mp3: "audio/mpeg", + mp4: "video/mp4", + mpeg: "video/mpeg", + oga: "audio/ogg", + ogv: "video/ogg", + ogx: "application/ogg", + opus: "audio/opus", + otf: "font/otf", + pdf: "application/pdf", + png: "image/png", + rtf: "application/rtf", + svg: "image/svg+xml", + tif: "image/tiff", + tiff: "image/tiff", + ts: "video/mp2t", + ttf: "font/ttf", + txt: "text/plain", + wasm: "application/wasm", + webm: "video/webm", + weba: "audio/webm", + webmanifest: "application/manifest+json", + webp: "image/webp", + woff: "font/woff", + woff2: "font/woff2", + xhtml: "application/xhtml+xml", + xml: "application/xml", + zip: "application/zip", + "3gp": "video/3gpp", + "3g2": "video/3gpp2", + gltf: "model/gltf+json", + glb: "model/gltf-binary" +}; +var baseMimes = _baseMimes; +export { + getExtension, + getMimeType, + baseMimes as mimes +}; diff --git a/node_modules/hono/dist/utils/stream.js b/node_modules/hono/dist/utils/stream.js new file mode 100644 index 000000000..9fb619170 --- /dev/null +++ b/node_modules/hono/dist/utils/stream.js @@ -0,0 +1,79 @@ +// src/utils/stream.ts +var StreamingApi = class { + writer; + encoder; + writable; + abortSubscribers = []; + responseReadable; + /** + * Whether the stream has been aborted. + */ + aborted = false; + /** + * Whether the stream has been closed normally. + */ + closed = false; + constructor(writable, _readable) { + this.writable = writable; + this.writer = writable.getWriter(); + this.encoder = new TextEncoder(); + const reader = _readable.getReader(); + this.abortSubscribers.push(async () => { + await reader.cancel(); + }); + this.responseReadable = new ReadableStream({ + async pull(controller) { + const { done, value } = await reader.read(); + done ? controller.close() : controller.enqueue(value); + }, + cancel: () => { + this.abort(); + } + }); + } + async write(input) { + try { + if (typeof input === "string") { + input = this.encoder.encode(input); + } + await this.writer.write(input); + } catch { + } + return this; + } + async writeln(input) { + await this.write(input + "\n"); + return this; + } + sleep(ms) { + return new Promise((res) => setTimeout(res, ms)); + } + async close() { + try { + await this.writer.close(); + } catch { + } + this.closed = true; + } + async pipe(body) { + this.writer.releaseLock(); + await body.pipeTo(this.writable, { preventClose: true }); + this.writer = this.writable.getWriter(); + } + onAbort(listener) { + this.abortSubscribers.push(listener); + } + /** + * Abort the stream. + * You can call this method when stream is aborted by external event. + */ + abort() { + if (!this.aborted) { + this.aborted = true; + this.abortSubscribers.forEach((subscriber) => subscriber()); + } + } +}; +export { + StreamingApi +}; diff --git a/node_modules/hono/dist/utils/types.js b/node_modules/hono/dist/utils/types.js new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/hono/dist/utils/url.js b/node_modules/hono/dist/utils/url.js new file mode 100644 index 000000000..5a77e2aa4 --- /dev/null +++ b/node_modules/hono/dist/utils/url.js @@ -0,0 +1,219 @@ +// src/utils/url.ts +var splitPath = (path) => { + const paths = path.split("/"); + if (paths[0] === "") { + paths.shift(); + } + return paths; +}; +var splitRoutingPath = (routePath) => { + const { groups, path } = extractGroupsFromPath(routePath); + const paths = splitPath(path); + return replaceGroupMarks(paths, groups); +}; +var extractGroupsFromPath = (path) => { + const groups = []; + path = path.replace(/\{[^}]+\}/g, (match, index) => { + const mark = `@${index}`; + groups.push([mark, match]); + return mark; + }); + return { groups, path }; +}; +var replaceGroupMarks = (paths, groups) => { + for (let i = groups.length - 1; i >= 0; i--) { + const [mark] = groups[i]; + for (let j = paths.length - 1; j >= 0; j--) { + if (paths[j].includes(mark)) { + paths[j] = paths[j].replace(mark, groups[i][1]); + break; + } + } + } + return paths; +}; +var patternCache = {}; +var getPattern = (label, next) => { + if (label === "*") { + return "*"; + } + const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); + if (match) { + const cacheKey = `${label}#${next}`; + if (!patternCache[cacheKey]) { + if (match[2]) { + patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)]; + } else { + patternCache[cacheKey] = [label, match[1], true]; + } + } + return patternCache[cacheKey]; + } + return null; +}; +var tryDecode = (str, decoder) => { + try { + return decoder(str); + } catch { + return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => { + try { + return decoder(match); + } catch { + return match; + } + }); + } +}; +var tryDecodeURI = (str) => tryDecode(str, decodeURI); +var getPath = (request) => { + const url = request.url; + const start = url.indexOf("/", url.indexOf(":") + 4); + let i = start; + for (; i < url.length; i++) { + const charCode = url.charCodeAt(i); + if (charCode === 37) { + const queryIndex = url.indexOf("?", i); + const path = url.slice(start, queryIndex === -1 ? void 0 : queryIndex); + return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path); + } else if (charCode === 63) { + break; + } + } + return url.slice(start, i); +}; +var getQueryStrings = (url) => { + const queryIndex = url.indexOf("?", 8); + return queryIndex === -1 ? "" : "?" + url.slice(queryIndex + 1); +}; +var getPathNoStrict = (request) => { + const result = getPath(request); + return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result; +}; +var mergePath = (base, sub, ...rest) => { + if (rest.length) { + sub = mergePath(sub, ...rest); + } + return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`; +}; +var checkOptionalParameter = (path) => { + if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) { + return null; + } + const segments = path.split("/"); + const results = []; + let basePath = ""; + segments.forEach((segment) => { + if (segment !== "" && !/\:/.test(segment)) { + basePath += "/" + segment; + } else if (/\:/.test(segment)) { + if (/\?/.test(segment)) { + if (results.length === 0 && basePath === "") { + results.push("/"); + } else { + results.push(basePath); + } + const optionalSegment = segment.replace("?", ""); + basePath += "/" + optionalSegment; + results.push(basePath); + } else { + basePath += "/" + segment; + } + } + }); + return results.filter((v, i, a) => a.indexOf(v) === i); +}; +var _decodeURI = (value) => { + if (!/[%+]/.test(value)) { + return value; + } + if (value.indexOf("+") !== -1) { + value = value.replace(/\+/g, " "); + } + return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value; +}; +var _getQueryParam = (url, key, multiple) => { + let encoded; + if (!multiple && key && !/[%+]/.test(key)) { + let keyIndex2 = url.indexOf("?", 8); + if (keyIndex2 === -1) { + return void 0; + } + if (!url.startsWith(key, keyIndex2 + 1)) { + keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1); + } + while (keyIndex2 !== -1) { + const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1); + if (trailingKeyCode === 61) { + const valueIndex = keyIndex2 + key.length + 2; + const endIndex = url.indexOf("&", valueIndex); + return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex)); + } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) { + return ""; + } + keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1); + } + encoded = /[%+]/.test(url); + if (!encoded) { + return void 0; + } + } + const results = {}; + encoded ??= /[%+]/.test(url); + let keyIndex = url.indexOf("?", 8); + while (keyIndex !== -1) { + const nextKeyIndex = url.indexOf("&", keyIndex + 1); + let valueIndex = url.indexOf("=", keyIndex); + if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) { + valueIndex = -1; + } + let name = url.slice( + keyIndex + 1, + valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex + ); + if (encoded) { + name = _decodeURI(name); + } + keyIndex = nextKeyIndex; + if (name === "") { + continue; + } + let value; + if (valueIndex === -1) { + value = ""; + } else { + value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex); + if (encoded) { + value = _decodeURI(value); + } + } + if (multiple) { + if (!(results[name] && Array.isArray(results[name]))) { + results[name] = []; + } + ; + results[name].push(value); + } else { + results[name] ??= value; + } + } + return key ? results[key] : results; +}; +var getQueryParam = _getQueryParam; +var getQueryParams = (url, key) => { + return _getQueryParam(url, key, true); +}; +var decodeURIComponent_ = decodeURIComponent; +export { + checkOptionalParameter, + decodeURIComponent_, + getPath, + getPathNoStrict, + getPattern, + getQueryParam, + getQueryParams, + getQueryStrings, + mergePath, + splitPath, + splitRoutingPath, + tryDecode +}; diff --git a/node_modules/hono/dist/validator/index.js b/node_modules/hono/dist/validator/index.js new file mode 100644 index 000000000..a8f176b46 --- /dev/null +++ b/node_modules/hono/dist/validator/index.js @@ -0,0 +1,5 @@ +// src/validator/index.ts +import { validator } from "./validator.js"; +export { + validator +}; diff --git a/node_modules/hono/dist/validator/utils.js b/node_modules/hono/dist/validator/utils.js new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/hono/dist/validator/validator.js b/node_modules/hono/dist/validator/validator.js new file mode 100644 index 000000000..6b3689ae0 --- /dev/null +++ b/node_modules/hono/dist/validator/validator.js @@ -0,0 +1,86 @@ +// src/validator/validator.ts +import { getCookie } from "../helper/cookie/index.js"; +import { HTTPException } from "../http-exception.js"; +import { bufferToFormData } from "../utils/buffer.js"; +var jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/; +var multipartRegex = /^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/; +var urlencodedRegex = /^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/; +var validator = (target, validationFunc) => { + return async (c, next) => { + let value = {}; + const contentType = c.req.header("Content-Type"); + switch (target) { + case "json": + if (!contentType || !jsonRegex.test(contentType)) { + break; + } + try { + value = await c.req.json(); + } catch { + const message = "Malformed JSON in request body"; + throw new HTTPException(400, { message }); + } + break; + case "form": { + if (!contentType || !(multipartRegex.test(contentType) || urlencodedRegex.test(contentType))) { + break; + } + let formData; + if (c.req.bodyCache.formData) { + formData = await c.req.bodyCache.formData; + } else { + try { + const arrayBuffer = await c.req.arrayBuffer(); + formData = await bufferToFormData(arrayBuffer, contentType); + c.req.bodyCache.formData = formData; + } catch (e) { + let message = "Malformed FormData request."; + message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`; + throw new HTTPException(400, { message }); + } + } + const form = {}; + formData.forEach((value2, key) => { + if (key.endsWith("[]")) { + ; + (form[key] ??= []).push(value2); + } else if (Array.isArray(form[key])) { + ; + form[key].push(value2); + } else if (key in form) { + form[key] = [form[key], value2]; + } else { + form[key] = value2; + } + }); + value = form; + break; + } + case "query": + value = Object.fromEntries( + Object.entries(c.req.queries()).map(([k, v]) => { + return v.length === 1 ? [k, v[0]] : [k, v]; + }) + ); + break; + case "param": + value = c.req.param(); + break; + case "header": + value = c.req.header(); + break; + case "cookie": + value = getCookie(c); + break; + } + const res = await validationFunc(value, c); + if (res instanceof Response) { + return res; + } + c.req.addValidatedData(target, res); + return await next(); + }; +}; +export { + validator +}; diff --git a/node_modules/hono/package.json b/node_modules/hono/package.json new file mode 100644 index 000000000..d464324f8 --- /dev/null +++ b/node_modules/hono/package.json @@ -0,0 +1,691 @@ +{ + "name": "hono", + "version": "4.11.5", + "description": "Web framework built on Web Standards", + "main": "dist/cjs/index.js", + "type": "module", + "module": "dist/index.js", + "types": "dist/types/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "test": "tsc --noEmit && vitest --run", + "test:watch": "vitest --watch", + "test:deno": "deno test --allow-read --allow-env --allow-write --allow-net -c runtime-tests/deno/deno.json runtime-tests/deno && deno test --no-lock -c runtime-tests/deno-jsx/deno.precompile.json runtime-tests/deno-jsx && deno test --no-lock -c runtime-tests/deno-jsx/deno.react-jsx.json runtime-tests/deno-jsx", + "test:bun": "bun test --jsx-import-source ../../src/jsx runtime-tests/bun/*", + "test:fastly": "vitest --run --project fastly", + "test:node": "vitest --run --project node", + "test:workerd": "vitest --run --project workerd", + "test:lambda": "vitest --run --project lambda", + "test:lambda-edge": "vitest --run --project lambda-edge", + "test:all": "bun run test && bun test:deno && bun test:bun", + "lint": "eslint src runtime-tests build perf-measures benchmarks", + "lint:fix": "eslint src runtime-tests build perf-measures benchmarks --fix", + "format": "prettier --check --cache \"src/**/*.{js,ts,tsx}\" \"runtime-tests/**/*.{js,ts,tsx}\" \"build/**/*.{js,ts,tsx}\" \"perf-measures/**/*.{js,ts,tsx}\" \"benchmarks/**/*.{js,ts,tsx}\"", + "format:fix": "prettier --write --cache --cache-strategy metadata \"src/**/*.{js,ts,tsx}\" \"runtime-tests/**/*.{js,ts,tsx}\" \"build/**/*.{js,ts,tsx}\" \"perf-measures/**/*.{js,ts,tsx}\" \"benchmarks/**/*.{js,ts,tsx}\"", + "editorconfig-checker": "editorconfig-checker", + "copy:package.cjs.json": "cp ./package.cjs.json ./dist/cjs/package.json && cp ./package.cjs.json ./dist/types/package.json", + "build": "bun run --shell bun remove-dist && bun ./build/build.ts && bun run copy:package.cjs.json", + "postbuild": "publint", + "watch": "bun run --shell bun remove-dist && bun ./build/build.ts --watch && bun run copy:package.cjs.json", + "coverage": "vitest --run --coverage", + "prerelease": "bun test:deno && bun run build", + "release": "np", + "remove-dist": "rm -rf dist" + }, + "exports": { + ".": { + "types": "./dist/types/index.d.ts", + "import": "./dist/index.js", + "require": "./dist/cjs/index.js" + }, + "./request": { + "types": "./dist/types/request.d.ts", + "import": "./dist/request.js", + "require": "./dist/cjs/request.js" + }, + "./types": { + "types": "./dist/types/types.d.ts", + "import": "./dist/types.js", + "require": "./dist/cjs/types.js" + }, + "./hono-base": { + "types": "./dist/types/hono-base.d.ts", + "import": "./dist/hono-base.js", + "require": "./dist/cjs/hono-base.js" + }, + "./tiny": { + "types": "./dist/types/preset/tiny.d.ts", + "import": "./dist/preset/tiny.js", + "require": "./dist/cjs/preset/tiny.js" + }, + "./quick": { + "types": "./dist/types/preset/quick.d.ts", + "import": "./dist/preset/quick.js", + "require": "./dist/cjs/preset/quick.js" + }, + "./http-exception": { + "types": "./dist/types/http-exception.d.ts", + "import": "./dist/http-exception.js", + "require": "./dist/cjs/http-exception.js" + }, + "./basic-auth": { + "types": "./dist/types/middleware/basic-auth/index.d.ts", + "import": "./dist/middleware/basic-auth/index.js", + "require": "./dist/cjs/middleware/basic-auth/index.js" + }, + "./bearer-auth": { + "types": "./dist/types/middleware/bearer-auth/index.d.ts", + "import": "./dist/middleware/bearer-auth/index.js", + "require": "./dist/cjs/middleware/bearer-auth/index.js" + }, + "./body-limit": { + "types": "./dist/types/middleware/body-limit/index.d.ts", + "import": "./dist/middleware/body-limit/index.js", + "require": "./dist/cjs/middleware/body-limit/index.js" + }, + "./ip-restriction": { + "types": "./dist/types/middleware/ip-restriction/index.d.ts", + "import": "./dist/middleware/ip-restriction/index.js", + "require": "./dist/cjs/middleware/ip-restriction/index.js" + }, + "./cache": { + "types": "./dist/types/middleware/cache/index.d.ts", + "import": "./dist/middleware/cache/index.js", + "require": "./dist/cjs/middleware/cache/index.js" + }, + "./route": { + "types": "./dist/types/helper/route/index.d.ts", + "import": "./dist/helper/route/index.js", + "require": "./dist/cjs/helper/route/index.js" + }, + "./cookie": { + "types": "./dist/types/helper/cookie/index.d.ts", + "import": "./dist/helper/cookie/index.js", + "require": "./dist/cjs/helper/cookie/index.js" + }, + "./accepts": { + "types": "./dist/types/helper/accepts/index.d.ts", + "import": "./dist/helper/accepts/index.js", + "require": "./dist/cjs/helper/accepts/index.js" + }, + "./compress": { + "types": "./dist/types/middleware/compress/index.d.ts", + "import": "./dist/middleware/compress/index.js", + "require": "./dist/cjs/middleware/compress/index.js" + }, + "./context-storage": { + "types": "./dist/types/middleware/context-storage/index.d.ts", + "import": "./dist/middleware/context-storage/index.js", + "require": "./dist/cjs/middleware/context-storage/index.js" + }, + "./cors": { + "types": "./dist/types/middleware/cors/index.d.ts", + "import": "./dist/middleware/cors/index.js", + "require": "./dist/cjs/middleware/cors/index.js" + }, + "./csrf": { + "types": "./dist/types/middleware/csrf/index.d.ts", + "import": "./dist/middleware/csrf/index.js", + "require": "./dist/cjs/middleware/csrf/index.js" + }, + "./etag": { + "types": "./dist/types/middleware/etag/index.d.ts", + "import": "./dist/middleware/etag/index.js", + "require": "./dist/cjs/middleware/etag/index.js" + }, + "./trailing-slash": { + "types": "./dist/types/middleware/trailing-slash/index.d.ts", + "import": "./dist/middleware/trailing-slash/index.js", + "require": "./dist/cjs/middleware/trailing-slash/index.js" + }, + "./html": { + "types": "./dist/types/helper/html/index.d.ts", + "import": "./dist/helper/html/index.js", + "require": "./dist/cjs/helper/html/index.js" + }, + "./css": { + "types": "./dist/types/helper/css/index.d.ts", + "import": "./dist/helper/css/index.js", + "require": "./dist/cjs/helper/css/index.js" + }, + "./jsx": { + "types": "./dist/types/jsx/index.d.ts", + "import": "./dist/jsx/index.js", + "require": "./dist/cjs/jsx/index.js" + }, + "./jsx/jsx-dev-runtime": { + "types": "./dist/types/jsx/jsx-dev-runtime.d.ts", + "import": "./dist/jsx/jsx-dev-runtime.js", + "require": "./dist/cjs/jsx/jsx-dev-runtime.js" + }, + "./jsx/jsx-runtime": { + "types": "./dist/types/jsx/jsx-runtime.d.ts", + "import": "./dist/jsx/jsx-runtime.js", + "require": "./dist/cjs/jsx/jsx-runtime.js" + }, + "./jsx/streaming": { + "types": "./dist/types/jsx/streaming.d.ts", + "import": "./dist/jsx/streaming.js", + "require": "./dist/cjs/jsx/streaming.js" + }, + "./jsx-renderer": { + "types": "./dist/types/middleware/jsx-renderer/index.d.ts", + "import": "./dist/middleware/jsx-renderer/index.js", + "require": "./dist/cjs/middleware/jsx-renderer/index.js" + }, + "./jsx/dom": { + "types": "./dist/types/jsx/dom/index.d.ts", + "import": "./dist/jsx/dom/index.js", + "require": "./dist/cjs/jsx/dom/index.js" + }, + "./jsx/dom/jsx-dev-runtime": { + "types": "./dist/types/jsx/dom/jsx-dev-runtime.d.ts", + "import": "./dist/jsx/dom/jsx-dev-runtime.js", + "require": "./dist/cjs/jsx/dom/jsx-dev-runtime.js" + }, + "./jsx/dom/jsx-runtime": { + "types": "./dist/types/jsx/dom/jsx-runtime.d.ts", + "import": "./dist/jsx/dom/jsx-runtime.js", + "require": "./dist/cjs/jsx/dom/jsx-runtime.js" + }, + "./jsx/dom/client": { + "types": "./dist/types/jsx/dom/client.d.ts", + "import": "./dist/jsx/dom/client.js", + "require": "./dist/cjs/jsx/dom/client.js" + }, + "./jsx/dom/css": { + "types": "./dist/types/jsx/dom/css.d.ts", + "import": "./dist/jsx/dom/css.js", + "require": "./dist/cjs/jsx/dom/css.js" + }, + "./jsx/dom/server": { + "types": "./dist/types/jsx/dom/server.d.ts", + "import": "./dist/jsx/dom/server.js", + "require": "./dist/cjs/jsx/dom/server.js" + }, + "./jwt": { + "types": "./dist/types/middleware/jwt/index.d.ts", + "import": "./dist/middleware/jwt/index.js", + "require": "./dist/cjs/middleware/jwt/index.js" + }, + "./jwk": { + "types": "./dist/types/middleware/jwk/index.d.ts", + "import": "./dist/middleware/jwk/index.js", + "require": "./dist/cjs/middleware/jwk/index.js" + }, + "./timeout": { + "types": "./dist/types/middleware/timeout/index.d.ts", + "import": "./dist/middleware/timeout/index.js", + "require": "./dist/cjs/middleware/timeout/index.js" + }, + "./timing": { + "types": "./dist/types/middleware/timing/index.d.ts", + "import": "./dist/middleware/timing/index.js", + "require": "./dist/cjs/middleware/timing/index.js" + }, + "./logger": { + "types": "./dist/types/middleware/logger/index.d.ts", + "import": "./dist/middleware/logger/index.js", + "require": "./dist/cjs/middleware/logger/index.js" + }, + "./method-override": { + "types": "./dist/types/middleware/method-override/index.d.ts", + "import": "./dist/middleware/method-override/index.js", + "require": "./dist/cjs/middleware/method-override/index.js" + }, + "./powered-by": { + "types": "./dist/types/middleware/powered-by/index.d.ts", + "import": "./dist/middleware/powered-by/index.js", + "require": "./dist/cjs/middleware/powered-by/index.js" + }, + "./pretty-json": { + "types": "./dist/types/middleware/pretty-json/index.d.ts", + "import": "./dist/middleware/pretty-json/index.js", + "require": "./dist/cjs/middleware/pretty-json/index.js" + }, + "./request-id": { + "types": "./dist/types/middleware/request-id/index.d.ts", + "import": "./dist/middleware/request-id/index.js", + "require": "./dist/cjs/middleware/request-id/index.js" + }, + "./language": { + "types": "./dist/types/middleware/language/index.d.ts", + "import": "./dist/middleware/language/index.js", + "require": "./dist/cjs/middleware/language/index.js" + }, + "./secure-headers": { + "types": "./dist/types/middleware/secure-headers/index.d.ts", + "import": "./dist/middleware/secure-headers/index.js", + "require": "./dist/cjs/middleware/secure-headers/index.js" + }, + "./combine": { + "types": "./dist/types/middleware/combine/index.d.ts", + "import": "./dist/middleware/combine/index.js", + "require": "./dist/cjs/middleware/combine/index.js" + }, + "./ssg": { + "types": "./dist/types/helper/ssg/index.d.ts", + "import": "./dist/helper/ssg/index.js", + "require": "./dist/cjs/helper/ssg/index.js" + }, + "./streaming": { + "types": "./dist/types/helper/streaming/index.d.ts", + "import": "./dist/helper/streaming/index.js", + "require": "./dist/cjs/helper/streaming/index.js" + }, + "./validator": { + "types": "./dist/types/validator/index.d.ts", + "import": "./dist/validator/index.js", + "require": "./dist/cjs/validator/index.js" + }, + "./router": { + "types": "./dist/types/router.d.ts", + "import": "./dist/router.js", + "require": "./dist/cjs/router.js" + }, + "./router/reg-exp-router": { + "types": "./dist/types/router/reg-exp-router/index.d.ts", + "import": "./dist/router/reg-exp-router/index.js", + "require": "./dist/cjs/router/reg-exp-router/index.js" + }, + "./router/smart-router": { + "types": "./dist/types/router/smart-router/index.d.ts", + "import": "./dist/router/smart-router/index.js", + "require": "./dist/cjs/router/smart-router/index.js" + }, + "./router/trie-router": { + "types": "./dist/types/router/trie-router/index.d.ts", + "import": "./dist/router/trie-router/index.js", + "require": "./dist/cjs/router/trie-router/index.js" + }, + "./router/pattern-router": { + "types": "./dist/types/router/pattern-router/index.d.ts", + "import": "./dist/router/pattern-router/index.js", + "require": "./dist/cjs/router/pattern-router/index.js" + }, + "./router/linear-router": { + "types": "./dist/types/router/linear-router/index.d.ts", + "import": "./dist/router/linear-router/index.js", + "require": "./dist/cjs/router/linear-router/index.js" + }, + "./utils/jwt": { + "types": "./dist/types/utils/jwt/index.d.ts", + "import": "./dist/utils/jwt/index.js", + "require": "./dist/cjs/utils/jwt/index.js" + }, + "./utils/*": { + "types": "./dist/types/utils/*.d.ts", + "import": "./dist/utils/*.js", + "require": "./dist/cjs/utils/*.js" + }, + "./client": { + "types": "./dist/types/client/index.d.ts", + "import": "./dist/client/index.js", + "require": "./dist/cjs/client/index.js" + }, + "./adapter": { + "types": "./dist/types/helper/adapter/index.d.ts", + "import": "./dist/helper/adapter/index.js", + "require": "./dist/cjs/helper/adapter/index.js" + }, + "./factory": { + "types": "./dist/types/helper/factory/index.d.ts", + "import": "./dist/helper/factory/index.js", + "require": "./dist/cjs/helper/factory/index.js" + }, + "./serve-static": { + "types": "./dist/types/middleware/serve-static/index.d.ts", + "import": "./dist/middleware/serve-static/index.js", + "require": "./dist/cjs/middleware/serve-static/index.js" + }, + "./cloudflare-workers": { + "types": "./dist/types/adapter/cloudflare-workers/index.d.ts", + "import": "./dist/adapter/cloudflare-workers/index.js", + "require": "./dist/cjs/adapter/cloudflare-workers/index.js" + }, + "./cloudflare-pages": { + "types": "./dist/types/adapter/cloudflare-pages/index.d.ts", + "import": "./dist/adapter/cloudflare-pages/index.js", + "require": "./dist/cjs/adapter/cloudflare-pages/index.js" + }, + "./deno": { + "types": "./dist/types/adapter/deno/index.d.ts", + "import": "./dist/adapter/deno/index.js", + "require": "./dist/cjs/adapter/deno/index.js" + }, + "./bun": { + "types": "./dist/types/adapter/bun/index.d.ts", + "import": "./dist/adapter/bun/index.js", + "require": "./dist/cjs/adapter/bun/index.js" + }, + "./aws-lambda": { + "types": "./dist/types/adapter/aws-lambda/index.d.ts", + "import": "./dist/adapter/aws-lambda/index.js", + "require": "./dist/cjs/adapter/aws-lambda/index.js" + }, + "./vercel": { + "types": "./dist/types/adapter/vercel/index.d.ts", + "import": "./dist/adapter/vercel/index.js", + "require": "./dist/cjs/adapter/vercel/index.js" + }, + "./netlify": { + "types": "./dist/types/adapter/netlify/index.d.ts", + "import": "./dist/adapter/netlify/index.js", + "require": "./dist/cjs/adapter/netlify/index.js" + }, + "./lambda-edge": { + "types": "./dist/types/adapter/lambda-edge/index.d.ts", + "import": "./dist/adapter/lambda-edge/index.js", + "require": "./dist/cjs/adapter/lambda-edge/index.js" + }, + "./service-worker": { + "types": "./dist/types/adapter/service-worker/index.d.ts", + "import": "./dist/adapter/service-worker/index.js", + "require": "./dist/cjs/adapter/service-worker/index.js" + }, + "./testing": { + "types": "./dist/types/helper/testing/index.d.ts", + "import": "./dist/helper/testing/index.js", + "require": "./dist/cjs/helper/testing/index.js" + }, + "./dev": { + "types": "./dist/types/helper/dev/index.d.ts", + "import": "./dist/helper/dev/index.js", + "require": "./dist/cjs/helper/dev/index.js" + }, + "./ws": { + "types": "./dist/types/helper/websocket/index.d.ts", + "import": "./dist/helper/websocket/index.js", + "require": "./dist/cjs/helper/websocket/index.js" + }, + "./conninfo": { + "types": "./dist/types/helper/conninfo/index.d.ts", + "import": "./dist/helper/conninfo/index.js", + "require": "./dist/cjs/helper/conninfo/index.js" + }, + "./proxy": { + "types": "./dist/types/helper/proxy/index.d.ts", + "import": "./dist/helper/proxy/index.js", + "require": "./dist/cjs/helper/proxy/index.js" + } + }, + "typesVersions": { + "*": { + "request": [ + "./dist/types/request" + ], + "types": [ + "./dist/types/types" + ], + "hono-base": [ + "./dist/types/hono-base" + ], + "tiny": [ + "./dist/types/preset/tiny" + ], + "quick": [ + "./dist/types/preset/quick" + ], + "http-exception": [ + "./dist/types/http-exception" + ], + "basic-auth": [ + "./dist/types/middleware/basic-auth" + ], + "bearer-auth": [ + "./dist/types/middleware/bearer-auth" + ], + "body-limit": [ + "./dist/types/middleware/body-limit" + ], + "ip-restriction": [ + "./dist/types/middleware/ip-restriction" + ], + "cache": [ + "./dist/types/middleware/cache" + ], + "route": [ + "./dist/types/helper/route" + ], + "cookie": [ + "./dist/types/helper/cookie" + ], + "accepts": [ + "./dist/types/helper/accepts" + ], + "compress": [ + "./dist/types/middleware/compress" + ], + "context-storage": [ + "./dist/types/middleware/context-storage" + ], + "cors": [ + "./dist/types/middleware/cors" + ], + "csrf": [ + "./dist/types/middleware/csrf" + ], + "etag": [ + "./dist/types/middleware/etag" + ], + "trailing-slash": [ + "./dist/types/middleware/trailing-slash" + ], + "html": [ + "./dist/types/helper/html" + ], + "css": [ + "./dist/types/helper/css" + ], + "jsx": [ + "./dist/types/jsx" + ], + "jsx/jsx-runtime": [ + "./dist/types/jsx/jsx-runtime.d.ts" + ], + "jsx/jsx-dev-runtime": [ + "./dist/types/jsx/jsx-dev-runtime.d.ts" + ], + "jsx/streaming": [ + "./dist/types/jsx/streaming.d.ts" + ], + "jsx-renderer": [ + "./dist/types/middleware/jsx-renderer" + ], + "jsx/dom": [ + "./dist/types/jsx/dom" + ], + "jsx/dom/client": [ + "./dist/types/jsx/dom/client.d.ts" + ], + "jsx/dom/css": [ + "./dist/types/jsx/dom/css.d.ts" + ], + "jsx/dom/server": [ + "./dist/types/jsx/dom/server.d.ts" + ], + "jwt": [ + "./dist/types/middleware/jwt" + ], + "timeout": [ + "./dist/types/middleware/timeout" + ], + "timing": [ + "./dist/types/middleware/timing" + ], + "logger": [ + "./dist/types/middleware/logger" + ], + "method-override": [ + "./dist/types/middleware/method-override" + ], + "powered-by": [ + "./dist/types/middleware/powered-by" + ], + "pretty-json": [ + "./dist/types/middleware/pretty-json" + ], + "request-id": [ + "./dist/types/middleware/request-id" + ], + "language": [ + "./dist/types/middleware/language" + ], + "streaming": [ + "./dist/types/helper/streaming" + ], + "ssg": [ + "./dist/types/helper/ssg" + ], + "secure-headers": [ + "./dist/types/middleware/secure-headers" + ], + "combine": [ + "./dist/types/middleware/combine" + ], + "validator": [ + "./dist/types/validator/index.d.ts" + ], + "router": [ + "./dist/types/router.d.ts" + ], + "router/reg-exp-router": [ + "./dist/types/router/reg-exp-router/router.d.ts" + ], + "router/smart-router": [ + "./dist/types/router/smart-router/router.d.ts" + ], + "router/trie-router": [ + "./dist/types/router/trie-router/router.d.ts" + ], + "router/pattern-router": [ + "./dist/types/router/pattern-router/router.d.ts" + ], + "router/linear-router": [ + "./dist/types/router/linear-router/router.d.ts" + ], + "utils/jwt": [ + "./dist/types/utils/jwt/index.d.ts" + ], + "utils/*": [ + "./dist/types/utils/*" + ], + "client": [ + "./dist/types/client/index.d.ts" + ], + "adapter": [ + "./dist/types/helper/adapter/index.d.ts" + ], + "factory": [ + "./dist/types/helper/factory/index.d.ts" + ], + "serve-static": [ + "./dist/types/middleware/serve-static" + ], + "cloudflare-workers": [ + "./dist/types/adapter/cloudflare-workers" + ], + "cloudflare-pages": [ + "./dist/types/adapter/cloudflare-pages" + ], + "deno": [ + "./dist/types/adapter/deno" + ], + "bun": [ + "./dist/types/adapter/bun" + ], + "nextjs": [ + "./dist/types/adapter/nextjs" + ], + "aws-lambda": [ + "./dist/types/adapter/aws-lambda" + ], + "vercel": [ + "./dist/types/adapter/vercel" + ], + "lambda-edge": [ + "./dist/types/adapter/lambda-edge" + ], + "service-worker": [ + "./dist/types/adapter/service-worker" + ], + "testing": [ + "./dist/types/helper/testing" + ], + "dev": [ + "./dist/types/helper/dev" + ], + "ws": [ + "./dist/types/helper/websocket" + ], + "conninfo": [ + "./dist/types/helper/conninfo" + ], + "proxy": [ + "./dist/types/helper/proxy" + ] + } + }, + "author": "Yusuke Wada (https://github.com/yusukebe)", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/honojs/hono.git" + }, + "publishConfig": { + "registry": "https://registry.npmjs.org" + }, + "homepage": "https://hono.dev", + "keywords": [ + "hono", + "web", + "app", + "http", + "application", + "framework", + "router", + "cloudflare", + "workers", + "fastly", + "compute", + "deno", + "bun", + "lambda", + "nodejs" + ], + "devDependencies": { + "@hono/eslint-config": "^2.0.5", + "@hono/node-server": "^1.13.5", + "@types/glob": "^9.0.0", + "@types/jsdom": "^21.1.7", + "@types/node": "^24.3.0", + "@typescript/native-preview": "7.0.0-dev.20251220.1", + "@vitest/coverage-v8": "^3.2.4", + "arg": "^5.0.2", + "bun-types": "^1.2.20", + "editorconfig-checker": "6.1.1", + "esbuild": "^0.27.1", + "eslint": "9.39.1", + "glob": "^11.0.0", + "jsdom": "22.1.0", + "msw": "^2.6.0", + "np": "10.2.0", + "oxc-parser": "^0.96.0", + "pkg-pr-new": "^0.0.53", + "prettier": "3.7.4", + "publint": "0.3.15", + "typescript": "^5.9.2", + "undici": "^6.21.3", + "vite-plugin-fastly-js-compute": "^0.4.2", + "vitest": "^3.2.4", + "wrangler": "4.12.0", + "ws": "^8.18.0", + "zod": "^3.23.8" + }, + "packageManager": "bun@1.2.20", + "engines": { + "node": ">=16.9.0" + } +} diff --git a/node_modules/http-errors/HISTORY.md b/node_modules/http-errors/HISTORY.md new file mode 100644 index 000000000..3d81d265f --- /dev/null +++ b/node_modules/http-errors/HISTORY.md @@ -0,0 +1,186 @@ +2.0.1 / 2025-11-20 +================== + + * deps: use tilde notation for dependencies + * deps: update statuses to 2.0.2 + +2.0.0 / 2021-12-17 +================== + + * Drop support for Node.js 0.6 + * Remove `I'mateapot` export; use `ImATeapot` instead + * Remove support for status being non-first argument + * Rename `UnorderedCollection` constructor to `TooEarly` + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: statuses@2.0.1 + - Fix messaging casing of `418 I'm a Teapot` + - Remove code 306 + - Rename `425 Unordered Collection` to standard `425 Too Early` + +2021-11-14 / 1.8.1 +================== + + * deps: toidentifier@1.0.1 + +2020-06-29 / 1.8.0 +================== + + * Add `isHttpError` export to determine if value is an HTTP error + * deps: setprototypeof@1.2.0 + +2019-06-24 / 1.7.3 +================== + + * deps: inherits@2.0.4 + +2019-02-18 / 1.7.2 +================== + + * deps: setprototypeof@1.1.1 + +2018-09-08 / 1.7.1 +================== + + * Fix error creating objects in some environments + +2018-07-30 / 1.7.0 +================== + + * Set constructor name when possible + * Use `toidentifier` module to make class names + * deps: statuses@'>= 1.5.0 < 2' + +2018-03-29 / 1.6.3 +================== + + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: setprototypeof@1.1.0 + * deps: statuses@'>= 1.4.0 < 2' + +2017-08-04 / 1.6.2 +================== + + * deps: depd@1.1.1 + - Remove unnecessary `Buffer` loading + +2017-02-20 / 1.6.1 +================== + + * deps: setprototypeof@1.0.3 + - Fix shim for old browsers + +2017-02-14 / 1.6.0 +================== + + * Accept custom 4xx and 5xx status codes in factory + * Add deprecation message to `"I'mateapot"` export + * Deprecate passing status code as anything except first argument in factory + * Deprecate using non-error status codes + * Make `message` property enumerable for `HttpError`s + +2016-11-16 / 1.5.1 +================== + + * deps: inherits@2.0.3 + - Fix issue loading in browser + * deps: setprototypeof@1.0.2 + * deps: statuses@'>= 1.3.1 < 2' + +2016-05-18 / 1.5.0 +================== + + * Support new code `421 Misdirected Request` + * Use `setprototypeof` module to replace `__proto__` setting + * deps: statuses@'>= 1.3.0 < 2' + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: enable strict mode + +2016-01-28 / 1.4.0 +================== + + * Add `HttpError` export, for `err instanceof createError.HttpError` + * deps: inherits@2.0.1 + * deps: statuses@'>= 1.2.1 < 2' + - Fix message for status 451 + - Remove incorrect nginx status code + +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/node_modules/http-errors/LICENSE b/node_modules/http-errors/LICENSE new file mode 100644 index 000000000..82af4df54 --- /dev/null +++ b/node_modules/http-errors/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Copyright (c) 2016 Douglas Christopher Wilson doug@somethingdoug.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/http-errors/README.md b/node_modules/http-errors/README.md new file mode 100644 index 000000000..a8b7330b0 --- /dev/null +++ b/node_modules/http-errors/README.md @@ -0,0 +1,169 @@ +# http-errors + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][node-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Install + +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): + +```console +$ npm install http-errors +``` + +## Example + +```js +var createError = require('http-errors') +var express = require('express') +var app = express() + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')) + next() +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +### Error Properties + +- `expose` - can be used to signal if `message` should be sent to the client, + defaulting to `false` when `status` >= 500 +- `headers` - can be an object of header names to values to be sent to the + client, defaulting to `undefined`. When defined, the key names should all + be lower-cased +- `message` - the traditional error message, which should be kept short and all + single line +- `status` - the status code of the error, mirroring `statusCode` for general + compatibility +- `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + +Create a new error object with the given message `msg`. +The error object inherits from `createError.HttpError`. + +```js +var err = createError(404, 'This video does not exist!') +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### createError([status], [error], [properties]) + +Extend the given `error` object with `createError.HttpError` +properties. This will not alter the inheritance of the given +`error` object, and the modified `error` object is the +return value. + + + +```js +fs.readFile('foo.txt', function (err, buf) { + if (err) { + if (err.code === 'ENOENT') { + var httpError = createError(404, err, { expose: false }) + } else { + var httpError = createError(500, err) + } + } +}) +``` + +- `status` - the status code as a number +- `error` - the error object to extend +- `properties` - custom properties to attach to the object + +### createError.isHttpError(val) + +Determine if the provided `val` is an `HttpError`. This will return `true` +if the error inherits from the `HttpError` constructor of this module or +matches the "duck type" for an error this module creates. All outputs from +the `createError` factory will return `true` for this function, including +if an non-`HttpError` was passed into the factory. + +### new createError\[code || name\](\[msg]\)) + +Create a new error object with the given message `msg`. +The error object inherits from `createError.HttpError`. + +```js +var err = new createError.NotFound() +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +#### List of all constructors + +|Status Code|Constructor Name | +|-----------|-----------------------------| +|400 |BadRequest | +|401 |Unauthorized | +|402 |PaymentRequired | +|403 |Forbidden | +|404 |NotFound | +|405 |MethodNotAllowed | +|406 |NotAcceptable | +|407 |ProxyAuthenticationRequired | +|408 |RequestTimeout | +|409 |Conflict | +|410 |Gone | +|411 |LengthRequired | +|412 |PreconditionFailed | +|413 |PayloadTooLarge | +|414 |URITooLong | +|415 |UnsupportedMediaType | +|416 |RangeNotSatisfiable | +|417 |ExpectationFailed | +|418 |ImATeapot | +|421 |MisdirectedRequest | +|422 |UnprocessableEntity | +|423 |Locked | +|424 |FailedDependency | +|425 |TooEarly | +|426 |UpgradeRequired | +|428 |PreconditionRequired | +|429 |TooManyRequests | +|431 |RequestHeaderFieldsTooLarge | +|451 |UnavailableForLegalReasons | +|500 |InternalServerError | +|501 |NotImplemented | +|502 |BadGateway | +|503 |ServiceUnavailable | +|504 |GatewayTimeout | +|505 |HTTPVersionNotSupported | +|506 |VariantAlsoNegotiates | +|507 |InsufficientStorage | +|508 |LoopDetected | +|509 |BandwidthLimitExceeded | +|510 |NotExtended | +|511 |NetworkAuthenticationRequired| + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/http-errors/master?label=ci +[ci-url]: https://github.com/jshttp/http-errors/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/http-errors/master +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors?branch=master +[node-image]: https://badgen.net/npm/node/http-errors +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/http-errors +[npm-url]: https://npmjs.org/package/http-errors +[npm-version-image]: https://badgen.net/npm/v/http-errors +[travis-image]: https://badgen.net/travis/jshttp/http-errors/master +[travis-url]: https://travis-ci.org/jshttp/http-errors diff --git a/node_modules/http-errors/index.js b/node_modules/http-errors/index.js new file mode 100644 index 000000000..82271f6f5 --- /dev/null +++ b/node_modules/http-errors/index.js @@ -0,0 +1,290 @@ +/*! + * http-errors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('http-errors') +var setPrototypeOf = require('setprototypeof') +var statuses = require('statuses') +var inherits = require('inherits') +var toIdentifier = require('toidentifier') + +/** + * Module exports. + * @public + */ + +module.exports = createError +module.exports.HttpError = createHttpErrorConstructor() +module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError) + +// Populate exports for all constructors +populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) + +/** + * Get the code class of a status code. + * @private + */ + +function codeClass (status) { + return Number(String(status).charAt(0) + '00') +} + +/** + * Create a new HTTP Error. + * + * @returns {Error} + * @public + */ + +function createError () { + // so much arity going on ~_~ + var err + var msg + var status = 500 + var props = {} + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i] + var type = typeof arg + if (type === 'object' && arg instanceof Error) { + err = arg + status = err.status || err.statusCode || status + } else if (type === 'number' && i === 0) { + status = arg + } else if (type === 'string') { + msg = arg + } else if (type === 'object') { + props = arg + } else { + throw new TypeError('argument #' + (i + 1) + ' unsupported type ' + type) + } + } + + if (typeof status === 'number' && (status < 400 || status >= 600)) { + deprecate('non-error status code; use only 4xx or 5xx status codes') + } + + if (typeof status !== 'number' || + (!statuses.message[status] && (status < 400 || status >= 600))) { + status = 500 + } + + // constructor + var HttpError = createError[status] || createError[codeClass(status)] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses.message[status]) + Error.captureStackTrace(err, createError) + } + + if (!HttpError || !(err instanceof HttpError) || err.status !== status) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err +} + +/** + * Create HTTP error abstract base class. + * @private + */ + +function createHttpErrorConstructor () { + function HttpError () { + throw new TypeError('cannot construct abstract class') + } + + inherits(HttpError, Error) + + return HttpError +} + +/** + * Create a constructor for a client error. + * @private + */ + +function createClientErrorConstructor (HttpError, name, code) { + var className = toClassName(name) + + function ClientError (message) { + // create the error object + var msg = message != null ? message : statuses.message[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ClientError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ClientError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ClientError, HttpError) + nameFunc(ClientError, className) + + ClientError.prototype.status = code + ClientError.prototype.statusCode = code + ClientError.prototype.expose = true + + return ClientError +} + +/** + * Create function to test is a value is a HttpError. + * @private + */ + +function createIsHttpErrorFunction (HttpError) { + return function isHttpError (val) { + if (!val || typeof val !== 'object') { + return false + } + + if (val instanceof HttpError) { + return true + } + + return val instanceof Error && + typeof val.expose === 'boolean' && + typeof val.statusCode === 'number' && val.status === val.statusCode + } +} + +/** + * Create a constructor for a server error. + * @private + */ + +function createServerErrorConstructor (HttpError, name, code) { + var className = toClassName(name) + + function ServerError (message) { + // create the error object + var msg = message != null ? message : statuses.message[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ServerError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ServerError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ServerError, HttpError) + nameFunc(ServerError, className) + + ServerError.prototype.status = code + ServerError.prototype.statusCode = code + ServerError.prototype.expose = false + + return ServerError +} + +/** + * Set the name of a function, if possible. + * @private + */ + +function nameFunc (func, name) { + var desc = Object.getOwnPropertyDescriptor(func, 'name') + + if (desc && desc.configurable) { + desc.value = name + Object.defineProperty(func, 'name', desc) + } +} + +/** + * Populate the exports object with constructors for every error class. + * @private + */ + +function populateConstructorExports (exports, codes, HttpError) { + codes.forEach(function forEachCode (code) { + var CodeError + var name = toIdentifier(statuses.message[code]) + + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError, name, code) + break + case 500: + CodeError = createServerErrorConstructor(HttpError, name, code) + break + } + + if (CodeError) { + // export the constructor + exports[code] = CodeError + exports[name] = CodeError + } + }) +} + +/** + * Get a class name from a name identifier. + * + * @param {string} name + * @returns {string} + * @private + */ + +function toClassName (name) { + return name.slice(-5) === 'Error' ? name : name + 'Error' +} diff --git a/node_modules/http-errors/package.json b/node_modules/http-errors/package.json new file mode 100644 index 000000000..4b46d62ad --- /dev/null +++ b/node_modules/http-errors/package.json @@ -0,0 +1,54 @@ +{ + "name": "http-errors", + "description": "Create HTTP error objects", + "version": "2.0.1", + "author": "Jonathan Ong (http://jongleberry.com)", + "contributors": [ + "Alan Plum ", + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "jshttp/http-errors", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.32.0", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.1.3", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint . && node ./scripts/lint-readme-list.js", + "test": "mocha --reporter spec", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + }, + "keywords": [ + "http", + "error" + ], + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ] +} diff --git a/node_modules/iconv-lite/LICENSE b/node_modules/iconv-lite/LICENSE new file mode 100644 index 000000000..d518d8376 --- /dev/null +++ b/node_modules/iconv-lite/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011 Alexander Shtuchkin + +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/iconv-lite/README.md b/node_modules/iconv-lite/README.md new file mode 100644 index 000000000..78a7a5f1c --- /dev/null +++ b/node_modules/iconv-lite/README.md @@ -0,0 +1,138 @@ +## iconv-lite: Pure JS character encoding conversion + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-downloads-url] +[![License][license-image]][license-url] +[![NPM Install Size][npm-install-size-image]][npm-install-size-url] + +* No need for native code compilation. Quick to install, works on Windows, Web, and in sandboxed environments. +* Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser), + [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. +* Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). +* Intuitive encode/decode API, including Streaming support. +* In-browser usage via [browserify](https://github.com/substack/node-browserify) or [webpack](https://webpack.js.org/) (~180kb gzip compressed with Buffer shim included). +* Typescript [type definition file](https://github.com/ashtuchkin/iconv-lite/blob/master/lib/index.d.ts) included. +* React Native is supported (need to install `stream` module to enable Streaming API). + +## Usage + +### Basic API + +```javascript +var iconv = require('iconv-lite'); + +// Convert from an encoded buffer to a js string. +str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); + +// Convert from a js string to an encoded buffer. +buf = iconv.encode("Sample input string", 'win1251'); + +// Check if encoding is supported +iconv.encodingExists("us-ascii") +``` + +### Streaming API + +```javascript +// Decode stream (from binary data stream to js strings) +http.createServer(function(req, res) { + var converterStream = iconv.decodeStream('win1251'); + req.pipe(converterStream); + + converterStream.on('data', function(str) { + console.log(str); // Do something with decoded strings, chunk-by-chunk. + }); +}); + +// Convert encoding streaming example +fs.createReadStream('file-in-win1251.txt') + .pipe(iconv.decodeStream('win1251')) + .pipe(iconv.encodeStream('ucs2')) + .pipe(fs.createWriteStream('file-in-ucs2.txt')); + +// Sugar: all encode/decode streams have .collect(cb) method to accumulate data. +http.createServer(function(req, res) { + req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { + assert(typeof body == 'string'); + console.log(body); // full request body string + }); +}); +``` + +## Supported encodings + + * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. + * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap, utf32, utf32-le, and utf32-be. + * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, + IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. + Aliases like 'latin1', 'us-ascii' also supported. + * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP. + +See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). + +Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! + +Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! + +## Encoding/decoding speed + +Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). +Note: your results may vary, so please always check on your hardware. + + operation iconv@2.1.4 iconv-lite@0.4.7 + ---------------------------------------------------------- + encode('win1251') ~96 Mb/s ~320 Mb/s + decode('win1251') ~95 Mb/s ~246 Mb/s + +## BOM handling + + * Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options + (f.ex. `iconv.decode(buf, enc, {stripBOM: false})`). + A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found. + * If you want to detect UTF-8 BOM when decoding other encodings, use [node-autodetect-decoder-stream](https://github.com/danielgindi/node-autodetect-decoder-stream) module. + * Encoding: No BOM added, unless overridden by `addBOM: true` option. + +## UTF-16 Encodings + +This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be +smart about endianness in the following ways: + * Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be + overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`. + * Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override. + +## UTF-32 Encodings + +This library supports UTF-32LE, UTF-32BE and UTF-32 encodings. Like the UTF-16 encoding above, UTF-32 defaults to UTF-32LE, but uses BOM and 'spaces heuristics' to determine input endianness. + * The default of UTF-32LE can be overridden with the `defaultEncoding: 'utf-32be'` option. Strips BOM unless `stripBOM: false`. + * Encoding: uses UTF-32LE and writes BOM by default. Use `addBOM: false` to override. (`defaultEncoding: 'utf-32be'` can also be used here to change encoding.) + +## Other notes + +When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). +Untranslatable characters are set to � or ?. No transliteration is currently supported. +Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see [#65](https://github.com/ashtuchkin/iconv-lite/issues/65), [#77](https://github.com/ashtuchkin/iconv-lite/issues/77)). + +## Testing + +```sh +git clone git@github.com:ashtuchkin/iconv-lite.git +cd iconv-lite +npm install +npm test + +# To view performance: +npm run test:performance + +# To view test coverage: +npm run test:cov +open coverage/index.html +``` + +[npm-downloads-image]: https://badgen.net/npm/dm/iconv-lite +[npm-downloads-url]: https://npmcharts.com/compare/iconv-lite?minimal=true +[npm-url]: https://npmjs.org/package/iconv-lite +[npm-version-image]: https://badgen.net/npm/v/iconv-lite +[npm-install-size-image]: https://badgen.net/packagephobia/install/iconv-lite +[npm-install-size-url]: https://packagephobia.com/result?p=iconv-lite +[license-image]: https://img.shields.io/npm/l/iconv-lite.svg +[license-url]: https://github.com/ashtuchkin/iconv-lite/blob/HEAD/LICENSE \ No newline at end of file diff --git a/node_modules/iconv-lite/encodings/dbcs-codec.js b/node_modules/iconv-lite/encodings/dbcs-codec.js new file mode 100644 index 000000000..bfec7f2ef --- /dev/null +++ b/node_modules/iconv-lite/encodings/dbcs-codec.js @@ -0,0 +1,532 @@ +"use strict" +var Buffer = require("safer-buffer").Buffer + +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. + +exports._dbcs = DBCSCodec + +var UNASSIGNED = -1 +var GB18030_CODE = -2 +var SEQ_START = -10 +var NODE_START = -1000 +var UNASSIGNED_NODE = new Array(0x100) +var DEF_CHAR = -1 + +for (var i = 0; i < 0x100; i++) { UNASSIGNED_NODE[i] = UNASSIGNED } + +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec (codecOptions, iconv) { + this.encodingName = codecOptions.encodingName + if (!codecOptions) { throw new Error("DBCS codec is called without the data.") } + if (!codecOptions.table) { throw new Error("Encoding '" + this.encodingName + "' has no data.") } + + // Load tables. + var mappingTable = codecOptions.table() + + // Decode tables: MBCS -> Unicode. + + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = [] + this.decodeTables[0] = UNASSIGNED_NODE.slice(0) // Create root node. + + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = [] + + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) { this._addDecodeChunk(mappingTable[i]) } + + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === "function") { + this.gb18030 = codecOptions.gb18030() // Load GB18030 ranges. + + // Add GB18030 common decode nodes. + var commonThirdByteNodeIdx = this.decodeTables.length + this.decodeTables.push(UNASSIGNED_NODE.slice(0)) + + var commonFourthByteNodeIdx = this.decodeTables.length + this.decodeTables.push(UNASSIGNED_NODE.slice(0)) + + // Fill out the tree + var firstByteNode = this.decodeTables[0] + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]] + for (var j = 0x30; j <= 0x39; j++) { + if (secondByteNode[j] === UNASSIGNED) { + secondByteNode[j] = NODE_START - commonThirdByteNodeIdx + } else if (secondByteNode[j] > NODE_START) { + throw new Error("gb18030 decode tables conflict at byte 2") + } + + var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]] + for (var k = 0x81; k <= 0xFE; k++) { + if (thirdByteNode[k] === UNASSIGNED) { + thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx + } else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) { + continue + } else if (thirdByteNode[k] > NODE_START) { + throw new Error("gb18030 decode tables conflict at byte 3") + } + + var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]] + for (var l = 0x30; l <= 0x39; l++) { + if (fourthByteNode[l] === UNASSIGNED) { fourthByteNode[l] = GB18030_CODE } + } + } + } + } + } + + this.defaultCharUnicode = iconv.defaultCharUnicode + + // Encode tables: Unicode -> DBCS. + + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = [] + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = [] + + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {} + if (codecOptions.encodeSkipVals) { + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i] + if (typeof val === "number") { skipEncodeChars[val] = true } else { + for (var j = val.from; j <= val.to; j++) { skipEncodeChars[j] = true } + } + } + } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars) + + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) { + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) { this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]) } + } + } + + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)] + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]["?"] + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0) +} + +DBCSCodec.prototype.encoder = DBCSEncoder +DBCSCodec.prototype.decoder = DBCSDecoder + +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function (addr) { + var bytes = [] + for (; addr > 0; addr >>>= 8) { bytes.push(addr & 0xFF) } + if (bytes.length == 0) { bytes.push(0) } + + var node = this.decodeTables[0] + for (var i = bytes.length - 1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]] + + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)) + } else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val] + } else { throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)) } + } + return node +} + +DBCSCodec.prototype._addDecodeChunk = function (chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16) + + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr) + curAddr = curAddr & 0xFF + + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k] + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++) + if (code >= 0xD800 && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++) + if (codeTrail >= 0xDC00 && codeTrail < 0xE000) { writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00) } else { throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]) } + } else if (code > 0x0FF0 && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2 + var seq = [] + for (var m = 0; m < len; m++) { seq.push(part.charCodeAt(l++)) } // Simple variation: don't support surrogates or subsequences in seq. + + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length + this.decodeTableSeq.push(seq) + } else { writeTable[curAddr++] = code } // Basic char + } + } else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1 + for (var l = 0; l < part; l++) { writeTable[curAddr++] = charCode++ } + } else { throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]) } + } + if (curAddr > 0xFF) { throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr) } +} + +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function (uCode) { + var high = uCode >> 8 // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) { + this.encodeTable[high] = UNASSIGNED_NODE.slice(0) + } // Create bucket on demand. + return this.encodeTable[high] +} + +DBCSCodec.prototype._setEncodeChar = function (uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode) + var low = uCode & 0xFF + if (bucket[low] <= SEQ_START) { this.encodeTableSeq[SEQ_START - bucket[low]][DEF_CHAR] = dbcsCode } // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) { bucket[low] = dbcsCode } +} + +DBCSCodec.prototype._setEncodeSequence = function (seq, dbcsCode) { + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0] + var bucket = this._getEncodeBucket(uCode) + var low = uCode & 0xFF + + var node + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START - bucket[low]] + } else { + // There was no sequence object - allocate a new one. + node = {} + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low] // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length + this.encodeTableSeq.push(node) + } + + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length - 1; j++) { + var oldVal = node[uCode] + if (typeof oldVal === "object") { node = oldVal } else { + node = node[uCode] = {} + if (oldVal !== undefined) { node[DEF_CHAR] = oldVal } + } + } + + // Set the leaf to given dbcsCode. + uCode = seq[seq.length - 1] + node[uCode] = dbcsCode +} + +DBCSCodec.prototype._fillEncodeTable = function (nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx] + var hasValues = false + var subNodeEmpty = {} + for (var i = 0; i < 0x100; i++) { + var uCode = node[i] + var mbCode = prefix + i + if (skipEncodeChars[mbCode]) { continue } + + if (uCode >= 0) { + this._setEncodeChar(uCode, mbCode) + hasValues = true + } else if (uCode <= NODE_START) { + var subNodeIdx = NODE_START - uCode + if (!subNodeEmpty[subNodeIdx]) { // Skip empty subtrees (they are too large in gb18030). + var newPrefix = (mbCode << 8) >>> 0 // NOTE: '>>> 0' keeps 32-bit num positive. + if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars)) { hasValues = true } else { subNodeEmpty[subNodeIdx] = true } + } + } else if (uCode <= SEQ_START) { + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode) + hasValues = true + } + } + return hasValues +} + +// == Encoder ================================================================== + +function DBCSEncoder (options, codec) { + // Encoder state + this.leadSurrogate = -1 + this.seqObj = undefined + + // Static data + this.encodeTable = codec.encodeTable + this.encodeTableSeq = codec.encodeTableSeq + this.defaultCharSingleByte = codec.defCharSB + this.gb18030 = codec.gb18030 +} + +DBCSEncoder.prototype.write = function (str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)) + var leadSurrogate = this.leadSurrogate + var seqObj = this.seqObj + var nextChar = -1 + var i = 0; var j = 0 + + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break + var uCode = str.charCodeAt(i++) + } else { + var uCode = nextChar + nextChar = -1 + } + + // 1. Handle surrogates. + if (uCode >= 0xD800 && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode + continue + } else { + leadSurrogate = uCode + // Double lead surrogate found. + uCode = UNASSIGNED + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00) + leadSurrogate = -1 + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED + } + } + } else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED // Write an error, then current char. + leadSurrogate = -1 + } + + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode] + if (typeof resCode === "object") { // Sequence continues. + seqObj = resCode + continue + } else if (typeof resCode === "number") { // Sequence finished. Write it. + dbcsCode = resCode + } else if (resCode == undefined) { // Current character is not part of the sequence. + // Try default character for this sequence + resCode = seqObj[DEF_CHAR] + if (resCode !== undefined) { + dbcsCode = resCode // Found. Write it. + nextChar = uCode // Current character will be written too in the next iteration. + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined + } else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8] + if (subtable !== undefined) { dbcsCode = subtable[uCode & 0xFF] } + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START - dbcsCode] + continue + } + + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode) + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]) + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600 + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260 + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10 + newBuf[j++] = 0x30 + dbcsCode + continue + } + } + } + + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) { dbcsCode = this.defaultCharSingleByte } + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode + } else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8 // high byte + newBuf[j++] = dbcsCode & 0xFF // low byte + } else if (dbcsCode < 0x1000000) { + newBuf[j++] = dbcsCode >> 16 + newBuf[j++] = (dbcsCode >> 8) & 0xFF + newBuf[j++] = dbcsCode & 0xFF + } else { + newBuf[j++] = dbcsCode >>> 24 + newBuf[j++] = (dbcsCode >>> 16) & 0xFF + newBuf[j++] = (dbcsCode >>> 8) & 0xFF + newBuf[j++] = dbcsCode & 0xFF + } + } + + this.seqObj = seqObj + this.leadSurrogate = leadSurrogate + return newBuf.slice(0, j) +} + +DBCSEncoder.prototype.end = function () { + if (this.leadSurrogate === -1 && this.seqObj === undefined) { return } // All clean. Most often case. + + var newBuf = Buffer.alloc(10); var j = 0 + + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR] + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode + } else { + newBuf[j++] = dbcsCode >> 8 // high byte + newBuf[j++] = dbcsCode & 0xFF // low byte + } + } else { + // See todo above. + } + this.seqObj = undefined + } + + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte + this.leadSurrogate = -1 + } + + return newBuf.slice(0, j) +} + +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx + +// == Decoder ================================================================== + +function DBCSDecoder (options, codec) { + // Decoder state + this.nodeIdx = 0 + this.prevBytes = [] + + // Static data + this.decodeTables = codec.decodeTables + this.decodeTableSeq = codec.decodeTableSeq + this.defaultCharUnicode = codec.defaultCharUnicode + this.gb18030 = codec.gb18030 +} + +DBCSDecoder.prototype.write = function (buf) { + var newBuf = Buffer.alloc(buf.length * 2) + var nodeIdx = this.nodeIdx + var prevBytes = this.prevBytes; var prevOffset = this.prevBytes.length + var seqStart = -this.prevBytes.length // idx of the start of current parsed sequence. + var uCode + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset] + + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte] + + if (uCode >= 0) { + // Normal character, just use it. + } else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + uCode = this.defaultCharUnicode.charCodeAt(0) + i = seqStart // Skip one byte ('i' will be incremented by the for loop) and try to parse again. + } else if (uCode === GB18030_CODE) { + if (i >= 3) { + var ptr = (buf[i - 3] - 0x81) * 12600 + (buf[i - 2] - 0x30) * 1260 + (buf[i - 1] - 0x81) * 10 + (curByte - 0x30) + } else { + var ptr = (prevBytes[i - 3 + prevOffset] - 0x81) * 12600 + + (((i - 2 >= 0) ? buf[i - 2] : prevBytes[i - 2 + prevOffset]) - 0x30) * 1260 + + (((i - 1 >= 0) ? buf[i - 1] : prevBytes[i - 1 + prevOffset]) - 0x81) * 10 + + (curByte - 0x30) + } + var idx = findIdx(this.gb18030.gbChars, ptr) + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx] + } else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode + continue + } else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode] + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k] + newBuf[j++] = uCode & 0xFF + newBuf[j++] = uCode >> 8 + } + uCode = seq[seq.length - 1] + } else { throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte) } + + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode >= 0x10000) { + uCode -= 0x10000 + var uCodeLead = 0xD800 | (uCode >> 10) + newBuf[j++] = uCodeLead & 0xFF + newBuf[j++] = uCodeLead >> 8 + + uCode = 0xDC00 | (uCode & 0x3FF) + } + newBuf[j++] = uCode & 0xFF + newBuf[j++] = uCode >> 8 + + // Reset trie node. + nodeIdx = 0; seqStart = i + 1 + } + + this.nodeIdx = nodeIdx + this.prevBytes = (seqStart >= 0) + ? Array.prototype.slice.call(buf, seqStart) + : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf)) + + return newBuf.slice(0, j).toString("ucs2") +} + +DBCSDecoder.prototype.end = function () { + var ret = "" + + // Try to parse all remaining chars. + while (this.prevBytes.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode + var bytesArr = this.prevBytes.slice(1) + + // Parse remaining as usual. + this.prevBytes = [] + this.nodeIdx = 0 + if (bytesArr.length > 0) { ret += this.write(bytesArr) } + } + + this.prevBytes = [] + this.nodeIdx = 0 + return ret +} + +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx (table, val) { + if (table[0] > val) { return -1 } + + var l = 0; var r = table.length + while (l < r - 1) { // always table[l] <= val < table[r] + var mid = l + ((r - l + 1) >> 1) + if (table[mid] <= val) { l = mid } else { r = mid } + } + return l +} diff --git a/node_modules/iconv-lite/encodings/dbcs-data.js b/node_modules/iconv-lite/encodings/dbcs-data.js new file mode 100644 index 000000000..a3858d4cf --- /dev/null +++ b/node_modules/iconv-lite/encodings/dbcs-data.js @@ -0,0 +1,185 @@ +"use strict" + +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. + +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + + shiftjis: { + type: "_dbcs", + table: function () { return require("./tables/shiftjis.json") }, + encodeAdd: { "\u00a5": 0x5C, "\u203E": 0x7E }, + encodeSkipVals: [{ from: 0xED40, to: 0xF940 }] + }, + csshiftjis: "shiftjis", + mskanji: "shiftjis", + sjis: "shiftjis", + windows31j: "shiftjis", + ms31j: "shiftjis", + xsjis: "shiftjis", + windows932: "shiftjis", + ms932: "shiftjis", + 932: "shiftjis", + cp932: "shiftjis", + + eucjp: { + type: "_dbcs", + table: function () { return require("./tables/eucjp.json") }, + encodeAdd: { "\u00a5": 0x5C, "\u203E": 0x7E } + }, + + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + gb2312: "cp936", + gb231280: "cp936", + gb23121980: "cp936", + csgb2312: "cp936", + csiso58gb231280: "cp936", + euccn: "cp936", + + // Microsoft's CP936 is a subset and approximation of GBK. + windows936: "cp936", + ms936: "cp936", + 936: "cp936", + cp936: { + type: "_dbcs", + table: function () { return require("./tables/cp936.json") } + }, + + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + gbk: { + type: "_dbcs", + table: function () { return require("./tables/cp936.json").concat(require("./tables/gbk-added.json")) } + }, + xgbk: "gbk", + isoir58: "gbk", + + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + gb18030: { + type: "_dbcs", + table: function () { return require("./tables/cp936.json").concat(require("./tables/gbk-added.json")) }, + gb18030: function () { return require("./tables/gb18030-ranges.json") }, + encodeSkipVals: [0x80], + encodeAdd: { "€": 0xA2E3 } + }, + + chinese: "gb18030", + + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + windows949: "cp949", + ms949: "cp949", + 949: "cp949", + cp949: { + type: "_dbcs", + table: function () { return require("./tables/cp949.json") } + }, + + cseuckr: "cp949", + csksc56011987: "cp949", + euckr: "cp949", + isoir149: "cp949", + korean: "cp949", + ksc56011987: "cp949", + ksc56011989: "cp949", + ksc5601: "cp949", + + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + + windows950: "cp950", + ms950: "cp950", + 950: "cp950", + cp950: { + type: "_dbcs", + table: function () { return require("./tables/cp950.json") } + }, + + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + big5: "big5hkscs", + big5hkscs: { + type: "_dbcs", + table: function () { return require("./tables/cp950.json").concat(require("./tables/big5-added.json")) }, + encodeSkipVals: [ + // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of + // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU. + // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter. + 0x8e69, 0x8e6f, 0x8e7e, 0x8eab, 0x8eb4, 0x8ecd, 0x8ed0, 0x8f57, 0x8f69, 0x8f6e, 0x8fcb, 0x8ffe, + 0x906d, 0x907a, 0x90c4, 0x90dc, 0x90f1, 0x91bf, 0x92af, 0x92b0, 0x92b1, 0x92b2, 0x92d1, 0x9447, 0x94ca, + 0x95d9, 0x96fc, 0x9975, 0x9b76, 0x9b78, 0x9b7b, 0x9bc6, 0x9bde, 0x9bec, 0x9bf6, 0x9c42, 0x9c53, 0x9c62, + 0x9c68, 0x9c6b, 0x9c77, 0x9cbc, 0x9cbd, 0x9cd0, 0x9d57, 0x9d5a, 0x9dc4, 0x9def, 0x9dfb, 0x9ea9, 0x9eef, + 0x9efd, 0x9f60, 0x9fcb, 0xa077, 0xa0dc, 0xa0df, 0x8fcc, 0x92c8, 0x9644, 0x96ed, + + // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345 + 0xa2a4, 0xa2a5, 0xa2a7, 0xa2a6, 0xa2cc, 0xa2ce + ] + }, + + cnbig5: "big5hkscs", + csbig5: "big5hkscs", + xxbig5: "big5hkscs" +} diff --git a/node_modules/iconv-lite/encodings/index.js b/node_modules/iconv-lite/encodings/index.js new file mode 100644 index 000000000..9d90e3cac --- /dev/null +++ b/node_modules/iconv-lite/encodings/index.js @@ -0,0 +1,23 @@ +"use strict" + +var mergeModules = require("../lib/helpers/merge-exports") + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + require("./internal"), + require("./utf32"), + require("./utf16"), + require("./utf7"), + require("./sbcs-codec"), + require("./sbcs-data"), + require("./sbcs-data-generated"), + require("./dbcs-codec"), + require("./dbcs-data") +] + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i] + mergeModules(exports, module) +} diff --git a/node_modules/iconv-lite/encodings/internal.js b/node_modules/iconv-lite/encodings/internal.js new file mode 100644 index 000000000..4e5c3ff25 --- /dev/null +++ b/node_modules/iconv-lite/encodings/internal.js @@ -0,0 +1,218 @@ +"use strict" +var Buffer = require("safer-buffer").Buffer + +// Export Node.js internal encodings. + +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true }, + cesu8: { type: "_internal", bomAware: true }, + unicode11utf8: "utf8", + + ucs2: { type: "_internal", bomAware: true }, + utf16le: "ucs2", + + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, + + // Codec. + _internal: InternalCodec +} + +// ------------------------------------------------------------------------------ + +function InternalCodec (codecOptions, iconv) { + this.enc = codecOptions.encodingName + this.bomAware = codecOptions.bomAware + + if (this.enc === "base64") { this.encoder = InternalEncoderBase64 } else if (this.enc === "utf8") { this.encoder = InternalEncoderUtf8 } else if (this.enc === "cesu8") { + this.enc = "utf8" // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8 + + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from("eda0bdedb2a9", "hex").toString() !== "💩") { + this.decoder = InternalDecoderCesu8 + this.defaultCharUnicode = iconv.defaultCharUnicode + } + } +} + +InternalCodec.prototype.encoder = InternalEncoder +InternalCodec.prototype.decoder = InternalDecoder + +// ------------------------------------------------------------------------------ + +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = require("string_decoder").StringDecoder + +function InternalDecoder (options, codec) { + this.decoder = new StringDecoder(codec.enc) +} + +InternalDecoder.prototype.write = function (buf) { + if (!Buffer.isBuffer(buf)) { + buf = Buffer.from(buf) + } + + return this.decoder.write(buf) +} + +InternalDecoder.prototype.end = function () { + return this.decoder.end() +} + +// ------------------------------------------------------------------------------ +// Encoder is mostly trivial + +function InternalEncoder (options, codec) { + this.enc = codec.enc +} + +InternalEncoder.prototype.write = function (str) { + return Buffer.from(str, this.enc) +} + +InternalEncoder.prototype.end = function () { +} + +// ------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. + +function InternalEncoderBase64 (options, codec) { + this.prevStr = "" +} + +InternalEncoderBase64.prototype.write = function (str) { + str = this.prevStr + str + var completeQuads = str.length - (str.length % 4) + this.prevStr = str.slice(completeQuads) + str = str.slice(0, completeQuads) + + return Buffer.from(str, "base64") +} + +InternalEncoderBase64.prototype.end = function () { + return Buffer.from(this.prevStr, "base64") +} + +// ------------------------------------------------------------------------------ +// CESU-8 encoder is also special. + +function InternalEncoderCesu8 (options, codec) { +} + +InternalEncoderCesu8.prototype.write = function (str) { + var buf = Buffer.alloc(str.length * 3); var bufIdx = 0 + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i) + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) { buf[bufIdx++] = charCode } else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6) + buf[bufIdx++] = 0x80 + (charCode & 0x3f) + } else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12) + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f) + buf[bufIdx++] = 0x80 + (charCode & 0x3f) + } + } + return buf.slice(0, bufIdx) +} + +InternalEncoderCesu8.prototype.end = function () { +} + +// ------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ + +function InternalDecoderCesu8 (options, codec) { + this.acc = 0 + this.contBytes = 0 + this.accBytes = 0 + this.defaultCharUnicode = codec.defaultCharUnicode +} + +InternalDecoderCesu8.prototype.write = function (buf) { + var acc = this.acc; var contBytes = this.contBytes; var accBytes = this.accBytes + var res = "" + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i] + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode + contBytes = 0 + } + + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte) + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F + contBytes = 1; accBytes = 1 + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F + contBytes = 2; accBytes = 1 + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode + } + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f) + contBytes--; accBytes++ + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) { + res += this.defaultCharUnicode + } else if (accBytes === 3 && acc < 0x800) { + res += this.defaultCharUnicode + } else { + // Actually add character. + res += String.fromCharCode(acc) + } + } + } else { // Unexpected continuation byte + res += this.defaultCharUnicode + } + } + } + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes + return res +} + +InternalDecoderCesu8.prototype.end = function () { + var res = 0 + if (this.contBytes > 0) { res += this.defaultCharUnicode } + return res +} + +// ------------------------------------------------------------------------------ +// check the chunk boundaries for surrogate pair + +function InternalEncoderUtf8 (options, codec) { + this.highSurrogate = "" +} + +InternalEncoderUtf8.prototype.write = function (str) { + if (this.highSurrogate) { + str = this.highSurrogate + str + this.highSurrogate = "" + } + + if (str.length > 0) { + var charCode = str.charCodeAt(str.length - 1) + if (charCode >= 0xd800 && charCode < 0xdc00) { + this.highSurrogate = str[str.length - 1] + str = str.slice(0, str.length - 1) + } + } + + return Buffer.from(str, this.enc) +} + +InternalEncoderUtf8.prototype.end = function () { + if (this.highSurrogate) { + var str = this.highSurrogate + this.highSurrogate = "" + return Buffer.from(str, this.enc) + } +} diff --git a/node_modules/iconv-lite/encodings/sbcs-codec.js b/node_modules/iconv-lite/encodings/sbcs-codec.js new file mode 100644 index 000000000..0e2fc924e --- /dev/null +++ b/node_modules/iconv-lite/encodings/sbcs-codec.js @@ -0,0 +1,75 @@ +"use strict" +var Buffer = require("safer-buffer").Buffer + +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). + +exports._sbcs = SBCSCodec +function SBCSCodec (codecOptions, iconv) { + if (!codecOptions) { + throw new Error("SBCS codec is called without the data.") + } + + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) { + throw new Error("Encoding '" + codecOptions.type + "' has incorrect 'chars' (must be of len 128 or 256)") + } + + if (codecOptions.chars.length === 128) { + var asciiString = "" + for (var i = 0; i < 128; i++) { + asciiString += String.fromCharCode(i) + } + codecOptions.chars = asciiString + codecOptions.chars + } + + this.decodeBuf = Buffer.from(codecOptions.chars, "ucs2") + + // Encoding buffer. + var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)) + + for (var i = 0; i < codecOptions.chars.length; i++) { + encodeBuf[codecOptions.chars.charCodeAt(i)] = i + } + + this.encodeBuf = encodeBuf +} + +SBCSCodec.prototype.encoder = SBCSEncoder +SBCSCodec.prototype.decoder = SBCSDecoder + +function SBCSEncoder (options, codec) { + this.encodeBuf = codec.encodeBuf +} + +SBCSEncoder.prototype.write = function (str) { + var buf = Buffer.alloc(str.length) + for (var i = 0; i < str.length; i++) { + buf[i] = this.encodeBuf[str.charCodeAt(i)] + } + + return buf +} + +SBCSEncoder.prototype.end = function () { +} + +function SBCSDecoder (options, codec) { + this.decodeBuf = codec.decodeBuf +} + +SBCSDecoder.prototype.write = function (buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf + var newBuf = Buffer.alloc(buf.length * 2) + var idx1 = 0; var idx2 = 0 + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i] * 2; idx2 = i * 2 + newBuf[idx2] = decodeBuf[idx1] + newBuf[idx2 + 1] = decodeBuf[idx1 + 1] + } + return newBuf.toString("ucs2") +} + +SBCSDecoder.prototype.end = function () { +} diff --git a/node_modules/iconv-lite/encodings/sbcs-data-generated.js b/node_modules/iconv-lite/encodings/sbcs-data-generated.js new file mode 100644 index 000000000..9b4823607 --- /dev/null +++ b/node_modules/iconv-lite/encodings/sbcs-data-generated.js @@ -0,0 +1,451 @@ +"use strict"; + +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } +} \ No newline at end of file diff --git a/node_modules/iconv-lite/encodings/sbcs-data.js b/node_modules/iconv-lite/encodings/sbcs-data.js new file mode 100644 index 000000000..d8f8e1729 --- /dev/null +++ b/node_modules/iconv-lite/encodings/sbcs-data.js @@ -0,0 +1,178 @@ +"use strict" + +// Manually added data to be used by sbcs codec in addition to generated one. + +module.exports = { + // Not supported by iconv, not sure why. + 10029: "maccenteuro", + maccenteuro: { + type: "_sbcs", + chars: "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, + + 808: "cp808", + ibm808: "cp808", + cp808: { + type: "_sbcs", + chars: "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, + + mik: { + type: "_sbcs", + chars: "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + + cp720: { + type: "_sbcs", + chars: "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0" + }, + + // Aliases of generated encodings. + ascii8bit: "ascii", + usascii: "ascii", + ansix34: "ascii", + ansix341968: "ascii", + ansix341986: "ascii", + csascii: "ascii", + cp367: "ascii", + ibm367: "ascii", + isoir6: "ascii", + iso646us: "ascii", + iso646irv: "ascii", + us: "ascii", + + latin1: "iso88591", + latin2: "iso88592", + latin3: "iso88593", + latin4: "iso88594", + latin5: "iso88599", + latin6: "iso885910", + latin7: "iso885913", + latin8: "iso885914", + latin9: "iso885915", + latin10: "iso885916", + + csisolatin1: "iso88591", + csisolatin2: "iso88592", + csisolatin3: "iso88593", + csisolatin4: "iso88594", + csisolatincyrillic: "iso88595", + csisolatinarabic: "iso88596", + csisolatingreek: "iso88597", + csisolatinhebrew: "iso88598", + csisolatin5: "iso88599", + csisolatin6: "iso885910", + + l1: "iso88591", + l2: "iso88592", + l3: "iso88593", + l4: "iso88594", + l5: "iso88599", + l6: "iso885910", + l7: "iso885913", + l8: "iso885914", + l9: "iso885915", + l10: "iso885916", + + isoir14: "iso646jp", + isoir57: "iso646cn", + isoir100: "iso88591", + isoir101: "iso88592", + isoir109: "iso88593", + isoir110: "iso88594", + isoir144: "iso88595", + isoir127: "iso88596", + isoir126: "iso88597", + isoir138: "iso88598", + isoir148: "iso88599", + isoir157: "iso885910", + isoir166: "tis620", + isoir179: "iso885913", + isoir199: "iso885914", + isoir203: "iso885915", + isoir226: "iso885916", + + cp819: "iso88591", + ibm819: "iso88591", + + cyrillic: "iso88595", + + arabic: "iso88596", + arabic8: "iso88596", + ecma114: "iso88596", + asmo708: "iso88596", + + greek: "iso88597", + greek8: "iso88597", + ecma118: "iso88597", + elot928: "iso88597", + + hebrew: "iso88598", + hebrew8: "iso88598", + + turkish: "iso88599", + turkish8: "iso88599", + + thai: "iso885911", + thai8: "iso885911", + + celtic: "iso885914", + celtic8: "iso885914", + isoceltic: "iso885914", + + tis6200: "tis620", + tis62025291: "tis620", + tis62025330: "tis620", + + 10000: "macroman", + 10006: "macgreek", + 10007: "maccyrillic", + 10079: "maciceland", + 10081: "macturkish", + + cspc8codepage437: "cp437", + cspc775baltic: "cp775", + cspc850multilingual: "cp850", + cspcp852: "cp852", + cspc862latinhebrew: "cp862", + cpgr: "cp869", + + msee: "cp1250", + mscyrl: "cp1251", + msansi: "cp1252", + msgreek: "cp1253", + msturk: "cp1254", + mshebr: "cp1255", + msarab: "cp1256", + winbaltrim: "cp1257", + + cp20866: "koi8r", + 20866: "koi8r", + ibm878: "koi8r", + cskoi8r: "koi8r", + + cp21866: "koi8u", + 21866: "koi8u", + ibm1168: "koi8u", + + strk10482002: "rk1048", + + tcvn5712: "tcvn", + tcvn57121: "tcvn", + + gb198880: "iso646cn", + cn: "iso646cn", + + csiso14jisc6220ro: "iso646jp", + jisc62201969ro: "iso646jp", + jp: "iso646jp", + + cshproman8: "hproman8", + r8: "hproman8", + roman8: "hproman8", + xroman8: "hproman8", + ibm1051: "hproman8", + + mac: "macintosh", + csmacintosh: "macintosh" +} diff --git a/node_modules/iconv-lite/encodings/tables/big5-added.json b/node_modules/iconv-lite/encodings/tables/big5-added.json new file mode 100644 index 000000000..3c3d3c2f7 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/big5-added.json @@ -0,0 +1,122 @@ +[ +["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"], +["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"], +["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"], +["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"], +["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"], +["8940","𪎩𡅅"], +["8943","攊"], +["8946","丽滝鵎釟"], +["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"], +["89a1","琑糼緍楆竉刧"], +["89ab","醌碸酞肼"], +["89b0","贋胶𠧧"], +["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"], +["89c1","溚舾甙"], +["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"], +["8a40","𧶄唥"], +["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"], +["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"], +["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"], +["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"], +["8aac","䠋𠆩㿺塳𢶍"], +["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"], +["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"], +["8ac9","𪘁𠸉𢫏𢳉"], +["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"], +["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"], +["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"], +["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"], +["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"], +["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"], +["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"], +["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"], +["8ca1","𣏹椙橃𣱣泿"], +["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"], +["8cc9","顨杫䉶圽"], +["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"], +["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"], +["8d40","𠮟"], +["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"], +["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"], +["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"], +["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"], +["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"], +["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"], +["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"], +["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"], +["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"], +["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"], +["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"], +["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"], +["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"], +["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"], +["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"], +["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"], +["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"], +["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"], +["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"], +["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"], +["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"], +["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"], +["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"], +["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"], +["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"], +["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"], +["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"], +["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"], +["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"], +["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"], +["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"], +["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"], +["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"], +["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"], +["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"], +["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"], +["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"], +["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"], +["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"], +["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"], +["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"], +["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"], +["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"], +["9fae","酙隁酜"], +["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"], +["9fc1","𤤙盖鮝个𠳔莾衂"], +["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"], +["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"], +["9fe7","毺蠘罸"], +["9feb","嘠𪙊蹷齓"], +["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"], +["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"], +["a055","𡠻𦸅"], +["a058","詾𢔛"], +["a05b","惽癧髗鵄鍮鮏蟵"], +["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"], +["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"], +["a0a1","嵗𨯂迚𨸹"], +["a0a6","僙𡵆礆匲阸𠼻䁥"], +["a0ae","矾"], +["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"], +["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"], +["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"], +["a3c0","␀",31,"␡"], +["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23], +["c740","す",58,"ァアィイ"], +["c7a1","ゥ",81,"А",5,"ЁЖ",4], +["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"], +["c8a1","龰冈龱𧘇"], +["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"], +["c8f5","ʃɐɛɔɵœøŋʊɪ"], +["f9fe","■"], +["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"], +["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"], +["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"], +["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"], +["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"], +["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"], +["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"], +["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"], +["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"], +["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"] +] diff --git a/node_modules/iconv-lite/encodings/tables/cp936.json b/node_modules/iconv-lite/encodings/tables/cp936.json new file mode 100644 index 000000000..49ddb9a1d --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/cp936.json @@ -0,0 +1,264 @@ +[ +["0","\u0000",127,"€"], +["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"], +["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"], +["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11], +["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"], +["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"], +["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5], +["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"], +["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"], +["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"], +["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"], +["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"], +["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"], +["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4], +["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6], +["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"], +["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7], +["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"], +["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"], +["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"], +["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5], +["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"], +["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6], +["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"], +["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4], +["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4], +["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"], +["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"], +["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6], +["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"], +["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"], +["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"], +["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6], +["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"], +["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"], +["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"], +["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"], +["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"], +["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"], +["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8], +["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"], +["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"], +["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"], +["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"], +["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5], +["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"], +["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"], +["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"], +["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"], +["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5], +["9980","檧檨檪檭",114,"欥欦欨",6], +["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"], +["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"], +["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"], +["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"], +["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"], +["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5], +["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"], +["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"], +["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6], +["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"], +["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"], +["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4], +["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19], +["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"], +["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"], +["a2a1","ⅰ",9], +["a2b1","⒈",19,"⑴",19,"①",9], +["a2e5","㈠",9], +["a2f1","Ⅰ",11], +["a3a1","!"#¥%",88," ̄"], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"], +["a6ee","︻︼︷︸︱"], +["a6f4","︳︴"], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6], +["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"], +["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"], +["a8bd","ńň"], +["a8c0","ɡ"], +["a8c5","ㄅ",36], +["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"], +["a959","℡㈱"], +["a95c","‐"], +["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8], +["a980","﹢",4,"﹨﹩﹪﹫"], +["a996","〇"], +["a9a4","─",75], +["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8], +["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"], +["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4], +["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4], +["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11], +["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"], +["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12], +["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"], +["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"], +["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"], +["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"], +["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"], +["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"], +["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"], +["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"], +["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"], +["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4], +["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"], +["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"], +["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"], +["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9], +["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"], +["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"], +["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"], +["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"], +["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"], +["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16], +["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"], +["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"], +["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"], +["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"], +["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"], +["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"], +["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"], +["bb40","籃",9,"籎",36,"籵",5,"籾",9], +["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"], +["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5], +["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"], +["bd40","紷",54,"絯",7], +["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"], +["be40","継",12,"綧",6,"綯",42], +["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"], +["bf40","緻",62], +["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"], +["c040","繞",35,"纃",23,"纜纝纞"], +["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"], +["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"], +["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"], +["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"], +["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"], +["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"], +["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"], +["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"], +["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"], +["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"], +["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"], +["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"], +["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"], +["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"], +["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"], +["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"], +["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"], +["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"], +["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"], +["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10], +["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"], +["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"], +["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"], +["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"], +["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"], +["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"], +["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"], +["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"], +["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"], +["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9], +["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"], +["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"], +["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"], +["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5], +["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"], +["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"], +["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"], +["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6], +["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"], +["d440","訞",31,"訿",8,"詉",21], +["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"], +["d540","誁",7,"誋",7,"誔",46], +["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"], +["d640","諤",34,"謈",27], +["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"], +["d740","譆",31,"譧",4,"譭",25], +["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"], +["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"], +["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"], +["d940","貮",62], +["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"], +["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"], +["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"], +["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"], +["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"], +["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7], +["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"], +["dd40","軥",62], +["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"], +["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"], +["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"], +["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"], +["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"], +["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"], +["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"], +["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"], +["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"], +["e240","釦",62], +["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"], +["e340","鉆",45,"鉵",16], +["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"], +["e440","銨",5,"銯",24,"鋉",31], +["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"], +["e540","錊",51,"錿",10], +["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"], +["e640","鍬",34,"鎐",27], +["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"], +["e740","鏎",7,"鏗",54], +["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"], +["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"], +["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"], +["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42], +["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"], +["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"], +["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"], +["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"], +["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"], +["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7], +["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"], +["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46], +["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"], +["ee40","頏",62], +["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"], +["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4], +["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"], +["f040","餈",4,"餎餏餑",28,"餯",26], +["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"], +["f140","馌馎馚",10,"馦馧馩",47], +["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"], +["f240","駺",62], +["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"], +["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"], +["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"], +["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5], +["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"], +["f540","魼",62], +["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"], +["f640","鯜",62], +["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"], +["f740","鰼",62], +["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"], +["f840","鳣",62], +["f880","鴢",32], +["f940","鵃",62], +["f980","鶂",32], +["fa40","鶣",62], +["fa80","鷢",32], +["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"], +["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"], +["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6], +["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"], +["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38], +["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"], +["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"] +] diff --git a/node_modules/iconv-lite/encodings/tables/cp949.json b/node_modules/iconv-lite/encodings/tables/cp949.json new file mode 100644 index 000000000..2022a007f --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/cp949.json @@ -0,0 +1,273 @@ +[ +["0","\u0000",127], +["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], +["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"], +["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"], +["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5], +["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], +["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18], +["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], +["8361","긝",18,"긲긳긵긶긹긻긼"], +["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8], +["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], +["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18], +["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"], +["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4], +["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], +["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"], +["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], +["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], +["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"], +["8741","놞",9,"놩",15], +["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"], +["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4], +["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], +["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], +["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"], +["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"], +["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"], +["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15], +["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"], +["8a61","둧",4,"둭",18,"뒁뒂"], +["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"], +["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], +["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8], +["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18], +["8c41","똀",15,"똒똓똕똖똗똙",4], +["8c61","똞",6,"똦",5,"똭",6,"똵",5], +["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], +["8d41","뛃",16,"뛕",8], +["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], +["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"], +["8e41","랟랡",6,"랪랮",5,"랶랷랹",8], +["8e61","럂",4,"럈럊",19], +["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], +["8f41","뢅",7,"뢎",17], +["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], +["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5], +["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"], +["9061","륾",5,"릆릈릋릌릏",15], +["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"], +["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5], +["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5], +["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6], +["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], +["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4], +["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"], +["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], +["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8], +["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"], +["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8], +["9461","봞",5,"봥",6,"봭",12], +["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24], +["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"], +["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"], +["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], +["9641","뺸",23,"뻒뻓"], +["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8], +["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], +["9741","뾃",16,"뾕",8], +["9761","뾞",17,"뾱",7], +["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"], +["9841","쁀",16,"쁒",5,"쁙쁚쁛"], +["9861","쁝쁞쁟쁡",6,"쁪",15], +["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], +["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"], +["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], +["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"], +["9a41","숤숥숦숧숪숬숮숰숳숵",16], +["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], +["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"], +["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8], +["9b61","쌳",17,"썆",7], +["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"], +["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5], +["9c61","쏿",8,"쐉",6,"쐑",9], +["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12], +["9d41","쒪",13,"쒹쒺쒻쒽",8], +["9d61","쓆",25], +["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"], +["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"], +["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"], +["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"], +["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], +["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], +["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], +["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"], +["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], +["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], +["a141","좥좦좧좩",18,"좾좿죀죁"], +["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"], +["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"], +["a241","줐줒",5,"줙",18], +["a261","줭",6,"줵",18], +["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"], +["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"], +["a361","즑",6,"즚즜즞",16], +["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"], +["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"], +["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], +["a481","쨦쨧쨨쨪",28,"ㄱ",93], +["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"], +["a561","쩫",17,"쩾",5,"쪅쪆"], +["a581","쪇",16,"쪙",14,"ⅰ",9], +["a5b0","Ⅰ",9], +["a5c1","Α",16,"Σ",6], +["a5e1","α",16,"σ",6], +["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"], +["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6], +["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7], +["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], +["a761","쬪",22,"쭂쭃쭄"], +["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"], +["a841","쭭",10,"쭺",14], +["a861","쮉",18,"쮝",6], +["a881","쮤",19,"쮹",11,"ÆÐªĦ"], +["a8a6","IJ"], +["a8a8","ĿŁØŒºÞŦŊ"], +["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"], +["a941","쯅",14,"쯕",10], +["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], +["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"], +["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"], +["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], +["aa81","챳챴챶",29,"ぁ",82], +["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"], +["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], +["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85], +["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"], +["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4], +["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25], +["acd1","а",5,"ёж",25], +["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7], +["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"], +["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"], +["ae41","췆",5,"췍췎췏췑",16], +["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], +["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], +["af41","츬츭츮츯츲츴츶",19], +["af61","칊",13,"칚칛칝칞칢",5,"칪칬"], +["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], +["b041","캚",5,"캢캦",5,"캮",12], +["b061","캻",5,"컂",19], +["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], +["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"], +["b161","켥",6,"켮켲",5,"켹",11], +["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"], +["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"], +["b261","쾎",18,"쾢",5,"쾩"], +["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"], +["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], +["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5], +["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"], +["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5], +["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"], +["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"], +["b541","킕",14,"킦킧킩킪킫킭",5], +["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], +["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], +["b641","턅",7,"턎",17], +["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"], +["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"], +["b741","텮",13,"텽",6,"톅톆톇톉톊"], +["b761","톋",20,"톢톣톥톦톧"], +["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"], +["b841","퇐",7,"퇙",17], +["b861","퇫",8,"퇵퇶퇷퇹",13], +["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], +["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], +["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"], +["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"], +["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"], +["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5], +["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"], +["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"], +["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"], +["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"], +["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"], +["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"], +["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"], +["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"], +["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13], +["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"], +["be41","퐸",7,"푁푂푃푅",14], +["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"], +["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], +["bf41","풞",10,"풪",14], +["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"], +["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"], +["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5], +["c061","픞",25], +["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"], +["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], +["c161","햌햍햎햏햑",19,"햦햧"], +["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"], +["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], +["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], +["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"], +["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4], +["c361","홢",4,"홨홪",5,"홲홳홵",11], +["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"], +["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], +["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], +["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], +["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"], +["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4], +["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"], +["c641","힍힎힏힑",6,"힚힜힞",5], +["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"], +["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"], +["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"], +["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"], +["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"], +["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"], +["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"], +["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"], +["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"], +["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"], +["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"], +["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"], +["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"], +["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"], +["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"], +["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"], +["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"], +["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"], +["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"], +["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"], +["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"], +["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"], +["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"], +["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"], +["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"], +["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"], +["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"], +["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"], +["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"], +["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"], +["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"], +["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"], +["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"], +["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"], +["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"], +["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"], +["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"], +["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"], +["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"], +["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"], +["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"], +["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"], +["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"], +["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"], +["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"], +["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"], +["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"], +["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"], +["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"], +["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"], +["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"], +["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"], +["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"], +["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"], +["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"] +] diff --git a/node_modules/iconv-lite/encodings/tables/cp950.json b/node_modules/iconv-lite/encodings/tables/cp950.json new file mode 100644 index 000000000..d8bc87178 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/cp950.json @@ -0,0 +1,177 @@ +[ +["0","\u0000",127], +["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"], +["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"], +["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"], +["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21], +["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10], +["a3a1","ㄐ",25,"˙ˉˊˇˋ"], +["a3e1","€"], +["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"], +["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"], +["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"], +["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"], +["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"], +["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"], +["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"], +["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"], +["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"], +["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"], +["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"], +["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"], +["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"], +["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"], +["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"], +["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"], +["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"], +["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"], +["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"], +["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"], +["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"], +["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"], +["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"], +["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"], +["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"], +["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"], +["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"], +["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"], +["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"], +["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"], +["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"], +["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"], +["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"], +["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"], +["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"], +["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"], +["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"], +["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"], +["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"], +["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"], +["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"], +["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"], +["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"], +["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"], +["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"], +["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"], +["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"], +["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"], +["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"], +["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"], +["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"], +["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"], +["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"], +["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"], +["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"], +["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"], +["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"], +["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"], +["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"], +["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"], +["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"], +["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"], +["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"], +["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"], +["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"], +["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"], +["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"], +["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"], +["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"], +["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"], +["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"], +["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"], +["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"], +["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"], +["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"], +["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"], +["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"], +["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"], +["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"], +["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"], +["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"], +["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"], +["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"], +["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"], +["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"], +["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"], +["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"], +["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"], +["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"], +["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"], +["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"], +["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"], +["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"], +["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"], +["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"], +["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"], +["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"], +["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"], +["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"], +["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"], +["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"], +["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"], +["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"], +["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"], +["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"], +["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"], +["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"], +["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"], +["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"], +["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"], +["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"], +["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"], +["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"], +["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"], +["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"], +["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"], +["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"], +["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"], +["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"], +["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"], +["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"], +["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"], +["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"], +["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"], +["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"], +["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"], +["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"], +["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"], +["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"], +["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"], +["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"], +["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"], +["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"], +["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"], +["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"], +["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"], +["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"], +["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"], +["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"], +["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"], +["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"], +["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"], +["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"], +["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"], +["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"], +["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"], +["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"], +["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"], +["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"], +["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"], +["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"], +["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"], +["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"], +["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"], +["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"], +["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"], +["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"], +["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"], +["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"], +["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"], +["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"], +["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"], +["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"], +["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"], +["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"], +["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"], +["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"] +] diff --git a/node_modules/iconv-lite/encodings/tables/eucjp.json b/node_modules/iconv-lite/encodings/tables/eucjp.json new file mode 100644 index 000000000..4fa61ca11 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/eucjp.json @@ -0,0 +1,182 @@ +[ +["0","\u0000",127], +["8ea1","。",62], +["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"], +["a2a1","◆□■△▲▽▼※〒→←↑↓〓"], +["a2ba","∈∋⊆⊇⊂⊃∪∩"], +["a2ca","∧∨¬⇒⇔∀∃"], +["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["a2f2","ʼn♯♭♪†‡¶"], +["a2fe","◯"], +["a3b0","0",9], +["a3c1","A",25], +["a3e1","a",25], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["ada1","①",19,"Ⅰ",9], +["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"], +["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"], +["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"], +["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"], +["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"], +["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"], +["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"], +["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"], +["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"], +["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"], +["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"], +["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"], +["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"], +["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"], +["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"], +["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"], +["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"], +["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"], +["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"], +["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"], +["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"], +["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"], +["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"], +["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"], +["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"], +["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"], +["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"], +["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"], +["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"], +["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"], +["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"], +["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"], +["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"], +["f4a1","堯槇遙瑤凜熙"], +["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"], +["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"], +["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["fcf1","ⅰ",9,"¬¦'""], +["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"], +["8fa2c2","¡¦¿"], +["8fa2eb","ºª©®™¤№"], +["8fa6e1","ΆΈΉΊΪ"], +["8fa6e7","Ό"], +["8fa6e9","ΎΫ"], +["8fa6ec","Ώ"], +["8fa6f1","άέήίϊΐόςύϋΰώ"], +["8fa7c2","Ђ",10,"ЎЏ"], +["8fa7f2","ђ",10,"ўџ"], +["8fa9a1","ÆĐ"], +["8fa9a4","Ħ"], +["8fa9a6","IJ"], +["8fa9a8","ŁĿ"], +["8fa9ab","ŊØŒ"], +["8fa9af","ŦÞ"], +["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"], +["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"], +["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"], +["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"], +["8fabbd","ġĥíìïîǐ"], +["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"], +["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"], +["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"], +["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"], +["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"], +["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"], +["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"], +["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"], +["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"], +["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"], +["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"], +["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"], +["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"], +["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"], +["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"], +["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"], +["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"], +["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"], +["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"], +["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"], +["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"], +["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"], +["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"], +["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"], +["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"], +["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"], +["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"], +["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"], +["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"], +["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"], +["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"], +["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"], +["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"], +["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"], +["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"], +["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5], +["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"], +["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"], +["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"], +["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"], +["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"], +["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"], +["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"], +["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"], +["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"], +["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"], +["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"], +["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"], +["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"], +["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"], +["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"], +["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"], +["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"], +["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"], +["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"], +["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"], +["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"], +["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"], +["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4], +["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"], +["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"], +["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"], +["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"] +] diff --git a/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json b/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json new file mode 100644 index 000000000..85c693475 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json @@ -0,0 +1 @@ +{"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]} \ No newline at end of file diff --git a/node_modules/iconv-lite/encodings/tables/gbk-added.json b/node_modules/iconv-lite/encodings/tables/gbk-added.json new file mode 100644 index 000000000..b742e368f --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/gbk-added.json @@ -0,0 +1,56 @@ +[ +["a140","",62], +["a180","",32], +["a240","",62], +["a280","",32], +["a2ab","",5], +["a2e3","€"], +["a2ef",""], +["a2fd",""], +["a340","",62], +["a380","",31," "], +["a440","",62], +["a480","",32], +["a4f4","",10], +["a540","",62], +["a580","",32], +["a5f7","",7], +["a640","",62], +["a680","",32], +["a6b9","",7], +["a6d9","",6], +["a6ec",""], +["a6f3",""], +["a6f6","",8], +["a740","",62], +["a780","",32], +["a7c2","",14], +["a7f2","",12], +["a896","",10], +["a8bc","ḿ"], +["a8bf","ǹ"], +["a8c1",""], +["a8ea","",20], +["a958",""], +["a95b",""], +["a95d",""], +["a989","〾⿰",11], +["a997","",12], +["a9f0","",14], +["aaa1","",93], +["aba1","",93], +["aca1","",93], +["ada1","",93], +["aea1","",93], +["afa1","",93], +["d7fa","",4], +["f8a1","",93], +["f9a1","",93], +["faa1","",93], +["fba1","",93], +["fca1","",93], +["fda1","",93], +["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"], +["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93], +["8135f437",""] +] diff --git a/node_modules/iconv-lite/encodings/tables/shiftjis.json b/node_modules/iconv-lite/encodings/tables/shiftjis.json new file mode 100644 index 000000000..5a3a43cf8 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/shiftjis.json @@ -0,0 +1,125 @@ +[ +["0","\u0000",128], +["a1","。",62], +["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"], +["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"], +["81b8","∈∋⊆⊇⊂⊃∪∩"], +["81c8","∧∨¬⇒⇔∀∃"], +["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["81f0","ʼn♯♭♪†‡¶"], +["81fc","◯"], +["824f","0",9], +["8260","A",25], +["8281","a",25], +["829f","ぁ",82], +["8340","ァ",62], +["8380","ム",22], +["839f","Α",16,"Σ",6], +["83bf","α",16,"σ",6], +["8440","А",5,"ЁЖ",25], +["8470","а",5,"ёж",7], +["8480","о",17], +["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["8740","①",19,"Ⅰ",9], +["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["877e","㍻"], +["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"], +["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"], +["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"], +["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"], +["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"], +["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"], +["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"], +["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"], +["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"], +["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"], +["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"], +["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"], +["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"], +["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"], +["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"], +["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"], +["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"], +["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"], +["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"], +["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"], +["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"], +["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"], +["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"], +["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"], +["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"], +["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"], +["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"], +["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"], +["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"], +["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"], +["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"], +["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"], +["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"], +["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"], +["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"], +["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"], +["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["eeef","ⅰ",9,"¬¦'""], +["f040","",62], +["f080","",124], +["f140","",62], +["f180","",124], +["f240","",62], +["f280","",124], +["f340","",62], +["f380","",124], +["f440","",62], +["f480","",124], +["f540","",62], +["f580","",124], +["f640","",62], +["f680","",124], +["f740","",62], +["f780","",124], +["f840","",62], +["f880","",124], +["f940",""], +["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"], +["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"], +["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"], +["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"], +["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"] +] diff --git a/node_modules/iconv-lite/encodings/utf16.js b/node_modules/iconv-lite/encodings/utf16.js new file mode 100644 index 000000000..ae60d98e3 --- /dev/null +++ b/node_modules/iconv-lite/encodings/utf16.js @@ -0,0 +1,187 @@ +"use strict" +var Buffer = require("safer-buffer").Buffer + +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js + +// == UTF16-BE codec. ========================================================== + +exports.utf16be = Utf16BECodec +function Utf16BECodec () { +} + +Utf16BECodec.prototype.encoder = Utf16BEEncoder +Utf16BECodec.prototype.decoder = Utf16BEDecoder +Utf16BECodec.prototype.bomAware = true + +// -- Encoding + +function Utf16BEEncoder () { +} + +Utf16BEEncoder.prototype.write = function (str) { + var buf = Buffer.from(str, "ucs2") + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i + 1]; buf[i + 1] = tmp + } + return buf +} + +Utf16BEEncoder.prototype.end = function () { +} + +// -- Decoding + +function Utf16BEDecoder () { + this.overflowByte = -1 +} + +Utf16BEDecoder.prototype.write = function (buf) { + if (buf.length == 0) { return "" } + + var buf2 = Buffer.alloc(buf.length + 1) + var i = 0; var j = 0 + + if (this.overflowByte !== -1) { + buf2[0] = buf[0] + buf2[1] = this.overflowByte + i = 1; j = 2 + } + + for (; i < buf.length - 1; i += 2, j += 2) { + buf2[j] = buf[i + 1] + buf2[j + 1] = buf[i] + } + + this.overflowByte = (i == buf.length - 1) ? buf[buf.length - 1] : -1 + + return buf2.slice(0, j).toString("ucs2") +} + +Utf16BEDecoder.prototype.end = function () { + this.overflowByte = -1 +} + +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + +exports.utf16 = Utf16Codec +function Utf16Codec (codecOptions, iconv) { + this.iconv = iconv +} + +Utf16Codec.prototype.encoder = Utf16Encoder +Utf16Codec.prototype.decoder = Utf16Decoder + +// -- Encoding (pass-through) + +function Utf16Encoder (options, codec) { + options = options || {} + if (options.addBOM === undefined) { options.addBOM = true } + this.encoder = codec.iconv.getEncoder("utf-16le", options) +} + +Utf16Encoder.prototype.write = function (str) { + return this.encoder.write(str) +} + +Utf16Encoder.prototype.end = function () { + return this.encoder.end() +} + +// -- Decoding + +function Utf16Decoder (options, codec) { + this.decoder = null + this.initialBufs = [] + this.initialBufsLen = 0 + + this.options = options || {} + this.iconv = codec.iconv +} + +Utf16Decoder.prototype.write = function (buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBufs.push(buf) + this.initialBufsLen += buf.length + + if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below) + { return "" } + + // We have enough bytes -> detect endianness. + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding) + this.decoder = this.iconv.getDecoder(encoding, this.options) + + var resStr = "" + for (var i = 0; i < this.initialBufs.length; i++) { resStr += this.decoder.write(this.initialBufs[i]) } + + this.initialBufs.length = this.initialBufsLen = 0 + return resStr + } + + return this.decoder.write(buf) +} + +Utf16Decoder.prototype.end = function () { + if (!this.decoder) { + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding) + this.decoder = this.iconv.getDecoder(encoding, this.options) + + var resStr = "" + for (var i = 0; i < this.initialBufs.length; i++) { resStr += this.decoder.write(this.initialBufs[i]) } + + var trail = this.decoder.end() + if (trail) { resStr += trail } + + this.initialBufs.length = this.initialBufsLen = 0 + return resStr + } + return this.decoder.end() +} + +function detectEncoding (bufs, defaultEncoding) { + var b = [] + var charsProcessed = 0 + // Number of ASCII chars when decoded as LE or BE. + var asciiCharsLE = 0 + var asciiCharsBE = 0 + + outerLoop: + for (var i = 0; i < bufs.length; i++) { + var buf = bufs[i] + for (var j = 0; j < buf.length; j++) { + b.push(buf[j]) + if (b.length === 2) { + if (charsProcessed === 0) { + // Check BOM first. + if (b[0] === 0xFF && b[1] === 0xFE) return "utf-16le" + if (b[0] === 0xFE && b[1] === 0xFF) return "utf-16be" + } + + if (b[0] === 0 && b[1] !== 0) asciiCharsBE++ + if (b[0] !== 0 && b[1] === 0) asciiCharsLE++ + + b.length = 0 + charsProcessed++ + + if (charsProcessed >= 100) { + break outerLoop + } + } + } + } + + // Make decisions. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + if (asciiCharsBE > asciiCharsLE) return "utf-16be" + if (asciiCharsBE < asciiCharsLE) return "utf-16le" + + // Couldn't decide (likely all zeros or not enough data). + return defaultEncoding || "utf-16le" +} diff --git a/node_modules/iconv-lite/encodings/utf32.js b/node_modules/iconv-lite/encodings/utf32.js new file mode 100644 index 000000000..723178937 --- /dev/null +++ b/node_modules/iconv-lite/encodings/utf32.js @@ -0,0 +1,307 @@ +"use strict" + +var Buffer = require("safer-buffer").Buffer + +// == UTF32-LE/BE codec. ========================================================== + +exports._utf32 = Utf32Codec + +function Utf32Codec (codecOptions, iconv) { + this.iconv = iconv + this.bomAware = true + this.isLE = codecOptions.isLE +} + +exports.utf32le = { type: "_utf32", isLE: true } +exports.utf32be = { type: "_utf32", isLE: false } + +// Aliases +exports.ucs4le = "utf32le" +exports.ucs4be = "utf32be" + +Utf32Codec.prototype.encoder = Utf32Encoder +Utf32Codec.prototype.decoder = Utf32Decoder + +// -- Encoding + +function Utf32Encoder (options, codec) { + this.isLE = codec.isLE + this.highSurrogate = 0 +} + +Utf32Encoder.prototype.write = function (str) { + var src = Buffer.from(str, "ucs2") + var dst = Buffer.alloc(src.length * 2) + var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE + var offset = 0 + + for (var i = 0; i < src.length; i += 2) { + var code = src.readUInt16LE(i) + var isHighSurrogate = (code >= 0xD800 && code < 0xDC00) + var isLowSurrogate = (code >= 0xDC00 && code < 0xE000) + + if (this.highSurrogate) { + if (isHighSurrogate || !isLowSurrogate) { + // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low + // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character + // (technically wrong, but expected by some applications, like Windows file names). + write32.call(dst, this.highSurrogate, offset) + offset += 4 + } else { + // Create 32-bit value from high and low surrogates; + var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000 + + write32.call(dst, codepoint, offset) + offset += 4 + this.highSurrogate = 0 + + continue + } + } + + if (isHighSurrogate) { this.highSurrogate = code } else { + // Even if the current character is a low surrogate, with no previous high surrogate, we'll + // encode it as a semi-invalid stand-alone character for the same reasons expressed above for + // unpaired high surrogates. + write32.call(dst, code, offset) + offset += 4 + this.highSurrogate = 0 + } + } + + if (offset < dst.length) { dst = dst.slice(0, offset) } + + return dst +} + +Utf32Encoder.prototype.end = function () { + // Treat any leftover high surrogate as a semi-valid independent character. + if (!this.highSurrogate) { return } + + var buf = Buffer.alloc(4) + + if (this.isLE) { buf.writeUInt32LE(this.highSurrogate, 0) } else { buf.writeUInt32BE(this.highSurrogate, 0) } + + this.highSurrogate = 0 + + return buf +} + +// -- Decoding + +function Utf32Decoder (options, codec) { + this.isLE = codec.isLE + this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0) + this.overflow = [] +} + +Utf32Decoder.prototype.write = function (src) { + if (src.length === 0) { return "" } + + var i = 0 + var codepoint = 0 + var dst = Buffer.alloc(src.length + 4) + var offset = 0 + var isLE = this.isLE + var overflow = this.overflow + var badChar = this.badChar + + if (overflow.length > 0) { + for (; i < src.length && overflow.length < 4; i++) { overflow.push(src[i]) } + + if (overflow.length === 4) { + // NOTE: codepoint is a signed int32 and can be negative. + // NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer). + if (isLE) { + codepoint = overflow[i] | (overflow[i + 1] << 8) | (overflow[i + 2] << 16) | (overflow[i + 3] << 24) + } else { + codepoint = overflow[i + 3] | (overflow[i + 2] << 8) | (overflow[i + 1] << 16) | (overflow[i] << 24) + } + overflow.length = 0 + + offset = _writeCodepoint(dst, offset, codepoint, badChar) + } + } + + // Main loop. Should be as optimized as possible. + for (; i < src.length - 3; i += 4) { + // NOTE: codepoint is a signed int32 and can be negative. + if (isLE) { + codepoint = src[i] | (src[i + 1] << 8) | (src[i + 2] << 16) | (src[i + 3] << 24) + } else { + codepoint = src[i + 3] | (src[i + 2] << 8) | (src[i + 1] << 16) | (src[i] << 24) + } + offset = _writeCodepoint(dst, offset, codepoint, badChar) + } + + // Keep overflowing bytes. + for (; i < src.length; i++) { + overflow.push(src[i]) + } + + return dst.slice(0, offset).toString("ucs2") +} + +function _writeCodepoint (dst, offset, codepoint, badChar) { + // NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations. + if (codepoint < 0 || codepoint > 0x10FFFF) { + // Not a valid Unicode codepoint + codepoint = badChar + } + + // Ephemeral Planes: Write high surrogate. + if (codepoint >= 0x10000) { + codepoint -= 0x10000 + + var high = 0xD800 | (codepoint >> 10) + dst[offset++] = high & 0xff + dst[offset++] = high >> 8 + + // Low surrogate is written below. + var codepoint = 0xDC00 | (codepoint & 0x3FF) + } + + // Write BMP char or low surrogate. + dst[offset++] = codepoint & 0xff + dst[offset++] = codepoint >> 8 + + return offset +}; + +Utf32Decoder.prototype.end = function () { + this.overflow.length = 0 +} + +// == UTF-32 Auto codec ============================================================= +// Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic. +// Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32 +// Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'}); + +// Encoder prepends BOM (which can be overridden with (addBOM: false}). + +exports.utf32 = Utf32AutoCodec +exports.ucs4 = "utf32" + +function Utf32AutoCodec (options, iconv) { + this.iconv = iconv +} + +Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder +Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder + +// -- Encoding + +function Utf32AutoEncoder (options, codec) { + options = options || {} + + if (options.addBOM === undefined) { + options.addBOM = true + } + + this.encoder = codec.iconv.getEncoder(options.defaultEncoding || "utf-32le", options) +} + +Utf32AutoEncoder.prototype.write = function (str) { + return this.encoder.write(str) +} + +Utf32AutoEncoder.prototype.end = function () { + return this.encoder.end() +} + +// -- Decoding + +function Utf32AutoDecoder (options, codec) { + this.decoder = null + this.initialBufs = [] + this.initialBufsLen = 0 + this.options = options || {} + this.iconv = codec.iconv +} + +Utf32AutoDecoder.prototype.write = function (buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBufs.push(buf) + this.initialBufsLen += buf.length + + if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below) + { return "" } + + // We have enough bytes -> detect endianness. + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding) + this.decoder = this.iconv.getDecoder(encoding, this.options) + + var resStr = "" + for (var i = 0; i < this.initialBufs.length; i++) { resStr += this.decoder.write(this.initialBufs[i]) } + + this.initialBufs.length = this.initialBufsLen = 0 + return resStr + } + + return this.decoder.write(buf) +} + +Utf32AutoDecoder.prototype.end = function () { + if (!this.decoder) { + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding) + this.decoder = this.iconv.getDecoder(encoding, this.options) + + var resStr = "" + for (var i = 0; i < this.initialBufs.length; i++) { resStr += this.decoder.write(this.initialBufs[i]) } + + var trail = this.decoder.end() + if (trail) { resStr += trail } + + this.initialBufs.length = this.initialBufsLen = 0 + return resStr + } + + return this.decoder.end() +} + +function detectEncoding (bufs, defaultEncoding) { + var b = [] + var charsProcessed = 0 + var invalidLE = 0; var invalidBE = 0 // Number of invalid chars when decoded as LE or BE. + var bmpCharsLE = 0; var bmpCharsBE = 0 // Number of BMP chars when decoded as LE or BE. + + outerLoop: + for (var i = 0; i < bufs.length; i++) { + var buf = bufs[i] + for (var j = 0; j < buf.length; j++) { + b.push(buf[j]) + if (b.length === 4) { + if (charsProcessed === 0) { + // Check BOM first. + if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) { + return "utf-32le" + } + if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) { + return "utf-32be" + } + } + + if (b[0] !== 0 || b[1] > 0x10) invalidBE++ + if (b[3] !== 0 || b[2] > 0x10) invalidLE++ + + if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++ + if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++ + + b.length = 0 + charsProcessed++ + + if (charsProcessed >= 100) { + break outerLoop + } + } + } + } + + // Make decisions. + if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return "utf-32be" + if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return "utf-32le" + + // Couldn't decide (likely all zeros or not enough data). + return defaultEncoding || "utf-32le" +} diff --git a/node_modules/iconv-lite/encodings/utf7.js b/node_modules/iconv-lite/encodings/utf7.js new file mode 100644 index 000000000..fe72a9d9b --- /dev/null +++ b/node_modules/iconv-lite/encodings/utf7.js @@ -0,0 +1,283 @@ +"use strict" +var Buffer = require("safer-buffer").Buffer + +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = Utf7Codec +exports.unicode11utf7 = "utf7" // Alias UNICODE-1-1-UTF-7 +function Utf7Codec (codecOptions, iconv) { + this.iconv = iconv +}; + +Utf7Codec.prototype.encoder = Utf7Encoder +Utf7Codec.prototype.decoder = Utf7Decoder +Utf7Codec.prototype.bomAware = true + +// -- Encoding + +// Why scape ()?./? +// eslint-disable-next-line no-useless-escape +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g + +function Utf7Encoder (options, codec) { + this.iconv = codec.iconv +} + +Utf7Encoder.prototype.write = function (str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return Buffer.from(str.replace(nonDirectChars, function (chunk) { + return "+" + (chunk === "+" + ? "" + : this.iconv.encode(chunk, "utf16-be").toString("base64").replace(/=+$/, "")) + + "-" + }.bind(this))) +} + +Utf7Encoder.prototype.end = function () { +} + +// -- Decoding + +function Utf7Decoder (options, codec) { + this.iconv = codec.iconv + this.inBase64 = false + this.base64Accum = "" +} + +// Why scape /? +// eslint-disable-next-line no-useless-escape +var base64Regex = /[A-Za-z0-9\/+]/ +var base64Chars = [] +for (var i = 0; i < 256; i++) { base64Chars[i] = base64Regex.test(String.fromCharCode(i)) } + +var plusChar = "+".charCodeAt(0) +var minusChar = "-".charCodeAt(0) +var andChar = "&".charCodeAt(0) + +Utf7Decoder.prototype.write = function (buf) { + var res = ""; var lastI = 0 + var inBase64 = this.inBase64 + var base64Accum = this.base64Accum + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii") // Write direct chars. + lastI = i + 1 + inBase64 = true + } + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "+-" -> "+" + res += "+" + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii") + res += this.iconv.decode(Buffer.from(b64str, "base64"), "utf16-be") + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + { i-- } + + lastI = i + 1 + inBase64 = false + base64Accum = "" + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii") // Write direct chars. + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii") + + var canBeDecoded = b64str.length - (b64str.length % 8) // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded) // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded) + + res += this.iconv.decode(Buffer.from(b64str, "base64"), "utf16-be") + } + + this.inBase64 = inBase64 + this.base64Accum = base64Accum + + return res +} + +Utf7Decoder.prototype.end = function () { + var res = "" + if (this.inBase64 && this.base64Accum.length > 0) { res = this.iconv.decode(Buffer.from(this.base64Accum, "base64"), "utf16-be") } + + this.inBase64 = false + this.base64Accum = "" + return res +} + +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. + +exports.utf7imap = Utf7IMAPCodec +function Utf7IMAPCodec (codecOptions, iconv) { + this.iconv = iconv +}; + +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder +Utf7IMAPCodec.prototype.bomAware = true + +// -- Encoding + +function Utf7IMAPEncoder (options, codec) { + this.iconv = codec.iconv + this.inBase64 = false + this.base64Accum = Buffer.alloc(6) + this.base64AccumIdx = 0 +} + +Utf7IMAPEncoder.prototype.write = function (str) { + var inBase64 = this.inBase64 + var base64Accum = this.base64Accum + var base64AccumIdx = this.base64AccumIdx + var buf = Buffer.alloc(str.length * 5 + 10); var bufIdx = 0 + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i) + if (uChar >= 0x20 && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString("base64").replace(/\//g, ",").replace(/=+$/, ""), bufIdx) + base64AccumIdx = 0 + } + + buf[bufIdx++] = minusChar // Write '-', then go to direct mode. + inBase64 = false + } + + if (!inBase64) { + buf[bufIdx++] = uChar // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + { buf[bufIdx++] = minusChar } + } + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar // Write '&', then go to base64 mode. + inBase64 = true + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8 + base64Accum[base64AccumIdx++] = uChar & 0xFF + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString("base64").replace(/\//g, ","), bufIdx) + base64AccumIdx = 0 + } + } + } + } + + this.inBase64 = inBase64 + this.base64AccumIdx = base64AccumIdx + + return buf.slice(0, bufIdx) +} + +Utf7IMAPEncoder.prototype.end = function () { + var buf = Buffer.alloc(10); var bufIdx = 0 + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString("base64").replace(/\//g, ",").replace(/=+$/, ""), bufIdx) + this.base64AccumIdx = 0 + } + + buf[bufIdx++] = minusChar // Write '-', then go to direct mode. + this.inBase64 = false + } + + return buf.slice(0, bufIdx) +} + +// -- Decoding + +function Utf7IMAPDecoder (options, codec) { + this.iconv = codec.iconv + this.inBase64 = false + this.base64Accum = "" +} + +var base64IMAPChars = base64Chars.slice() +base64IMAPChars[",".charCodeAt(0)] = true + +Utf7IMAPDecoder.prototype.write = function (buf) { + var res = ""; var lastI = 0 + var inBase64 = this.inBase64 + var base64Accum = this.base64Accum + + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii") // Write direct chars. + lastI = i + 1 + inBase64 = true + } + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&" + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii").replace(/,/g, "/") + res += this.iconv.decode(Buffer.from(b64str, "base64"), "utf16-be") + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + { i-- } + + lastI = i + 1 + inBase64 = false + base64Accum = "" + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii") // Write direct chars. + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, "/") + + var canBeDecoded = b64str.length - (b64str.length % 8) // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded) // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded) + + res += this.iconv.decode(Buffer.from(b64str, "base64"), "utf16-be") + } + + this.inBase64 = inBase64 + this.base64Accum = base64Accum + + return res +} + +Utf7IMAPDecoder.prototype.end = function () { + var res = "" + if (this.inBase64 && this.base64Accum.length > 0) { res = this.iconv.decode(Buffer.from(this.base64Accum, "base64"), "utf16-be") } + + this.inBase64 = false + this.base64Accum = "" + return res +} diff --git a/node_modules/iconv-lite/lib/bom-handling.js b/node_modules/iconv-lite/lib/bom-handling.js new file mode 100644 index 000000000..a86a6b55c --- /dev/null +++ b/node_modules/iconv-lite/lib/bom-handling.js @@ -0,0 +1,48 @@ +"use strict" + +var BOMChar = "\uFEFF" + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper (encoder, options) { + this.encoder = encoder + this.addBOM = true +} + +PrependBOMWrapper.prototype.write = function (str) { + if (this.addBOM) { + str = BOMChar + str + this.addBOM = false + } + + return this.encoder.write(str) +} + +PrependBOMWrapper.prototype.end = function () { + return this.encoder.end() +} + +// ------------------------------------------------------------------------------ + +exports.StripBOM = StripBOMWrapper +function StripBOMWrapper (decoder, options) { + this.decoder = decoder + this.pass = false + this.options = options || {} +} + +StripBOMWrapper.prototype.write = function (buf) { + var res = this.decoder.write(buf) + if (this.pass || !res) { return res } + + if (res[0] === BOMChar) { + res = res.slice(1) + if (typeof this.options.stripBOM === "function") { this.options.stripBOM() } + } + + this.pass = true + return res +} + +StripBOMWrapper.prototype.end = function () { + return this.decoder.end() +} diff --git a/node_modules/iconv-lite/lib/helpers/merge-exports.js b/node_modules/iconv-lite/lib/helpers/merge-exports.js new file mode 100644 index 000000000..e79e041d9 --- /dev/null +++ b/node_modules/iconv-lite/lib/helpers/merge-exports.js @@ -0,0 +1,13 @@ +"use strict" + +var hasOwn = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn + +function mergeModules (target, module) { + for (var key in module) { + if (hasOwn(module, key)) { + target[key] = module[key] + } + } +} + +module.exports = mergeModules diff --git a/node_modules/iconv-lite/lib/index.d.ts b/node_modules/iconv-lite/lib/index.d.ts new file mode 100644 index 000000000..b11d99e91 --- /dev/null +++ b/node_modules/iconv-lite/lib/index.d.ts @@ -0,0 +1,129 @@ +/* --------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + * REQUIREMENT: This definition is dependent on the @types/node definition. + * Install with `npm install @types/node --save-dev` + *-------------------------------------------------------------------------------------------- */ + +/* --------------------------------------------------------------------------------------------- + * This file provides detailed typings for the public API of iconv-lite + *-------------------------------------------------------------------------------------------- */ + +import type Stream = require("stream") +import type { Encoding } from "../types/encodings" + +declare namespace iconv { + export interface DecodeOptions { + /** + * Strip the Byte Order Mark (BOM) from the input, + * when decoding, if the codec is BOM-aware. @default true + */ + stripBOM?: boolean; + /** Override the default endianness for `UTF-16` and `UTF-32` decodings. */ + defaultEncoding?: "utf16be" | "utf32be"; + } + + export interface EncodeOptions { + /** + * Add a Byte Order Mark (BOM) to the output, when encoding, + * if the codec is BOM-aware. @default false + */ + addBOM?: boolean; + /** Override the default endianness for `UTF-32` encoding. */ + defaultEncoding?: "utf32be"; + } + + export interface EncoderStream { + write(str: string): Buffer; + end(): Buffer | undefined; + } + + export interface DecoderStream { + write(buf: Buffer): string; + end(): string | undefined; + } + + export interface Codec { + encoder: new (options?: EncodeOptions, codec?: Codec) => EncoderStream; + decoder: new (options?: DecodeOptions, codec?: Codec) => DecoderStream; + bomAware?: boolean; + [key: string]: any; + } + + /** Encodes a `string` into a `Buffer`, using the provided `encoding`. */ + export function encode (content: string, encoding: Encoding, options?: EncodeOptions): Buffer + + /** Decodes a `Buffer` into a `string`, using the provided `encoding`. */ + export function decode (buffer: Buffer | Uint8Array, encoding: Encoding, options?: DecodeOptions): string + + /** Checks if a given encoding is supported by `iconv-lite`. */ + export function encodingExists (encoding: string): encoding is Encoding + + /** Legacy alias for {@link iconv.encode}. */ + export const toEncoding: typeof iconv.encode + + /** Legacy alias for {@link iconv.decode}. */ + export const fromEncoding: typeof iconv.decode + + /** Creates a stream that decodes binary data from a given `encoding` into strings. */ + export function decodeStream (encoding: Encoding, options?: DecodeOptions): NodeJS.ReadWriteStream + + /** Creates a stream that encodes strings into binary data in a given `encoding`. */ + export function encodeStream (encoding: Encoding, options?: EncodeOptions): NodeJS.ReadWriteStream + + /** + * Explicitly enable Streaming API in browser environments by passing in: + * ```js + * require('stream') + * ``` + * @example iconv.enableStreamingAPI(require('stream')); + */ + export function enableStreamingAPI (stream_module: { Transform: typeof Stream.Transform }): void + + /** Creates and returns a low-level encoder stream. */ + export function getEncoder (encoding: Encoding, options?: EncodeOptions): EncoderStream + + /** Creates and returns a low-level decoder stream. */ + export function getDecoder (encoding: Encoding, options?: DecodeOptions): DecoderStream + + /** + * Returns a codec object for the given `encoding`. + * @throws If the `encoding` is not recognized. + */ + export function getCodec (encoding: Encoding): Codec + + /** Strips all non-alphanumeric characters and appended year from `encoding`. */ + export function _canonicalizeEncoding (encoding: Encoding): string + + /** A cache of all loaded encoding definitions. */ + export let encodings: Record< + Encoding, + | string + | { + type: string; + [key: string]: any; + } + > | null + + /** A cache of initialized codec objects. */ + export let _codecDataCache: Record + + /** The character used for untranslatable `Unicode` characters. @default "�" */ + export let defaultCharUnicode: string + + /** The character used for untranslatable `single-byte` characters. @default "?" */ + export let defaultCharSingleByte: string + + /** + * Skip deprecation warning when strings are used instead of Buffers during decoding. + * Note: {@link iconv.decode} converts the string to Buffer regardless. + */ + export let skipDecodeWarning: boolean + + /** @readonly Whether or not, Streaming API is enabled. */ + export const supportsStreams: boolean + + export type { iconv as Iconv, Encoding } +} + +export = iconv diff --git a/node_modules/iconv-lite/lib/index.js b/node_modules/iconv-lite/lib/index.js new file mode 100644 index 000000000..bd5d6bc0d --- /dev/null +++ b/node_modules/iconv-lite/lib/index.js @@ -0,0 +1,182 @@ +"use strict" + +var Buffer = require("safer-buffer").Buffer + +var bomHandling = require("./bom-handling") +var mergeModules = require("./helpers/merge-exports") + +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +// Cannot initialize with { __proto__: null } because Boolean({ __proto__: null }) === true +module.exports.encodings = null + +// Characters emitted in case of error. +module.exports.defaultCharUnicode = "�" +module.exports.defaultCharSingleByte = "?" + +// Public API. +module.exports.encode = function encode (str, encoding, options) { + str = "" + (str || "") // Ensure string. + + var encoder = module.exports.getEncoder(encoding, options) + + var res = encoder.write(str) + var trail = encoder.end() + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res +} + +module.exports.decode = function decode (buf, encoding, options) { + if (typeof buf === "string") { + if (!module.exports.skipDecodeWarning) { + console.error("Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding") + module.exports.skipDecodeWarning = true + } + + buf = Buffer.from("" + (buf || ""), "binary") // Ensure buffer. + } + + var decoder = module.exports.getDecoder(encoding, options) + + var res = decoder.write(buf) + var trail = decoder.end() + + return trail ? (res + trail) : res +} + +module.exports.encodingExists = function encodingExists (enc) { + try { + module.exports.getCodec(enc) + return true + } catch (e) { + return false + } +} + +// Legacy aliases to convert functions +module.exports.toEncoding = module.exports.encode +module.exports.fromEncoding = module.exports.decode + +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +module.exports._codecDataCache = { __proto__: null } + +module.exports.getCodec = function getCodec (encoding) { + if (!module.exports.encodings) { + var raw = require("../encodings") + // TODO: In future versions when old nodejs support is removed can use object.assign + module.exports.encodings = { __proto__: null } // Initialize as empty object. + mergeModules(module.exports.encodings, raw) + } + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = module.exports._canonicalizeEncoding(encoding) + + // Traverse iconv.encodings to find actual codec. + var codecOptions = {} + while (true) { + var codec = module.exports._codecDataCache[enc] + + if (codec) { return codec } + + var codecDef = module.exports.encodings[enc] + + switch (typeof codecDef) { + case "string": // Direct alias to other encoding. + enc = codecDef + break + + case "object": // Alias with options. Can be layered. + for (var key in codecDef) { codecOptions[key] = codecDef[key] } + + if (!codecOptions.encodingName) { codecOptions.encodingName = enc } + + enc = codecDef.type + break + + case "function": // Codec itself. + if (!codecOptions.encodingName) { codecOptions.encodingName = enc } + + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + // + codec = new codecDef(codecOptions, module.exports) + + module.exports._codecDataCache[codecOptions.encodingName] = codec // Save it to be reused later. + return codec + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '" + enc + "')") + } + } +} + +module.exports._canonicalizeEncoding = function (encoding) { + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + return ("" + encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, "") +} + +module.exports.getEncoder = function getEncoder (encoding, options) { + var codec = module.exports.getCodec(encoding) + var encoder = new codec.encoder(options, codec) + + if (codec.bomAware && options && options.addBOM) { encoder = new bomHandling.PrependBOM(encoder, options) } + + return encoder +} + +module.exports.getDecoder = function getDecoder (encoding, options) { + var codec = module.exports.getCodec(encoding) + var decoder = new codec.decoder(options, codec) + + if (codec.bomAware && !(options && options.stripBOM === false)) { decoder = new bomHandling.StripBOM(decoder, options) } + + return decoder +} + +// Streaming API +// NOTE: Streaming API naturally depends on 'stream' module from Node.js. Unfortunately in browser environments this module can add +// up to 100Kb to the output bundle. To avoid unnecessary code bloat, we don't enable Streaming API in browser by default. +// If you would like to enable it explicitly, please add the following code to your app: +// > iconv.enableStreamingAPI(require('stream')); +module.exports.enableStreamingAPI = function enableStreamingAPI (streamModule) { + if (module.exports.supportsStreams) { return } + + // Dependency-inject stream module to create IconvLite stream classes. + var streams = require("./streams")(streamModule) + + // Not public API yet, but expose the stream classes. + module.exports.IconvLiteEncoderStream = streams.IconvLiteEncoderStream + module.exports.IconvLiteDecoderStream = streams.IconvLiteDecoderStream + + // Streaming API. + module.exports.encodeStream = function encodeStream (encoding, options) { + return new module.exports.IconvLiteEncoderStream(module.exports.getEncoder(encoding, options), options) + } + + module.exports.decodeStream = function decodeStream (encoding, options) { + return new module.exports.IconvLiteDecoderStream(module.exports.getDecoder(encoding, options), options) + } + + module.exports.supportsStreams = true +} + +// Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments). +var streamModule +try { + streamModule = require("stream") +} catch (e) {} + +if (streamModule && streamModule.Transform) { + module.exports.enableStreamingAPI(streamModule) +} else { + // In rare cases where 'stream' module is not available by default, throw a helpful exception. + module.exports.encodeStream = module.exports.decodeStream = function () { + throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it.") + } +} + +// Some environments, such as browsers, may not load JavaScript files as UTF-8 +// eslint-disable-next-line no-constant-condition +if ("Ā" !== "\u0100") { + console.error("iconv-lite warning: js files use non-utf8 encoding. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info.") +} diff --git a/node_modules/iconv-lite/lib/streams.js b/node_modules/iconv-lite/lib/streams.js new file mode 100644 index 000000000..ebfed8e0d --- /dev/null +++ b/node_modules/iconv-lite/lib/streams.js @@ -0,0 +1,105 @@ +"use strict" + +var Buffer = require("safer-buffer").Buffer + +// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), +// we opt to dependency-inject it instead of creating a hard dependency. +module.exports = function (streamModule) { + var Transform = streamModule.Transform + + // == Encoder stream ======================================================= + + function IconvLiteEncoderStream (conv, options) { + this.conv = conv + options = options || {} + options.decodeStrings = false // We accept only strings, so we don't need to decode them. + Transform.call(this, options) + } + + IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } + }) + + IconvLiteEncoderStream.prototype._transform = function (chunk, encoding, done) { + if (typeof chunk !== "string") { + return done(new Error("Iconv encoding stream needs strings as its input.")) + } + + try { + var res = this.conv.write(chunk) + if (res && res.length) this.push(res) + done() + } catch (e) { + done(e) + } + } + + IconvLiteEncoderStream.prototype._flush = function (done) { + try { + var res = this.conv.end() + if (res && res.length) this.push(res) + done() + } catch (e) { + done(e) + } + } + + IconvLiteEncoderStream.prototype.collect = function (cb) { + var chunks = [] + this.on("error", cb) + this.on("data", function (chunk) { chunks.push(chunk) }) + this.on("end", function () { + cb(null, Buffer.concat(chunks)) + }) + return this + } + + // == Decoder stream ======================================================= + + function IconvLiteDecoderStream (conv, options) { + this.conv = conv + options = options || {} + options.encoding = this.encoding = "utf8" // We output strings. + Transform.call(this, options) + } + + IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } + }) + + IconvLiteDecoderStream.prototype._transform = function (chunk, encoding, done) { + if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array)) { return done(new Error("Iconv decoding stream needs buffers as its input.")) } + try { + var res = this.conv.write(chunk) + if (res && res.length) this.push(res, this.encoding) + done() + } catch (e) { + done(e) + } + } + + IconvLiteDecoderStream.prototype._flush = function (done) { + try { + var res = this.conv.end() + if (res && res.length) this.push(res, this.encoding) + done() + } catch (e) { + done(e) + } + } + + IconvLiteDecoderStream.prototype.collect = function (cb) { + var res = "" + this.on("error", cb) + this.on("data", function (chunk) { res += chunk }) + this.on("end", function () { + cb(null, res) + }) + return this + } + + return { + IconvLiteEncoderStream: IconvLiteEncoderStream, + IconvLiteDecoderStream: IconvLiteDecoderStream + } +} diff --git a/node_modules/iconv-lite/package.json b/node_modules/iconv-lite/package.json new file mode 100644 index 000000000..2a5735742 --- /dev/null +++ b/node_modules/iconv-lite/package.json @@ -0,0 +1,70 @@ +{ + "name": "iconv-lite", + "description": "Convert character encodings in pure javascript.", + "version": "0.7.2", + "license": "MIT", + "keywords": [ + "iconv", + "convert", + "charset", + "icu" + ], + "author": "Alexander Shtuchkin ", + "main": "./lib/index.js", + "typings": "./lib/index.d.ts", + "homepage": "https://github.com/pillarjs/iconv-lite", + "bugs": "https://github.com/pillarjs/iconv-lite/issues", + "files": [ + "lib/", + "encodings/", + "types/" + ], + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "repository": { + "type": "git", + "url": "https://github.com/pillarjs/iconv-lite.git" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "lint": "eslint", + "lint:fix": "eslint --fix", + "test": "mocha --reporter spec --check-leaks --grep .", + "test:ci": "nyc --exclude test --reporter=lcovonly --reporter=text npm test", + "test:cov": "nyc --exclude test --reporter=html --reporter=text npm test", + "test:performance": "node --allow-natives-syntax performance/index.js", + "test:tap": "mocha --reporter tap --check-leaks --grep .", + "test:typescript": "tsc && attw --pack", + "test:webpack": "npm pack && mv iconv-lite-*.tgz test/webpack/iconv-lite.tgz && cd test/webpack && npm install && npm run test && rm iconv-lite.tgz", + "typegen": "node generation/gen-typings.js" + }, + "browser": { + "stream": false + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.4", + "@stylistic/eslint-plugin": "^5.1.0", + "@stylistic/eslint-plugin-js": "^4.1.0", + "@types/node": "^24.0.12", + "async": "^3.2.0", + "bench-node": "^0.10.0", + "eslint": "^9.0.0", + "errto": "^0.2.1", + "expect-type": "^1.2.0", + "iconv": "^2.3.5", + "mocha": "^6.2.2", + "neostandard": "^0.12.0", + "nyc": "^14.1.1", + "request": "^2.88.2", + "semver": "^6.3.0", + "typescript": "~5.9.2", + "unorm": "^1.6.0" + }, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + } +} diff --git a/node_modules/iconv-lite/types/encodings.d.ts b/node_modules/iconv-lite/types/encodings.d.ts new file mode 100644 index 000000000..bedbe33f8 --- /dev/null +++ b/node_modules/iconv-lite/types/encodings.d.ts @@ -0,0 +1,423 @@ +/* + * --------------------------------------------------------------------------------------------- + * DO NOT EDIT THIS FILE MANUALLY. + * THIS FILE IS AUTOMATICALLY GENERATED. + * TO UPDATE, RUN `npm run typegen` AND COMMIT THE CHANGES. + * --------------------------------------------------------------------------------------------- + */ + +/** A union of all supported encoding strings in `iconv-lite`. */ +export type Encoding = + | "10000" + | "10006" + | "10007" + | "10029" + | "10079" + | "10081" + | "1046" + | "1124" + | "1125" + | "1129" + | "1133" + | "1161" + | "1162" + | "1163" + | "1250" + | "1251" + | "1252" + | "1253" + | "1254" + | "1255" + | "1256" + | "1257" + | "1258" + | "20866" + | "21866" + | "28591" + | "28592" + | "28593" + | "28594" + | "28595" + | "28596" + | "28597" + | "28598" + | "28599" + | "28600" + | "28601" + | "28603" + | "28604" + | "28605" + | "28606" + | "437" + | "737" + | "775" + | "808" + | "850" + | "852" + | "855" + | "856" + | "857" + | "858" + | "860" + | "861" + | "862" + | "863" + | "864" + | "865" + | "866" + | "869" + | "874" + | "922" + | "932" + | "936" + | "949" + | "950" + | "ansix34" + | "ansix341968" + | "ansix341986" + | "arabic" + | "arabic8" + | "armscii8" + | "ascii" + | "ascii8bit" + | "asmo708" + | "base64" + | "big5" + | "big5hkscs" + | "binary" + | "celtic" + | "celtic8" + | "cesu8" + | "chinese" + | "cn" + | "cnbig5" + | "cp1046" + | "cp1124" + | "cp1125" + | "cp1129" + | "cp1133" + | "cp1161" + | "cp1162" + | "cp1163" + | "cp1250" + | "cp1251" + | "cp1252" + | "cp1253" + | "cp1254" + | "cp1255" + | "cp1256" + | "cp1257" + | "cp1258" + | "cp20866" + | "cp21866" + | "cp28591" + | "cp28592" + | "cp28593" + | "cp28594" + | "cp28595" + | "cp28596" + | "cp28597" + | "cp28598" + | "cp28599" + | "cp28600" + | "cp28601" + | "cp28603" + | "cp28604" + | "cp28605" + | "cp28606" + | "cp367" + | "cp437" + | "cp720" + | "cp737" + | "cp775" + | "cp808" + | "cp819" + | "cp850" + | "cp852" + | "cp855" + | "cp856" + | "cp857" + | "cp858" + | "cp860" + | "cp861" + | "cp862" + | "cp863" + | "cp864" + | "cp865" + | "cp866" + | "cp869" + | "cp874" + | "cp922" + | "cp932" + | "cp936" + | "cp949" + | "cp950" + | "cpgr" + | "csascii" + | "csbig5" + | "cseuckr" + | "csgb2312" + | "cshproman8" + | "csibm1046" + | "csibm1124" + | "csibm1125" + | "csibm1129" + | "csibm1133" + | "csibm1161" + | "csibm1162" + | "csibm1163" + | "csibm437" + | "csibm737" + | "csibm775" + | "csibm850" + | "csibm852" + | "csibm855" + | "csibm856" + | "csibm857" + | "csibm858" + | "csibm860" + | "csibm861" + | "csibm862" + | "csibm863" + | "csibm864" + | "csibm865" + | "csibm866" + | "csibm869" + | "csibm922" + | "csiso14jisc6220ro" + | "csiso58gb231280" + | "csisolatin1" + | "csisolatin2" + | "csisolatin3" + | "csisolatin4" + | "csisolatin5" + | "csisolatin6" + | "csisolatinarabic" + | "csisolatincyrillic" + | "csisolatingreek" + | "csisolatinhebrew" + | "cskoi8r" + | "csksc56011987" + | "csmacintosh" + | "cspc775baltic" + | "cspc850multilingual" + | "cspc862latinhebrew" + | "cspc8codepage437" + | "cspcp852" + | "csshiftjis" + | "cyrillic" + | "ecma114" + | "ecma118" + | "elot928" + | "euccn" + | "eucjp" + | "euckr" + | "gb18030" + | "gb198880" + | "gb2312" + | "gb23121980" + | "gb231280" + | "gbk" + | "georgianacademy" + | "georgianps" + | "greek" + | "greek8" + | "hebrew" + | "hebrew8" + | "hex" + | "hproman8" + | "ibm1046" + | "ibm1051" + | "ibm1124" + | "ibm1125" + | "ibm1129" + | "ibm1133" + | "ibm1161" + | "ibm1162" + | "ibm1163" + | "ibm1168" + | "ibm367" + | "ibm437" + | "ibm737" + | "ibm775" + | "ibm808" + | "ibm819" + | "ibm850" + | "ibm852" + | "ibm855" + | "ibm856" + | "ibm857" + | "ibm858" + | "ibm860" + | "ibm861" + | "ibm862" + | "ibm863" + | "ibm864" + | "ibm865" + | "ibm866" + | "ibm869" + | "ibm878" + | "ibm922" + | "iso646cn" + | "iso646irv" + | "iso646jp" + | "iso646us" + | "iso88591" + | "iso885910" + | "iso885911" + | "iso885913" + | "iso885914" + | "iso885915" + | "iso885916" + | "iso88592" + | "iso88593" + | "iso88594" + | "iso88595" + | "iso88596" + | "iso88597" + | "iso88598" + | "iso88599" + | "isoceltic" + | "isoir100" + | "isoir101" + | "isoir109" + | "isoir110" + | "isoir126" + | "isoir127" + | "isoir138" + | "isoir14" + | "isoir144" + | "isoir148" + | "isoir149" + | "isoir157" + | "isoir166" + | "isoir179" + | "isoir199" + | "isoir203" + | "isoir226" + | "isoir57" + | "isoir58" + | "isoir6" + | "jisc62201969ro" + | "jp" + | "koi8r" + | "koi8ru" + | "koi8t" + | "koi8u" + | "korean" + | "ksc5601" + | "ksc56011987" + | "ksc56011989" + | "l1" + | "l10" + | "l2" + | "l3" + | "l4" + | "l5" + | "l6" + | "l7" + | "l8" + | "l9" + | "latin1" + | "latin10" + | "latin2" + | "latin3" + | "latin4" + | "latin5" + | "latin6" + | "latin7" + | "latin8" + | "latin9" + | "mac" + | "maccenteuro" + | "maccroatian" + | "maccyrillic" + | "macgreek" + | "maciceland" + | "macintosh" + | "macroman" + | "macromania" + | "macthai" + | "macturkish" + | "macukraine" + | "mik" + | "ms31j" + | "ms932" + | "ms936" + | "ms949" + | "ms950" + | "msansi" + | "msarab" + | "mscyrl" + | "msee" + | "msgreek" + | "mshebr" + | "mskanji" + | "msturk" + | "pt154" + | "r8" + | "rk1048" + | "roman8" + | "shiftjis" + | "sjis" + | "strk10482002" + | "tcvn" + | "tcvn5712" + | "tcvn57121" + | "thai" + | "thai8" + | "tis620" + | "tis6200" + | "tis62025291" + | "tis62025330" + | "turkish" + | "turkish8" + | "ucs2" + | "ucs4" + | "ucs4be" + | "ucs4le" + | "unicode11utf7" + | "unicode11utf8" + | "us" + | "usascii" + | "utf16" + | "utf16be" + | "utf16le" + | "utf32" + | "utf32be" + | "utf32le" + | "utf7" + | "utf7imap" + | "utf8" + | "viscii" + | "win1250" + | "win1251" + | "win1252" + | "win1253" + | "win1254" + | "win1255" + | "win1256" + | "win1257" + | "win1258" + | "win874" + | "winbaltrim" + | "windows1250" + | "windows1251" + | "windows1252" + | "windows1253" + | "windows1254" + | "windows1255" + | "windows1256" + | "windows1257" + | "windows1258" + | "windows31j" + | "windows874" + | "windows932" + | "windows936" + | "windows949" + | "windows950" + | "xgbk" + | "xroman8" + | "xsjis" + | "xxbig5" + | (string & {}) diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 000000000..dea3013d6 --- /dev/null +++ b/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 000000000..b1c566585 --- /dev/null +++ b/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 000000000..f71f2d932 --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,9 @@ +try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 000000000..86bbb3dc2 --- /dev/null +++ b/node_modules/inherits/inherits_browser.js @@ -0,0 +1,27 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 000000000..37b4366b8 --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,29 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.4", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": "git://github.com/isaacs/inherits", + "license": "ISC", + "scripts": { + "test": "tap" + }, + "devDependencies": { + "tap": "^14.2.4" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ] +} diff --git a/node_modules/ipaddr.js/LICENSE b/node_modules/ipaddr.js/LICENSE new file mode 100644 index 000000000..f6b37b52d --- /dev/null +++ b/node_modules/ipaddr.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011-2017 whitequark + +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/ipaddr.js/README.md b/node_modules/ipaddr.js/README.md new file mode 100644 index 000000000..f57725b0f --- /dev/null +++ b/node_modules/ipaddr.js/README.md @@ -0,0 +1,233 @@ +# ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) + +ipaddr.js is a small (1.9K minified and gzipped) library for manipulating +IP addresses in JavaScript environments. It runs on both CommonJS runtimes +(e.g. [nodejs]) and in a web browser. + +ipaddr.js allows you to verify and parse string representation of an IP +address, match it against a CIDR range or range list, determine if it falls +into some reserved ranges (examples include loopback and private ranges), +and convert between IPv4 and IPv4-mapped IPv6 addresses. + +[nodejs]: http://nodejs.org + +## Installation + +`npm install ipaddr.js` + +or + +`bower install ipaddr.js` + +## API + +ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, +it is exported from the module: + +```js +var ipaddr = require('ipaddr.js'); +``` + +The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. + +### Global methods + +There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and +`ipaddr.process`. All of them receive a string as a single parameter. + +The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or +IPv6 address, and `false` otherwise. It does not throw any exceptions. + +The `ipaddr.parse` method returns an object representing the IP address, +or throws an `Error` if the passed string is not a valid representation of an +IP address. + +The `ipaddr.process` method works just like the `ipaddr.parse` one, but it +automatically converts IPv4-mapped IPv6 addresses to their IPv4 counterparts +before returning. It is useful when you have a Node.js instance listening +on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its +equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 +connections on your IPv6-only socket, but the remote address will be mangled. +Use `ipaddr.process` method to automatically demangle it. + +### Object representation + +Parsing methods return an object which descends from `ipaddr.IPv6` or +`ipaddr.IPv4`. These objects share some properties, but most of them differ. + +#### Shared properties + +One can determine the type of address by calling `addr.kind()`. It will return +either `"ipv6"` or `"ipv4"`. + +An address can be converted back to its string representation with `addr.toString()`. +Note that this method: + * does not return the original string used to create the object (in fact, there is + no way of getting that string) + * returns a compact representation (when it is applicable) + +A `match(range, bits)` method can be used to check if the address falls into a +certain CIDR range. +Note that an address can be (obviously) matched only against an address of the same type. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); +var range = ipaddr.parse("2001:db8::"); + +addr.match(range, 32); // => true +``` + +Alternatively, `match` can also be called as `match([range, bits])`. In this way, +it can be used together with the `parseCIDR(string)` method, which parses an IP +address together with a CIDR range. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); + +addr.match(ipaddr.parseCIDR("2001:db8::/32")); // => true +``` + +A `range()` method returns one of predefined names for several special ranges defined +by IP protocols. The exact names (and their respective CIDR ranges) can be looked up +in the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `"unicast"` +(the default one) and `"reserved"`. + +You can match against your own range list by using +`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with a mix of IPv6 or IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: + +```js +var rangeList = { + documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], + tunnelProviders: [ + [ ipaddr.parse('2001:470::'), 32 ], // he.net + [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 + ] +}; +ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "tunnelProviders" +``` + +The addresses can be converted to their byte representation with `toByteArray()`. +(Actually, JavaScript mostly does not know about byte buffers. They are emulated with +arrays of numbers, each in range of 0..255.) + +```js +var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com +bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ] +``` + +The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them +have the same interface for both protocols, and are similar to global methods. + +`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address +for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. + +`ipaddr.IPvX.isValid(string)` uses the same format for parsing as the POSIX `inet_ntoa` function, which accepts unusual formats like `0xc0.168.1.1` or `0x10000000`. The function `ipaddr.IPv4.isValidFourPartDecimal(string)` validates the IPv4 address and also ensures that it is written in four-part decimal format. + +[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 +[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 + +#### IPv6 properties + +Sometimes you will want to convert IPv6 not to a compact string representation (with +the `::` substitution); the `toNormalizedString()` method will return an address where +all zeroes are explicit. + +For example: + +```js +var addr = ipaddr.parse("2001:0db8::0001"); +addr.toString(); // => "2001:db8::1" +addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" +``` + +The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped +one, and `toIPv4Address()` will return an IPv4 object address. + +To access the underlying binary representation of the address, use `addr.parts`. + +```js +var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); +addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] +``` + +A IPv6 zone index can be accessed via `addr.zoneId`: + +```js +var addr = ipaddr.parse("2001:db8::%eth0"); +addr.zoneId // => 'eth0' +``` + +#### IPv4 properties + +`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. + +To access the underlying representation of the address, use `addr.octets`. + +```js +var addr = ipaddr.parse("192.168.1.1"); +addr.octets // => [192, 168, 1, 1] +``` + +`prefixLengthFromSubnetMask()` will return a CIDR prefix length for a valid IPv4 netmask or +null if the netmask is not valid. + +```js +ipaddr.IPv4.parse('255.255.255.240').prefixLengthFromSubnetMask() == 28 +ipaddr.IPv4.parse('255.192.164.0').prefixLengthFromSubnetMask() == null +``` + +`subnetMaskFromPrefixLength()` will return an IPv4 netmask for a valid CIDR prefix length. + +```js +ipaddr.IPv4.subnetMaskFromPrefixLength(24) == "255.255.255.0" +ipaddr.IPv4.subnetMaskFromPrefixLength(29) == "255.255.255.248" +``` + +`broadcastAddressFromCIDR()` will return the broadcast address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.broadcastAddressFromCIDR("172.0.0.1/24") == "172.0.0.255" +``` +`networkAddressFromCIDR()` will return the network address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.networkAddressFromCIDR("172.0.0.1/24") == "172.0.0.0" +``` + +#### Conversion + +IPv4 and IPv6 can be converted bidirectionally to and from network byte order (MSB) byte arrays. + +The `fromByteArray()` method will take an array and create an appropriate IPv4 or IPv6 object +if the input satisfies the requirements. For IPv4 it has to be an array of four 8-bit values, +while for IPv6 it has to be an array of sixteen 8-bit values. + +For example: +```js +var addr = ipaddr.fromByteArray([0x7f, 0, 0, 1]); +addr.toString(); // => "127.0.0.1" +``` + +or + +```js +var addr = ipaddr.fromByteArray([0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) +addr.toString(); // => "2001:db8::1" +``` + +Both objects also offer a `toByteArray()` method, which returns an array in network byte order (MSB). + +For example: +```js +var addr = ipaddr.parse("127.0.0.1"); +addr.toByteArray(); // => [0x7f, 0, 0, 1] +``` + +or + +```js +var addr = ipaddr.parse("2001:db8::1"); +addr.toByteArray(); // => [0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] +``` diff --git a/node_modules/ipaddr.js/ipaddr.min.js b/node_modules/ipaddr.js/ipaddr.min.js new file mode 100644 index 000000000..b54a7cc42 --- /dev/null +++ b/node_modules/ipaddr.js/ipaddr.min.js @@ -0,0 +1 @@ +(function(){var r,t,n,e,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;e>0;){if((o=n-e)<0&&(o=0),r[i]>>o!=t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;null==n&&(n="unicast");for(o in t)for(!(a=t[o])[0]||a[0]instanceof Array||(a=[a]),e=0,i=a.length;e=0;t=n+=-1){if(!((e=this.octets[t])in a))return null;if(o=a[e],i&&0!==o)return null;8!==o&&(i=!0),r+=o}return 32-r},r}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(a=[],r=0,e=(o=t.slice(1,6)).length;r4294967295||a<0)throw new Error("ipaddr: address outside defined range");return function(){var r,t;for(t=[],o=r=0;r<=24;o=r+=8)t.push(a>>o&255);return t}().reverse()}return null},t.IPv6=function(){function r(r,t){var n,e,i,o,a,s;if(16===r.length)for(this.parts=[],n=e=0;e<=14;n=e+=2)this.parts.push(r[n]<<8|r[n+1]);else{if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=r}for(i=0,o=(s=this.parts).length;it&&(r=n.index,t=n[0].length);return t<0?i:i.substring(0,r)+"::"+i.substring(r+t)},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],t=0,n=(i=this.parts).length;t>8),r.push(255&e);return r},r.prototype.toNormalizedString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r>8,255&r,n>>8,255&n])},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r=0,i=!1,t=n=7;n>=0;t=n+=-1){if(!((e=this.parts[t])in a))return null;if(o=a[e],i&&0!==o)return null;16!==o&&(i=!0),r+=o}return 128-r},r}(),i="(?:[0-9a-f]+::?)+",o={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"(%[0-9a-z]{1,})?$","i")},r=function(r,t){var n,e,i,a,s,p;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for((p=(r.match(o.zoneIndex)||[])[0])&&(p=p.substring(1),r=r.replace(/%.+$/,"")),n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(s=t-n,a=":";s--;)a+="0:";return":"===(r=r.replace("::",a))[0]&&(r=r.slice(1)),":"===r[r.length-1]&&(r=r.slice(0,-1)),t=function(){var t,n,e,o;for(o=[],t=0,n=(e=r.split(":")).length;t=0&&t<=32)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv4.subnetMaskFromPrefixLength=function(r){var t,n,e;if((r=parseInt(r))<0||r>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(e=[0,0,0,0],n=0,t=Math.floor(r/8);n=0&&t<=128)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},t.isValid=function(r){return t.IPv6.isValid(r)||t.IPv4.isValid(r)},t.parse=function(r){if(t.IPv6.isValid(r))return t.IPv6.parse(r);if(t.IPv4.isValid(r))return t.IPv4.parse(r);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},t.parseCIDR=function(r){try{return t.IPv6.parseCIDR(r)}catch(n){n;try{return t.IPv4.parseCIDR(r)}catch(r){throw r,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},t.fromByteArray=function(r){var n;if(4===(n=r.length))return new t.IPv4(r);if(16===n)return new t.IPv6(r);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},t.process=function(r){var t;return t=this.parse(r),"ipv6"===t.kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(this); \ No newline at end of file diff --git a/node_modules/ipaddr.js/lib/ipaddr.js b/node_modules/ipaddr.js/lib/ipaddr.js new file mode 100644 index 000000000..18bd93b5e --- /dev/null +++ b/node_modules/ipaddr.js/lib/ipaddr.js @@ -0,0 +1,673 @@ +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; + + ipaddr = {}; + + root = this; + + if ((typeof module !== "undefined" && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } + + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + }; + + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var k, len, rangeName, rangeSubnets, subnet; + if (defaultName == null) { + defaultName = 'unicast'; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (k = 0, len = rangeSubnets.length; k < len; k++) { + subnet = rangeSubnets[k]; + if (address.kind() === subnet[0].kind()) { + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + } + return defaultName; + }; + + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var k, len, octet; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); + } + } + this.octets = octets; + } + + IPv4.prototype.kind = function() { + return 'ipv4'; + }; + + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; + + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; + + IPv4.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv4') { + throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; + + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; + + IPv4.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, octet, stop, zeros, zerotable; + zerotable = { + 0: 8, + 128: 7, + 192: 6, + 224: 5, + 240: 4, + 248: 3, + 252: 2, + 254: 1, + 255: 0 + }; + cidr = 0; + stop = false; + for (i = k = 3; k >= 0; i = k += -1) { + octet = this.octets[i]; + if (octet in zerotable) { + zeros = zerotable[octet]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 8) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 32 - cidr; + }; + + return IPv4; + + })(); + + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; + + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var k, len, ref, results; + ref = match.slice(1, 6); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseIntAuto(part)); + } + return results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var k, results; + results = []; + for (shift = k = 0; k <= 24; shift = k += 8) { + results.push((value >> shift) & 0xff); + } + return results; + })()).reverse(); + } else { + return null; + } + }; + + ipaddr.IPv6 = (function() { + function IPv6(parts, zoneId) { + var i, k, l, len, part, ref; + if (parts.length === 16) { + this.parts = []; + for (i = k = 0; k <= 14; i = k += 2) { + this.parts.push((parts[i] << 8) | parts[i + 1]); + } + } else if (parts.length === 8) { + this.parts = parts; + } else { + throw new Error("ipaddr: ipv6 part count should be 8 or 16"); + } + ref = this.parts; + for (l = 0, len = ref.length; l < len; l++) { + part = ref[l]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit in 16 bits"); + } + } + if (zoneId) { + this.zoneId = zoneId; + } + } + + IPv6.prototype.kind = function() { + return 'ipv6'; + }; + + IPv6.prototype.toString = function() { + return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); + }; + + IPv6.prototype.toRFC5952String = function() { + var bestMatchIndex, bestMatchLength, match, regex, string; + regex = /((^|:)(0(:|$)){2,})/g; + string = this.toNormalizedString(); + bestMatchIndex = 0; + bestMatchLength = -1; + while ((match = regex.exec(string))) { + if (match[0].length > bestMatchLength) { + bestMatchIndex = match.index; + bestMatchLength = match[0].length; + } + } + if (bestMatchLength < 0) { + return string; + } + return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength); + }; + + IPv6.prototype.toByteArray = function() { + var bytes, k, len, part, ref; + bytes = []; + ref = this.parts; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; + + IPv6.prototype.toNormalizedString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16)); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; + + IPv6.prototype.toFixedLengthString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16).padStart(4, '0')); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; + + IPv6.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv6') { + throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; + + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; + + IPv6.prototype.toIPv4Address = function() { + var high, low, ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + ref = this.parts.slice(-2), high = ref[0], low = ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; + + IPv6.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, part, stop, zeros, zerotable; + zerotable = { + 0: 16, + 32768: 15, + 49152: 14, + 57344: 13, + 61440: 12, + 63488: 11, + 64512: 10, + 65024: 9, + 65280: 8, + 65408: 7, + 65472: 6, + 65504: 5, + 65520: 4, + 65528: 3, + 65532: 2, + 65534: 1, + 65535: 0 + }; + cidr = 0; + stop = false; + for (i = k = 7; k >= 0; i = k += -1) { + part = this.parts[i]; + if (part in zerotable) { + zeros = zerotable[part]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 16) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 128 - cidr; + }; + + return IPv6; + + })(); + + ipv6Part = "(?:[0-9a-f]+::?)+"; + + zoneIndex = "%[0-9a-z]{1,}"; + + ipv6Regexes = { + zoneIndex: new RegExp(zoneIndex, 'i'), + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') + }; + + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount, zoneId; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; + } + zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; + if (zoneId) { + zoneId = zoneId.substring(1); + string = string.replace(/%.+$/, ''); + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + parts = (function() { + var k, len, ref, results; + ref = string.split(":"); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseInt(part, 16)); + } + return results; + })(); + return { + parts: parts, + zoneId: zoneId + }; + }; + + ipaddr.IPv6.parser = function(string) { + var addr, k, len, match, octet, octets, zoneId; + if (ipv6Regexes['native'].test(string)) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + zoneId = match[6] || ''; + addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); + if (addr.parts) { + octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + return null; + } + } + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; + } + } + return null; + }; + + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; + + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + + ipaddr.IPv4.isValidFourPartDecimal = function(string) { + if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { + return true; + } else { + return false; + } + }; + + ipaddr.IPv6.isValid = function(string) { + var addr, e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + addr = this.parser(string); + new this(addr.parts, addr.zoneId); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + + ipaddr.IPv4.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; + + ipaddr.IPv6.parse = function(string) { + var addr; + addr = this.parser(string); + if (addr.parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(addr.parts, addr.zoneId); + }; + + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; + + ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { + var filledOctetCount, j, octets; + prefix = parseInt(prefix); + if (prefix < 0 || prefix > 32) { + throw new Error('ipaddr: invalid IPv4 prefix length'); + } + octets = [0, 0, 0, 0]; + j = 0; + filledOctetCount = Math.floor(prefix / 8); + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + if (filledOctetCount < 4) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + } + return new this(octets); + }; + + ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + ipaddr.IPv4.networkAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + + ipaddr.parseCIDR = function(string) { + var e; + try { + return ipaddr.IPv6.parseCIDR(string); + } catch (error1) { + e = error1; + try { + return ipaddr.IPv4.parseCIDR(string); + } catch (error1) { + e = error1; + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + } + } + }; + + ipaddr.fromByteArray = function(bytes) { + var length; + length = bytes.length; + if (length === 4) { + return new ipaddr.IPv4(bytes); + } else if (length === 16) { + return new ipaddr.IPv6(bytes); + } else { + throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); + } + }; + + ipaddr.process = function(string) { + var addr; + addr = this.parse(string); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + +}).call(this); diff --git a/node_modules/ipaddr.js/lib/ipaddr.js.d.ts b/node_modules/ipaddr.js/lib/ipaddr.js.d.ts new file mode 100644 index 000000000..52174b6b6 --- /dev/null +++ b/node_modules/ipaddr.js/lib/ipaddr.js.d.ts @@ -0,0 +1,68 @@ +declare module "ipaddr.js" { + type IPv4Range = 'unicast' | 'unspecified' | 'broadcast' | 'multicast' | 'linkLocal' | 'loopback' | 'carrierGradeNat' | 'private' | 'reserved'; + type IPv6Range = 'unicast' | 'unspecified' | 'linkLocal' | 'multicast' | 'loopback' | 'uniqueLocal' | 'ipv4Mapped' | 'rfc6145' | 'rfc6052' | '6to4' | 'teredo' | 'reserved'; + + interface RangeList { + [name: string]: [T, number] | [T, number][]; + } + + // Common methods/properties for IPv4 and IPv6 classes. + class IP { + prefixLengthFromSubnetMask(): number | null; + toByteArray(): number[]; + toNormalizedString(): string; + toString(): string; + } + + namespace Address { + export function isValid(addr: string): boolean; + export function fromByteArray(bytes: number[]): IPv4 | IPv6; + export function parse(addr: string): IPv4 | IPv6; + export function parseCIDR(mask: string): [IPv4 | IPv6, number]; + export function process(addr: string): IPv4 | IPv6; + export function subnetMatch(addr: IPv4, rangeList: RangeList, defaultName?: string): string; + export function subnetMatch(addr: IPv6, rangeList: RangeList, defaultName?: string): string; + + export class IPv4 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv4; + static isIPv4(addr: string): boolean; + static isValidFourPartDecimal(addr: string): boolean; + static isValid(addr: string): boolean; + static networkAddressFromCIDR(addr: string): IPv4; + static parse(addr: string): IPv4; + static parseCIDR(addr: string): [IPv4, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv4; + constructor(octets: number[]); + octets: number[] + + kind(): 'ipv4'; + match(addr: IPv4, bits: number): boolean; + match(mask: [IPv4, number]): boolean; + range(): IPv4Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4MappedAddress(): IPv6; + } + + export class IPv6 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv6; + static isIPv6(addr: string): boolean; + static isValid(addr: string): boolean; + static parse(addr: string): IPv6; + static parseCIDR(addr: string): [IPv6, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv6; + constructor(parts: number[]); + parts: number[] + zoneId?: string + + isIPv4MappedAddress(): boolean; + kind(): 'ipv6'; + match(addr: IPv6, bits: number): boolean; + match(mask: [IPv6, number]): boolean; + range(): IPv6Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4Address(): IPv4; + } + } + + export = Address; +} diff --git a/node_modules/ipaddr.js/package.json b/node_modules/ipaddr.js/package.json new file mode 100644 index 000000000..f4d35475d --- /dev/null +++ b/node_modules/ipaddr.js/package.json @@ -0,0 +1,35 @@ +{ + "name": "ipaddr.js", + "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", + "version": "1.9.1", + "author": "whitequark ", + "directories": { + "lib": "./lib" + }, + "dependencies": {}, + "devDependencies": { + "coffee-script": "~1.12.6", + "nodeunit": "^0.11.3", + "uglify-js": "~3.0.19" + }, + "scripts": { + "test": "cake build test" + }, + "files": [ + "lib/", + "LICENSE", + "ipaddr.min.js" + ], + "keywords": [ + "ip", + "ipv4", + "ipv6" + ], + "repository": "git://github.com/whitequark/ipaddr.js", + "main": "./lib/ipaddr.js", + "engines": { + "node": ">= 0.10" + }, + "license": "MIT", + "types": "./lib/ipaddr.js.d.ts" +} diff --git a/node_modules/is-promise/LICENSE b/node_modules/is-promise/LICENSE new file mode 100644 index 000000000..27cc9f377 --- /dev/null +++ b/node_modules/is-promise/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Forbes Lindesay + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/is-promise/index.d.ts b/node_modules/is-promise/index.d.ts new file mode 100644 index 000000000..2107b4289 --- /dev/null +++ b/node_modules/is-promise/index.d.ts @@ -0,0 +1,2 @@ +declare function isPromise(obj: PromiseLike | S): obj is PromiseLike; +export default isPromise; diff --git a/node_modules/is-promise/index.js b/node_modules/is-promise/index.js new file mode 100644 index 000000000..1bed0871b --- /dev/null +++ b/node_modules/is-promise/index.js @@ -0,0 +1,6 @@ +module.exports = isPromise; +module.exports.default = isPromise; + +function isPromise(obj) { + return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; +} diff --git a/node_modules/is-promise/index.mjs b/node_modules/is-promise/index.mjs new file mode 100644 index 000000000..bf9e99b5c --- /dev/null +++ b/node_modules/is-promise/index.mjs @@ -0,0 +1,3 @@ +export default function isPromise(obj) { + return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; +} diff --git a/node_modules/is-promise/package.json b/node_modules/is-promise/package.json new file mode 100644 index 000000000..2a3c5404a --- /dev/null +++ b/node_modules/is-promise/package.json @@ -0,0 +1,30 @@ +{ + "name": "is-promise", + "version": "4.0.0", + "description": "Test whether an object looks like a promises-a+ promise", + "main": "./index.js", + "scripts": { + "test": "node test" + }, + "files": [ + "index.js", + "index.mjs", + "index.d.ts" + ], + "exports": { + ".": [ + { + "import": "./index.mjs", + "require": "./index.js", + "default": "./index.js" + }, + "./index.js" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/then/is-promise.git" + }, + "author": "ForbesLindesay", + "license": "MIT" +} diff --git a/node_modules/is-promise/readme.md b/node_modules/is-promise/readme.md new file mode 100644 index 000000000..d53d34bd5 --- /dev/null +++ b/node_modules/is-promise/readme.md @@ -0,0 +1,33 @@ + + +# is-promise + + Test whether an object looks like a promises-a+ promise + + [![Build Status](https://img.shields.io/travis/then/is-promise/master.svg)](https://travis-ci.org/then/is-promise) + [![Dependency Status](https://img.shields.io/david/then/is-promise.svg)](https://david-dm.org/then/is-promise) + [![NPM version](https://img.shields.io/npm/v/is-promise.svg)](https://www.npmjs.org/package/is-promise) + + + +## Installation + + $ npm install is-promise + +You can also use it client side via npm. + +## API + +```typescript +import isPromise from 'is-promise'; + +isPromise(Promise.resolve());//=>true +isPromise({then:function () {...}});//=>true +isPromise(null);//=>false +isPromise({});//=>false +isPromise({then: true})//=>false +``` + +## License + + MIT diff --git a/node_modules/isexe/.npmignore b/node_modules/isexe/.npmignore new file mode 100644 index 000000000..c1cb757ac --- /dev/null +++ b/node_modules/isexe/.npmignore @@ -0,0 +1,2 @@ +.nyc_output/ +coverage/ diff --git a/node_modules/isexe/LICENSE b/node_modules/isexe/LICENSE new file mode 100644 index 000000000..19129e315 --- /dev/null +++ b/node_modules/isexe/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/isexe/README.md b/node_modules/isexe/README.md new file mode 100644 index 000000000..35769e844 --- /dev/null +++ b/node_modules/isexe/README.md @@ -0,0 +1,51 @@ +# isexe + +Minimal module to check if a file is executable, and a normal file. + +Uses `fs.stat` and tests against the `PATHEXT` environment variable on +Windows. + +## USAGE + +```javascript +var isexe = require('isexe') +isexe('some-file-name', function (err, isExe) { + if (err) { + console.error('probably file does not exist or something', err) + } else if (isExe) { + console.error('this thing can be run') + } else { + console.error('cannot be run') + } +}) + +// same thing but synchronous, throws errors +var isExe = isexe.sync('some-file-name') + +// treat errors as just "not executable" +isexe('maybe-missing-file', { ignoreErrors: true }, callback) +var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true }) +``` + +## API + +### `isexe(path, [options], [callback])` + +Check if the path is executable. If no callback provided, and a +global `Promise` object is available, then a Promise will be returned. + +Will raise whatever errors may be raised by `fs.stat`, unless +`options.ignoreErrors` is set to true. + +### `isexe.sync(path, [options])` + +Same as `isexe` but returns the value and throws any errors raised. + +### Options + +* `ignoreErrors` Treat all errors as "no, this is not executable", but + don't raise them. +* `uid` Number to use as the user id +* `gid` Number to use as the group id +* `pathExt` List of path extensions to use instead of `PATHEXT` + environment variable on Windows. diff --git a/node_modules/isexe/index.js b/node_modules/isexe/index.js new file mode 100644 index 000000000..553fb32b1 --- /dev/null +++ b/node_modules/isexe/index.js @@ -0,0 +1,57 @@ +var fs = require('fs') +var core +if (process.platform === 'win32' || global.TESTING_WINDOWS) { + core = require('./windows.js') +} else { + core = require('./mode.js') +} + +module.exports = isexe +isexe.sync = sync + +function isexe (path, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } + + return new Promise(function (resolve, reject) { + isexe(path, options || {}, function (er, is) { + if (er) { + reject(er) + } else { + resolve(is) + } + }) + }) + } + + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null + is = false + } + } + cb(er, is) + }) +} + +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} diff --git a/node_modules/isexe/mode.js b/node_modules/isexe/mode.js new file mode 100644 index 000000000..1995ea4a0 --- /dev/null +++ b/node_modules/isexe/mode.js @@ -0,0 +1,41 @@ +module.exports = isexe +isexe.sync = sync + +var fs = require('fs') + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), options) +} + +function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) +} + +function checkMode (stat, options) { + var mod = stat.mode + var uid = stat.uid + var gid = stat.gid + + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid() + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid() + + var u = parseInt('100', 8) + var g = parseInt('010', 8) + var o = parseInt('001', 8) + var ug = u | g + + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0 + + return ret +} diff --git a/node_modules/isexe/package.json b/node_modules/isexe/package.json new file mode 100644 index 000000000..e45268944 --- /dev/null +++ b/node_modules/isexe/package.json @@ -0,0 +1,31 @@ +{ + "name": "isexe", + "version": "2.0.0", + "description": "Minimal module to check if a file is executable.", + "main": "index.js", + "directories": { + "test": "test" + }, + "devDependencies": { + "mkdirp": "^0.5.1", + "rimraf": "^2.5.0", + "tap": "^10.3.0" + }, + "scripts": { + "test": "tap test/*.js --100", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/isexe.git" + }, + "keywords": [], + "bugs": { + "url": "https://github.com/isaacs/isexe/issues" + }, + "homepage": "https://github.com/isaacs/isexe#readme" +} diff --git a/node_modules/isexe/test/basic.js b/node_modules/isexe/test/basic.js new file mode 100644 index 000000000..d926df64b --- /dev/null +++ b/node_modules/isexe/test/basic.js @@ -0,0 +1,221 @@ +var t = require('tap') +var fs = require('fs') +var path = require('path') +var fixture = path.resolve(__dirname, 'fixtures') +var meow = fixture + '/meow.cat' +var mine = fixture + '/mine.cat' +var ours = fixture + '/ours.cat' +var fail = fixture + '/fail.false' +var noent = fixture + '/enoent.exe' +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') + +var isWindows = process.platform === 'win32' +var hasAccess = typeof fs.access === 'function' +var winSkip = isWindows && 'windows' +var accessSkip = !hasAccess && 'no fs.access function' +var hasPromise = typeof Promise === 'function' +var promiseSkip = !hasPromise && 'no global Promise' + +function reset () { + delete require.cache[require.resolve('../')] + return require('../') +} + +t.test('setup fixtures', function (t) { + rimraf.sync(fixture) + mkdirp.sync(fixture) + fs.writeFileSync(meow, '#!/usr/bin/env cat\nmeow\n') + fs.chmodSync(meow, parseInt('0755', 8)) + fs.writeFileSync(fail, '#!/usr/bin/env false\n') + fs.chmodSync(fail, parseInt('0644', 8)) + fs.writeFileSync(mine, '#!/usr/bin/env cat\nmine\n') + fs.chmodSync(mine, parseInt('0744', 8)) + fs.writeFileSync(ours, '#!/usr/bin/env cat\nours\n') + fs.chmodSync(ours, parseInt('0754', 8)) + t.end() +}) + +t.test('promise', { skip: promiseSkip }, function (t) { + var isexe = reset() + t.test('meow async', function (t) { + isexe(meow).then(function (is) { + t.ok(is) + t.end() + }) + }) + t.test('fail async', function (t) { + isexe(fail).then(function (is) { + t.notOk(is) + t.end() + }) + }) + t.test('noent async', function (t) { + isexe(noent).catch(function (er) { + t.ok(er) + t.end() + }) + }) + t.test('noent ignore async', function (t) { + isexe(noent, { ignoreErrors: true }).then(function (is) { + t.notOk(is) + t.end() + }) + }) + t.end() +}) + +t.test('no promise', function (t) { + global.Promise = null + var isexe = reset() + t.throws('try to meow a promise', function () { + isexe(meow) + }) + t.end() +}) + +t.test('access', { skip: accessSkip || winSkip }, function (t) { + runTest(t) +}) + +t.test('mode', { skip: winSkip }, function (t) { + delete fs.access + delete fs.accessSync + var isexe = reset() + t.ok(isexe.sync(ours, { uid: 0, gid: 0 })) + t.ok(isexe.sync(mine, { uid: 0, gid: 0 })) + runTest(t) +}) + +t.test('windows', function (t) { + global.TESTING_WINDOWS = true + var pathExt = '.EXE;.CAT;.CMD;.COM' + t.test('pathExt option', function (t) { + runTest(t, { pathExt: '.EXE;.CAT;.CMD;.COM' }) + }) + t.test('pathExt env', function (t) { + process.env.PATHEXT = pathExt + runTest(t) + }) + t.test('no pathExt', function (t) { + // with a pathExt of '', any filename is fine. + // so the "fail" one would still pass. + runTest(t, { pathExt: '', skipFail: true }) + }) + t.test('pathext with empty entry', function (t) { + // with a pathExt of '', any filename is fine. + // so the "fail" one would still pass. + runTest(t, { pathExt: ';' + pathExt, skipFail: true }) + }) + t.end() +}) + +t.test('cleanup', function (t) { + rimraf.sync(fixture) + t.end() +}) + +function runTest (t, options) { + var isexe = reset() + + var optionsIgnore = Object.create(options || {}) + optionsIgnore.ignoreErrors = true + + if (!options || !options.skipFail) { + t.notOk(isexe.sync(fail, options)) + } + t.notOk(isexe.sync(noent, optionsIgnore)) + if (!options) { + t.ok(isexe.sync(meow)) + } else { + t.ok(isexe.sync(meow, options)) + } + + t.ok(isexe.sync(mine, options)) + t.ok(isexe.sync(ours, options)) + t.throws(function () { + isexe.sync(noent, options) + }) + + t.test('meow async', function (t) { + if (!options) { + isexe(meow, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + } else { + isexe(meow, options, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + } + }) + + t.test('mine async', function (t) { + isexe(mine, options, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + }) + + t.test('ours async', function (t) { + isexe(ours, options, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + }) + + if (!options || !options.skipFail) { + t.test('fail async', function (t) { + isexe(fail, options, function (er, is) { + if (er) { + throw er + } + t.notOk(is) + t.end() + }) + }) + } + + t.test('noent async', function (t) { + isexe(noent, options, function (er, is) { + t.ok(er) + t.notOk(is) + t.end() + }) + }) + + t.test('noent ignore async', function (t) { + isexe(noent, optionsIgnore, function (er, is) { + if (er) { + throw er + } + t.notOk(is) + t.end() + }) + }) + + t.test('directory is not executable', function (t) { + isexe(__dirname, options, function (er, is) { + if (er) { + throw er + } + t.notOk(is) + t.end() + }) + }) + + t.end() +} diff --git a/node_modules/isexe/windows.js b/node_modules/isexe/windows.js new file mode 100644 index 000000000..34996734d --- /dev/null +++ b/node_modules/isexe/windows.js @@ -0,0 +1,42 @@ +module.exports = isexe +isexe.sync = sync + +var fs = require('fs') + +function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT + + if (!pathext) { + return true + } + + pathext = pathext.split(';') + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase() + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false +} + +function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) +} + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), path, options) +} diff --git a/node_modules/jose/LICENSE.md b/node_modules/jose/LICENSE.md new file mode 100644 index 000000000..d0ec038a8 --- /dev/null +++ b/node_modules/jose/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Filip Skokan + +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/jose/README.md b/node_modules/jose/README.md new file mode 100644 index 000000000..6ab1f3e17 --- /dev/null +++ b/node_modules/jose/README.md @@ -0,0 +1,153 @@ +# jose + +`jose` is a JavaScript module for JSON Object Signing and Encryption, providing support for JSON Web Tokens (JWT), JSON Web Signature (JWS), JSON Web Encryption (JWE), JSON Web Key (JWK), JSON Web Key Set (JWKS), and more. The module is designed to work across various Web-interoperable runtimes including Node.js, browsers, Cloudflare Workers, Deno, Bun, and others. + +## Sponsor + + + + + Auth0 by Okta + + +If you want to quickly add JWT authentication to JavaScript apps, feel free to check out Auth0's JavaScript SDK and free plan. [Create an Auth0 account; it's free!][sponsor-auth0]

+ +## [💗 Help the project](https://github.com/sponsors/panva) + +Support from the community to continue maintaining and improving this module is welcome. If you find the module useful, please consider supporting the project by [becoming a sponsor](https://github.com/sponsors/panva). + +## Dependencies: 0 + +`jose` has no dependencies and it exports tree-shakeable ESM[^cjs]. + +## Documentation + +`jose` is distributed via [npmjs.com](https://www.npmjs.com/package/jose), [jsr.io](https://jsr.io/@panva/jose), [jsdelivr.com](https://www.jsdelivr.com/package/npm/jose), and [github.com](https://github.com/panva/jose). + +**`example`** ESM import[^cjs] + +```js +import * as jose from 'jose' +``` + +### JSON Web Tokens (JWT) + +The `jose` module supports JSON Web Tokens (JWT) and provides functionality for signing and verifying tokens, as well as their JWT Claims Set validation. + +- [JWT Claims Set Validation & Signature Verification](docs/jwt/verify/functions/jwtVerify.md) using the `jwtVerify` function + - [Using a remote JSON Web Key Set (JWKS)](docs/jwks/remote/functions/createRemoteJWKSet.md) + - [Using a local JSON Web Key Set (JWKS)](docs/jwks/local/functions/createLocalJWKSet.md) +- [Signing](docs/jwt/sign/classes/SignJWT.md) using the `SignJWT` class +- Utility functions + - [Decoding Token's Protected Header](docs/util/decode_protected_header/functions/decodeProtectedHeader.md) + - [Decoding JWT Claims Set](docs/util/decode_jwt/functions/decodeJwt.md) prior to its validation + +### Encrypted JSON Web Tokens + +The `jose` module supports encrypted JSON Web Tokens and provides functionality for encrypting and decrypting tokens, as well as their JWT Claims Set validation. + +- [Decryption & JWT Claims Set Validation](docs/jwt/decrypt/functions/jwtDecrypt.md) using the `jwtDecrypt` function +- [Encryption](docs/jwt/encrypt/classes/EncryptJWT.md) using the `EncryptJWT` class +- Utility functions + - [Decoding Token's Protected Header](docs/util/decode_protected_header/functions/decodeProtectedHeader.md) + +### Key Utilities + +The `jose` module supports importing, exporting, and generating keys and secrets in various formats, including PEM formats like SPKI, X.509 certificate, and PKCS #8, as well as JSON Web Key (JWK). + +- Key Import Functions + - [JWK Import](docs/key/import/functions/importJWK.md) + - [Public Key Import (SPKI)](docs/key/import/functions/importSPKI.md) + - [Public Key Import (X.509 Certificate)](docs/key/import/functions/importX509.md) + - [Private Key Import (PKCS #8)](docs/key/import/functions/importPKCS8.md) +- Key and Secret Generation Functions + - [Asymmetric Key Pair Generation](docs/key/generate_key_pair/functions/generateKeyPair.md) + - [Symmetric Secret Generation](docs/key/generate_secret/functions/generateSecret.md) +- Key Export Functions + - [JWK Export](docs/key/export/functions/exportJWK.md) + - [Private Key Export](docs/key/export/functions/exportPKCS8.md) + - [Public Key Export](docs/key/export/functions/exportSPKI.md) + +### JSON Web Signature (JWS) + +The `jose` module supports signing and verification of JWS messages with arbitrary payloads in Compact, Flattened JSON, and General JSON serialization syntaxes. + +- Signing - [Compact](docs/jws/compact/sign/classes/CompactSign.md), [Flattened JSON](docs/jws/flattened/sign/classes/FlattenedSign.md), [General JSON](docs/jws/general/sign/classes/GeneralSign.md) +- Verification - [Compact](docs/jws/compact/verify/functions/compactVerify.md), [Flattened JSON](docs/jws/flattened/verify/functions/flattenedVerify.md), [General JSON](docs/jws/general/verify/functions/generalVerify.md) + - [Using a remote JSON Web Key Set (JWKS)](docs/jwks/remote/functions/createRemoteJWKSet.md) + - [Using a local JSON Web Key Set (JWKS)](docs/jwks/local/functions/createLocalJWKSet.md) +- Utility functions + - [Decoding Token's Protected Header](docs/util/decode_protected_header/functions/decodeProtectedHeader.md) + +### JSON Web Encryption (JWE) + +The `jose` module supports encryption and decryption of JWE messages with arbitrary plaintext in Compact, Flattened JSON, and General JSON serialization syntaxes. + +- Encryption - [Compact](docs/jwe/compact/encrypt/classes/CompactEncrypt.md), [Flattened JSON](docs/jwe/flattened/encrypt/classes/FlattenedEncrypt.md), [General JSON](docs/jwe/general/encrypt/classes/GeneralEncrypt.md) +- Decryption - [Compact](docs/jwe/compact/decrypt/functions/compactDecrypt.md), [Flattened JSON](docs/jwe/flattened/decrypt/functions/flattenedDecrypt.md), [General JSON](docs/jwe/general/decrypt/functions/generalDecrypt.md) +- Utility functions + - [Decoding Token's Protected Header](docs/util/decode_protected_header/functions/decodeProtectedHeader.md) + +### Other + +The following are additional features and utilities provided by the `jose` module: + +- [Calculating JWK Thumbprint](docs/jwk/thumbprint/functions/calculateJwkThumbprint.md) +- [Calculating JWK Thumbprint URI](docs/jwk/thumbprint/functions/calculateJwkThumbprintUri.md) +- [Verification using a JWK Embedded in a JWS Header](docs/jwk/embedded/functions/EmbeddedJWK.md) +- [Unsecured JWT](docs/jwt/unsecured/classes/UnsecuredJWT.md) +- [JOSE Errors](docs/util/errors/README.md) + +## Supported Runtimes + +The `jose` module is compatible with JavaScript runtimes that support the utilized Web API globals and standard built-in objects or are Node.js. + +The following runtimes are supported _(this is not an exhaustive list)_: + +- [Bun](https://github.com/panva/jose/issues/471) +- [Browsers](https://github.com/panva/jose/issues/263) +- [Cloudflare Workers](https://github.com/panva/jose/issues/265) +- [Deno](https://github.com/panva/jose/issues/266) +- [Electron](https://github.com/panva/jose/issues/264) +- [Node.js](https://github.com/panva/jose/issues/262) + +Please note that certain algorithms may not be available depending on the runtime used. You can find a list of available algorithms for each runtime in the specific issue links provided above. + +## Supported Versions + +| Version | Security Fixes 🔑 | Other Bug Fixes 🐞 | New Features ⭐ | Runtime and Module type | +| ----------------------------------------------- | ----------------- | ------------------ | --------------- | ------------------------------- | +| [v6.x](https://github.com/panva/jose/tree/v6.x) | [Security Policy] | ✅ | ✅ | Universal[^universal] ESM[^cjs] | +| [v5.x](https://github.com/panva/jose/tree/v5.x) | [Security Policy] | ❌ | ❌ | Universal[^universal] CJS + ESM | +| [v4.x](https://github.com/panva/jose/tree/v4.x) | [Security Policy] | ❌ | ❌ | Universal[^universal] CJS + ESM | +| [v2.x](https://github.com/panva/jose/tree/v2.x) | [Security Policy] | ❌ | ❌ | Node.js CJS | + +## Specifications + +
+Details + +- JSON Web Signature (JWS) - [RFC7515](https://www.rfc-editor.org/rfc/rfc7515) +- JSON Web Encryption (JWE) - [RFC7516](https://www.rfc-editor.org/rfc/rfc7516) +- JSON Web Key (JWK) - [RFC7517](https://www.rfc-editor.org/rfc/rfc7517) +- JSON Web Algorithms (JWA) - [RFC7518](https://www.rfc-editor.org/rfc/rfc7518) +- JSON Web Token (JWT) - [RFC7519](https://www.rfc-editor.org/rfc/rfc7519) +- JSON Web Key Thumbprint - [RFC7638](https://www.rfc-editor.org/rfc/rfc7638) +- JSON Web Key Thumbprint URI - [RFC9278](https://www.rfc-editor.org/rfc/rfc9278) +- JWS Unencoded Payload Option - [RFC7797](https://www.rfc-editor.org/rfc/rfc7797) +- CFRG Elliptic Curve ECDH and Signatures - [RFC8037](https://www.rfc-editor.org/rfc/rfc8037) +- Fully-Specified Algorithms for JOSE - [RFC9864](https://www.rfc-editor.org/rfc/rfc9864.html) +- ML-DSA for JOSE - [draft-ietf-cose-dilithium-10](https://www.ietf.org/archive/id/draft-ietf-cose-dilithium-10.html) + +The algorithm implementations in `jose` have been tested using test vectors from their respective specifications as well as [RFC7520](https://www.rfc-editor.org/rfc/rfc7520). + +
+ +[sponsor-auth0]: https://a0.to/signup/panva +[WebCryptoAPI]: https://w3c.github.io/webcrypto/ +[Fetch API]: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API +[Security Policy]: https://github.com/panva/jose/security/policy + +[^cjs]: CJS style `let jose = require('jose')` is possible in Node.js versions where the `require(esm)` feature is enabled by default (^20.19.0 || ^22.12.0 || >= 23.0.0). + +[^universal]: Assumes runtime support of [WebCryptoAPI][] and [Fetch API][] diff --git a/node_modules/jose/dist/types/index.d.ts b/node_modules/jose/dist/types/index.d.ts new file mode 100644 index 000000000..cb360d882 --- /dev/null +++ b/node_modules/jose/dist/types/index.d.ts @@ -0,0 +1,55 @@ +export { compactDecrypt } from './jwe/compact/decrypt.js'; +export type { CompactDecryptGetKey } from './jwe/compact/decrypt.js'; +export { flattenedDecrypt } from './jwe/flattened/decrypt.js'; +export type { FlattenedDecryptGetKey } from './jwe/flattened/decrypt.js'; +export { generalDecrypt } from './jwe/general/decrypt.js'; +export type { GeneralDecryptGetKey } from './jwe/general/decrypt.js'; +export { GeneralEncrypt } from './jwe/general/encrypt.js'; +export type { Recipient } from './jwe/general/encrypt.js'; +export { compactVerify } from './jws/compact/verify.js'; +export type { CompactVerifyGetKey } from './jws/compact/verify.js'; +export { flattenedVerify } from './jws/flattened/verify.js'; +export type { FlattenedVerifyGetKey } from './jws/flattened/verify.js'; +export { generalVerify } from './jws/general/verify.js'; +export type { GeneralVerifyGetKey } from './jws/general/verify.js'; +export { jwtVerify } from './jwt/verify.js'; +export type { JWTVerifyOptions, JWTVerifyGetKey } from './jwt/verify.js'; +export { jwtDecrypt } from './jwt/decrypt.js'; +export type { JWTDecryptOptions, JWTDecryptGetKey } from './jwt/decrypt.js'; +export { CompactEncrypt } from './jwe/compact/encrypt.js'; +export { FlattenedEncrypt } from './jwe/flattened/encrypt.js'; +export { CompactSign } from './jws/compact/sign.js'; +export { FlattenedSign } from './jws/flattened/sign.js'; +export { GeneralSign } from './jws/general/sign.js'; +export type { Signature } from './jws/general/sign.js'; +export { SignJWT } from './jwt/sign.js'; +export { EncryptJWT } from './jwt/encrypt.js'; +export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js'; +export { EmbeddedJWK } from './jwk/embedded.js'; +export { createLocalJWKSet } from './jwks/local.js'; +export { createRemoteJWKSet, jwksCache, customFetch } from './jwks/remote.js'; +export type { RemoteJWKSetOptions, JWKSCacheInput, ExportedJWKSCache, FetchImplementation, } from './jwks/remote.js'; +export { UnsecuredJWT } from './jwt/unsecured.js'; +export type { UnsecuredResult } from './jwt/unsecured.js'; +export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js'; +export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js'; +export type { KeyImportOptions } from './key/import.js'; +export { decodeProtectedHeader } from './util/decode_protected_header.js'; +export { decodeJwt } from './util/decode_jwt.js'; +export type { ProtectedHeaderParameters } from './util/decode_protected_header.js'; +import * as errors from './util/errors.js'; +export { errors }; +export { generateKeyPair } from './key/generate_key_pair.js'; +export type { GenerateKeyPairResult, GenerateKeyPairOptions } from './key/generate_key_pair.js'; +export { generateSecret } from './key/generate_secret.js'; +export type { GenerateSecretOptions } from './key/generate_secret.js'; +import * as base64url from './util/base64url.js'; +export { base64url }; +export type { CompactDecryptResult, CompactJWEHeaderParameters, CompactJWSHeaderParameters, CompactVerifyResult, CritOption, CryptoKey, DecryptOptions, EncryptOptions, FlattenedDecryptResult, FlattenedJWE, FlattenedJWS, FlattenedJWSInput, FlattenedVerifyResult, GeneralDecryptResult, GeneralJWE, GeneralJWS, GeneralJWSInput, GeneralVerifyResult, GetKeyFunction, JoseHeaderParameters, JSONWebKeySet, JWEHeaderParameters, JWEKeyManagementHeaderParameters, JWK_EC_Private, JWK_EC_Public, JWK_oct, JWK_OKP_Private, JWK_OKP_Public, JWK_RSA_Private, JWK_RSA_Public, JWK, JWKParameters, JWSHeaderParameters, JWTClaimVerificationOptions, JWTDecryptResult, JWTHeaderParameters, JWTPayload, JWTVerifyResult, KeyObject, ProduceJWT, ResolvedKey, SignOptions, VerifyOptions, } from './types.d.ts'; +/** + * In prior releases this indicated whether a Node.js-specific build was loaded, this is now fixed + * to `"WebCryptoAPI"` + * + * @deprecated + */ +export declare const cryptoRuntime = "WebCryptoAPI"; diff --git a/node_modules/jose/dist/types/jwe/compact/decrypt.d.ts b/node_modules/jose/dist/types/jwe/compact/decrypt.d.ts new file mode 100644 index 000000000..fd323764e --- /dev/null +++ b/node_modules/jose/dist/types/jwe/compact/decrypt.d.ts @@ -0,0 +1,31 @@ +/** + * Decrypting JSON Web Encryption (JWE) in Compact Serialization + * + * @module + */ +import type * as types from '../../types.d.ts'; +/** + * Interface for Compact JWE Decryption dynamic key resolution. No token components have been + * verified at the time of this function call. + */ +export interface CompactDecryptGetKey extends types.GetKeyFunction { +} +/** + * Decrypts a Compact JWE. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jwe/compact/decrypt'`. + * + * @param jwe Compact JWE. + * @param key Private Key or Secret to decrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Decryption options. + */ +export declare function compactDecrypt(jwe: string | Uint8Array, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.DecryptOptions): Promise; +/** + * @param jwe Compact JWE. + * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Decryption options. + */ +export declare function compactDecrypt(jwe: string | Uint8Array, getKey: CompactDecryptGetKey, options?: types.DecryptOptions): Promise; diff --git a/node_modules/jose/dist/types/jwe/compact/encrypt.d.ts b/node_modules/jose/dist/types/jwe/compact/encrypt.d.ts new file mode 100644 index 000000000..3bdcc4bd7 --- /dev/null +++ b/node_modules/jose/dist/types/jwe/compact/encrypt.d.ts @@ -0,0 +1,65 @@ +/** + * Encrypting JSON Web Encryption (JWE) in Compact Serialization + * + * @module + */ +import type * as types from '../../types.d.ts'; +/** + * The CompactEncrypt class is used to build and encrypt Compact JWE strings. + * + * This class is exported (as a named export) from the main `'jose'` module entry point as well as + * from its subpath export `'jose/jwe/compact/encrypt'`. + * + */ +export declare class CompactEncrypt { + #private; + /** + * {@link CompactEncrypt} constructor + * + * @param plaintext Binary representation of the plaintext to encrypt. + */ + constructor(plaintext: Uint8Array); + /** + * Sets a content encryption key to use, by default a random suitable one is generated for the JWE + * enc" (Encryption Algorithm) Header Parameter. + * + * @deprecated You should not use this method. It is only really intended for test and vector + * validation purposes. + * + * @param cek JWE Content Encryption Key. + */ + setContentEncryptionKey(cek: Uint8Array): this; + /** + * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable + * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. + * + * @deprecated You should not use this method. It is only really intended for test and vector + * validation purposes. + * + * @param iv JWE Initialization Vector. + */ + setInitializationVector(iv: Uint8Array): this; + /** + * Sets the JWE Protected Header on the CompactEncrypt object. + * + * @param protectedHeader JWE Protected Header object. + */ + setProtectedHeader(protectedHeader: types.CompactJWEHeaderParameters): this; + /** + * Sets the JWE Key Management parameters to be used when encrypting. + * + * (ECDH-ES) Use of this method is needed for ECDH based algorithms to set the "apu" (Agreement + * PartyUInfo) or "apv" (Agreement PartyVInfo) parameters. + * + * @param parameters JWE Key Management parameters. + */ + setKeyManagementParameters(parameters: types.JWEKeyManagementHeaderParameters): this; + /** + * Encrypts and resolves the value of the Compact JWE string. + * + * @param key Public Key or Secret to encrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Encryption options. + */ + encrypt(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.EncryptOptions): Promise; +} diff --git a/node_modules/jose/dist/types/jwe/flattened/decrypt.d.ts b/node_modules/jose/dist/types/jwe/flattened/decrypt.d.ts new file mode 100644 index 000000000..19a24bfad --- /dev/null +++ b/node_modules/jose/dist/types/jwe/flattened/decrypt.d.ts @@ -0,0 +1,31 @@ +/** + * Decrypting JSON Web Encryption (JWE) in Flattened JSON Serialization + * + * @module + */ +import type * as types from '../../types.d.ts'; +/** + * Interface for Flattened JWE Decryption dynamic key resolution. No token components have been + * verified at the time of this function call. + */ +export interface FlattenedDecryptGetKey extends types.GetKeyFunction { +} +/** + * Decrypts a Flattened JWE. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jwe/flattened/decrypt'`. + * + * @param jwe Flattened JWE. + * @param key Private Key or Secret to decrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Decryption options. + */ +export declare function flattenedDecrypt(jwe: types.FlattenedJWE, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.DecryptOptions): Promise; +/** + * @param jwe Flattened JWE. + * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Decryption options. + */ +export declare function flattenedDecrypt(jwe: types.FlattenedJWE, getKey: FlattenedDecryptGetKey, options?: types.DecryptOptions): Promise; diff --git a/node_modules/jose/dist/types/jwe/flattened/encrypt.d.ts b/node_modules/jose/dist/types/jwe/flattened/encrypt.d.ts new file mode 100644 index 000000000..fa348bee2 --- /dev/null +++ b/node_modules/jose/dist/types/jwe/flattened/encrypt.d.ts @@ -0,0 +1,83 @@ +/** + * Encrypting JSON Web Encryption (JWE) in Flattened JSON Serialization + * + * @module + */ +import type * as types from '../../types.d.ts'; +/** + * The FlattenedEncrypt class is used to build and encrypt Flattened JWE objects. + * + * This class is exported (as a named export) from the main `'jose'` module entry point as well as + * from its subpath export `'jose/jwe/flattened/encrypt'`. + * + */ +export declare class FlattenedEncrypt { + #private; + /** + * {@link FlattenedEncrypt} constructor + * + * @param plaintext Binary representation of the plaintext to encrypt. + */ + constructor(plaintext: Uint8Array); + /** + * Sets the JWE Key Management parameters to be used when encrypting. + * + * (ECDH-ES) Use of this method is needed for ECDH based algorithms to set the "apu" (Agreement + * PartyUInfo) or "apv" (Agreement PartyVInfo) parameters. + * + * @param parameters JWE Key Management parameters. + */ + setKeyManagementParameters(parameters: types.JWEKeyManagementHeaderParameters): this; + /** + * Sets the JWE Protected Header on the FlattenedEncrypt object. + * + * @param protectedHeader JWE Protected Header. + */ + setProtectedHeader(protectedHeader: types.JWEHeaderParameters): this; + /** + * Sets the JWE Shared Unprotected Header on the FlattenedEncrypt object. + * + * @param sharedUnprotectedHeader JWE Shared Unprotected Header. + */ + setSharedUnprotectedHeader(sharedUnprotectedHeader: types.JWEHeaderParameters): this; + /** + * Sets the JWE Per-Recipient Unprotected Header on the FlattenedEncrypt object. + * + * @param unprotectedHeader JWE Per-Recipient Unprotected Header. + */ + setUnprotectedHeader(unprotectedHeader: types.JWEHeaderParameters): this; + /** + * Sets the Additional Authenticated Data on the FlattenedEncrypt object. + * + * @param aad Additional Authenticated Data. + */ + setAdditionalAuthenticatedData(aad: Uint8Array): this; + /** + * Sets a content encryption key to use, by default a random suitable one is generated for the JWE + * enc" (Encryption Algorithm) Header Parameter. + * + * @deprecated You should not use this method. It is only really intended for test and vector + * validation purposes. + * + * @param cek JWE Content Encryption Key. + */ + setContentEncryptionKey(cek: Uint8Array): this; + /** + * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable + * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. + * + * @deprecated You should not use this method. It is only really intended for test and vector + * validation purposes. + * + * @param iv JWE Initialization Vector. + */ + setInitializationVector(iv: Uint8Array): this; + /** + * Encrypts and resolves the value of the Flattened JWE object. + * + * @param key Public Key or Secret to encrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Encryption options. + */ + encrypt(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.EncryptOptions): Promise; +} diff --git a/node_modules/jose/dist/types/jwe/general/decrypt.d.ts b/node_modules/jose/dist/types/jwe/general/decrypt.d.ts new file mode 100644 index 000000000..ccb87c903 --- /dev/null +++ b/node_modules/jose/dist/types/jwe/general/decrypt.d.ts @@ -0,0 +1,31 @@ +/** + * Decrypting JSON Web Encryption (JWE) in General JSON Serialization + * + * @module + */ +import type * as types from '../../types.d.ts'; +/** + * Interface for General JWE Decryption dynamic key resolution. No token components have been + * verified at the time of this function call. + */ +export interface GeneralDecryptGetKey extends types.GetKeyFunction { +} +/** + * Decrypts a General JWE. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jwe/general/decrypt'`. + * + * @param jwe General JWE. + * @param key Private Key or Secret to decrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Decryption options. + */ +export declare function generalDecrypt(jwe: types.GeneralJWE, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.DecryptOptions): Promise; +/** + * @param jwe General JWE. + * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Decryption options. + */ +export declare function generalDecrypt(jwe: types.GeneralJWE, getKey: GeneralDecryptGetKey, options?: types.DecryptOptions): Promise; diff --git a/node_modules/jose/dist/types/jwe/general/encrypt.d.ts b/node_modules/jose/dist/types/jwe/general/encrypt.d.ts new file mode 100644 index 000000000..7a2e1d3c5 --- /dev/null +++ b/node_modules/jose/dist/types/jwe/general/encrypt.d.ts @@ -0,0 +1,74 @@ +/** + * Encrypting JSON Web Encryption (JWE) in General JSON Serialization + * + * @module + */ +import type * as types from '../../types.d.ts'; +/** Used to build General JWE object's individual recipients. */ +export interface Recipient { + /** + * Sets the JWE Per-Recipient Unprotected Header on the Recipient object. + * + * @param unprotectedHeader JWE Per-Recipient Unprotected Header. + */ + setUnprotectedHeader(unprotectedHeader: types.JWEHeaderParameters): Recipient; + /** + * Sets the JWE Key Management parameters to be used when encrypting. + * + * (ECDH-ES) Use of this method is needed for ECDH based algorithms to set the "apu" (Agreement + * PartyUInfo) or "apv" (Agreement PartyVInfo) parameters. + * + * @param parameters JWE Key Management parameters. + */ + setKeyManagementParameters(parameters: types.JWEKeyManagementHeaderParameters): Recipient; + /** A shorthand for calling addRecipient() on the enclosing {@link GeneralEncrypt} instance */ + addRecipient(...args: Parameters): Recipient; + /** A shorthand for calling encrypt() on the enclosing {@link GeneralEncrypt} instance */ + encrypt(...args: Parameters): Promise; + /** Returns the enclosing {@link GeneralEncrypt} instance */ + done(): GeneralEncrypt; +} +/** + * The GeneralEncrypt class is used to build and encrypt General JWE objects. + * + * This class is exported (as a named export) from the main `'jose'` module entry point as well as + * from its subpath export `'jose/jwe/general/encrypt'`. + * + */ +export declare class GeneralEncrypt { + #private; + /** + * {@link GeneralEncrypt} constructor + * + * @param plaintext Binary representation of the plaintext to encrypt. + */ + constructor(plaintext: Uint8Array); + /** + * Adds an additional recipient for the General JWE object. + * + * @param key Public Key or Secret to encrypt the Content Encryption Key for the recipient with. + * See {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Encryption options. + */ + addRecipient(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.CritOption): Recipient; + /** + * Sets the JWE Protected Header on the GeneralEncrypt object. + * + * @param protectedHeader JWE Protected Header object. + */ + setProtectedHeader(protectedHeader: types.JWEHeaderParameters): this; + /** + * Sets the JWE Shared Unprotected Header on the GeneralEncrypt object. + * + * @param sharedUnprotectedHeader JWE Shared Unprotected Header object. + */ + setSharedUnprotectedHeader(sharedUnprotectedHeader: types.JWEHeaderParameters): this; + /** + * Sets the Additional Authenticated Data on the GeneralEncrypt object. + * + * @param aad Additional Authenticated Data. + */ + setAdditionalAuthenticatedData(aad: Uint8Array): this; + /** Encrypts and resolves the value of the General JWE object. */ + encrypt(): Promise; +} diff --git a/node_modules/jose/dist/types/jwk/embedded.d.ts b/node_modules/jose/dist/types/jwk/embedded.d.ts new file mode 100644 index 000000000..69110388b --- /dev/null +++ b/node_modules/jose/dist/types/jwk/embedded.d.ts @@ -0,0 +1,17 @@ +/** + * Verification using a JWK Embedded in a JWS Header + * + * @module + */ +import type * as types from '../types.d.ts'; +/** + * EmbeddedJWK is an implementation of a GetKeyFunction intended to be used with the JWS/JWT verify + * operations whenever you need to opt-in to verify signatures with a public key embedded in the + * token's "jwk" (JSON Web Key) Header Parameter. It is recommended to combine this with the verify + * function's `algorithms` option to define accepted JWS "alg" (Algorithm) Header Parameter values. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jwk/embedded'`. + * + */ +export declare function EmbeddedJWK(protectedHeader?: types.JWSHeaderParameters, token?: types.FlattenedJWSInput): Promise; diff --git a/node_modules/jose/dist/types/jwk/thumbprint.d.ts b/node_modules/jose/dist/types/jwk/thumbprint.d.ts new file mode 100644 index 000000000..1d8450d87 --- /dev/null +++ b/node_modules/jose/dist/types/jwk/thumbprint.d.ts @@ -0,0 +1,32 @@ +/** + * JSON Web Key Thumbprint and JSON Web Key Thumbprint URI + * + * @module + */ +import type * as types from '../types.d.ts'; +/** + * Calculates a base64url-encoded JSON Web Key (JWK) Thumbprint + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jwk/thumbprint'`. + * + * @param key Key to calculate the thumbprint for. + * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is + * "sha256". + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7638 RFC7638} + */ +export declare function calculateJwkThumbprint(key: types.JWK | types.CryptoKey | types.KeyObject, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512'): Promise; +/** + * Calculates a JSON Web Key (JWK) Thumbprint URI + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jwk/thumbprint'`. + * + * @param key Key to calculate the thumbprint for. + * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is + * "sha256". + * + * @see {@link https://www.rfc-editor.org/rfc/rfc9278 RFC9278} + */ +export declare function calculateJwkThumbprintUri(key: types.CryptoKey | types.KeyObject | types.JWK, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512'): Promise; diff --git a/node_modules/jose/dist/types/jwks/local.d.ts b/node_modules/jose/dist/types/jwks/local.d.ts new file mode 100644 index 000000000..fd9d31c95 --- /dev/null +++ b/node_modules/jose/dist/types/jwks/local.d.ts @@ -0,0 +1,29 @@ +/** + * Verification using a JSON Web Key Set (JWKS) available locally + * + * @module + */ +import type * as types from '../types.d.ts'; +/** + * Returns a function that resolves a JWS JOSE Header to a public key object from a locally stored, + * or otherwise available, JSON Web Key Set. + * + * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type), + * then proceeds to match the JWK "kid" (Key ID) with one found in the JWS Header Parameters (if + * there is one) while also respecting the JWK "use" (Public Key Use) and JWK "key_ops" (Key + * Operations) Parameters (if they are present on the JWK). + * + * Only a single public key must match the selection process. As shown in the example below when + * multiple keys get matched it is possible to opt-in to iterate over the matched keys and attempt + * verification in an iterative manner. + * + * > [!NOTE]\ + * > The function's purpose is to resolve public keys used for verifying signatures and will not work + * > for public encryption keys. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jwks/local'`. + * + * @param jwks JSON Web Key Set formatted object. + */ +export declare function createLocalJWKSet(jwks: types.JSONWebKeySet): (protectedHeader?: types.JWSHeaderParameters, token?: types.FlattenedJWSInput) => Promise; diff --git a/node_modules/jose/dist/types/jwks/remote.d.ts b/node_modules/jose/dist/types/jwks/remote.d.ts new file mode 100644 index 000000000..dae489da4 --- /dev/null +++ b/node_modules/jose/dist/types/jwks/remote.d.ts @@ -0,0 +1,237 @@ +/** + * Verification using a JSON Web Key Set (JWKS) available on an HTTP(S) URL + * + * @module + */ +import type * as types from '../types.d.ts'; +/** + * When passed to {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} this allows the resolver + * to make use of advanced fetch configurations, HTTP Proxies, retry on network errors, etc. + * + * > [!NOTE]\ + * > Known caveat: Expect Type-related issues when passing the inputs through to fetch-like modules, + * > they hardly ever get their typings inline with actual fetch, you should `@ts-expect-error` them. + * + * import ky from 'ky' + * + * let logRequest!: (request: Request) => void + * let logResponse!: (request: Request, response: Response) => void + * let logRetry!: (request: Request, error: Error, retryCount: number) => void + * + * const JWKS = jose.createRemoteJWKSet(url, { + * [jose.customFetch]: (...args) => + * ky(args[0], { + * ...args[1], + * hooks: { + * beforeRequest: [ + * (request) => { + * logRequest(request) + * }, + * ], + * beforeRetry: [ + * ({ request, error, retryCount }) => { + * logRetry(request, error, retryCount) + * }, + * ], + * afterResponse: [ + * (request, _, response) => { + * logResponse(request, response) + * }, + * ], + * }, + * }), + * }) + * ``` + * + * import * as undici from 'undici' + * + * // see https://undici.nodejs.org/#/docs/api/EnvHttpProxyAgent + * let envHttpProxyAgent = new undici.EnvHttpProxyAgent() + * + * // @ts-ignore + * const JWKS = jose.createRemoteJWKSet(url, { + * [jose.customFetch]: (...args) => { + * // @ts-ignore + * return undici.fetch(args[0], { ...args[1], dispatcher: envHttpProxyAgent }) // prettier-ignore + * }, + * }) + * ``` + * + * import * as undici from 'undici' + * + * // see https://undici.nodejs.org/#/docs/api/RetryAgent + * let retryAgent = new undici.RetryAgent(new undici.Agent(), { + * statusCodes: [], + * errorCodes: [ + * 'ECONNRESET', + * 'ECONNREFUSED', + * 'ENOTFOUND', + * 'ENETDOWN', + * 'ENETUNREACH', + * 'EHOSTDOWN', + * 'UND_ERR_SOCKET', + * ], + * }) + * + * // @ts-ignore + * const JWKS = jose.createRemoteJWKSet(url, { + * [jose.customFetch]: (...args) => { + * // @ts-ignore + * return undici.fetch(args[0], { ...args[1], dispatcher: retryAgent }) // prettier-ignore + * }, + * }) + * ``` + * + * import * as undici from 'undici' + * + * // see https://undici.nodejs.org/#/docs/api/MockAgent + * let mockAgent = new undici.MockAgent() + * mockAgent.disableNetConnect() + * + * // @ts-ignore + * const JWKS = jose.createRemoteJWKSet(url, { + * [jose.customFetch]: (...args) => { + * // @ts-ignore + * return undici.fetch(args[0], { ...args[1], dispatcher: mockAgent }) // prettier-ignore + * }, + * }) + * ``` + */ +export declare const customFetch: unique symbol; +/** See {@link customFetch}. */ +export type FetchImplementation = ( +/** URL the request is being made sent to {@link !fetch} as the `resource` argument */ +url: string, +/** Options otherwise sent to {@link !fetch} as the `options` argument */ +options: { + /** HTTP Headers */ + headers: Headers; + /** The {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods request method} */ + method: 'GET'; + /** See {@link !Request.redirect} */ + redirect: 'manual'; + signal: AbortSignal; +}) => Promise; +/** + * > [!WARNING]\ + * > This option has security implications that must be understood, assessed for applicability, and + * > accepted before use. It is critical that the JSON Web Key Set cache only be writable by your own + * > code. + * + * This option is intended for cloud computing runtimes that cannot keep an in memory cache between + * their code's invocations. Use in runtimes where an in memory cache between requests is available + * is not desirable. + * + * When passed to {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} this allows the passed in + * object to: + * + * - Serve as an initial value for the JSON Web Key Set that the module would otherwise need to + * trigger an HTTP request for + * - Have the JSON Web Key Set the function optionally ended up triggering an HTTP request for + * assigned to it as properties + * + * The intended use pattern is: + * + * - Before verifying with {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} you pull the + * previously cached object from a low-latency key-value store offered by the cloud computing + * runtime it is executed on; + * - Default to an empty object `{}` instead when there's no previously cached value; + * - Pass it in as {@link RemoteJWKSetOptions[jwksCache]}; + * - Afterwards, update the key-value storage if the {@link ExportedJWKSCache.uat `uat`} property of + * the object has changed. + * + * // Prerequisites + * let url!: URL + * let jwt!: string + * let getPreviouslyCachedJWKS!: () => Promise + * let storeNewJWKScache!: (cache: jose.ExportedJWKSCache) => Promise + * + * // Load JSON Web Key Set cache + * const jwksCache: jose.JWKSCacheInput = (await getPreviouslyCachedJWKS()) || {} + * const { uat } = jwksCache + * + * const JWKS = jose.createRemoteJWKSet(url, { + * [jose.jwksCache]: jwksCache, + * }) + * + * // Use JSON Web Key Set cache + * await jose.jwtVerify(jwt, JWKS) + * + * if (uat !== jwksCache.uat) { + * // Update JSON Web Key Set cache + * await storeNewJWKScache(jwksCache) + * } + * ``` + */ +export declare const jwksCache: unique symbol; +/** Options for the remote JSON Web Key Set. */ +export interface RemoteJWKSetOptions { + /** + * Timeout (in milliseconds) for the HTTP request. When reached the request will be aborted and + * the verification will fail. Default is 5000 (5 seconds). + */ + timeoutDuration?: number; + /** + * Duration (in milliseconds) for which no more HTTP requests will be triggered after a previous + * successful fetch. Default is 30000 (30 seconds). + */ + cooldownDuration?: number; + /** + * Maximum time (in milliseconds) between successful HTTP requests. Default is 600000 (10 + * minutes). + */ + cacheMaxAge?: number | typeof Infinity; + /** Headers to be sent with the HTTP request. */ + headers?: Record; + /** See {@link jwksCache}. */ + [jwksCache]?: JWKSCacheInput; + /** See {@link customFetch}. */ + [customFetch]?: FetchImplementation; +} +/** See {@link jwksCache}. */ +export interface ExportedJWKSCache { + /** Current cached JSON Web Key Set */ + jwks: types.JSONWebKeySet; + /** Last updated at timestamp (seconds since epoch) */ + uat: number; +} +/** See {@link jwksCache}. */ +export type JWKSCacheInput = ExportedJWKSCache | Record; +/** + * Returns a function that resolves a JWS JOSE Header to a public key object downloaded from a + * remote endpoint returning a JSON Web Key Set, that is, for example, an OAuth 2.0 or OIDC + * jwks_uri. The JSON Web Key Set is fetched when no key matches the selection process but only as + * frequently as the `cooldownDuration` option allows to prevent abuse. + * + * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type), + * then proceeds to match the JWK "kid" (Key ID) with one found in the JWS Header Parameters (if + * there is one) while also respecting the JWK "use" (Public Key Use) and JWK "key_ops" (Key + * Operations) Parameters (if they are present on the JWK). + * + * Only a single public key must match the selection process. As shown in the example below when + * multiple keys get matched it is possible to opt-in to iterate over the matched keys and attempt + * verification in an iterative manner. + * + * > [!NOTE]\ + * > The function's purpose is to resolve public keys used for verifying signatures and will not work + * > for public encryption keys. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jwks/remote'`. + * + * @param url URL to fetch the JSON Web Key Set from. + * @param options Options for the remote JSON Web Key Set. + */ +export declare function createRemoteJWKSet(url: URL, options?: RemoteJWKSetOptions): { + (protectedHeader?: types.JWSHeaderParameters, token?: types.FlattenedJWSInput): Promise; + /** @ignore */ + coolingDown: boolean; + /** @ignore */ + fresh: boolean; + /** @ignore */ + reloading: boolean; + /** @ignore */ + reload: () => Promise; + /** @ignore */ + jwks: () => types.JSONWebKeySet | undefined; +}; diff --git a/node_modules/jose/dist/types/jws/compact/sign.d.ts b/node_modules/jose/dist/types/jws/compact/sign.d.ts new file mode 100644 index 000000000..dc729585a --- /dev/null +++ b/node_modules/jose/dist/types/jws/compact/sign.d.ts @@ -0,0 +1,36 @@ +/** + * Signing JSON Web Signature (JWS) in Compact Serialization + * + * @module + */ +import type * as types from '../../types.d.ts'; +/** + * The CompactSign class is used to build and sign Compact JWS strings. + * + * This class is exported (as a named export) from the main `'jose'` module entry point as well as + * from its subpath export `'jose/jws/compact/sign'`. + * + */ +export declare class CompactSign { + #private; + /** + * {@link CompactSign} constructor + * + * @param payload Binary representation of the payload to sign. + */ + constructor(payload: Uint8Array); + /** + * Sets the JWS Protected Header on the CompactSign object. + * + * @param protectedHeader JWS Protected Header. + */ + setProtectedHeader(protectedHeader: types.CompactJWSHeaderParameters): this; + /** + * Signs and resolves the value of the Compact JWS string. + * + * @param key Private Key or Secret to sign the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Sign options. + */ + sign(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.SignOptions): Promise; +} diff --git a/node_modules/jose/dist/types/jws/compact/verify.d.ts b/node_modules/jose/dist/types/jws/compact/verify.d.ts new file mode 100644 index 000000000..1a7ea3215 --- /dev/null +++ b/node_modules/jose/dist/types/jws/compact/verify.d.ts @@ -0,0 +1,33 @@ +/** + * Verifying JSON Web Signature (JWS) in Compact Serialization + * + * @module + */ +import type * as types from '../../types.d.ts'; +/** + * Interface for Compact JWS Verification dynamic key resolution. No token components have been + * verified at the time of this function call. + * + * @see {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} to verify using a remote JSON Web Key Set. + */ +export interface CompactVerifyGetKey extends types.GenericGetKeyFunction { +} +/** + * Verifies the signature and format of and afterwards decodes the Compact JWS. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jws/compact/verify'`. + * + * @param jws Compact JWS. + * @param key Key to verify the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Verify options. + */ +export declare function compactVerify(jws: string | Uint8Array, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.VerifyOptions): Promise; +/** + * @param jws Compact JWS. + * @param getKey Function resolving a key to verify the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Verify options. + */ +export declare function compactVerify(jws: string | Uint8Array, getKey: CompactVerifyGetKey, options?: types.VerifyOptions): Promise; diff --git a/node_modules/jose/dist/types/jws/flattened/sign.d.ts b/node_modules/jose/dist/types/jws/flattened/sign.d.ts new file mode 100644 index 000000000..d8c11e8f0 --- /dev/null +++ b/node_modules/jose/dist/types/jws/flattened/sign.d.ts @@ -0,0 +1,42 @@ +/** + * Signing JSON Web Signature (JWS) in Flattened JSON Serialization + * + * @module + */ +import type * as types from '../../types.d.ts'; +/** + * The FlattenedSign class is used to build and sign Flattened JWS objects. + * + * This class is exported (as a named export) from the main `'jose'` module entry point as well as + * from its subpath export `'jose/jws/flattened/sign'`. + * + */ +export declare class FlattenedSign { + #private; + /** + * {@link FlattenedSign} constructor + * + * @param payload Binary representation of the payload to sign. + */ + constructor(payload: Uint8Array); + /** + * Sets the JWS Protected Header on the FlattenedSign object. + * + * @param protectedHeader JWS Protected Header. + */ + setProtectedHeader(protectedHeader: types.JWSHeaderParameters): this; + /** + * Sets the JWS Unprotected Header on the FlattenedSign object. + * + * @param unprotectedHeader JWS Unprotected Header. + */ + setUnprotectedHeader(unprotectedHeader: types.JWSHeaderParameters): this; + /** + * Signs and resolves the value of the Flattened JWS object. + * + * @param key Private Key or Secret to sign the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Sign options. + */ + sign(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.SignOptions): Promise; +} diff --git a/node_modules/jose/dist/types/jws/flattened/verify.d.ts b/node_modules/jose/dist/types/jws/flattened/verify.d.ts new file mode 100644 index 000000000..e5e6a3898 --- /dev/null +++ b/node_modules/jose/dist/types/jws/flattened/verify.d.ts @@ -0,0 +1,33 @@ +/** + * Verifying JSON Web Signature (JWS) in Flattened JSON Serialization + * + * @module + */ +import type * as types from '../../types.d.ts'; +/** + * Interface for Flattened JWS Verification dynamic key resolution. No token components have been + * verified at the time of this function call. + * + * @see {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} to verify using a remote JSON Web Key Set. + */ +export interface FlattenedVerifyGetKey extends types.GenericGetKeyFunction { +} +/** + * Verifies the signature and format of and afterwards decodes the Flattened JWS. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jws/flattened/verify'`. + * + * @param jws Flattened JWS. + * @param key Key to verify the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Verify options. + */ +export declare function flattenedVerify(jws: types.FlattenedJWSInput, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.VerifyOptions): Promise; +/** + * @param jws Flattened JWS. + * @param getKey Function resolving a key to verify the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Verify options. + */ +export declare function flattenedVerify(jws: types.FlattenedJWSInput, getKey: FlattenedVerifyGetKey, options?: types.VerifyOptions): Promise; diff --git a/node_modules/jose/dist/types/jws/general/sign.d.ts b/node_modules/jose/dist/types/jws/general/sign.d.ts new file mode 100644 index 000000000..122fe2b98 --- /dev/null +++ b/node_modules/jose/dist/types/jws/general/sign.d.ts @@ -0,0 +1,53 @@ +/** + * Signing JSON Web Signature (JWS) in General JSON Serialization + * + * @module + */ +import type * as types from '../../types.d.ts'; +/** Used to build General JWS object's individual signatures. */ +export interface Signature { + /** + * Sets the JWS Protected Header on the Signature object. + * + * @param protectedHeader JWS Protected Header. + */ + setProtectedHeader(protectedHeader: types.JWSHeaderParameters): Signature; + /** + * Sets the JWS Unprotected Header on the Signature object. + * + * @param unprotectedHeader JWS Unprotected Header. + */ + setUnprotectedHeader(unprotectedHeader: types.JWSHeaderParameters): Signature; + /** A shorthand for calling addSignature() on the enclosing {@link GeneralSign} instance */ + addSignature(...args: Parameters): Signature; + /** A shorthand for calling encrypt() on the enclosing {@link GeneralSign} instance */ + sign(...args: Parameters): Promise; + /** Returns the enclosing {@link GeneralSign} instance */ + done(): GeneralSign; +} +/** + * The GeneralSign class is used to build and sign General JWS objects. + * + * This class is exported (as a named export) from the main `'jose'` module entry point as well as + * from its subpath export `'jose/jws/general/sign'`. + * + */ +export declare class GeneralSign { + #private; + /** + * {@link GeneralSign} constructor + * + * @param payload Binary representation of the payload to sign. + */ + constructor(payload: Uint8Array); + /** + * Adds an additional signature for the General JWS object. + * + * @param key Private Key or Secret to sign the individual JWS signature with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Sign options. + */ + addSignature(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.SignOptions): Signature; + /** Signs and resolves the value of the General JWS object. */ + sign(): Promise; +} diff --git a/node_modules/jose/dist/types/jws/general/verify.d.ts b/node_modules/jose/dist/types/jws/general/verify.d.ts new file mode 100644 index 000000000..ed8114359 --- /dev/null +++ b/node_modules/jose/dist/types/jws/general/verify.d.ts @@ -0,0 +1,33 @@ +/** + * Verifying JSON Web Signature (JWS) in General JSON Serialization + * + * @module + */ +import type * as types from '../../types.d.ts'; +/** + * Interface for General JWS Verification dynamic key resolution. No token components have been + * verified at the time of this function call. + * + * @see {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} to verify using a remote JSON Web Key Set. + */ +export interface GeneralVerifyGetKey extends types.GenericGetKeyFunction { +} +/** + * Verifies the signature and format of and afterwards decodes the General JWS. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jws/general/verify'`. + * + * @param jws General JWS. + * @param key Key to verify the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Verify options. + */ +export declare function generalVerify(jws: types.GeneralJWSInput, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.VerifyOptions): Promise; +/** + * @param jws General JWS. + * @param getKey Function resolving a key to verify the JWS with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWS Verify options. + */ +export declare function generalVerify(jws: types.GeneralJWSInput, getKey: GeneralVerifyGetKey, options?: types.VerifyOptions): Promise; diff --git a/node_modules/jose/dist/types/jwt/decrypt.d.ts b/node_modules/jose/dist/types/jwt/decrypt.d.ts new file mode 100644 index 000000000..8a27aad1e --- /dev/null +++ b/node_modules/jose/dist/types/jwt/decrypt.d.ts @@ -0,0 +1,35 @@ +/** + * JSON Web Token (JWT) Decryption (JWT is in JWE format) + * + * @module + */ +import type * as types from '../types.d.ts'; +/** Combination of JWE Decryption options and JWT Claims Set verification options. */ +export interface JWTDecryptOptions extends types.DecryptOptions, types.JWTClaimVerificationOptions { +} +/** + * Interface for JWT Decryption dynamic key resolution. No token components have been verified at + * the time of this function call. + */ +export interface JWTDecryptGetKey extends types.GetKeyFunction { +} +/** + * Verifies the JWT format (to be a JWE Compact format), decrypts the ciphertext, validates the JWT + * Claims Set. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jwt/decrypt'`. + * + * @param jwt JSON Web Token value (encoded as JWE). + * @param key Private Key or Secret to decrypt and verify the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWT Decryption and JWT Claims Set validation options. + */ +export declare function jwtDecrypt(jwt: string | Uint8Array, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: JWTDecryptOptions): Promise>; +/** + * @param jwt JSON Web Token value (encoded as JWE). + * @param getKey Function resolving Private Key or Secret to decrypt and verify the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWT Decryption and JWT Claims Set validation options. + */ +export declare function jwtDecrypt(jwt: string | Uint8Array, getKey: JWTDecryptGetKey, options?: JWTDecryptOptions): Promise & types.ResolvedKey>; diff --git a/node_modules/jose/dist/types/jwt/encrypt.d.ts b/node_modules/jose/dist/types/jwt/encrypt.d.ts new file mode 100644 index 000000000..ea62e0efe --- /dev/null +++ b/node_modules/jose/dist/types/jwt/encrypt.d.ts @@ -0,0 +1,91 @@ +/** + * JSON Web Token (JWT) Encryption (JWT is in JWE format) + * + * @module + */ +import type * as types from '../types.d.ts'; +/** + * The EncryptJWT class is used to build and encrypt Compact JWE formatted JSON Web Tokens. + * + * This class is exported (as a named export) from the main `'jose'` module entry point as well as + * from its subpath export `'jose/jwt/encrypt'`. + * + */ +export declare class EncryptJWT implements types.ProduceJWT { + #private; + /** + * {@link EncryptJWT} constructor + * + * @param payload The JWT Claims Set object. Defaults to an empty object. + */ + constructor(payload?: types.JWTPayload); + setIssuer(issuer: string): this; + setSubject(subject: string): this; + setAudience(audience: string | string[]): this; + setJti(jwtId: string): this; + setNotBefore(input: number | string | Date): this; + setExpirationTime(input: number | string | Date): this; + setIssuedAt(input?: number | string | Date): this; + /** + * Sets the JWE Protected Header on the EncryptJWT object. + * + * @param protectedHeader JWE Protected Header. Must contain an "alg" (JWE Algorithm) and "enc" + * (JWE Encryption Algorithm) properties. + */ + setProtectedHeader(protectedHeader: types.CompactJWEHeaderParameters): this; + /** + * Sets the JWE Key Management parameters to be used when encrypting. + * + * (ECDH-ES) Use of this method is needed for ECDH based algorithms to set the "apu" (Agreement + * PartyUInfo) or "apv" (Agreement PartyVInfo) parameters. + * + * @param parameters JWE Key Management parameters. + */ + setKeyManagementParameters(parameters: types.JWEKeyManagementHeaderParameters): this; + /** + * Sets a content encryption key to use, by default a random suitable one is generated for the JWE + * enc" (Encryption Algorithm) Header Parameter. + * + * @deprecated You should not use this method. It is only really intended for test and vector + * validation purposes. + * + * @param cek JWE Content Encryption Key. + */ + setContentEncryptionKey(cek: Uint8Array): this; + /** + * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable + * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. + * + * @deprecated You should not use this method. It is only really intended for test and vector + * validation purposes. + * + * @param iv JWE Initialization Vector. + */ + setInitializationVector(iv: Uint8Array): this; + /** + * Replicates the "iss" (Issuer) Claim as a JWE Protected Header Parameter. + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3} + */ + replicateIssuerAsHeader(): this; + /** + * Replicates the "sub" (Subject) Claim as a JWE Protected Header Parameter. + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3} + */ + replicateSubjectAsHeader(): this; + /** + * Replicates the "aud" (Audience) Claim as a JWE Protected Header Parameter. + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3} + */ + replicateAudienceAsHeader(): this; + /** + * Encrypts and returns the JWT. + * + * @param key Public Key or Secret to encrypt the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + * @param options JWE Encryption options. + */ + encrypt(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.EncryptOptions): Promise; +} diff --git a/node_modules/jose/dist/types/jwt/sign.d.ts b/node_modules/jose/dist/types/jwt/sign.d.ts new file mode 100644 index 000000000..6e68a217e --- /dev/null +++ b/node_modules/jose/dist/types/jwt/sign.d.ts @@ -0,0 +1,43 @@ +/** + * JSON Web Token (JWT) Signing (JWT is in JWS format) + * + * @module + */ +import type * as types from '../types.d.ts'; +/** + * The SignJWT class is used to build and sign Compact JWS formatted JSON Web Tokens. + * + * This class is exported (as a named export) from the main `'jose'` module entry point as well as + * from its subpath export `'jose/jwt/sign'`. + * + */ +export declare class SignJWT implements types.ProduceJWT { + #private; + /** + * {@link SignJWT} constructor + * + * @param payload The JWT Claims Set object. Defaults to an empty object. + */ + constructor(payload?: types.JWTPayload); + setIssuer(issuer: string): this; + setSubject(subject: string): this; + setAudience(audience: string | string[]): this; + setJti(jwtId: string): this; + setNotBefore(input: number | string | Date): this; + setExpirationTime(input: number | string | Date): this; + setIssuedAt(input?: number | string | Date): this; + /** + * Sets the JWS Protected Header on the SignJWT object. + * + * @param protectedHeader JWS Protected Header. Must contain an "alg" (JWS Algorithm) property. + */ + setProtectedHeader(protectedHeader: types.JWTHeaderParameters): this; + /** + * Signs and returns the JWT. + * + * @param key Private Key or Secret to sign the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWT Sign options. + */ + sign(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.SignOptions): Promise; +} diff --git a/node_modules/jose/dist/types/jwt/unsecured.d.ts b/node_modules/jose/dist/types/jwt/unsecured.d.ts new file mode 100644 index 000000000..8dd69e366 --- /dev/null +++ b/node_modules/jose/dist/types/jwt/unsecured.d.ts @@ -0,0 +1,43 @@ +/** + * Unsecured (unsigned & unencrypted) JSON Web Tokens (JWT) + * + * @module + */ +import type * as types from '../types.d.ts'; +/** Result of decoding an Unsecured JWT. */ +export interface UnsecuredResult { + payload: PayloadType & types.JWTPayload; + header: types.JWSHeaderParameters; +} +/** + * The UnsecuredJWT class is a utility for dealing with `{ "alg": "none" }` Unsecured JWTs. + * + * This class is exported (as a named export) from the main `'jose'` module entry point as well as + * from its subpath export `'jose/jwt/unsecured'`. + * + */ +export declare class UnsecuredJWT implements types.ProduceJWT { + #private; + /** + * {@link UnsecuredJWT} constructor + * + * @param payload The JWT Claims Set object. Defaults to an empty object. + */ + constructor(payload?: types.JWTPayload); + /** Encodes the Unsecured JWT. */ + encode(): string; + setIssuer(issuer: string): this; + setSubject(subject: string): this; + setAudience(audience: string | string[]): this; + setJti(jwtId: string): this; + setNotBefore(input: number | string | Date): this; + setExpirationTime(input: number | string | Date): this; + setIssuedAt(input?: number | string | Date): this; + /** + * Decodes an unsecured JWT. + * + * @param jwt Unsecured JWT to decode the payload of. + * @param options JWT Claims Set validation options. + */ + static decode(jwt: string, options?: types.JWTClaimVerificationOptions): UnsecuredResult; +} diff --git a/node_modules/jose/dist/types/jwt/verify.d.ts b/node_modules/jose/dist/types/jwt/verify.d.ts new file mode 100644 index 000000000..285b56704 --- /dev/null +++ b/node_modules/jose/dist/types/jwt/verify.d.ts @@ -0,0 +1,37 @@ +/** + * JSON Web Token (JWT) Verification (JWT is in JWS format) + * + * @module + */ +import type * as types from '../types.d.ts'; +/** Combination of JWS Verification options and JWT Claims Set verification options. */ +export interface JWTVerifyOptions extends types.VerifyOptions, types.JWTClaimVerificationOptions { +} +/** + * Interface for JWT Verification dynamic key resolution. No token components have been verified at + * the time of this function call. + * + * @see {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} to verify using a remote JSON Web Key Set. + */ +export interface JWTVerifyGetKey extends types.GenericGetKeyFunction { +} +/** + * Verifies the JWT format (to be a JWS Compact format), verifies the JWS signature, validates the + * JWT Claims Set. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jwt/verify'`. + * + * @param jwt JSON Web Token value (encoded as JWS). + * @param key Key to verify the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWT Decryption and JWT Claims Set validation options. + */ +export declare function jwtVerify(jwt: string | Uint8Array, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: JWTVerifyOptions): Promise>; +/** + * @param jwt JSON Web Token value (encoded as JWS). + * @param getKey Function resolving a key to verify the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. + * @param options JWT Decryption and JWT Claims Set validation options. + */ +export declare function jwtVerify(jwt: string | Uint8Array, getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): Promise & types.ResolvedKey>; diff --git a/node_modules/jose/dist/types/key/export.d.ts b/node_modules/jose/dist/types/key/export.d.ts new file mode 100644 index 000000000..9ca16cc0a --- /dev/null +++ b/node_modules/jose/dist/types/key/export.d.ts @@ -0,0 +1,33 @@ +/** + * Cryptographic key export functions + * + * @module + */ +import type * as types from '../types.d.ts'; +/** + * Exports a public {@link !CryptoKey} or {@link !KeyObject} to a PEM-encoded SPKI string format. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/key/export'`. + * + * @param key Key to export to a PEM-encoded SPKI string format. + */ +export declare function exportSPKI(key: types.CryptoKey | types.KeyObject): Promise; +/** + * Exports a private {@link !CryptoKey} or {@link !KeyObject} to a PEM-encoded PKCS8 string format. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/key/export'`. + * + * @param key Key to export to a PEM-encoded PKCS8 string format. + */ +export declare function exportPKCS8(key: types.CryptoKey | types.KeyObject): Promise; +/** + * Exports a {@link !CryptoKey}, {@link !KeyObject}, or {@link !Uint8Array} to a JWK. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/key/export'`. + * + * @param key Key to export as JWK. + */ +export declare function exportJWK(key: types.CryptoKey | types.KeyObject | Uint8Array): Promise; diff --git a/node_modules/jose/dist/types/key/generate_key_pair.d.ts b/node_modules/jose/dist/types/key/generate_key_pair.d.ts new file mode 100644 index 000000000..81677f772 --- /dev/null +++ b/node_modules/jose/dist/types/key/generate_key_pair.d.ts @@ -0,0 +1,47 @@ +/** + * Asymmetric key generation + * + * @module + */ +import type * as types from '../types.d.ts'; +/** Asymmetric key pair generation function result. */ +export interface GenerateKeyPairResult { + /** The generated Private Key. */ + privateKey: types.CryptoKey; + /** Public Key corresponding to the generated Private Key. */ + publicKey: types.CryptoKey; +} +/** Asymmetric key pair generation function options. */ +export interface GenerateKeyPairOptions { + /** + * The EC "crv" (Curve) or OKP "crv" (Subtype of Key Pair) value to generate. The curve must be + * both supported on the runtime as well as applicable for the given JWA algorithm identifier. + */ + crv?: string; + /** + * A hint for RSA algorithms to generate an RSA key of a given `modulusLength` (Key size in bits). + * JOSE requires 2048 bits or larger. Default is 2048. + */ + modulusLength?: number; + /** + * The value to use as {@link !SubtleCrypto.generateKey} `extractable` argument. Default is false. + * + */ + extractable?: boolean; +} +/** + * Generates a private and a public key for a given JWA algorithm identifier. This can only generate + * asymmetric key pairs. For symmetric secrets use the `generateSecret` function. + * + * > [!NOTE]\ + * > The `privateKey` is generated with `extractable` set to `false` by default. See + * > {@link GenerateKeyPairOptions.extractable} to generate an extractable `privateKey`. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/generate/keypair'`. + * + * @param alg JWA Algorithm Identifier to be used with the generated key pair. See + * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. + * @param options Additional options passed down to the key pair generation. + */ +export declare function generateKeyPair(alg: string, options?: GenerateKeyPairOptions): Promise; diff --git a/node_modules/jose/dist/types/key/generate_secret.d.ts b/node_modules/jose/dist/types/key/generate_secret.d.ts new file mode 100644 index 000000000..9c41dc5e2 --- /dev/null +++ b/node_modules/jose/dist/types/key/generate_secret.d.ts @@ -0,0 +1,35 @@ +/** + * Symmetric key generation + * + * @module + */ +import type * as types from '../types.d.ts'; +/** Secret generation function options. */ +export interface GenerateSecretOptions { + /** + * The value to use as {@link !SubtleCrypto.generateKey} `extractable` argument. Default is false. + * + * > [!NOTE]\ + * > Because A128CBC-HS256, A192CBC-HS384, and A256CBC-HS512 secrets cannot be represented as + * > {@link !CryptoKey} this option has no effect for them. + */ + extractable?: boolean; +} +/** + * Generates a symmetric secret key for a given JWA algorithm identifier. + * + * > [!NOTE]\ + * > The secret key is generated with `extractable` set to `false` by default. + * + * > [!NOTE]\ + * > Because A128CBC-HS256, A192CBC-HS384, and A256CBC-HS512 secrets cannot be represented as + * > {@link !CryptoKey} this method yields a {@link !Uint8Array} for them instead. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/generate/secret'`. + * + * @param alg JWA Algorithm Identifier to be used with the generated secret. See + * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. + * @param options Additional options passed down to the secret generation. + */ +export declare function generateSecret(alg: string, options?: GenerateSecretOptions): Promise; diff --git a/node_modules/jose/dist/types/key/import.d.ts b/node_modules/jose/dist/types/key/import.d.ts new file mode 100644 index 000000000..e0cbfe00b --- /dev/null +++ b/node_modules/jose/dist/types/key/import.d.ts @@ -0,0 +1,83 @@ +/** + * Cryptographic key import functions + * + * @module + */ +import type * as types from '../types.d.ts'; +/** Key Import Function options. */ +export interface KeyImportOptions { + /** + * The value to use as {@link !SubtleCrypto.importKey} `extractable` argument. Default is false for + * private keys, true otherwise. + */ + extractable?: boolean; +} +/** + * Imports a PEM-encoded SPKI string as a {@link !CryptoKey}. + * + * > [!NOTE]\ + * > The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in + * > {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption + * > (1.2.840.113549.1.1.1) instead for all RSA algorithms. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/key/import'`. + * + * @param spki PEM-encoded SPKI string + * @param alg JSON Web Algorithm identifier to be used with the imported key. See + * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. + */ +export declare function importSPKI(spki: string, alg: string, options?: KeyImportOptions): Promise; +/** + * Imports the SPKI from an X.509 string certificate as a {@link !CryptoKey}. + * + * > [!NOTE]\ + * > The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in + * > {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption + * > (1.2.840.113549.1.1.1) instead for all RSA algorithms. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/key/import'`. + * + * @param x509 X.509 certificate string + * @param alg JSON Web Algorithm identifier to be used with the imported key. See + * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. + */ +export declare function importX509(x509: string, alg: string, options?: KeyImportOptions): Promise; +/** + * Imports a PEM-encoded PKCS#8 string as a {@link !CryptoKey}. + * + * > [!NOTE]\ + * > The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in + * > {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption + * > (1.2.840.113549.1.1.1) instead for all RSA algorithms. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/key/import'`. + * + * @param pkcs8 PEM-encoded PKCS#8 string + * @param alg JSON Web Algorithm identifier to be used with the imported key. See + * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. + */ +export declare function importPKCS8(pkcs8: string, alg: string, options?: KeyImportOptions): Promise; +/** + * Imports a JWK to a {@link !CryptoKey}. Either the JWK "alg" (Algorithm) Parameter, or the optional + * "alg" argument, must be present for asymmetric JSON Web Key imports. + * + * > [!NOTE]\ + * > The JSON Web Key parameters "use", "key_ops", and "ext" are also used in the {@link !CryptoKey} + * > import process. + * + * > [!NOTE]\ + * > Symmetric JSON Web Keys (i.e. `kty: "oct"`) yield back an {@link !Uint8Array} instead of a + * > {@link !CryptoKey}. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/key/import'`. + * + * @param jwk JSON Web Key. + * @param alg JSON Web Algorithm identifier to be used with the imported key. Default is the "alg" + * property on the JWK. See + * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. + */ +export declare function importJWK(jwk: types.JWK, alg?: string, options?: KeyImportOptions): Promise; diff --git a/node_modules/jose/dist/types/types.d.ts b/node_modules/jose/dist/types/types.d.ts new file mode 100644 index 000000000..5e08fa11e --- /dev/null +++ b/node_modules/jose/dist/types/types.d.ts @@ -0,0 +1,841 @@ +/** Generic JSON Web Key Parameters. */ +export interface JWKParameters { + /** JWK "kty" (Key Type) Parameter */ + kty?: string + /** + * JWK "alg" (Algorithm) Parameter + * + * @see {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements} + */ + alg?: string + /** JWK "key_ops" (Key Operations) Parameter */ + key_ops?: string[] + /** JWK "ext" (Extractable) Parameter */ + ext?: boolean + /** JWK "use" (Public Key Use) Parameter */ + use?: string + /** JWK "x5c" (X.509 Certificate Chain) Parameter */ + x5c?: string[] + /** JWK "x5t" (X.509 Certificate SHA-1 Thumbprint) Parameter */ + x5t?: string + /** JWK "x5t#S256" (X.509 Certificate SHA-256 Thumbprint) Parameter */ + 'x5t#S256'?: string + /** JWK "x5u" (X.509 URL) Parameter */ + x5u?: string + /** JWK "kid" (Key ID) Parameter */ + kid?: string +} + +/** Convenience interface for Public OKP JSON Web Keys */ +export interface JWK_OKP_Public extends JWKParameters { + /** OKP JWK "crv" (The Subtype of Key Pair) Parameter */ + crv: string + /** OKP JWK "x" (The public key) Parameter */ + x: string +} + +/** Convenience interface for Private OKP JSON Web Keys */ +export interface JWK_OKP_Private extends JWK_OKP_Public { + /** OKP JWK "d" (The Private Key) Parameter */ + d: string +} + +/** Convenience interface for Public AKP JSON Web Keys */ +export interface JWK_AKP_Public extends JWKParameters { + /** JWK "alg" (Algorithm) Parameter */ + alg: string + /** AKP JWK "pub" (The Public key) Parameter */ + pub: string +} + +/** Convenience interface for Private AKP JSON Web Keys */ +export interface JWK_AKP_Private extends JWK_AKP_Public { + /** AKP JWK "priv" (The Private Key) Parameter */ + priv: string +} + +/** Convenience interface for Public EC JSON Web Keys */ +export interface JWK_EC_Public extends JWKParameters { + /** EC JWK "crv" (Curve) Parameter */ + crv: string + /** EC JWK "x" (X Coordinate) Parameter */ + x: string + /** EC JWK "y" (Y Coordinate) Parameter */ + y: string +} + +/** Convenience interface for Private EC JSON Web Keys */ +export interface JWK_EC_Private extends JWK_EC_Public { + /** EC JWK "d" (ECC Private Key) Parameter */ + d: string +} + +/** Convenience interface for Public RSA JSON Web Keys */ +export interface JWK_RSA_Public extends JWKParameters { + /** RSA JWK "e" (Exponent) Parameter */ + e: string + /** RSA JWK "n" (Modulus) Parameter */ + n: string +} + +/** Convenience interface for Private RSA JSON Web Keys */ +export interface JWK_RSA_Private extends JWK_RSA_Public { + /** RSA JWK "d" (Private Exponent) Parameter */ + d: string + /** RSA JWK "dp" (First Factor CRT Exponent) Parameter */ + dp: string + /** RSA JWK "dq" (Second Factor CRT Exponent) Parameter */ + dq: string + /** RSA JWK "p" (First Prime Factor) Parameter */ + p: string + /** RSA JWK "q" (Second Prime Factor) Parameter */ + q: string + /** RSA JWK "qi" (First CRT Coefficient) Parameter */ + qi: string +} + +/** Convenience interface for oct JSON Web Keys */ +export interface JWK_oct extends JWKParameters { + /** Oct JWK "k" (Key Value) Parameter */ + k: string +} + +/** + * JSON Web Key ({@link https://www.rfc-editor.org/rfc/rfc7517 JWK}). "RSA", "EC", "OKP", "AKP", and + * "oct" key types are supported. + * + * @see {@link JWK_AKP_Public} + * @see {@link JWK_AKP_Private} + * @see {@link JWK_OKP_Public} + * @see {@link JWK_OKP_Private} + * @see {@link JWK_EC_Public} + * @see {@link JWK_EC_Private} + * @see {@link JWK_RSA_Public} + * @see {@link JWK_RSA_Private} + * @see {@link JWK_oct} + */ +export interface JWK extends JWKParameters { + /** + * - EC JWK "crv" (Curve) Parameter + * - OKP JWK "crv" (The Subtype of Key Pair) Parameter + */ + crv?: string + /** + * - Private RSA JWK "d" (Private Exponent) Parameter + * - Private EC JWK "d" (ECC Private Key) Parameter + * - Private OKP JWK "d" (The Private Key) Parameter + */ + d?: string + /** Private RSA JWK "dp" (First Factor CRT Exponent) Parameter */ + dp?: string + /** Private RSA JWK "dq" (Second Factor CRT Exponent) Parameter */ + dq?: string + /** RSA JWK "e" (Exponent) Parameter */ + e?: string + /** Oct JWK "k" (Key Value) Parameter */ + k?: string + /** RSA JWK "n" (Modulus) Parameter */ + n?: string + /** Private RSA JWK "p" (First Prime Factor) Parameter */ + p?: string + /** Private RSA JWK "q" (Second Prime Factor) Parameter */ + q?: string + /** Private RSA JWK "qi" (First CRT Coefficient) Parameter */ + qi?: string + /** + * - EC JWK "x" (X Coordinate) Parameter + * - OKP JWK "x" (The public key) Parameter + */ + x?: string + /** EC JWK "y" (Y Coordinate) Parameter */ + y?: string + /** AKP JWK "pub" (Public Key) Parameter */ + pub?: string + /** AKP JWK "priv" (Private key) Parameter */ + priv?: string +} + +/** + * @private + * + * @internal + */ +export interface GenericGetKeyFunction { + /** + * Dynamic key resolution function. No token components have been verified at the time of this + * function call. + * + * If a suitable key for the token cannot be matched, throw an error instead. + * + * @param protectedHeader JWE or JWS Protected Header. + * @param token The consumed JWE or JWS token. + */ + (protectedHeader: IProtectedHeader, token: IToken): Promise | ReturnKeyTypes +} + +/** + * Generic Interface for consuming operations dynamic key resolution. + * + * @param IProtectedHeader Type definition of the JWE or JWS Protected Header. + * @param IToken Type definition of the consumed JWE or JWS token. + */ +export interface GetKeyFunction extends GenericGetKeyFunction< + IProtectedHeader, + IToken, + CryptoKey | KeyObject | JWK | Uint8Array +> {} + +/** + * Flattened JWS definition for verify function inputs, allows payload as {@link !Uint8Array} for + * detached signature validation. + */ +export interface FlattenedJWSInput { + /** + * The "header" member MUST be present and contain the value JWS Unprotected Header when the JWS + * Unprotected Header value is non- empty; otherwise, it MUST be absent. This value is represented + * as an unencoded JSON object, rather than as a string. These Header Parameter values are not + * integrity protected. + */ + header?: JWSHeaderParameters + + /** + * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797 + * "b64": false is used the value passed may also be a {@link !Uint8Array}. + */ + payload: string | Uint8Array + + /** + * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWS Protected + * Header)) when the JWS Protected Header value is non-empty; otherwise, it MUST be absent. These + * Header Parameter values are integrity protected. + */ + protected?: string + + /** The "signature" member MUST be present and contain the value BASE64URL(JWS Signature). */ + signature: string +} + +/** + * General JWS definition for verify function inputs, allows payload as {@link !Uint8Array} for + * detached signature validation. + */ +export interface GeneralJWSInput { + /** + * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When when + * JWS Unencoded Payload ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) "b64": false is + * used the value passed may also be a {@link !Uint8Array}. + */ + payload: string | Uint8Array + + /** + * The "signatures" member value MUST be an array of JSON objects. Each object represents a + * signature or MAC over the JWS Payload and the JWS Protected Header. + */ + signatures: Omit[] +} + +/** + * Flattened JWS JSON Serialization Syntax token. Payload is returned as an empty string when JWS + * Unencoded Payload ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) is used. + */ +export interface FlattenedJWS extends Partial { + payload: string + signature: string +} + +/** + * General JWS JSON Serialization Syntax token. Payload is returned as an empty string when JWS + * Unencoded Payload ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) is used. + */ +export interface GeneralJWS { + payload: string + signatures: Omit[] +} + +/** Header Parameters common to JWE and JWS */ +export interface JoseHeaderParameters { + /** "kid" (Key ID) Header Parameter */ + kid?: string + + /** "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter */ + x5t?: string + + /** "x5c" (X.509 Certificate Chain) Header Parameter */ + x5c?: string[] + + /** "x5u" (X.509 URL) Header Parameter */ + x5u?: string + + /** "jku" (JWK Set URL) Header Parameter */ + jku?: string + + /** "jwk" (JSON Web Key) Header Parameter */ + jwk?: Pick + + /** "typ" (Type) Header Parameter */ + typ?: string + + /** "cty" (Content Type) Header Parameter */ + cty?: string +} + +/** Recognized JWS Header Parameters, any other Header Members may also be present. */ +export interface JWSHeaderParameters extends JoseHeaderParameters { + /** + * JWS "alg" (Algorithm) Header Parameter + * + * @see {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements} + */ + alg?: string + + /** + * This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing + * Input computation as per {@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}. + */ + b64?: boolean + + /** JWS "crit" (Critical) Header Parameter */ + crit?: string[] + + /** Any other JWS Header member. */ + [propName: string]: unknown +} + +/** Recognized JWE Key Management-related Header Parameters. */ +export interface JWEKeyManagementHeaderParameters { + /** + * ECDH-ES "apu" (Agreement PartyUInfo). This will be used as a JOSE Header Parameter and will be + * used in ECDH's ConcatKDF. + */ + apu?: Uint8Array + + /** + * ECDH-ES "apv" (Agreement PartyVInfo). This will be used as a JOSE Header Parameter and will be + * used in ECDH's ConcatKDF. + */ + apv?: Uint8Array + /** + * @deprecated You should not use this parameter. It is only intended for testing and vector + * validation purposes. + */ + p2c?: number + /** + * @deprecated You should not use this parameter. It is only intended for testing and vector + * validation purposes. + */ + p2s?: Uint8Array + /** + * @deprecated You should not use this parameter. It is only intended for testing and vector + * validation purposes. + */ + iv?: Uint8Array + /** + * @deprecated You should not use this parameter. It is only intended for testing and vector + * validation purposes. + */ + epk?: CryptoKey | KeyObject +} + +/** Flattened JWE JSON Serialization Syntax token. */ +export interface FlattenedJWE { + /** + * The "aad" member MUST be present and contain the value BASE64URL(JWE AAD)) when the JWE AAD + * value is non-empty; otherwise, it MUST be absent. A JWE AAD value can be included to supply a + * base64url-encoded value to be integrity protected but not encrypted. + */ + aad?: string + + /** The "ciphertext" member MUST be present and contain the value BASE64URL(JWE Ciphertext). */ + ciphertext: string + + /** + * The "encrypted_key" member MUST be present and contain the value BASE64URL(JWE Encrypted Key) + * when the JWE Encrypted Key value is non-empty; otherwise, it MUST be absent. + */ + encrypted_key?: string + + /** + * The "header" member MUST be present and contain the value JWE Per- Recipient Unprotected Header + * when the JWE Per-Recipient Unprotected Header value is non-empty; otherwise, it MUST be absent. + * This value is represented as an unencoded JSON object, rather than as a string. These Header + * Parameter values are not integrity protected. + */ + header?: JWEHeaderParameters + + /** + * The "iv" member MUST be present and contain the value BASE64URL(JWE Initialization Vector) when + * the JWE Initialization Vector value is non-empty; otherwise, it MUST be absent. + */ + iv?: string + + /** + * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWE Protected + * Header)) when the JWE Protected Header value is non-empty; otherwise, it MUST be absent. These + * Header Parameter values are integrity protected. + */ + protected?: string + + /** + * The "tag" member MUST be present and contain the value BASE64URL(JWE Authentication Tag) when + * the JWE Authentication Tag value is non-empty; otherwise, it MUST be absent. + */ + tag?: string + + /** + * The "unprotected" member MUST be present and contain the value JWE Shared Unprotected Header + * when the JWE Shared Unprotected Header value is non-empty; otherwise, it MUST be absent. This + * value is represented as an unencoded JSON object, rather than as a string. These Header + * Parameter values are not integrity protected. + */ + unprotected?: JWEHeaderParameters +} + +/** General JWE JSON Serialization Syntax token. */ +export interface GeneralJWE extends Omit { + recipients: Pick[] +} + +/** Recognized JWE Header Parameters, any other Header members may also be present. */ +export interface JWEHeaderParameters extends JoseHeaderParameters { + /** + * JWE "alg" (Algorithm) Header Parameter + * + * @see {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements} + */ + alg?: string + + /** + * JWE "enc" (Encryption Algorithm) Header Parameter + * + * @see {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements} + */ + enc?: string + + /** JWE "crit" (Critical) Header Parameter */ + crit?: string[] + + /** + * JWE "zip" (Compression Algorithm) Header Parameter. This parameter is not supported anymore. + * + * @deprecated Compression of data SHOULD NOT be done before encryption, because such compressed + * data often reveals information about the plaintext. + * + * @see {@link https://www.rfc-editor.org/rfc/rfc8725#name-avoid-compression-of-encryp Avoid Compression of Encryption Inputs} + */ + zip?: string + + /** Any other JWE Header member. */ + [propName: string]: unknown +} + +/** Shared Interface with a "crit" property for all sign, verify, encrypt and decrypt operations. */ +export interface CritOption { + /** + * An object with keys representing recognized "crit" (Critical) Header Parameter names. The value + * for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity + * protected, `false` when it's irrelevant. + * + * This makes the "Extension Header Parameter "..." is not recognized" error go away. + * + * Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" + * (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically + * correct when provided and that it is optionally integrity protected. It will not process the + * Header Parameter in any way or reject the operation if it is missing. You MUST still verify the + * Header Parameter was present and process it according to the profile's validation steps after + * the operation succeeds. + * + * The JWS extension Header Parameter `b64` is always recognized and processed properly. No other + * registered Header Parameters that need this kind of default built-in treatment are currently + * available. + */ + crit?: { + [propName: string]: boolean + } +} + +/** JWE Decryption options. */ +export interface DecryptOptions extends CritOption { + /** + * A list of accepted JWE "alg" (Algorithm) Header Parameter values. By default all "alg" + * (Algorithm) Header Parameter values applicable for the used key/secret are allowed except for + * all PBES2 Key Management Algorithms, these need to be explicitly allowed using this option. + */ + keyManagementAlgorithms?: string[] + + /** + * A list of accepted JWE "enc" (Encryption Algorithm) Header Parameter values. By default all + * "enc" (Encryption Algorithm) values applicable for the used key/secret are allowed. + */ + contentEncryptionAlgorithms?: string[] + + /** + * (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter + * value. The PBKDF2 iteration count defines the algorithm's computational expense. By default + * this value is set to 10000. + */ + maxPBES2Count?: number +} + +/** JWE Encryption options. */ +export interface EncryptOptions extends CritOption {} + +/** JWT Claims Set verification options. */ +export interface JWTClaimVerificationOptions { + /** + * Expected JWT "aud" (Audience) Claim value(s). + * + * This option makes the JWT "aud" (Audience) Claim presence required. + */ + audience?: string | string[] + + /** + * Clock skew tolerance + * + * - In seconds when number (e.g. 5) + * - Resolved into a number of seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). + * + * Used when validating the JWT "nbf" (Not Before) and "exp" (Expiration Time) claims, and when + * validating the "iat" (Issued At) claim if the {@link maxTokenAge `maxTokenAge` option} is set. + */ + clockTolerance?: string | number + + /** + * Expected JWT "iss" (Issuer) Claim value(s). + * + * This option makes the JWT "iss" (Issuer) Claim presence required. + */ + issuer?: string | string[] + + /** + * Maximum time elapsed (in seconds) from the JWT "iat" (Issued At) Claim value. + * + * - In seconds when number (e.g. 5) + * - Resolved into a number of seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). + * + * This option makes the JWT "iat" (Issued At) Claim presence required. + */ + maxTokenAge?: string | number + + /** + * Expected JWT "sub" (Subject) Claim value. + * + * This option makes the JWT "sub" (Subject) Claim presence required. + */ + subject?: string + + /** + * Expected JWT "typ" (Type) Header Parameter value. + * + * This option makes the JWT "typ" (Type) Header Parameter presence required. + */ + typ?: string + + /** Date to use when comparing NumericDate claims, defaults to `new Date()`. */ + currentDate?: Date + + /** + * Array of required Claim Names that must be present in the JWT Claims Set. Default is that: if + * the {@link issuer `issuer` option} is set, then JWT "iss" (Issuer) Claim must be present; if the + * {@link audience `audience` option} is set, then JWT "aud" (Audience) Claim must be present; if + * the {@link subject `subject` option} is set, then JWT "sub" (Subject) Claim must be present; if + * the {@link maxTokenAge `maxTokenAge` option} is set, then JWT "iat" (Issued At) Claim must be + * present. + */ + requiredClaims?: string[] +} + +/** JWS Verification options. */ +export interface VerifyOptions extends CritOption { + /** + * A list of accepted JWS "alg" (Algorithm) Header Parameter values. By default all "alg" + * (Algorithm) values applicable for the used key/secret are allowed. + * + * > [!NOTE]\ + * > Unsecured JWTs (`{ "alg": "none" }`) are never accepted by this API. + */ + algorithms?: string[] +} + +/** JWS Signing options. */ +export interface SignOptions extends CritOption {} + +/** Recognized JWT Claims Set members, any other members may also be present. */ +export interface JWTPayload { + /** + * JWT Issuer + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1 RFC7519#section-4.1.1} + */ + iss?: string + + /** + * JWT Subject + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2 RFC7519#section-4.1.2} + */ + sub?: string + + /** + * JWT Audience + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3 RFC7519#section-4.1.3} + */ + aud?: string | string[] + + /** + * JWT ID + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7 RFC7519#section-4.1.7} + */ + jti?: string + + /** + * JWT Not Before + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5 RFC7519#section-4.1.5} + */ + nbf?: number + + /** + * JWT Expiration Time + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4 RFC7519#section-4.1.4} + */ + exp?: number + + /** + * JWT Issued At + * + * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 RFC7519#section-4.1.6} + */ + iat?: number + + /** Any other JWT Claim Set member. */ + [propName: string]: unknown +} + +/** Flattened JWE JSON Serialization Syntax decryption result */ +export interface FlattenedDecryptResult { + /** JWE AAD. */ + additionalAuthenticatedData?: Uint8Array + + /** Plaintext. */ + plaintext: Uint8Array + + /** JWE Protected Header. */ + protectedHeader?: JWEHeaderParameters + + /** JWE Shared Unprotected Header. */ + sharedUnprotectedHeader?: JWEHeaderParameters + + /** JWE Per-Recipient Unprotected Header. */ + unprotectedHeader?: JWEHeaderParameters +} + +/** General JWE JSON Serialization Syntax decryption result */ +export interface GeneralDecryptResult extends FlattenedDecryptResult {} + +/** Compact JWE decryption result */ +export interface CompactDecryptResult { + /** Plaintext. */ + plaintext: Uint8Array + + /** JWE Protected Header. */ + protectedHeader: CompactJWEHeaderParameters +} + +/** Flattened JWS JSON Serialization Syntax verification result */ +export interface FlattenedVerifyResult { + /** JWS Payload. */ + payload: Uint8Array + + /** JWS Protected Header. */ + protectedHeader?: JWSHeaderParameters + + /** JWS Unprotected Header. */ + unprotectedHeader?: JWSHeaderParameters +} + +/** General JWS JSON Serialization Syntax verification result */ +export interface GeneralVerifyResult extends FlattenedVerifyResult {} + +/** Compact JWS verification result */ +export interface CompactVerifyResult { + /** JWS Payload. */ + payload: Uint8Array + + /** JWS Protected Header. */ + protectedHeader: CompactJWSHeaderParameters +} + +/** Signed JSON Web Token (JWT) verification result */ +export interface JWTVerifyResult { + /** JWT Claims Set. */ + payload: PayloadType & JWTPayload + + /** JWS Protected Header. */ + protectedHeader: JWTHeaderParameters +} + +/** Encrypted JSON Web Token (JWT) decryption result */ +export interface JWTDecryptResult { + /** JWT Claims Set. */ + payload: PayloadType & JWTPayload + + /** JWE Protected Header. */ + protectedHeader: CompactJWEHeaderParameters +} + +/** When key resolver functions are used this becomes part of successful resolves */ +export interface ResolvedKey { + /** Key resolved from the key resolver function. */ + key: CryptoKey | Uint8Array +} + +/** Recognized Compact JWS Header Parameters, any other Header Members may also be present. */ +export interface CompactJWSHeaderParameters extends JWSHeaderParameters { + alg: string +} + +/** Recognized Signed JWT Header Parameters, any other Header Members may also be present. */ +export interface JWTHeaderParameters extends CompactJWSHeaderParameters { + b64?: true +} + +/** Recognized Compact JWE Header Parameters, any other Header Members may also be present. */ +export interface CompactJWEHeaderParameters extends JWEHeaderParameters { + alg: string + enc: string +} + +/** JSON Web Key Set */ +export interface JSONWebKeySet { + keys: JWK[] +} + +/** + * {@link !KeyObject} is a representation of a key/secret available in the Node.js runtime. You may + * use the Node.js runtime APIs {@link !createPublicKey}, {@link !createPrivateKey}, and + * {@link !createSecretKey} to obtain a {@link !KeyObject} from your existing key material. + */ +export interface KeyObject { + type: string +} + +/** + * {@link !CryptoKey} is a representation of a key/secret available in all supported runtimes. In + * addition to the {@link key/import Key Import Functions} you may use the + * {@link !SubtleCrypto.importKey} API to obtain a {@link !CryptoKey} from your existing key + * material. + */ +export type CryptoKey = Extract< + Awaited>, + { type: string } +> + +/** Generic interface for JWT producing classes. */ +export interface ProduceJWT { + /** + * Set the "iss" (Issuer) Claim. + * + * @param issuer "Issuer" Claim value to set on the JWT Claims Set. + */ + setIssuer(issuer: string): this + + /** + * Set the "sub" (Subject) Claim. + * + * @param subject "sub" (Subject) Claim value to set on the JWT Claims Set. + */ + setSubject(subject: string): this + + /** + * Set the "aud" (Audience) Claim. + * + * @param audience "aud" (Audience) Claim value to set on the JWT Claims Set. + */ + setAudience(audience: string | string[]): this + + /** + * Set the "jti" (JWT ID) Claim. + * + * @param jwtId "jti" (JWT ID) Claim value to set on the JWT Claims Set. + */ + setJti(jwtId: string): this + + /** + * Set the "nbf" (Not Before) Claim. + * + * - If a `number` is passed as an argument it is used as the claim directly. + * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the + * claim. + * - If a `string` is passed as an argument it is resolved to a time span, and then added to the + * current unix timestamp and used as the claim. + * + * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1 + * day". + * + * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins", + * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year", + * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an + * alias for a year. + * + * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets + * subtracted from the current unix timestamp. A "from now" suffix can also be used for + * readability when adding to the current unix timestamp. + * + * @param input "nbf" (Not Before) Claim value to set on the JWT Claims Set. + */ + setNotBefore(input: number | string | Date): this + + /** + * Set the "exp" (Expiration Time) Claim. + * + * - If a `number` is passed as an argument it is used as the claim directly. + * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the + * claim. + * - If a `string` is passed as an argument it is resolved to a time span, and then added to the + * current unix timestamp and used as the claim. + * + * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1 + * day". + * + * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins", + * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year", + * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an + * alias for a year. + * + * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets + * subtracted from the current unix timestamp. A "from now" suffix can also be used for + * readability when adding to the current unix timestamp. + * + * @param input "exp" (Expiration Time) Claim value to set on the JWT Claims Set. + */ + setExpirationTime(input: number | string | Date): this + + /** + * Set the "iat" (Issued At) Claim. + * + * - If no argument is used the current unix timestamp is used as the claim. + * - If a `number` is passed as an argument it is used as the claim directly. + * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the + * claim. + * - If a `string` is passed as an argument it is resolved to a time span, and then added to the + * current unix timestamp and used as the claim. + * + * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1 + * day". + * + * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins", + * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year", + * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an + * alias for a year. + * + * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets + * subtracted from the current unix timestamp. A "from now" suffix can also be used for + * readability when adding to the current unix timestamp. + * + * @param input "iat" (Expiration Time) Claim value to set on the JWT Claims Set. + */ + setIssuedAt(input?: number | string | Date): this +} diff --git a/node_modules/jose/dist/types/util/base64url.d.ts b/node_modules/jose/dist/types/util/base64url.d.ts new file mode 100644 index 000000000..7ec0d31f7 --- /dev/null +++ b/node_modules/jose/dist/types/util/base64url.d.ts @@ -0,0 +1,9 @@ +/** + * Base64URL encoding and decoding utilities + * + * @module + */ +/** Decodes a Base64URL encoded input. */ +export declare function decode(input: Uint8Array | string): Uint8Array; +/** Encodes an input using Base64URL with no padding. */ +export declare function encode(input: Uint8Array | string): string; diff --git a/node_modules/jose/dist/types/util/decode_jwt.d.ts b/node_modules/jose/dist/types/util/decode_jwt.d.ts new file mode 100644 index 000000000..3fd77ab5d --- /dev/null +++ b/node_modules/jose/dist/types/util/decode_jwt.d.ts @@ -0,0 +1,18 @@ +/** + * JSON Web Token (JWT) Claims Set Decoding (no validation, no signature checking) + * + * @module + */ +import type * as types from '../types.d.ts'; +/** + * Decodes a signed JSON Web Token payload. This does not validate the JWT Claims Set types or + * values. This does not validate the JWS Signature. For a proper Signed JWT Claims Set validation + * and JWS signature verification use `jose.jwtVerify()`. For an encrypted JWT Claims Set validation + * and JWE decryption use `jose.jwtDecrypt()`. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/jwt/decode'`. + * + * @param jwt JWT token in compact JWS serialization. + */ +export declare function decodeJwt(jwt: string): PayloadType & types.JWTPayload; diff --git a/node_modules/jose/dist/types/util/decode_protected_header.d.ts b/node_modules/jose/dist/types/util/decode_protected_header.d.ts new file mode 100644 index 000000000..bec6fc03f --- /dev/null +++ b/node_modules/jose/dist/types/util/decode_protected_header.d.ts @@ -0,0 +1,17 @@ +/** + * JOSE Protected Header Decoding (JWE, JWS, all serialization syntaxes) + * + * @module + */ +import type * as types from '../types.d.ts'; +/** JWE and JWS Header Parameters */ +export type ProtectedHeaderParameters = types.JWSHeaderParameters & types.JWEHeaderParameters; +/** + * Decodes the Protected Header of a JWE/JWS/JWT token utilizing any JOSE serialization. + * + * This function is exported (as a named export) from the main `'jose'` module entry point as well + * as from its subpath export `'jose/decode/protected_header'`. + * + * @param token JWE/JWS/JWT token in any JOSE serialization. + */ +export declare function decodeProtectedHeader(token: string | object): ProtectedHeaderParameters; diff --git a/node_modules/jose/dist/types/util/errors.d.ts b/node_modules/jose/dist/types/util/errors.d.ts new file mode 100644 index 000000000..bad54f817 --- /dev/null +++ b/node_modules/jose/dist/types/util/errors.d.ts @@ -0,0 +1,213 @@ +/** + * JOSE module errors and error codes + * + * @module + */ +import type * as types from '../types.d.ts'; +/** + * A generic Error that all other JOSE specific Error subclasses extend. + * + */ +export declare class JOSEError extends Error { + /** + * A unique error code for the particular error subclass. + * + * @ignore + */ + static code: string; + /** A unique error code for {@link JOSEError}. */ + code: string; + /** @ignore */ + constructor(message?: string, options?: { + cause?: unknown; + }); +} +/** + * An error subclass thrown when a JWT Claim Set member validation fails. + * + */ +export declare class JWTClaimValidationFailed extends JOSEError { + /** @ignore */ + static code: string; + /** A unique error code for {@link JWTClaimValidationFailed}. */ + code: string; + /** The Claim for which the validation failed. */ + claim: string; + /** Reason code for the validation failure. */ + reason: string; + /** + * The parsed JWT Claims Set (aka payload). Other JWT claims may or may not have been verified at + * this point. The JSON Web Signature (JWS) or a JSON Web Encryption (JWE) structures' integrity + * has however been verified. Claims Set verification happens after the JWS Signature or JWE + * Decryption processes. + */ + payload: types.JWTPayload; + /** @ignore */ + constructor(message: string, payload: types.JWTPayload, claim?: string, reason?: string); +} +/** + * An error subclass thrown when a JWT is expired. + * + */ +export declare class JWTExpired extends JOSEError implements JWTClaimValidationFailed { + /** @ignore */ + static code: string; + /** A unique error code for {@link JWTExpired}. */ + code: string; + /** The Claim for which the validation failed. */ + claim: string; + /** Reason code for the validation failure. */ + reason: string; + /** + * The parsed JWT Claims Set (aka payload). Other JWT claims may or may not have been verified at + * this point. The JSON Web Signature (JWS) or a JSON Web Encryption (JWE) structures' integrity + * has however been verified. Claims Set verification happens after the JWS Signature or JWE + * Decryption processes. + */ + payload: types.JWTPayload; + /** @ignore */ + constructor(message: string, payload: types.JWTPayload, claim?: string, reason?: string); +} +/** + * An error subclass thrown when a JOSE Algorithm is not allowed per developer preference. + * + */ +export declare class JOSEAlgNotAllowed extends JOSEError { + /** @ignore */ + static code: string; + /** A unique error code for {@link JOSEAlgNotAllowed}. */ + code: string; +} +/** + * An error subclass thrown when a particular feature or algorithm is not supported by this + * implementation or JOSE in general. + * + */ +export declare class JOSENotSupported extends JOSEError { + /** @ignore */ + static code: string; + /** A unique error code for {@link JOSENotSupported}. */ + code: string; +} +/** + * An error subclass thrown when a JWE ciphertext decryption fails. + * + */ +export declare class JWEDecryptionFailed extends JOSEError { + /** @ignore */ + static code: string; + /** A unique error code for {@link JWEDecryptionFailed}. */ + code: string; + /** @ignore */ + constructor(message?: string, options?: { + cause?: unknown; + }); +} +/** + * An error subclass thrown when a JWE is invalid. + * + */ +export declare class JWEInvalid extends JOSEError { + /** @ignore */ + static code: string; + /** A unique error code for {@link JWEInvalid}. */ + code: string; +} +/** + * An error subclass thrown when a JWS is invalid. + * + */ +export declare class JWSInvalid extends JOSEError { + /** @ignore */ + static code: string; + /** A unique error code for {@link JWSInvalid}. */ + code: string; +} +/** + * An error subclass thrown when a JWT is invalid. + * + */ +export declare class JWTInvalid extends JOSEError { + /** @ignore */ + static code: string; + /** A unique error code for {@link JWTInvalid}. */ + code: string; +} +/** + * An error subclass thrown when a JWK is invalid. + * + */ +export declare class JWKInvalid extends JOSEError { + /** @ignore */ + static code: string; + /** A unique error code for {@link JWKInvalid}. */ + code: string; +} +/** + * An error subclass thrown when a JWKS is invalid. + * + */ +export declare class JWKSInvalid extends JOSEError { + /** @ignore */ + static code: string; + /** A unique error code for {@link JWKSInvalid}. */ + code: string; +} +/** + * An error subclass thrown when no keys match from a JWKS. + * + */ +export declare class JWKSNoMatchingKey extends JOSEError { + /** @ignore */ + static code: string; + /** A unique error code for {@link JWKSNoMatchingKey}. */ + code: string; + /** @ignore */ + constructor(message?: string, options?: { + cause?: unknown; + }); +} +/** + * An error subclass thrown when multiple keys match from a JWKS. + * + */ +export declare class JWKSMultipleMatchingKeys extends JOSEError { + /** @ignore */ + [Symbol.asyncIterator]: () => AsyncIterableIterator; + /** @ignore */ + static code: string; + /** A unique error code for {@link JWKSMultipleMatchingKeys}. */ + code: string; + /** @ignore */ + constructor(message?: string, options?: { + cause?: unknown; + }); +} +/** + * Timeout was reached when retrieving the JWKS response. + * + */ +export declare class JWKSTimeout extends JOSEError { + /** @ignore */ + static code: string; + /** A unique error code for {@link JWKSTimeout}. */ + code: string; + /** @ignore */ + constructor(message?: string, options?: { + cause?: unknown; + }); +} +/** + * An error subclass thrown when JWS signature verification fails. + * + */ +export declare class JWSSignatureVerificationFailed extends JOSEError { + /** @ignore */ + static code: string; + /** A unique error code for {@link JWSSignatureVerificationFailed}. */ + code: string; + /** @ignore */ + constructor(message?: string, options?: { + cause?: unknown; + }); +} diff --git a/node_modules/jose/dist/webapi/index.js b/node_modules/jose/dist/webapi/index.js new file mode 100644 index 000000000..939f09b87 --- /dev/null +++ b/node_modules/jose/dist/webapi/index.js @@ -0,0 +1,32 @@ +export { compactDecrypt } from './jwe/compact/decrypt.js'; +export { flattenedDecrypt } from './jwe/flattened/decrypt.js'; +export { generalDecrypt } from './jwe/general/decrypt.js'; +export { GeneralEncrypt } from './jwe/general/encrypt.js'; +export { compactVerify } from './jws/compact/verify.js'; +export { flattenedVerify } from './jws/flattened/verify.js'; +export { generalVerify } from './jws/general/verify.js'; +export { jwtVerify } from './jwt/verify.js'; +export { jwtDecrypt } from './jwt/decrypt.js'; +export { CompactEncrypt } from './jwe/compact/encrypt.js'; +export { FlattenedEncrypt } from './jwe/flattened/encrypt.js'; +export { CompactSign } from './jws/compact/sign.js'; +export { FlattenedSign } from './jws/flattened/sign.js'; +export { GeneralSign } from './jws/general/sign.js'; +export { SignJWT } from './jwt/sign.js'; +export { EncryptJWT } from './jwt/encrypt.js'; +export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js'; +export { EmbeddedJWK } from './jwk/embedded.js'; +export { createLocalJWKSet } from './jwks/local.js'; +export { createRemoteJWKSet, jwksCache, customFetch } from './jwks/remote.js'; +export { UnsecuredJWT } from './jwt/unsecured.js'; +export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js'; +export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js'; +export { decodeProtectedHeader } from './util/decode_protected_header.js'; +export { decodeJwt } from './util/decode_jwt.js'; +import * as errors from './util/errors.js'; +export { errors }; +export { generateKeyPair } from './key/generate_key_pair.js'; +export { generateSecret } from './key/generate_secret.js'; +import * as base64url from './util/base64url.js'; +export { base64url }; +export const cryptoRuntime = 'WebCryptoAPI'; diff --git a/node_modules/jose/dist/webapi/jwe/compact/decrypt.js b/node_modules/jose/dist/webapi/jwe/compact/decrypt.js new file mode 100644 index 000000000..d74a67b13 --- /dev/null +++ b/node_modules/jose/dist/webapi/jwe/compact/decrypt.js @@ -0,0 +1,27 @@ +import { flattenedDecrypt } from '../flattened/decrypt.js'; +import { JWEInvalid } from '../../util/errors.js'; +import { decoder } from '../../lib/buffer_utils.js'; +export async function compactDecrypt(jwe, key, options) { + if (jwe instanceof Uint8Array) { + jwe = decoder.decode(jwe); + } + if (typeof jwe !== 'string') { + throw new JWEInvalid('Compact JWE must be a string or Uint8Array'); + } + const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.'); + if (length !== 5) { + throw new JWEInvalid('Invalid Compact JWE'); + } + const decrypted = await flattenedDecrypt({ + ciphertext, + iv: iv || undefined, + protected: protectedHeader, + tag: tag || undefined, + encrypted_key: encryptedKey || undefined, + }, key, options); + const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: decrypted.key }; + } + return result; +} diff --git a/node_modules/jose/dist/webapi/jwe/compact/encrypt.js b/node_modules/jose/dist/webapi/jwe/compact/encrypt.js new file mode 100644 index 000000000..5492e2c2e --- /dev/null +++ b/node_modules/jose/dist/webapi/jwe/compact/encrypt.js @@ -0,0 +1,27 @@ +import { FlattenedEncrypt } from '../flattened/encrypt.js'; +export class CompactEncrypt { + #flattened; + constructor(plaintext) { + this.#flattened = new FlattenedEncrypt(plaintext); + } + setContentEncryptionKey(cek) { + this.#flattened.setContentEncryptionKey(cek); + return this; + } + setInitializationVector(iv) { + this.#flattened.setInitializationVector(iv); + return this; + } + setProtectedHeader(protectedHeader) { + this.#flattened.setProtectedHeader(protectedHeader); + return this; + } + setKeyManagementParameters(parameters) { + this.#flattened.setKeyManagementParameters(parameters); + return this; + } + async encrypt(key, options) { + const jwe = await this.#flattened.encrypt(key, options); + return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.'); + } +} diff --git a/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js b/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js new file mode 100644 index 000000000..d7a846aea --- /dev/null +++ b/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js @@ -0,0 +1,165 @@ +import { decode as b64u } from '../../util/base64url.js'; +import { decrypt } from '../../lib/decrypt.js'; +import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js'; +import { isDisjoint } from '../../lib/is_disjoint.js'; +import { isObject } from '../../lib/is_object.js'; +import { decryptKeyManagement } from '../../lib/decrypt_key_management.js'; +import { decoder, concat, encode } from '../../lib/buffer_utils.js'; +import { generateCek } from '../../lib/cek.js'; +import { validateCrit } from '../../lib/validate_crit.js'; +import { validateAlgorithms } from '../../lib/validate_algorithms.js'; +import { normalizeKey } from '../../lib/normalize_key.js'; +import { checkKeyType } from '../../lib/check_key_type.js'; +export async function flattenedDecrypt(jwe, key, options) { + if (!isObject(jwe)) { + throw new JWEInvalid('Flattened JWE must be an object'); + } + if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { + throw new JWEInvalid('JOSE Header missing'); + } + if (jwe.iv !== undefined && typeof jwe.iv !== 'string') { + throw new JWEInvalid('JWE Initialization Vector incorrect type'); + } + if (typeof jwe.ciphertext !== 'string') { + throw new JWEInvalid('JWE Ciphertext missing or incorrect type'); + } + if (jwe.tag !== undefined && typeof jwe.tag !== 'string') { + throw new JWEInvalid('JWE Authentication Tag incorrect type'); + } + if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { + throw new JWEInvalid('JWE Protected Header incorrect type'); + } + if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { + throw new JWEInvalid('JWE Encrypted Key incorrect type'); + } + if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { + throw new JWEInvalid('JWE AAD incorrect type'); + } + if (jwe.header !== undefined && !isObject(jwe.header)) { + throw new JWEInvalid('JWE Shared Unprotected Header incorrect type'); + } + if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) { + throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type'); + } + let parsedProt; + if (jwe.protected) { + try { + const protectedHeader = b64u(jwe.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader)); + } + catch { + throw new JWEInvalid('JWE Protected Header is invalid'); + } + } + if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { + throw new JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...parsedProt, + ...jwe.header, + ...jwe.unprotected, + }; + validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader); + if (joseHeader.zip !== undefined) { + throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); + } + const { alg, enc } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header'); + } + if (typeof enc !== 'string' || !enc) { + throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header'); + } + const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms); + const contentEncryptionAlgorithms = options && + validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms); + if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) || + (!keyManagementAlgorithms && alg.startsWith('PBES2'))) { + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); + } + if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { + throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed'); + } + let encryptedKey; + if (jwe.encrypted_key !== undefined) { + try { + encryptedKey = b64u(jwe.encrypted_key); + } + catch { + throw new JWEInvalid('Failed to base64url decode the encrypted_key'); + } + } + let resolvedKey = false; + if (typeof key === 'function') { + key = await key(parsedProt, jwe); + resolvedKey = true; + } + checkKeyType(alg === 'dir' ? enc : alg, key, 'decrypt'); + const k = await normalizeKey(key, alg); + let cek; + try { + cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options); + } + catch (err) { + if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { + throw err; + } + cek = generateCek(enc); + } + let iv; + let tag; + if (jwe.iv !== undefined) { + try { + iv = b64u(jwe.iv); + } + catch { + throw new JWEInvalid('Failed to base64url decode the iv'); + } + } + if (jwe.tag !== undefined) { + try { + tag = b64u(jwe.tag); + } + catch { + throw new JWEInvalid('Failed to base64url decode the tag'); + } + } + const protectedHeader = jwe.protected !== undefined ? encode(jwe.protected) : new Uint8Array(); + let additionalData; + if (jwe.aad !== undefined) { + additionalData = concat(protectedHeader, encode('.'), encode(jwe.aad)); + } + else { + additionalData = protectedHeader; + } + let ciphertext; + try { + ciphertext = b64u(jwe.ciphertext); + } + catch { + throw new JWEInvalid('Failed to base64url decode the ciphertext'); + } + const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData); + const result = { plaintext }; + if (jwe.protected !== undefined) { + result.protectedHeader = parsedProt; + } + if (jwe.aad !== undefined) { + try { + result.additionalAuthenticatedData = b64u(jwe.aad); + } + catch { + throw new JWEInvalid('Failed to base64url decode the aad'); + } + } + if (jwe.unprotected !== undefined) { + result.sharedUnprotectedHeader = jwe.unprotected; + } + if (jwe.header !== undefined) { + result.unprotectedHeader = jwe.header; + } + if (resolvedKey) { + return { ...result, key: k }; + } + return result; +} diff --git a/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js b/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js new file mode 100644 index 000000000..aa2cd1c0b --- /dev/null +++ b/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js @@ -0,0 +1,169 @@ +import { encode as b64u } from '../../util/base64url.js'; +import { unprotected } from '../../lib/private_symbols.js'; +import { encrypt } from '../../lib/encrypt.js'; +import { encryptKeyManagement } from '../../lib/encrypt_key_management.js'; +import { JOSENotSupported, JWEInvalid } from '../../util/errors.js'; +import { isDisjoint } from '../../lib/is_disjoint.js'; +import { concat, encode } from '../../lib/buffer_utils.js'; +import { validateCrit } from '../../lib/validate_crit.js'; +import { normalizeKey } from '../../lib/normalize_key.js'; +import { checkKeyType } from '../../lib/check_key_type.js'; +export class FlattenedEncrypt { + #plaintext; + #protectedHeader; + #sharedUnprotectedHeader; + #unprotectedHeader; + #aad; + #cek; + #iv; + #keyManagementParameters; + constructor(plaintext) { + if (!(plaintext instanceof Uint8Array)) { + throw new TypeError('plaintext must be an instance of Uint8Array'); + } + this.#plaintext = plaintext; + } + setKeyManagementParameters(parameters) { + if (this.#keyManagementParameters) { + throw new TypeError('setKeyManagementParameters can only be called once'); + } + this.#keyManagementParameters = parameters; + return this; + } + setProtectedHeader(protectedHeader) { + if (this.#protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this.#protectedHeader = protectedHeader; + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + if (this.#sharedUnprotectedHeader) { + throw new TypeError('setSharedUnprotectedHeader can only be called once'); + } + this.#sharedUnprotectedHeader = sharedUnprotectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this.#unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this.#unprotectedHeader = unprotectedHeader; + return this; + } + setAdditionalAuthenticatedData(aad) { + this.#aad = aad; + return this; + } + setContentEncryptionKey(cek) { + if (this.#cek) { + throw new TypeError('setContentEncryptionKey can only be called once'); + } + this.#cek = cek; + return this; + } + setInitializationVector(iv) { + if (this.#iv) { + throw new TypeError('setInitializationVector can only be called once'); + } + this.#iv = iv; + return this; + } + async encrypt(key, options) { + if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) { + throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()'); + } + if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) { + throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this.#protectedHeader, + ...this.#unprotectedHeader, + ...this.#sharedUnprotectedHeader, + }; + validateCrit(JWEInvalid, new Map(), options?.crit, this.#protectedHeader, joseHeader); + if (joseHeader.zip !== undefined) { + throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); + } + const { alg, enc } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (typeof enc !== 'string' || !enc) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + let encryptedKey; + if (this.#cek && (alg === 'dir' || alg === 'ECDH-ES')) { + throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`); + } + checkKeyType(alg === 'dir' ? enc : alg, key, 'encrypt'); + let cek; + { + let parameters; + const k = await normalizeKey(key, alg); + ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, this.#cek, this.#keyManagementParameters)); + if (parameters) { + if (options && unprotected in options) { + if (!this.#unprotectedHeader) { + this.setUnprotectedHeader(parameters); + } + else { + this.#unprotectedHeader = { ...this.#unprotectedHeader, ...parameters }; + } + } + else if (!this.#protectedHeader) { + this.setProtectedHeader(parameters); + } + else { + this.#protectedHeader = { ...this.#protectedHeader, ...parameters }; + } + } + } + let additionalData; + let protectedHeaderS; + let protectedHeaderB; + let aadMember; + if (this.#protectedHeader) { + protectedHeaderS = b64u(JSON.stringify(this.#protectedHeader)); + protectedHeaderB = encode(protectedHeaderS); + } + else { + protectedHeaderS = ''; + protectedHeaderB = new Uint8Array(); + } + if (this.#aad) { + aadMember = b64u(this.#aad); + const aadMemberBytes = encode(aadMember); + additionalData = concat(protectedHeaderB, encode('.'), aadMemberBytes); + } + else { + additionalData = protectedHeaderB; + } + const { ciphertext, tag, iv } = await encrypt(enc, this.#plaintext, cek, this.#iv, additionalData); + const jwe = { + ciphertext: b64u(ciphertext), + }; + if (iv) { + jwe.iv = b64u(iv); + } + if (tag) { + jwe.tag = b64u(tag); + } + if (encryptedKey) { + jwe.encrypted_key = b64u(encryptedKey); + } + if (aadMember) { + jwe.aad = aadMember; + } + if (this.#protectedHeader) { + jwe.protected = protectedHeaderS; + } + if (this.#sharedUnprotectedHeader) { + jwe.unprotected = this.#sharedUnprotectedHeader; + } + if (this.#unprotectedHeader) { + jwe.header = this.#unprotectedHeader; + } + return jwe; + } +} diff --git a/node_modules/jose/dist/webapi/jwe/general/decrypt.js b/node_modules/jose/dist/webapi/jwe/general/decrypt.js new file mode 100644 index 000000000..65436afcf --- /dev/null +++ b/node_modules/jose/dist/webapi/jwe/general/decrypt.js @@ -0,0 +1,31 @@ +import { flattenedDecrypt } from '../flattened/decrypt.js'; +import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.js'; +import { isObject } from '../../lib/is_object.js'; +export async function generalDecrypt(jwe, key, options) { + if (!isObject(jwe)) { + throw new JWEInvalid('General JWE must be an object'); + } + if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { + throw new JWEInvalid('JWE Recipients missing or incorrect type'); + } + if (!jwe.recipients.length) { + throw new JWEInvalid('JWE Recipients has no members'); + } + for (const recipient of jwe.recipients) { + try { + return await flattenedDecrypt({ + aad: jwe.aad, + ciphertext: jwe.ciphertext, + encrypted_key: recipient.encrypted_key, + header: recipient.header, + iv: jwe.iv, + protected: jwe.protected, + tag: jwe.tag, + unprotected: jwe.unprotected, + }, key, options); + } + catch { + } + } + throw new JWEDecryptionFailed(); +} diff --git a/node_modules/jose/dist/webapi/jwe/general/encrypt.js b/node_modules/jose/dist/webapi/jwe/general/encrypt.js new file mode 100644 index 000000000..0ee1ebfbc --- /dev/null +++ b/node_modules/jose/dist/webapi/jwe/general/encrypt.js @@ -0,0 +1,187 @@ +import { FlattenedEncrypt } from '../flattened/encrypt.js'; +import { unprotected } from '../../lib/private_symbols.js'; +import { JOSENotSupported, JWEInvalid } from '../../util/errors.js'; +import { generateCek } from '../../lib/cek.js'; +import { isDisjoint } from '../../lib/is_disjoint.js'; +import { encryptKeyManagement } from '../../lib/encrypt_key_management.js'; +import { encode as b64u } from '../../util/base64url.js'; +import { validateCrit } from '../../lib/validate_crit.js'; +import { normalizeKey } from '../../lib/normalize_key.js'; +import { checkKeyType } from '../../lib/check_key_type.js'; +class IndividualRecipient { + #parent; + unprotectedHeader; + keyManagementParameters; + key; + options; + constructor(enc, key, options) { + this.#parent = enc; + this.key = key; + this.options = options; + } + setUnprotectedHeader(unprotectedHeader) { + if (this.unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this.unprotectedHeader = unprotectedHeader; + return this; + } + setKeyManagementParameters(parameters) { + if (this.keyManagementParameters) { + throw new TypeError('setKeyManagementParameters can only be called once'); + } + this.keyManagementParameters = parameters; + return this; + } + addRecipient(...args) { + return this.#parent.addRecipient(...args); + } + encrypt(...args) { + return this.#parent.encrypt(...args); + } + done() { + return this.#parent; + } +} +export class GeneralEncrypt { + #plaintext; + #recipients = []; + #protectedHeader; + #unprotectedHeader; + #aad; + constructor(plaintext) { + this.#plaintext = plaintext; + } + addRecipient(key, options) { + const recipient = new IndividualRecipient(this, key, { crit: options?.crit }); + this.#recipients.push(recipient); + return recipient; + } + setProtectedHeader(protectedHeader) { + if (this.#protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this.#protectedHeader = protectedHeader; + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + if (this.#unprotectedHeader) { + throw new TypeError('setSharedUnprotectedHeader can only be called once'); + } + this.#unprotectedHeader = sharedUnprotectedHeader; + return this; + } + setAdditionalAuthenticatedData(aad) { + this.#aad = aad; + return this; + } + async encrypt() { + if (!this.#recipients.length) { + throw new JWEInvalid('at least one recipient must be added'); + } + if (this.#recipients.length === 1) { + const [recipient] = this.#recipients; + const flattened = await new FlattenedEncrypt(this.#plaintext) + .setAdditionalAuthenticatedData(this.#aad) + .setProtectedHeader(this.#protectedHeader) + .setSharedUnprotectedHeader(this.#unprotectedHeader) + .setUnprotectedHeader(recipient.unprotectedHeader) + .encrypt(recipient.key, { ...recipient.options }); + const jwe = { + ciphertext: flattened.ciphertext, + iv: flattened.iv, + recipients: [{}], + tag: flattened.tag, + }; + if (flattened.aad) + jwe.aad = flattened.aad; + if (flattened.protected) + jwe.protected = flattened.protected; + if (flattened.unprotected) + jwe.unprotected = flattened.unprotected; + if (flattened.encrypted_key) + jwe.recipients[0].encrypted_key = flattened.encrypted_key; + if (flattened.header) + jwe.recipients[0].header = flattened.header; + return jwe; + } + let enc; + for (let i = 0; i < this.#recipients.length; i++) { + const recipient = this.#recipients[i]; + if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, recipient.unprotectedHeader)) { + throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this.#protectedHeader, + ...this.#unprotectedHeader, + ...recipient.unprotectedHeader, + }; + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (alg === 'dir' || alg === 'ECDH-ES') { + throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); + } + if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + if (!enc) { + enc = joseHeader.enc; + } + else if (enc !== joseHeader.enc) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); + } + validateCrit(JWEInvalid, new Map(), recipient.options.crit, this.#protectedHeader, joseHeader); + if (joseHeader.zip !== undefined) { + throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); + } + } + const cek = generateCek(enc); + const jwe = { + ciphertext: '', + recipients: [], + }; + for (let i = 0; i < this.#recipients.length; i++) { + const recipient = this.#recipients[i]; + const target = {}; + jwe.recipients.push(target); + if (i === 0) { + const flattened = await new FlattenedEncrypt(this.#plaintext) + .setAdditionalAuthenticatedData(this.#aad) + .setContentEncryptionKey(cek) + .setProtectedHeader(this.#protectedHeader) + .setSharedUnprotectedHeader(this.#unprotectedHeader) + .setUnprotectedHeader(recipient.unprotectedHeader) + .setKeyManagementParameters(recipient.keyManagementParameters) + .encrypt(recipient.key, { + ...recipient.options, + [unprotected]: true, + }); + jwe.ciphertext = flattened.ciphertext; + jwe.iv = flattened.iv; + jwe.tag = flattened.tag; + if (flattened.aad) + jwe.aad = flattened.aad; + if (flattened.protected) + jwe.protected = flattened.protected; + if (flattened.unprotected) + jwe.unprotected = flattened.unprotected; + target.encrypted_key = flattened.encrypted_key; + if (flattened.header) + target.header = flattened.header; + continue; + } + const alg = recipient.unprotectedHeader?.alg || + this.#protectedHeader?.alg || + this.#unprotectedHeader?.alg; + checkKeyType(alg === 'dir' ? enc : alg, recipient.key, 'encrypt'); + const k = await normalizeKey(recipient.key, alg); + const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, recipient.keyManagementParameters); + target.encrypted_key = b64u(encryptedKey); + if (recipient.unprotectedHeader || parameters) + target.header = { ...recipient.unprotectedHeader, ...parameters }; + } + return jwe; + } +} diff --git a/node_modules/jose/dist/webapi/jwk/embedded.js b/node_modules/jose/dist/webapi/jwk/embedded.js new file mode 100644 index 000000000..ac716b338 --- /dev/null +++ b/node_modules/jose/dist/webapi/jwk/embedded.js @@ -0,0 +1,17 @@ +import { importJWK } from '../key/import.js'; +import { isObject } from '../lib/is_object.js'; +import { JWSInvalid } from '../util/errors.js'; +export async function EmbeddedJWK(protectedHeader, token) { + const joseHeader = { + ...protectedHeader, + ...token?.header, + }; + if (!isObject(joseHeader.jwk)) { + throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); + } + const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg); + if (key instanceof Uint8Array || key.type !== 'public') { + throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); + } + return key; +} diff --git a/node_modules/jose/dist/webapi/jwk/thumbprint.js b/node_modules/jose/dist/webapi/jwk/thumbprint.js new file mode 100644 index 000000000..51f577244 --- /dev/null +++ b/node_modules/jose/dist/webapi/jwk/thumbprint.js @@ -0,0 +1,68 @@ +import { digest } from '../lib/digest.js'; +import { encode as b64u } from '../util/base64url.js'; +import { JOSENotSupported, JWKInvalid } from '../util/errors.js'; +import { encode } from '../lib/buffer_utils.js'; +import { isKeyLike } from '../lib/is_key_like.js'; +import { isJWK } from '../lib/is_jwk.js'; +import { exportJWK } from '../key/export.js'; +import { invalidKeyInput } from '../lib/invalid_key_input.js'; +const check = (value, description) => { + if (typeof value !== 'string' || !value) { + throw new JWKInvalid(`${description} missing or invalid`); + } +}; +export async function calculateJwkThumbprint(key, digestAlgorithm) { + let jwk; + if (isJWK(key)) { + jwk = key; + } + else if (isKeyLike(key)) { + jwk = await exportJWK(key); + } + else { + throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key')); + } + digestAlgorithm ??= 'sha256'; + if (digestAlgorithm !== 'sha256' && + digestAlgorithm !== 'sha384' && + digestAlgorithm !== 'sha512') { + throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); + } + let components; + switch (jwk.kty) { + case 'AKP': + check(jwk.alg, '"alg" (Algorithm) Parameter'); + check(jwk.pub, '"pub" (Public key) Parameter'); + components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub }; + break; + case 'EC': + check(jwk.crv, '"crv" (Curve) Parameter'); + check(jwk.x, '"x" (X Coordinate) Parameter'); + check(jwk.y, '"y" (Y Coordinate) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; + break; + case 'OKP': + check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); + check(jwk.x, '"x" (Public Key) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; + break; + case 'RSA': + check(jwk.e, '"e" (Exponent) Parameter'); + check(jwk.n, '"n" (Modulus) Parameter'); + components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; + break; + case 'oct': + check(jwk.k, '"k" (Key Value) Parameter'); + components = { k: jwk.k, kty: jwk.kty }; + break; + default: + throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); + } + const data = encode(JSON.stringify(components)); + return b64u(await digest(digestAlgorithm, data)); +} +export async function calculateJwkThumbprintUri(key, digestAlgorithm) { + digestAlgorithm ??= 'sha256'; + const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm); + return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; +} diff --git a/node_modules/jose/dist/webapi/jwks/local.js b/node_modules/jose/dist/webapi/jwks/local.js new file mode 100644 index 000000000..c62bdc79c --- /dev/null +++ b/node_modules/jose/dist/webapi/jwks/local.js @@ -0,0 +1,119 @@ +import { importJWK } from '../key/import.js'; +import { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js'; +import { isObject } from '../lib/is_object.js'; +function getKtyFromAlg(alg) { + switch (typeof alg === 'string' && alg.slice(0, 2)) { + case 'RS': + case 'PS': + return 'RSA'; + case 'ES': + return 'EC'; + case 'Ed': + return 'OKP'; + case 'ML': + return 'AKP'; + default: + throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); + } +} +function isJWKSLike(jwks) { + return (jwks && + typeof jwks === 'object' && + Array.isArray(jwks.keys) && + jwks.keys.every(isJWKLike)); +} +function isJWKLike(key) { + return isObject(key); +} +class LocalJWKSet { + #jwks; + #cached = new WeakMap(); + constructor(jwks) { + if (!isJWKSLike(jwks)) { + throw new JWKSInvalid('JSON Web Key Set malformed'); + } + this.#jwks = structuredClone(jwks); + } + jwks() { + return this.#jwks; + } + async getKey(protectedHeader, token) { + const { alg, kid } = { ...protectedHeader, ...token?.header }; + const kty = getKtyFromAlg(alg); + const candidates = this.#jwks.keys.filter((jwk) => { + let candidate = kty === jwk.kty; + if (candidate && typeof kid === 'string') { + candidate = kid === jwk.kid; + } + if (candidate && (typeof jwk.alg === 'string' || kty === 'AKP')) { + candidate = alg === jwk.alg; + } + if (candidate && typeof jwk.use === 'string') { + candidate = jwk.use === 'sig'; + } + if (candidate && Array.isArray(jwk.key_ops)) { + candidate = jwk.key_ops.includes('verify'); + } + if (candidate) { + switch (alg) { + case 'ES256': + candidate = jwk.crv === 'P-256'; + break; + case 'ES384': + candidate = jwk.crv === 'P-384'; + break; + case 'ES512': + candidate = jwk.crv === 'P-521'; + break; + case 'Ed25519': + case 'EdDSA': + candidate = jwk.crv === 'Ed25519'; + break; + } + } + return candidate; + }); + const { 0: jwk, length } = candidates; + if (length === 0) { + throw new JWKSNoMatchingKey(); + } + if (length !== 1) { + const error = new JWKSMultipleMatchingKeys(); + const _cached = this.#cached; + error[Symbol.asyncIterator] = async function* () { + for (const jwk of candidates) { + try { + yield await importWithAlgCache(_cached, jwk, alg); + } + catch { } + } + }; + throw error; + } + return importWithAlgCache(this.#cached, jwk, alg); + } +} +async function importWithAlgCache(cache, jwk, alg) { + const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); + if (cached[alg] === undefined) { + const key = await importJWK({ ...jwk, ext: true }, alg); + if (key instanceof Uint8Array || key.type !== 'public') { + throw new JWKSInvalid('JSON Web Key Set members must be public keys'); + } + cached[alg] = key; + } + return cached[alg]; +} +export function createLocalJWKSet(jwks) { + const set = new LocalJWKSet(jwks); + const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); + Object.defineProperties(localJWKSet, { + jwks: { + value: () => structuredClone(set.jwks()), + enumerable: false, + configurable: false, + writable: false, + }, + }); + return localJWKSet; +} diff --git a/node_modules/jose/dist/webapi/jwks/remote.js b/node_modules/jose/dist/webapi/jwks/remote.js new file mode 100644 index 000000000..3a7f0d48b --- /dev/null +++ b/node_modules/jose/dist/webapi/jwks/remote.js @@ -0,0 +1,179 @@ +import { JOSEError, JWKSNoMatchingKey, JWKSTimeout } from '../util/errors.js'; +import { createLocalJWKSet } from './local.js'; +import { isObject } from '../lib/is_object.js'; +function isCloudflareWorkers() { + return (typeof WebSocketPair !== 'undefined' || + (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || + (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel')); +} +let USER_AGENT; +if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { + const NAME = 'jose'; + const VERSION = 'v6.1.3'; + USER_AGENT = `${NAME}/${VERSION}`; +} +export const customFetch = Symbol(); +async function fetchJwks(url, headers, signal, fetchImpl = fetch) { + const response = await fetchImpl(url, { + method: 'GET', + signal, + redirect: 'manual', + headers, + }).catch((err) => { + if (err.name === 'TimeoutError') { + throw new JWKSTimeout(); + } + throw err; + }); + if (response.status !== 200) { + throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response'); + } + try { + return await response.json(); + } + catch { + throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON'); + } +} +export const jwksCache = Symbol(); +function isFreshJwksCache(input, cacheMaxAge) { + if (typeof input !== 'object' || input === null) { + return false; + } + if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) { + return false; + } + if (!('jwks' in input) || + !isObject(input.jwks) || + !Array.isArray(input.jwks.keys) || + !Array.prototype.every.call(input.jwks.keys, isObject)) { + return false; + } + return true; +} +class RemoteJWKSet { + #url; + #timeoutDuration; + #cooldownDuration; + #cacheMaxAge; + #jwksTimestamp; + #pendingFetch; + #headers; + #customFetch; + #local; + #cache; + constructor(url, options) { + if (!(url instanceof URL)) { + throw new TypeError('url must be an instance of URL'); + } + this.#url = new URL(url.href); + this.#timeoutDuration = + typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000; + this.#cooldownDuration = + typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000; + this.#cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000; + this.#headers = new Headers(options?.headers); + if (USER_AGENT && !this.#headers.has('User-Agent')) { + this.#headers.set('User-Agent', USER_AGENT); + } + if (!this.#headers.has('accept')) { + this.#headers.set('accept', 'application/json'); + this.#headers.append('accept', 'application/jwk-set+json'); + } + this.#customFetch = options?.[customFetch]; + if (options?.[jwksCache] !== undefined) { + this.#cache = options?.[jwksCache]; + if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) { + this.#jwksTimestamp = this.#cache.uat; + this.#local = createLocalJWKSet(this.#cache.jwks); + } + } + } + pendingFetch() { + return !!this.#pendingFetch; + } + coolingDown() { + return typeof this.#jwksTimestamp === 'number' + ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration + : false; + } + fresh() { + return typeof this.#jwksTimestamp === 'number' + ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge + : false; + } + jwks() { + return this.#local?.jwks(); + } + async getKey(protectedHeader, token) { + if (!this.#local || !this.fresh()) { + await this.reload(); + } + try { + return await this.#local(protectedHeader, token); + } + catch (err) { + if (err instanceof JWKSNoMatchingKey) { + if (this.coolingDown() === false) { + await this.reload(); + return this.#local(protectedHeader, token); + } + } + throw err; + } + } + async reload() { + if (this.#pendingFetch && isCloudflareWorkers()) { + this.#pendingFetch = undefined; + } + this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch) + .then((json) => { + this.#local = createLocalJWKSet(json); + if (this.#cache) { + this.#cache.uat = Date.now(); + this.#cache.jwks = json; + } + this.#jwksTimestamp = Date.now(); + this.#pendingFetch = undefined; + }) + .catch((err) => { + this.#pendingFetch = undefined; + throw err; + }); + await this.#pendingFetch; + } +} +export function createRemoteJWKSet(url, options) { + const set = new RemoteJWKSet(url, options); + const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); + Object.defineProperties(remoteJWKSet, { + coolingDown: { + get: () => set.coolingDown(), + enumerable: true, + configurable: false, + }, + fresh: { + get: () => set.fresh(), + enumerable: true, + configurable: false, + }, + reload: { + value: () => set.reload(), + enumerable: true, + configurable: false, + writable: false, + }, + reloading: { + get: () => set.pendingFetch(), + enumerable: true, + configurable: false, + }, + jwks: { + value: () => set.jwks(), + enumerable: true, + configurable: false, + writable: false, + }, + }); + return remoteJWKSet; +} diff --git a/node_modules/jose/dist/webapi/jws/compact/sign.js b/node_modules/jose/dist/webapi/jws/compact/sign.js new file mode 100644 index 000000000..2069b6d2c --- /dev/null +++ b/node_modules/jose/dist/webapi/jws/compact/sign.js @@ -0,0 +1,18 @@ +import { FlattenedSign } from '../flattened/sign.js'; +export class CompactSign { + #flattened; + constructor(payload) { + this.#flattened = new FlattenedSign(payload); + } + setProtectedHeader(protectedHeader) { + this.#flattened.setProtectedHeader(protectedHeader); + return this; + } + async sign(key, options) { + const jws = await this.#flattened.sign(key, options); + if (jws.payload === undefined) { + throw new TypeError('use the flattened module for creating JWS with b64: false'); + } + return `${jws.protected}.${jws.payload}.${jws.signature}`; + } +} diff --git a/node_modules/jose/dist/webapi/jws/compact/verify.js b/node_modules/jose/dist/webapi/jws/compact/verify.js new file mode 100644 index 000000000..c651ffb94 --- /dev/null +++ b/node_modules/jose/dist/webapi/jws/compact/verify.js @@ -0,0 +1,21 @@ +import { flattenedVerify } from '../flattened/verify.js'; +import { JWSInvalid } from '../../util/errors.js'; +import { decoder } from '../../lib/buffer_utils.js'; +export async function compactVerify(jws, key, options) { + if (jws instanceof Uint8Array) { + jws = decoder.decode(jws); + } + if (typeof jws !== 'string') { + throw new JWSInvalid('Compact JWS must be a string or Uint8Array'); + } + const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.'); + if (length !== 3) { + throw new JWSInvalid('Invalid Compact JWS'); + } + const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); + const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: verified.key }; + } + return result; +} diff --git a/node_modules/jose/dist/webapi/jws/flattened/sign.js b/node_modules/jose/dist/webapi/jws/flattened/sign.js new file mode 100644 index 000000000..e9d4a7dd5 --- /dev/null +++ b/node_modules/jose/dist/webapi/jws/flattened/sign.js @@ -0,0 +1,92 @@ +import { encode as b64u } from '../../util/base64url.js'; +import { sign } from '../../lib/sign.js'; +import { isDisjoint } from '../../lib/is_disjoint.js'; +import { JWSInvalid } from '../../util/errors.js'; +import { concat, encode } from '../../lib/buffer_utils.js'; +import { checkKeyType } from '../../lib/check_key_type.js'; +import { validateCrit } from '../../lib/validate_crit.js'; +import { normalizeKey } from '../../lib/normalize_key.js'; +export class FlattenedSign { + #payload; + #protectedHeader; + #unprotectedHeader; + constructor(payload) { + if (!(payload instanceof Uint8Array)) { + throw new TypeError('payload must be an instance of Uint8Array'); + } + this.#payload = payload; + } + setProtectedHeader(protectedHeader) { + if (this.#protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this.#protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this.#unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this.#unprotectedHeader = unprotectedHeader; + return this; + } + async sign(key, options) { + if (!this.#protectedHeader && !this.#unprotectedHeader) { + throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()'); + } + if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) { + throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this.#protectedHeader, + ...this.#unprotectedHeader, + }; + const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this.#protectedHeader, joseHeader); + let b64 = true; + if (extensions.has('b64')) { + b64 = this.#protectedHeader.b64; + if (typeof b64 !== 'boolean') { + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + checkKeyType(alg, key, 'sign'); + let payloadS; + let payloadB; + if (b64) { + payloadS = b64u(this.#payload); + payloadB = encode(payloadS); + } + else { + payloadB = this.#payload; + payloadS = ''; + } + let protectedHeaderString; + let protectedHeaderBytes; + if (this.#protectedHeader) { + protectedHeaderString = b64u(JSON.stringify(this.#protectedHeader)); + protectedHeaderBytes = encode(protectedHeaderString); + } + else { + protectedHeaderString = ''; + protectedHeaderBytes = new Uint8Array(); + } + const data = concat(protectedHeaderBytes, encode('.'), payloadB); + const k = await normalizeKey(key, alg); + const signature = await sign(alg, k, data); + const jws = { + signature: b64u(signature), + payload: payloadS, + }; + if (this.#unprotectedHeader) { + jws.header = this.#unprotectedHeader; + } + if (this.#protectedHeader) { + jws.protected = protectedHeaderString; + } + return jws; + } +} diff --git a/node_modules/jose/dist/webapi/jws/flattened/verify.js b/node_modules/jose/dist/webapi/jws/flattened/verify.js new file mode 100644 index 000000000..3e749121e --- /dev/null +++ b/node_modules/jose/dist/webapi/jws/flattened/verify.js @@ -0,0 +1,120 @@ +import { decode as b64u } from '../../util/base64url.js'; +import { verify } from '../../lib/verify.js'; +import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; +import { concat, encoder, decoder, encode } from '../../lib/buffer_utils.js'; +import { isDisjoint } from '../../lib/is_disjoint.js'; +import { isObject } from '../../lib/is_object.js'; +import { checkKeyType } from '../../lib/check_key_type.js'; +import { validateCrit } from '../../lib/validate_crit.js'; +import { validateAlgorithms } from '../../lib/validate_algorithms.js'; +import { normalizeKey } from '../../lib/normalize_key.js'; +export async function flattenedVerify(jws, key, options) { + if (!isObject(jws)) { + throw new JWSInvalid('Flattened JWS must be an object'); + } + if (jws.protected === undefined && jws.header === undefined) { + throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); + } + if (jws.protected !== undefined && typeof jws.protected !== 'string') { + throw new JWSInvalid('JWS Protected Header incorrect type'); + } + if (jws.payload === undefined) { + throw new JWSInvalid('JWS Payload missing'); + } + if (typeof jws.signature !== 'string') { + throw new JWSInvalid('JWS Signature missing or incorrect type'); + } + if (jws.header !== undefined && !isObject(jws.header)) { + throw new JWSInvalid('JWS Unprotected Header incorrect type'); + } + let parsedProt = {}; + if (jws.protected) { + try { + const protectedHeader = b64u(jws.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader)); + } + catch { + throw new JWSInvalid('JWS Protected Header is invalid'); + } + } + if (!isDisjoint(parsedProt, jws.header)) { + throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...parsedProt, + ...jws.header, + }; + const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader); + let b64 = true; + if (extensions.has('b64')) { + b64 = parsedProt.b64; + if (typeof b64 !== 'boolean') { + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + const algorithms = options && validateAlgorithms('algorithms', options.algorithms); + if (algorithms && !algorithms.has(alg)) { + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); + } + if (b64) { + if (typeof jws.payload !== 'string') { + throw new JWSInvalid('JWS Payload must be a string'); + } + } + else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { + throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance'); + } + let resolvedKey = false; + if (typeof key === 'function') { + key = await key(parsedProt, jws); + resolvedKey = true; + } + checkKeyType(alg, key, 'verify'); + const data = concat(jws.protected !== undefined ? encode(jws.protected) : new Uint8Array(), encode('.'), typeof jws.payload === 'string' + ? b64 + ? encode(jws.payload) + : encoder.encode(jws.payload) + : jws.payload); + let signature; + try { + signature = b64u(jws.signature); + } + catch { + throw new JWSInvalid('Failed to base64url decode the signature'); + } + const k = await normalizeKey(key, alg); + const verified = await verify(alg, k, signature, data); + if (!verified) { + throw new JWSSignatureVerificationFailed(); + } + let payload; + if (b64) { + try { + payload = b64u(jws.payload); + } + catch { + throw new JWSInvalid('Failed to base64url decode the payload'); + } + } + else if (typeof jws.payload === 'string') { + payload = encoder.encode(jws.payload); + } + else { + payload = jws.payload; + } + const result = { payload }; + if (jws.protected !== undefined) { + result.protectedHeader = parsedProt; + } + if (jws.header !== undefined) { + result.unprotectedHeader = jws.header; + } + if (resolvedKey) { + return { ...result, key: k }; + } + return result; +} diff --git a/node_modules/jose/dist/webapi/jws/general/sign.js b/node_modules/jose/dist/webapi/jws/general/sign.js new file mode 100644 index 000000000..d85de18ef --- /dev/null +++ b/node_modules/jose/dist/webapi/jws/general/sign.js @@ -0,0 +1,73 @@ +import { FlattenedSign } from '../flattened/sign.js'; +import { JWSInvalid } from '../../util/errors.js'; +class IndividualSignature { + #parent; + protectedHeader; + unprotectedHeader; + options; + key; + constructor(sig, key, options) { + this.#parent = sig; + this.key = key; + this.options = options; + } + setProtectedHeader(protectedHeader) { + if (this.protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this.protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this.unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this.unprotectedHeader = unprotectedHeader; + return this; + } + addSignature(...args) { + return this.#parent.addSignature(...args); + } + sign(...args) { + return this.#parent.sign(...args); + } + done() { + return this.#parent; + } +} +export class GeneralSign { + #payload; + #signatures = []; + constructor(payload) { + this.#payload = payload; + } + addSignature(key, options) { + const signature = new IndividualSignature(this, key, options); + this.#signatures.push(signature); + return signature; + } + async sign() { + if (!this.#signatures.length) { + throw new JWSInvalid('at least one signature must be added'); + } + const jws = { + signatures: [], + payload: '', + }; + for (let i = 0; i < this.#signatures.length; i++) { + const signature = this.#signatures[i]; + const flattened = new FlattenedSign(this.#payload); + flattened.setProtectedHeader(signature.protectedHeader); + flattened.setUnprotectedHeader(signature.unprotectedHeader); + const { payload, ...rest } = await flattened.sign(signature.key, signature.options); + if (i === 0) { + jws.payload = payload; + } + else if (jws.payload !== payload) { + throw new JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)'); + } + jws.signatures.push(rest); + } + return jws; + } +} diff --git a/node_modules/jose/dist/webapi/jws/general/verify.js b/node_modules/jose/dist/webapi/jws/general/verify.js new file mode 100644 index 000000000..cb95d385e --- /dev/null +++ b/node_modules/jose/dist/webapi/jws/general/verify.js @@ -0,0 +1,24 @@ +import { flattenedVerify } from '../flattened/verify.js'; +import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; +import { isObject } from '../../lib/is_object.js'; +export async function generalVerify(jws, key, options) { + if (!isObject(jws)) { + throw new JWSInvalid('General JWS must be an object'); + } + if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { + throw new JWSInvalid('JWS Signatures missing or incorrect type'); + } + for (const signature of jws.signatures) { + try { + return await flattenedVerify({ + header: signature.header, + payload: jws.payload, + protected: signature.protected, + signature: signature.signature, + }, key, options); + } + catch { + } + } + throw new JWSSignatureVerificationFailed(); +} diff --git a/node_modules/jose/dist/webapi/jwt/decrypt.js b/node_modules/jose/dist/webapi/jwt/decrypt.js new file mode 100644 index 000000000..d75e3d725 --- /dev/null +++ b/node_modules/jose/dist/webapi/jwt/decrypt.js @@ -0,0 +1,23 @@ +import { compactDecrypt } from '../jwe/compact/decrypt.js'; +import { validateClaimsSet } from '../lib/jwt_claims_set.js'; +import { JWTClaimValidationFailed } from '../util/errors.js'; +export async function jwtDecrypt(jwt, key, options) { + const decrypted = await compactDecrypt(jwt, key, options); + const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options); + const { protectedHeader } = decrypted; + if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { + throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, 'iss', 'mismatch'); + } + if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { + throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, 'sub', 'mismatch'); + } + if (protectedHeader.aud !== undefined && + JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { + throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, 'aud', 'mismatch'); + } + const result = { payload, protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: decrypted.key }; + } + return result; +} diff --git a/node_modules/jose/dist/webapi/jwt/encrypt.js b/node_modules/jose/dist/webapi/jwt/encrypt.js new file mode 100644 index 000000000..44282a883 --- /dev/null +++ b/node_modules/jose/dist/webapi/jwt/encrypt.js @@ -0,0 +1,108 @@ +import { CompactEncrypt } from '../jwe/compact/encrypt.js'; +import { JWTClaimsBuilder } from '../lib/jwt_claims_set.js'; +export class EncryptJWT { + #cek; + #iv; + #keyManagementParameters; + #protectedHeader; + #replicateIssuerAsHeader; + #replicateSubjectAsHeader; + #replicateAudienceAsHeader; + #jwt; + constructor(payload = {}) { + this.#jwt = new JWTClaimsBuilder(payload); + } + setIssuer(issuer) { + this.#jwt.iss = issuer; + return this; + } + setSubject(subject) { + this.#jwt.sub = subject; + return this; + } + setAudience(audience) { + this.#jwt.aud = audience; + return this; + } + setJti(jwtId) { + this.#jwt.jti = jwtId; + return this; + } + setNotBefore(input) { + this.#jwt.nbf = input; + return this; + } + setExpirationTime(input) { + this.#jwt.exp = input; + return this; + } + setIssuedAt(input) { + this.#jwt.iat = input; + return this; + } + setProtectedHeader(protectedHeader) { + if (this.#protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this.#protectedHeader = protectedHeader; + return this; + } + setKeyManagementParameters(parameters) { + if (this.#keyManagementParameters) { + throw new TypeError('setKeyManagementParameters can only be called once'); + } + this.#keyManagementParameters = parameters; + return this; + } + setContentEncryptionKey(cek) { + if (this.#cek) { + throw new TypeError('setContentEncryptionKey can only be called once'); + } + this.#cek = cek; + return this; + } + setInitializationVector(iv) { + if (this.#iv) { + throw new TypeError('setInitializationVector can only be called once'); + } + this.#iv = iv; + return this; + } + replicateIssuerAsHeader() { + this.#replicateIssuerAsHeader = true; + return this; + } + replicateSubjectAsHeader() { + this.#replicateSubjectAsHeader = true; + return this; + } + replicateAudienceAsHeader() { + this.#replicateAudienceAsHeader = true; + return this; + } + async encrypt(key, options) { + const enc = new CompactEncrypt(this.#jwt.data()); + if (this.#protectedHeader && + (this.#replicateIssuerAsHeader || + this.#replicateSubjectAsHeader || + this.#replicateAudienceAsHeader)) { + this.#protectedHeader = { + ...this.#protectedHeader, + iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : undefined, + sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : undefined, + aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : undefined, + }; + } + enc.setProtectedHeader(this.#protectedHeader); + if (this.#iv) { + enc.setInitializationVector(this.#iv); + } + if (this.#cek) { + enc.setContentEncryptionKey(this.#cek); + } + if (this.#keyManagementParameters) { + enc.setKeyManagementParameters(this.#keyManagementParameters); + } + return enc.encrypt(key, options); + } +} diff --git a/node_modules/jose/dist/webapi/jwt/sign.js b/node_modules/jose/dist/webapi/jwt/sign.js new file mode 100644 index 000000000..34b96c37f --- /dev/null +++ b/node_modules/jose/dist/webapi/jwt/sign.js @@ -0,0 +1,52 @@ +import { CompactSign } from '../jws/compact/sign.js'; +import { JWTInvalid } from '../util/errors.js'; +import { JWTClaimsBuilder } from '../lib/jwt_claims_set.js'; +export class SignJWT { + #protectedHeader; + #jwt; + constructor(payload = {}) { + this.#jwt = new JWTClaimsBuilder(payload); + } + setIssuer(issuer) { + this.#jwt.iss = issuer; + return this; + } + setSubject(subject) { + this.#jwt.sub = subject; + return this; + } + setAudience(audience) { + this.#jwt.aud = audience; + return this; + } + setJti(jwtId) { + this.#jwt.jti = jwtId; + return this; + } + setNotBefore(input) { + this.#jwt.nbf = input; + return this; + } + setExpirationTime(input) { + this.#jwt.exp = input; + return this; + } + setIssuedAt(input) { + this.#jwt.iat = input; + return this; + } + setProtectedHeader(protectedHeader) { + this.#protectedHeader = protectedHeader; + return this; + } + async sign(key, options) { + const sig = new CompactSign(this.#jwt.data()); + sig.setProtectedHeader(this.#protectedHeader); + if (Array.isArray(this.#protectedHeader?.crit) && + this.#protectedHeader.crit.includes('b64') && + this.#protectedHeader.b64 === false) { + throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); + } + return sig.sign(key, options); + } +} diff --git a/node_modules/jose/dist/webapi/jwt/unsecured.js b/node_modules/jose/dist/webapi/jwt/unsecured.js new file mode 100644 index 000000000..18a20c83e --- /dev/null +++ b/node_modules/jose/dist/webapi/jwt/unsecured.js @@ -0,0 +1,63 @@ +import * as b64u from '../util/base64url.js'; +import { decoder } from '../lib/buffer_utils.js'; +import { JWTInvalid } from '../util/errors.js'; +import { validateClaimsSet, JWTClaimsBuilder } from '../lib/jwt_claims_set.js'; +export class UnsecuredJWT { + #jwt; + constructor(payload = {}) { + this.#jwt = new JWTClaimsBuilder(payload); + } + encode() { + const header = b64u.encode(JSON.stringify({ alg: 'none' })); + const payload = b64u.encode(this.#jwt.data()); + return `${header}.${payload}.`; + } + setIssuer(issuer) { + this.#jwt.iss = issuer; + return this; + } + setSubject(subject) { + this.#jwt.sub = subject; + return this; + } + setAudience(audience) { + this.#jwt.aud = audience; + return this; + } + setJti(jwtId) { + this.#jwt.jti = jwtId; + return this; + } + setNotBefore(input) { + this.#jwt.nbf = input; + return this; + } + setExpirationTime(input) { + this.#jwt.exp = input; + return this; + } + setIssuedAt(input) { + this.#jwt.iat = input; + return this; + } + static decode(jwt, options) { + if (typeof jwt !== 'string') { + throw new JWTInvalid('Unsecured JWT must be a string'); + } + const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.'); + if (length !== 3 || signature !== '') { + throw new JWTInvalid('Invalid Unsecured JWT'); + } + let header; + try { + header = JSON.parse(decoder.decode(b64u.decode(encodedHeader))); + if (header.alg !== 'none') + throw new Error(); + } + catch { + throw new JWTInvalid('Invalid Unsecured JWT'); + } + const payload = validateClaimsSet(header, b64u.decode(encodedPayload), options); + return { payload, header }; + } +} diff --git a/node_modules/jose/dist/webapi/jwt/verify.js b/node_modules/jose/dist/webapi/jwt/verify.js new file mode 100644 index 000000000..5e4f91559 --- /dev/null +++ b/node_modules/jose/dist/webapi/jwt/verify.js @@ -0,0 +1,15 @@ +import { compactVerify } from '../jws/compact/verify.js'; +import { validateClaimsSet } from '../lib/jwt_claims_set.js'; +import { JWTInvalid } from '../util/errors.js'; +export async function jwtVerify(jwt, key, options) { + const verified = await compactVerify(jwt, key, options); + if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) { + throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); + } + const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options); + const result = { payload, protectedHeader: verified.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: verified.key }; + } + return result; +} diff --git a/node_modules/jose/dist/webapi/key/export.js b/node_modules/jose/dist/webapi/key/export.js new file mode 100644 index 000000000..1d81adb1e --- /dev/null +++ b/node_modules/jose/dist/webapi/key/export.js @@ -0,0 +1,11 @@ +import { toSPKI as exportPublic, toPKCS8 as exportPrivate } from '../lib/asn1.js'; +import { keyToJWK } from '../lib/key_to_jwk.js'; +export async function exportSPKI(key) { + return exportPublic(key); +} +export async function exportPKCS8(key) { + return exportPrivate(key); +} +export async function exportJWK(key) { + return keyToJWK(key); +} diff --git a/node_modules/jose/dist/webapi/key/generate_key_pair.js b/node_modules/jose/dist/webapi/key/generate_key_pair.js new file mode 100644 index 000000000..33d9f5eb5 --- /dev/null +++ b/node_modules/jose/dist/webapi/key/generate_key_pair.js @@ -0,0 +1,97 @@ +import { JOSENotSupported } from '../util/errors.js'; +function getModulusLengthOption(options) { + const modulusLength = options?.modulusLength ?? 2048; + if (typeof modulusLength !== 'number' || modulusLength < 2048) { + throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used'); + } + return modulusLength; +} +export async function generateKeyPair(alg, options) { + let algorithm; + let keyUsages; + switch (alg) { + case 'PS256': + case 'PS384': + case 'PS512': + algorithm = { + name: 'RSA-PSS', + hash: `SHA-${alg.slice(-3)}`, + publicExponent: Uint8Array.of(0x01, 0x00, 0x01), + modulusLength: getModulusLengthOption(options), + }; + keyUsages = ['sign', 'verify']; + break; + case 'RS256': + case 'RS384': + case 'RS512': + algorithm = { + name: 'RSASSA-PKCS1-v1_5', + hash: `SHA-${alg.slice(-3)}`, + publicExponent: Uint8Array.of(0x01, 0x00, 0x01), + modulusLength: getModulusLengthOption(options), + }; + keyUsages = ['sign', 'verify']; + break; + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + algorithm = { + name: 'RSA-OAEP', + hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, + publicExponent: Uint8Array.of(0x01, 0x00, 0x01), + modulusLength: getModulusLengthOption(options), + }; + keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey']; + break; + case 'ES256': + algorithm = { name: 'ECDSA', namedCurve: 'P-256' }; + keyUsages = ['sign', 'verify']; + break; + case 'ES384': + algorithm = { name: 'ECDSA', namedCurve: 'P-384' }; + keyUsages = ['sign', 'verify']; + break; + case 'ES512': + algorithm = { name: 'ECDSA', namedCurve: 'P-521' }; + keyUsages = ['sign', 'verify']; + break; + case 'Ed25519': + case 'EdDSA': { + keyUsages = ['sign', 'verify']; + algorithm = { name: 'Ed25519' }; + break; + } + case 'ML-DSA-44': + case 'ML-DSA-65': + case 'ML-DSA-87': { + keyUsages = ['sign', 'verify']; + algorithm = { name: alg }; + break; + } + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + keyUsages = ['deriveBits']; + const crv = options?.crv ?? 'P-256'; + switch (crv) { + case 'P-256': + case 'P-384': + case 'P-521': { + algorithm = { name: 'ECDH', namedCurve: crv }; + break; + } + case 'X25519': + algorithm = { name: 'X25519' }; + break; + default: + throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519'); + } + break; + } + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages); +} diff --git a/node_modules/jose/dist/webapi/key/generate_secret.js b/node_modules/jose/dist/webapi/key/generate_secret.js new file mode 100644 index 000000000..0fe2a12b1 --- /dev/null +++ b/node_modules/jose/dist/webapi/key/generate_secret.js @@ -0,0 +1,40 @@ +import { JOSENotSupported } from '../util/errors.js'; +export async function generateSecret(alg, options) { + let length; + let algorithm; + let keyUsages; + switch (alg) { + case 'HS256': + case 'HS384': + case 'HS512': + length = parseInt(alg.slice(-3), 10); + algorithm = { name: 'HMAC', hash: `SHA-${length}`, length }; + keyUsages = ['sign', 'verify']; + break; + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + length = parseInt(alg.slice(-3), 10); + return crypto.getRandomValues(new Uint8Array(length >> 3)); + case 'A128KW': + case 'A192KW': + case 'A256KW': + length = parseInt(alg.slice(1, 4), 10); + algorithm = { name: 'AES-KW', length }; + keyUsages = ['wrapKey', 'unwrapKey']; + break; + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + length = parseInt(alg.slice(1, 4), 10); + algorithm = { name: 'AES-GCM', length }; + keyUsages = ['encrypt', 'decrypt']; + break; + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages); +} diff --git a/node_modules/jose/dist/webapi/key/import.js b/node_modules/jose/dist/webapi/key/import.js new file mode 100644 index 000000000..16ba0ce2e --- /dev/null +++ b/node_modules/jose/dist/webapi/key/import.js @@ -0,0 +1,57 @@ +import { decode as decodeBase64URL } from '../util/base64url.js'; +import { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js'; +import { jwkToKey } from '../lib/jwk_to_key.js'; +import { JOSENotSupported } from '../util/errors.js'; +import { isObject } from '../lib/is_object.js'; +export async function importSPKI(spki, alg, options) { + if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { + throw new TypeError('"spki" must be SPKI formatted string'); + } + return fromSPKI(spki, alg, options); +} +export async function importX509(x509, alg, options) { + if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { + throw new TypeError('"x509" must be X.509 formatted string'); + } + return fromX509(x509, alg, options); +} +export async function importPKCS8(pkcs8, alg, options) { + if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { + throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); + } + return fromPKCS8(pkcs8, alg, options); +} +export async function importJWK(jwk, alg, options) { + if (!isObject(jwk)) { + throw new TypeError('JWK must be an object'); + } + let ext; + alg ??= jwk.alg; + ext ??= options?.extractable ?? jwk.ext; + switch (jwk.kty) { + case 'oct': + if (typeof jwk.k !== 'string' || !jwk.k) { + throw new TypeError('missing "k" (Key Value) Parameter value'); + } + return decodeBase64URL(jwk.k); + case 'RSA': + if ('oth' in jwk && jwk.oth !== undefined) { + throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); + } + return jwkToKey({ ...jwk, alg, ext }); + case 'AKP': { + if (typeof jwk.alg !== 'string' || !jwk.alg) { + throw new TypeError('missing "alg" (Algorithm) Parameter value'); + } + if (alg !== undefined && alg !== jwk.alg) { + throw new TypeError('JWK alg and alg option value mismatch'); + } + return jwkToKey({ ...jwk, ext }); + } + case 'EC': + case 'OKP': + return jwkToKey({ ...jwk, alg, ext }); + default: + throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); + } +} diff --git a/node_modules/jose/dist/webapi/lib/aesgcmkw.js b/node_modules/jose/dist/webapi/lib/aesgcmkw.js new file mode 100644 index 000000000..924f4c5cc --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/aesgcmkw.js @@ -0,0 +1,16 @@ +import { encrypt } from './encrypt.js'; +import { decrypt } from './decrypt.js'; +import { encode as b64u } from '../util/base64url.js'; +export async function wrap(alg, key, cek, iv) { + const jweAlgorithm = alg.slice(0, 7); + const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array()); + return { + encryptedKey: wrapped.ciphertext, + iv: b64u(wrapped.iv), + tag: b64u(wrapped.tag), + }; +} +export async function unwrap(alg, key, encryptedKey, iv, tag) { + const jweAlgorithm = alg.slice(0, 7); + return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array()); +} diff --git a/node_modules/jose/dist/webapi/lib/aeskw.js b/node_modules/jose/dist/webapi/lib/aeskw.js new file mode 100644 index 000000000..666b69cae --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/aeskw.js @@ -0,0 +1,25 @@ +import { checkEncCryptoKey } from './crypto_key.js'; +function checkKeySize(key, alg) { + if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) { + throw new TypeError(`Invalid key size for alg: ${alg}`); + } +} +function getCryptoKey(key, alg, usage) { + if (key instanceof Uint8Array) { + return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]); + } + checkEncCryptoKey(key, alg, usage); + return key; +} +export async function wrap(alg, key, cek) { + const cryptoKey = await getCryptoKey(key, alg, 'wrapKey'); + checkKeySize(cryptoKey, alg); + const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, { hash: 'SHA-256', name: 'HMAC' }, true, ['sign']); + return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW')); +} +export async function unwrap(alg, key, encryptedKey) { + const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey'); + checkKeySize(cryptoKey, alg); + const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, cryptoKey, 'AES-KW', { hash: 'SHA-256', name: 'HMAC' }, true, ['sign']); + return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)); +} diff --git a/node_modules/jose/dist/webapi/lib/asn1.js b/node_modules/jose/dist/webapi/lib/asn1.js new file mode 100644 index 000000000..e9cd57015 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/asn1.js @@ -0,0 +1,243 @@ +import { invalidKeyInput } from './invalid_key_input.js'; +import { encodeBase64, decodeBase64 } from '../lib/base64.js'; +import { JOSENotSupported } from '../util/errors.js'; +import { isCryptoKey, isKeyObject } from './is_key_like.js'; +const formatPEM = (b64, descriptor) => { + const newlined = (b64.match(/.{1,64}/g) || []).join('\n'); + return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----`; +}; +const genericExport = async (keyType, keyFormat, key) => { + if (isKeyObject(key)) { + if (key.type !== keyType) { + throw new TypeError(`key is not a ${keyType} key`); + } + return key.export({ format: 'pem', type: keyFormat }); + } + if (!isCryptoKey(key)) { + throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject')); + } + if (!key.extractable) { + throw new TypeError('CryptoKey is not extractable'); + } + if (key.type !== keyType) { + throw new TypeError(`key is not a ${keyType} key`); + } + return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`); +}; +export const toSPKI = (key) => genericExport('public', 'spki', key); +export const toPKCS8 = (key) => genericExport('private', 'pkcs8', key); +const bytesEqual = (a, b) => { + if (a.byteLength !== b.length) + return false; + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) + return false; + } + return true; +}; +const createASN1State = (data) => ({ data, pos: 0 }); +const parseLength = (state) => { + const first = state.data[state.pos++]; + if (first & 0x80) { + const lengthOfLen = first & 0x7f; + let length = 0; + for (let i = 0; i < lengthOfLen; i++) { + length = (length << 8) | state.data[state.pos++]; + } + return length; + } + return first; +}; +const skipElement = (state, count = 1) => { + if (count <= 0) + return; + state.pos++; + const length = parseLength(state); + state.pos += length; + if (count > 1) { + skipElement(state, count - 1); + } +}; +const expectTag = (state, expectedTag, errorMessage) => { + if (state.data[state.pos++] !== expectedTag) { + throw new Error(errorMessage); + } +}; +const getSubarray = (state, length) => { + const result = state.data.subarray(state.pos, state.pos + length); + state.pos += length; + return result; +}; +const parseAlgorithmOID = (state) => { + expectTag(state, 0x06, 'Expected algorithm OID'); + const oidLen = parseLength(state); + return getSubarray(state, oidLen); +}; +function parsePKCS8Header(state) { + expectTag(state, 0x30, 'Invalid PKCS#8 structure'); + parseLength(state); + expectTag(state, 0x02, 'Expected version field'); + const verLen = parseLength(state); + state.pos += verLen; + expectTag(state, 0x30, 'Expected algorithm identifier'); + const algIdLen = parseLength(state); + const algIdStart = state.pos; + return { algIdStart, algIdLength: algIdLen }; +} +function parseSPKIHeader(state) { + expectTag(state, 0x30, 'Invalid SPKI structure'); + parseLength(state); + expectTag(state, 0x30, 'Expected algorithm identifier'); + const algIdLen = parseLength(state); + const algIdStart = state.pos; + return { algIdStart, algIdLength: algIdLen }; +} +const parseECAlgorithmIdentifier = (state) => { + const algOid = parseAlgorithmOID(state); + if (bytesEqual(algOid, [0x2b, 0x65, 0x6e])) { + return 'X25519'; + } + if (!bytesEqual(algOid, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01])) { + throw new Error('Unsupported key algorithm'); + } + expectTag(state, 0x06, 'Expected curve OID'); + const curveOidLen = parseLength(state); + const curveOid = getSubarray(state, curveOidLen); + for (const { name, oid } of [ + { name: 'P-256', oid: [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07] }, + { name: 'P-384', oid: [0x2b, 0x81, 0x04, 0x00, 0x22] }, + { name: 'P-521', oid: [0x2b, 0x81, 0x04, 0x00, 0x23] }, + ]) { + if (bytesEqual(curveOid, oid)) { + return name; + } + } + throw new Error('Unsupported named curve'); +}; +const genericImport = async (keyFormat, keyData, alg, options) => { + let algorithm; + let keyUsages; + const isPublic = keyFormat === 'spki'; + const getSigUsages = () => (isPublic ? ['verify'] : ['sign']); + const getEncUsages = () => isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey']; + switch (alg) { + case 'PS256': + case 'PS384': + case 'PS512': + algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` }; + keyUsages = getSigUsages(); + break; + case 'RS256': + case 'RS384': + case 'RS512': + algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` }; + keyUsages = getSigUsages(); + break; + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + algorithm = { + name: 'RSA-OAEP', + hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, + }; + keyUsages = getEncUsages(); + break; + case 'ES256': + case 'ES384': + case 'ES512': { + const curveMap = { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' }; + algorithm = { name: 'ECDSA', namedCurve: curveMap[alg] }; + keyUsages = getSigUsages(); + break; + } + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + try { + const namedCurve = options.getNamedCurve(keyData); + algorithm = namedCurve === 'X25519' ? { name: 'X25519' } : { name: 'ECDH', namedCurve }; + } + catch (cause) { + throw new JOSENotSupported('Invalid or unsupported key format'); + } + keyUsages = isPublic ? [] : ['deriveBits']; + break; + } + case 'Ed25519': + case 'EdDSA': + algorithm = { name: 'Ed25519' }; + keyUsages = getSigUsages(); + break; + case 'ML-DSA-44': + case 'ML-DSA-65': + case 'ML-DSA-87': + algorithm = { name: alg }; + keyUsages = getSigUsages(); + break; + default: + throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value'); + } + return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages); +}; +const processPEMData = (pem, pattern) => { + return decodeBase64(pem.replace(pattern, '')); +}; +export const fromPKCS8 = (pem, alg, options) => { + const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g); + let opts = options; + if (alg?.startsWith?.('ECDH-ES')) { + opts ||= {}; + opts.getNamedCurve = (keyData) => { + const state = createASN1State(keyData); + parsePKCS8Header(state); + return parseECAlgorithmIdentifier(state); + }; + } + return genericImport('pkcs8', keyData, alg, opts); +}; +export const fromSPKI = (pem, alg, options) => { + const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g); + let opts = options; + if (alg?.startsWith?.('ECDH-ES')) { + opts ||= {}; + opts.getNamedCurve = (keyData) => { + const state = createASN1State(keyData); + parseSPKIHeader(state); + return parseECAlgorithmIdentifier(state); + }; + } + return genericImport('spki', keyData, alg, opts); +}; +function spkiFromX509(buf) { + const state = createASN1State(buf); + expectTag(state, 0x30, 'Invalid certificate structure'); + parseLength(state); + expectTag(state, 0x30, 'Invalid tbsCertificate structure'); + parseLength(state); + if (buf[state.pos] === 0xa0) { + skipElement(state, 6); + } + else { + skipElement(state, 5); + } + const spkiStart = state.pos; + expectTag(state, 0x30, 'Invalid SPKI structure'); + const spkiContentLen = parseLength(state); + return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart)); +} +function extractX509SPKI(x509) { + const derBytes = processPEMData(x509, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g); + return spkiFromX509(derBytes); +} +export const fromX509 = (pem, alg, options) => { + let spki; + try { + spki = extractX509SPKI(pem); + } + catch (cause) { + throw new TypeError('Failed to parse the X.509 certificate', { cause }); + } + return fromSPKI(formatPEM(encodeBase64(spki), 'PUBLIC KEY'), alg, options); +}; diff --git a/node_modules/jose/dist/webapi/lib/base64.js b/node_modules/jose/dist/webapi/lib/base64.js new file mode 100644 index 000000000..0ac97a703 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/base64.js @@ -0,0 +1,22 @@ +export function encodeBase64(input) { + if (Uint8Array.prototype.toBase64) { + return input.toBase64(); + } + const CHUNK_SIZE = 0x8000; + const arr = []; + for (let i = 0; i < input.length; i += CHUNK_SIZE) { + arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE))); + } + return btoa(arr.join('')); +} +export function decodeBase64(encoded) { + if (Uint8Array.fromBase64) { + return Uint8Array.fromBase64(encoded); + } + const binary = atob(encoded); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes; +} diff --git a/node_modules/jose/dist/webapi/lib/buffer_utils.js b/node_modules/jose/dist/webapi/lib/buffer_utils.js new file mode 100644 index 000000000..64fb377fb --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/buffer_utils.js @@ -0,0 +1,43 @@ +export const encoder = new TextEncoder(); +export const decoder = new TextDecoder(); +const MAX_INT32 = 2 ** 32; +export function concat(...buffers) { + const size = buffers.reduce((acc, { length }) => acc + length, 0); + const buf = new Uint8Array(size); + let i = 0; + for (const buffer of buffers) { + buf.set(buffer, i); + i += buffer.length; + } + return buf; +} +function writeUInt32BE(buf, value, offset) { + if (value < 0 || value >= MAX_INT32) { + throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); + } + buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset); +} +export function uint64be(value) { + const high = Math.floor(value / MAX_INT32); + const low = value % MAX_INT32; + const buf = new Uint8Array(8); + writeUInt32BE(buf, high, 0); + writeUInt32BE(buf, low, 4); + return buf; +} +export function uint32be(value) { + const buf = new Uint8Array(4); + writeUInt32BE(buf, value); + return buf; +} +export function encode(string) { + const bytes = new Uint8Array(string.length); + for (let i = 0; i < string.length; i++) { + const code = string.charCodeAt(i); + if (code > 127) { + throw new TypeError('non-ASCII string encountered in encode()'); + } + bytes[i] = code; + } + return bytes; +} diff --git a/node_modules/jose/dist/webapi/lib/cek.js b/node_modules/jose/dist/webapi/lib/cek.js new file mode 100644 index 000000000..d10d2cbd6 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/cek.js @@ -0,0 +1,19 @@ +import { JOSENotSupported } from '../util/errors.js'; +export function cekLength(alg) { + switch (alg) { + case 'A128GCM': + return 128; + case 'A192GCM': + return 192; + case 'A256GCM': + case 'A128CBC-HS256': + return 256; + case 'A192CBC-HS384': + return 384; + case 'A256CBC-HS512': + return 512; + default: + throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); + } +} +export const generateCek = (alg) => crypto.getRandomValues(new Uint8Array(cekLength(alg) >> 3)); diff --git a/node_modules/jose/dist/webapi/lib/check_cek_length.js b/node_modules/jose/dist/webapi/lib/check_cek_length.js new file mode 100644 index 000000000..8baaa1d4a --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/check_cek_length.js @@ -0,0 +1,7 @@ +import { JWEInvalid } from '../util/errors.js'; +export function checkCekLength(cek, expected) { + const actual = cek.byteLength << 3; + if (actual !== expected) { + throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + } +} diff --git a/node_modules/jose/dist/webapi/lib/check_iv_length.js b/node_modules/jose/dist/webapi/lib/check_iv_length.js new file mode 100644 index 000000000..17718b11f --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/check_iv_length.js @@ -0,0 +1,7 @@ +import { JWEInvalid } from '../util/errors.js'; +import { bitLength } from './iv.js'; +export function checkIvLength(enc, iv) { + if (iv.length << 3 !== bitLength(enc)) { + throw new JWEInvalid('Invalid Initialization Vector length'); + } +} diff --git a/node_modules/jose/dist/webapi/lib/check_key_length.js b/node_modules/jose/dist/webapi/lib/check_key_length.js new file mode 100644 index 000000000..8a02c979f --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/check_key_length.js @@ -0,0 +1,8 @@ +export function checkKeyLength(alg, key) { + if (alg.startsWith('RS') || alg.startsWith('PS')) { + const { modulusLength } = key.algorithm; + if (typeof modulusLength !== 'number' || modulusLength < 2048) { + throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); + } + } +} diff --git a/node_modules/jose/dist/webapi/lib/check_key_type.js b/node_modules/jose/dist/webapi/lib/check_key_type.js new file mode 100644 index 000000000..7d22a992f --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/check_key_type.js @@ -0,0 +1,122 @@ +import { withAlg as invalidKeyInput } from './invalid_key_input.js'; +import { isKeyLike } from './is_key_like.js'; +import * as jwk from './is_jwk.js'; +const tag = (key) => key?.[Symbol.toStringTag]; +const jwkMatchesOp = (alg, key, usage) => { + if (key.use !== undefined) { + let expected; + switch (usage) { + case 'sign': + case 'verify': + expected = 'sig'; + break; + case 'encrypt': + case 'decrypt': + expected = 'enc'; + break; + } + if (key.use !== expected) { + throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`); + } + } + if (key.alg !== undefined && key.alg !== alg) { + throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`); + } + if (Array.isArray(key.key_ops)) { + let expectedKeyOp; + switch (true) { + case usage === 'sign' || usage === 'verify': + case alg === 'dir': + case alg.includes('CBC-HS'): + expectedKeyOp = usage; + break; + case alg.startsWith('PBES2'): + expectedKeyOp = 'deriveBits'; + break; + case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg): + if (!alg.includes('GCM') && alg.endsWith('KW')) { + expectedKeyOp = usage === 'encrypt' ? 'wrapKey' : 'unwrapKey'; + } + else { + expectedKeyOp = usage; + } + break; + case usage === 'encrypt' && alg.startsWith('RSA'): + expectedKeyOp = 'wrapKey'; + break; + case usage === 'decrypt': + expectedKeyOp = alg.startsWith('RSA') ? 'unwrapKey' : 'deriveBits'; + break; + } + if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) { + throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`); + } + } + return true; +}; +const symmetricTypeCheck = (alg, key, usage) => { + if (key instanceof Uint8Array) + return; + if (jwk.isJWK(key)) { + if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) + return; + throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); + } + if (!isKeyLike(key)) { + throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key', 'Uint8Array')); + } + if (key.type !== 'secret') { + throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); + } +}; +const asymmetricTypeCheck = (alg, key, usage) => { + if (jwk.isJWK(key)) { + switch (usage) { + case 'decrypt': + case 'sign': + if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) + return; + throw new TypeError(`JSON Web Key for this operation must be a private JWK`); + case 'encrypt': + case 'verify': + if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) + return; + throw new TypeError(`JSON Web Key for this operation must be a public JWK`); + } + } + if (!isKeyLike(key)) { + throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key')); + } + if (key.type === 'secret') { + throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); + } + if (key.type === 'public') { + switch (usage) { + case 'sign': + throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); + case 'decrypt': + throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); + } + } + if (key.type === 'private') { + switch (usage) { + case 'verify': + throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); + case 'encrypt': + throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); + } + } +}; +export function checkKeyType(alg, key, usage) { + switch (alg.substring(0, 2)) { + case 'A1': + case 'A2': + case 'di': + case 'HS': + case 'PB': + symmetricTypeCheck(alg, key, usage); + break; + default: + asymmetricTypeCheck(alg, key, usage); + } +} diff --git a/node_modules/jose/dist/webapi/lib/crypto_key.js b/node_modules/jose/dist/webapi/lib/crypto_key.js new file mode 100644 index 000000000..8154148ab --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/crypto_key.js @@ -0,0 +1,143 @@ +const unusable = (name, prop = 'algorithm.name') => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); +const isAlgorithm = (algorithm, name) => algorithm.name === name; +function getHashLength(hash) { + return parseInt(hash.name.slice(4), 10); +} +function getNamedCurve(alg) { + switch (alg) { + case 'ES256': + return 'P-256'; + case 'ES384': + return 'P-384'; + case 'ES512': + return 'P-521'; + default: + throw new Error('unreachable'); + } +} +function checkUsage(key, usage) { + if (usage && !key.usages.includes(usage)) { + throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`); + } +} +export function checkSigCryptoKey(key, alg, usage) { + switch (alg) { + case 'HS256': + case 'HS384': + case 'HS512': { + if (!isAlgorithm(key.algorithm, 'HMAC')) + throw unusable('HMAC'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'RS256': + case 'RS384': + case 'RS512': { + if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) + throw unusable('RSASSA-PKCS1-v1_5'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'PS256': + case 'PS384': + case 'PS512': { + if (!isAlgorithm(key.algorithm, 'RSA-PSS')) + throw unusable('RSA-PSS'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'Ed25519': + case 'EdDSA': { + if (!isAlgorithm(key.algorithm, 'Ed25519')) + throw unusable('Ed25519'); + break; + } + case 'ML-DSA-44': + case 'ML-DSA-65': + case 'ML-DSA-87': { + if (!isAlgorithm(key.algorithm, alg)) + throw unusable(alg); + break; + } + case 'ES256': + case 'ES384': + case 'ES512': { + if (!isAlgorithm(key.algorithm, 'ECDSA')) + throw unusable('ECDSA'); + const expected = getNamedCurve(alg); + const actual = key.algorithm.namedCurve; + if (actual !== expected) + throw unusable(expected, 'algorithm.namedCurve'); + break; + } + default: + throw new TypeError('CryptoKey does not support this operation'); + } + checkUsage(key, usage); +} +export function checkEncCryptoKey(key, alg, usage) { + switch (alg) { + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': { + if (!isAlgorithm(key.algorithm, 'AES-GCM')) + throw unusable('AES-GCM'); + const expected = parseInt(alg.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, 'algorithm.length'); + break; + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + if (!isAlgorithm(key.algorithm, 'AES-KW')) + throw unusable('AES-KW'); + const expected = parseInt(alg.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, 'algorithm.length'); + break; + } + case 'ECDH': { + switch (key.algorithm.name) { + case 'ECDH': + case 'X25519': + break; + default: + throw unusable('ECDH or X25519'); + } + break; + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': + if (!isAlgorithm(key.algorithm, 'PBKDF2')) + throw unusable('PBKDF2'); + break; + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + if (!isAlgorithm(key.algorithm, 'RSA-OAEP')) + throw unusable('RSA-OAEP'); + const expected = parseInt(alg.slice(9), 10) || 1; + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + default: + throw new TypeError('CryptoKey does not support this operation'); + } + checkUsage(key, usage); +} diff --git a/node_modules/jose/dist/webapi/lib/decrypt.js b/node_modules/jose/dist/webapi/lib/decrypt.js new file mode 100644 index 000000000..efe1e33c2 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/decrypt.js @@ -0,0 +1,106 @@ +import { concat, uint64be } from './buffer_utils.js'; +import { checkIvLength } from './check_iv_length.js'; +import { checkCekLength } from './check_cek_length.js'; +import { JOSENotSupported, JWEDecryptionFailed, JWEInvalid } from '../util/errors.js'; +import { checkEncCryptoKey } from './crypto_key.js'; +import { invalidKeyInput } from './invalid_key_input.js'; +import { isCryptoKey } from './is_key_like.js'; +async function timingSafeEqual(a, b) { + if (!(a instanceof Uint8Array)) { + throw new TypeError('First argument must be a buffer'); + } + if (!(b instanceof Uint8Array)) { + throw new TypeError('Second argument must be a buffer'); + } + const algorithm = { name: 'HMAC', hash: 'SHA-256' }; + const key = (await crypto.subtle.generateKey(algorithm, false, ['sign'])); + const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a)); + const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b)); + let out = 0; + let i = -1; + while (++i < 32) { + out |= aHmac[i] ^ bHmac[i]; + } + return out === 0; +} +async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { + if (!(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, 'Uint8Array')); + } + const keySize = parseInt(enc.slice(1, 4), 10); + const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['decrypt']); + const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), { + hash: `SHA-${keySize << 1}`, + name: 'HMAC', + }, false, ['sign']); + const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); + const expectedTag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3)); + let macCheckPassed; + try { + macCheckPassed = await timingSafeEqual(tag, expectedTag); + } + catch { + } + if (!macCheckPassed) { + throw new JWEDecryptionFailed(); + } + let plaintext; + try { + plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv: iv, name: 'AES-CBC' }, encKey, ciphertext)); + } + catch { + } + if (!plaintext) { + throw new JWEDecryptionFailed(); + } + return plaintext; +} +async function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { + let encKey; + if (cek instanceof Uint8Array) { + encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt']); + } + else { + checkEncCryptoKey(cek, enc, 'decrypt'); + encKey = cek; + } + try { + return new Uint8Array(await crypto.subtle.decrypt({ + additionalData: aad, + iv: iv, + name: 'AES-GCM', + tagLength: 128, + }, encKey, concat(ciphertext, tag))); + } + catch { + throw new JWEDecryptionFailed(); + } +} +export async function decrypt(enc, cek, ciphertext, iv, tag, aad) { + if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, 'CryptoKey', 'KeyObject', 'Uint8Array', 'JSON Web Key')); + } + if (!iv) { + throw new JWEInvalid('JWE Initialization Vector missing'); + } + if (!tag) { + throw new JWEInvalid('JWE Authentication Tag missing'); + } + checkIvLength(enc, iv); + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + if (cek instanceof Uint8Array) + checkCekLength(cek, parseInt(enc.slice(-3), 10)); + return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad); + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + if (cek instanceof Uint8Array) + checkCekLength(cek, parseInt(enc.slice(1, 4), 10)); + return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad); + default: + throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); + } +} diff --git a/node_modules/jose/dist/webapi/lib/decrypt_key_management.js b/node_modules/jose/dist/webapi/lib/decrypt_key_management.js new file mode 100644 index 000000000..1abfc0f0b --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/decrypt_key_management.js @@ -0,0 +1,127 @@ +import * as aeskw from './aeskw.js'; +import * as ecdhes from './ecdhes.js'; +import * as pbes2kw from './pbes2kw.js'; +import * as rsaes from './rsaes.js'; +import { decode as b64u } from '../util/base64url.js'; +import { JOSENotSupported, JWEInvalid } from '../util/errors.js'; +import { cekLength } from '../lib/cek.js'; +import { importJWK } from '../key/import.js'; +import { isObject } from './is_object.js'; +import { unwrap as aesGcmKw } from './aesgcmkw.js'; +import { assertCryptoKey } from './is_key_like.js'; +export async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { + switch (alg) { + case 'dir': { + if (encryptedKey !== undefined) + throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); + return key; + } + case 'ECDH-ES': + if (encryptedKey !== undefined) + throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + if (!isObject(joseHeader.epk)) + throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); + assertCryptoKey(key); + if (!ecdhes.allowed(key)) + throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); + const epk = await importJWK(joseHeader.epk, alg); + assertCryptoKey(epk); + let partyUInfo; + let partyVInfo; + if (joseHeader.apu !== undefined) { + if (typeof joseHeader.apu !== 'string') + throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); + try { + partyUInfo = b64u(joseHeader.apu); + } + catch { + throw new JWEInvalid('Failed to base64url decode the apu'); + } + } + if (joseHeader.apv !== undefined) { + if (typeof joseHeader.apv !== 'string') + throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); + try { + partyVInfo = b64u(joseHeader.apv); + } + catch { + throw new JWEInvalid('Failed to base64url decode the apv'); + } + } + const sharedSecret = await ecdhes.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); + if (alg === 'ECDH-ES') + return sharedSecret; + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + return aeskw.unwrap(alg.slice(-6), sharedSecret, encryptedKey); + } + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + assertCryptoKey(key); + return rsaes.decrypt(alg, key, encryptedKey); + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': { + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + if (typeof joseHeader.p2c !== 'number') + throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); + const p2cLimit = options?.maxPBES2Count || 10_000; + if (joseHeader.p2c > p2cLimit) + throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); + if (typeof joseHeader.p2s !== 'string') + throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); + let p2s; + try { + p2s = b64u(joseHeader.p2s); + } + catch { + throw new JWEInvalid('Failed to base64url decode the p2s'); + } + return pbes2kw.unwrap(alg, key, encryptedKey, joseHeader.p2c, p2s); + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + return aeskw.unwrap(alg, key, encryptedKey); + } + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': { + if (encryptedKey === undefined) + throw new JWEInvalid('JWE Encrypted Key missing'); + if (typeof joseHeader.iv !== 'string') + throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); + if (typeof joseHeader.tag !== 'string') + throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); + let iv; + try { + iv = b64u(joseHeader.iv); + } + catch { + throw new JWEInvalid('Failed to base64url decode the iv'); + } + let tag; + try { + tag = b64u(joseHeader.tag); + } + catch { + throw new JWEInvalid('Failed to base64url decode the tag'); + } + return aesGcmKw(alg, key, encryptedKey, iv, tag); + } + default: { + throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); + } + } +} diff --git a/node_modules/jose/dist/webapi/lib/digest.js b/node_modules/jose/dist/webapi/lib/digest.js new file mode 100644 index 000000000..697ffe98d --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/digest.js @@ -0,0 +1,4 @@ +export async function digest(algorithm, data) { + const subtleDigest = `SHA-${algorithm.slice(-3)}`; + return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); +} diff --git a/node_modules/jose/dist/webapi/lib/ecdhes.js b/node_modules/jose/dist/webapi/lib/ecdhes.js new file mode 100644 index 000000000..4bd950f16 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/ecdhes.js @@ -0,0 +1,52 @@ +import { encode, concat, uint32be } from './buffer_utils.js'; +import { checkEncCryptoKey } from './crypto_key.js'; +import { digest } from './digest.js'; +function lengthAndInput(input) { + return concat(uint32be(input.length), input); +} +async function concatKdf(Z, L, OtherInfo) { + const dkLen = L >> 3; + const hashLen = 32; + const reps = Math.ceil(dkLen / hashLen); + const dk = new Uint8Array(reps * hashLen); + for (let i = 1; i <= reps; i++) { + const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length); + hashInput.set(uint32be(i), 0); + hashInput.set(Z, 4); + hashInput.set(OtherInfo, 4 + Z.length); + const hashResult = await digest('sha256', hashInput); + dk.set(hashResult, (i - 1) * hashLen); + } + return dk.slice(0, dkLen); +} +export async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) { + checkEncCryptoKey(publicKey, 'ECDH'); + checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits'); + const algorithmID = lengthAndInput(encode(algorithm)); + const partyUInfo = lengthAndInput(apu); + const partyVInfo = lengthAndInput(apv); + const suppPubInfo = uint32be(keyLength); + const suppPrivInfo = new Uint8Array(); + const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo); + const Z = new Uint8Array(await crypto.subtle.deriveBits({ + name: publicKey.algorithm.name, + public: publicKey, + }, privateKey, getEcdhBitLength(publicKey))); + return concatKdf(Z, keyLength, otherInfo); +} +function getEcdhBitLength(publicKey) { + if (publicKey.algorithm.name === 'X25519') { + return 256; + } + return (Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3); +} +export function allowed(key) { + switch (key.algorithm.namedCurve) { + case 'P-256': + case 'P-384': + case 'P-521': + return true; + default: + return key.algorithm.name === 'X25519'; + } +} diff --git a/node_modules/jose/dist/webapi/lib/encrypt.js b/node_modules/jose/dist/webapi/lib/encrypt.js new file mode 100644 index 000000000..44853a23e --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/encrypt.js @@ -0,0 +1,74 @@ +import { concat, uint64be } from './buffer_utils.js'; +import { checkIvLength } from './check_iv_length.js'; +import { checkCekLength } from './check_cek_length.js'; +import { checkEncCryptoKey } from './crypto_key.js'; +import { invalidKeyInput } from './invalid_key_input.js'; +import { generateIv } from './iv.js'; +import { JOSENotSupported } from '../util/errors.js'; +import { isCryptoKey } from './is_key_like.js'; +async function cbcEncrypt(enc, plaintext, cek, iv, aad) { + if (!(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, 'Uint8Array')); + } + const keySize = parseInt(enc.slice(1, 4), 10); + const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['encrypt']); + const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), { + hash: `SHA-${keySize << 1}`, + name: 'HMAC', + }, false, ['sign']); + const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ + iv: iv, + name: 'AES-CBC', + }, encKey, plaintext)); + const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); + const tag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3)); + return { ciphertext, tag, iv }; +} +async function gcmEncrypt(enc, plaintext, cek, iv, aad) { + let encKey; + if (cek instanceof Uint8Array) { + encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']); + } + else { + checkEncCryptoKey(cek, enc, 'encrypt'); + encKey = cek; + } + const encrypted = new Uint8Array(await crypto.subtle.encrypt({ + additionalData: aad, + iv: iv, + name: 'AES-GCM', + tagLength: 128, + }, encKey, plaintext)); + const tag = encrypted.slice(-16); + const ciphertext = encrypted.slice(0, -16); + return { ciphertext, tag, iv }; +} +export async function encrypt(enc, plaintext, cek, iv, aad) { + if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, 'CryptoKey', 'KeyObject', 'Uint8Array', 'JSON Web Key')); + } + if (iv) { + checkIvLength(enc, iv); + } + else { + iv = generateIv(enc); + } + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + if (cek instanceof Uint8Array) { + checkCekLength(cek, parseInt(enc.slice(-3), 10)); + } + return cbcEncrypt(enc, plaintext, cek, iv, aad); + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + if (cek instanceof Uint8Array) { + checkCekLength(cek, parseInt(enc.slice(1, 4), 10)); + } + return gcmEncrypt(enc, plaintext, cek, iv, aad); + default: + throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); + } +} diff --git a/node_modules/jose/dist/webapi/lib/encrypt_key_management.js b/node_modules/jose/dist/webapi/lib/encrypt_key_management.js new file mode 100644 index 000000000..da24d0515 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/encrypt_key_management.js @@ -0,0 +1,92 @@ +import * as aeskw from './aeskw.js'; +import * as ecdhes from './ecdhes.js'; +import * as pbes2kw from './pbes2kw.js'; +import * as rsaes from './rsaes.js'; +import { encode as b64u } from '../util/base64url.js'; +import { normalizeKey } from './normalize_key.js'; +import { generateCek, cekLength } from '../lib/cek.js'; +import { JOSENotSupported } from '../util/errors.js'; +import { exportJWK } from '../key/export.js'; +import { wrap as aesGcmKw } from './aesgcmkw.js'; +import { assertCryptoKey } from './is_key_like.js'; +export async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { + let encryptedKey; + let parameters; + let cek; + switch (alg) { + case 'dir': { + cek = key; + break; + } + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + assertCryptoKey(key); + if (!ecdhes.allowed(key)) { + throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); + } + const { apu, apv } = providedParameters; + let ephemeralKey; + if (providedParameters.epk) { + ephemeralKey = (await normalizeKey(providedParameters.epk, alg)); + } + else { + ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ['deriveBits'])).privateKey; + } + const { x, y, crv, kty } = await exportJWK(ephemeralKey); + const sharedSecret = await ecdhes.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); + parameters = { epk: { x, crv, kty } }; + if (kty === 'EC') + parameters.epk.y = y; + if (apu) + parameters.apu = b64u(apu); + if (apv) + parameters.apv = b64u(apv); + if (alg === 'ECDH-ES') { + cek = sharedSecret; + break; + } + cek = providedCek || generateCek(enc); + const kwAlg = alg.slice(-6); + encryptedKey = await aeskw.wrap(kwAlg, sharedSecret, cek); + break; + } + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + cek = providedCek || generateCek(enc); + assertCryptoKey(key); + encryptedKey = await rsaes.encrypt(alg, key, cek); + break; + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': { + cek = providedCek || generateCek(enc); + const { p2c, p2s } = providedParameters; + ({ encryptedKey, ...parameters } = await pbes2kw.wrap(alg, key, cek, p2c, p2s)); + break; + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + cek = providedCek || generateCek(enc); + encryptedKey = await aeskw.wrap(alg, key, cek); + break; + } + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': { + cek = providedCek || generateCek(enc); + const { iv } = providedParameters; + ({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv)); + break; + } + default: { + throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); + } + } + return { cek, encryptedKey, parameters }; +} diff --git a/node_modules/jose/dist/webapi/lib/get_sign_verify_key.js b/node_modules/jose/dist/webapi/lib/get_sign_verify_key.js new file mode 100644 index 000000000..46b1c161a --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/get_sign_verify_key.js @@ -0,0 +1,12 @@ +import { checkSigCryptoKey } from './crypto_key.js'; +import { invalidKeyInput } from './invalid_key_input.js'; +export async function getSigKey(alg, key, usage) { + if (key instanceof Uint8Array) { + if (!alg.startsWith('HS')) { + throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key')); + } + return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]); + } + checkSigCryptoKey(key, alg, usage); + return key; +} diff --git a/node_modules/jose/dist/webapi/lib/invalid_key_input.js b/node_modules/jose/dist/webapi/lib/invalid_key_input.js new file mode 100644 index 000000000..8bb76d4d3 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/invalid_key_input.js @@ -0,0 +1,27 @@ +function message(msg, actual, ...types) { + types = types.filter(Boolean); + if (types.length > 2) { + const last = types.pop(); + msg += `one of type ${types.join(', ')}, or ${last}.`; + } + else if (types.length === 2) { + msg += `one of type ${types[0]} or ${types[1]}.`; + } + else { + msg += `of type ${types[0]}.`; + } + if (actual == null) { + msg += ` Received ${actual}`; + } + else if (typeof actual === 'function' && actual.name) { + msg += ` Received function ${actual.name}`; + } + else if (typeof actual === 'object' && actual != null) { + if (actual.constructor?.name) { + msg += ` Received an instance of ${actual.constructor.name}`; + } + } + return msg; +} +export const invalidKeyInput = (actual, ...types) => message('Key must be ', actual, ...types); +export const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types); diff --git a/node_modules/jose/dist/webapi/lib/is_disjoint.js b/node_modules/jose/dist/webapi/lib/is_disjoint.js new file mode 100644 index 000000000..5230e3b4e --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/is_disjoint.js @@ -0,0 +1,21 @@ +export function isDisjoint(...headers) { + const sources = headers.filter(Boolean); + if (sources.length === 0 || sources.length === 1) { + return true; + } + let acc; + for (const header of sources) { + const parameters = Object.keys(header); + if (!acc || acc.size === 0) { + acc = new Set(parameters); + continue; + } + for (const parameter of parameters) { + if (acc.has(parameter)) { + return false; + } + acc.add(parameter); + } + } + return true; +} diff --git a/node_modules/jose/dist/webapi/lib/is_jwk.js b/node_modules/jose/dist/webapi/lib/is_jwk.js new file mode 100644 index 000000000..017b1dd06 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/is_jwk.js @@ -0,0 +1,6 @@ +import { isObject } from './is_object.js'; +export const isJWK = (key) => isObject(key) && typeof key.kty === 'string'; +export const isPrivateJWK = (key) => key.kty !== 'oct' && + ((key.kty === 'AKP' && typeof key.priv === 'string') || typeof key.d === 'string'); +export const isPublicJWK = (key) => key.kty !== 'oct' && key.d === undefined && key.priv === undefined; +export const isSecretJWK = (key) => key.kty === 'oct' && typeof key.k === 'string'; diff --git a/node_modules/jose/dist/webapi/lib/is_key_like.js b/node_modules/jose/dist/webapi/lib/is_key_like.js new file mode 100644 index 000000000..8b65dc2da --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/is_key_like.js @@ -0,0 +1,17 @@ +export function assertCryptoKey(key) { + if (!isCryptoKey(key)) { + throw new Error('CryptoKey instance expected'); + } +} +export const isCryptoKey = (key) => { + if (key?.[Symbol.toStringTag] === 'CryptoKey') + return true; + try { + return key instanceof CryptoKey; + } + catch { + return false; + } +}; +export const isKeyObject = (key) => key?.[Symbol.toStringTag] === 'KeyObject'; +export const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key); diff --git a/node_modules/jose/dist/webapi/lib/is_object.js b/node_modules/jose/dist/webapi/lib/is_object.js new file mode 100644 index 000000000..246e61d67 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/is_object.js @@ -0,0 +1,14 @@ +const isObjectLike = (value) => typeof value === 'object' && value !== null; +export function isObject(input) { + if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') { + return false; + } + if (Object.getPrototypeOf(input) === null) { + return true; + } + let proto = input; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(input) === proto; +} diff --git a/node_modules/jose/dist/webapi/lib/iv.js b/node_modules/jose/dist/webapi/lib/iv.js new file mode 100644 index 000000000..53427298b --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/iv.js @@ -0,0 +1,19 @@ +import { JOSENotSupported } from '../util/errors.js'; +export function bitLength(alg) { + switch (alg) { + case 'A128GCM': + case 'A128GCMKW': + case 'A192GCM': + case 'A192GCMKW': + case 'A256GCM': + case 'A256GCMKW': + return 96; + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + return 128; + default: + throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); + } +} +export const generateIv = (alg) => crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3)); diff --git a/node_modules/jose/dist/webapi/lib/jwk_to_key.js b/node_modules/jose/dist/webapi/lib/jwk_to_key.js new file mode 100644 index 000000000..1210d6710 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/jwk_to_key.js @@ -0,0 +1,109 @@ +import { JOSENotSupported } from '../util/errors.js'; +function subtleMapping(jwk) { + let algorithm; + let keyUsages; + switch (jwk.kty) { + case 'AKP': { + switch (jwk.alg) { + case 'ML-DSA-44': + case 'ML-DSA-65': + case 'ML-DSA-87': + algorithm = { name: jwk.alg }; + keyUsages = jwk.priv ? ['sign'] : ['verify']; + break; + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + break; + } + case 'RSA': { + switch (jwk.alg) { + case 'PS256': + case 'PS384': + case 'PS512': + algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` }; + keyUsages = jwk.d ? ['sign'] : ['verify']; + break; + case 'RS256': + case 'RS384': + case 'RS512': + algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` }; + keyUsages = jwk.d ? ['sign'] : ['verify']; + break; + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + algorithm = { + name: 'RSA-OAEP', + hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`, + }; + keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey']; + break; + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + break; + } + case 'EC': { + switch (jwk.alg) { + case 'ES256': + algorithm = { name: 'ECDSA', namedCurve: 'P-256' }; + keyUsages = jwk.d ? ['sign'] : ['verify']; + break; + case 'ES384': + algorithm = { name: 'ECDSA', namedCurve: 'P-384' }; + keyUsages = jwk.d ? ['sign'] : ['verify']; + break; + case 'ES512': + algorithm = { name: 'ECDSA', namedCurve: 'P-521' }; + keyUsages = jwk.d ? ['sign'] : ['verify']; + break; + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': + algorithm = { name: 'ECDH', namedCurve: jwk.crv }; + keyUsages = jwk.d ? ['deriveBits'] : []; + break; + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + break; + } + case 'OKP': { + switch (jwk.alg) { + case 'Ed25519': + case 'EdDSA': + algorithm = { name: 'Ed25519' }; + keyUsages = jwk.d ? ['sign'] : ['verify']; + break; + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': + algorithm = { name: jwk.crv }; + keyUsages = jwk.d ? ['deriveBits'] : []; + break; + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + break; + } + default: + throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); + } + return { algorithm, keyUsages }; +} +export async function jwkToKey(jwk) { + if (!jwk.alg) { + throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); + } + const { algorithm, keyUsages } = subtleMapping(jwk); + const keyData = { ...jwk }; + if (keyData.kty !== 'AKP') { + delete keyData.alg; + } + delete keyData.use; + return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages); +} diff --git a/node_modules/jose/dist/webapi/lib/jwt_claims_set.js b/node_modules/jose/dist/webapi/lib/jwt_claims_set.js new file mode 100644 index 000000000..86976a869 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/jwt_claims_set.js @@ -0,0 +1,238 @@ +import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js'; +import { encoder, decoder } from './buffer_utils.js'; +import { isObject } from './is_object.js'; +const epoch = (date) => Math.floor(date.getTime() / 1000); +const minute = 60; +const hour = minute * 60; +const day = hour * 24; +const week = day * 7; +const year = day * 365.25; +const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; +export function secs(str) { + const matched = REGEX.exec(str); + if (!matched || (matched[4] && matched[1])) { + throw new TypeError('Invalid time period format'); + } + const value = parseFloat(matched[2]); + const unit = matched[3].toLowerCase(); + let numericDate; + switch (unit) { + case 'sec': + case 'secs': + case 'second': + case 'seconds': + case 's': + numericDate = Math.round(value); + break; + case 'minute': + case 'minutes': + case 'min': + case 'mins': + case 'm': + numericDate = Math.round(value * minute); + break; + case 'hour': + case 'hours': + case 'hr': + case 'hrs': + case 'h': + numericDate = Math.round(value * hour); + break; + case 'day': + case 'days': + case 'd': + numericDate = Math.round(value * day); + break; + case 'week': + case 'weeks': + case 'w': + numericDate = Math.round(value * week); + break; + default: + numericDate = Math.round(value * year); + break; + } + if (matched[1] === '-' || matched[4] === 'ago') { + return -numericDate; + } + return numericDate; +} +function validateInput(label, input) { + if (!Number.isFinite(input)) { + throw new TypeError(`Invalid ${label} input`); + } + return input; +} +const normalizeTyp = (value) => { + if (value.includes('/')) { + return value.toLowerCase(); + } + return `application/${value.toLowerCase()}`; +}; +const checkAudiencePresence = (audPayload, audOption) => { + if (typeof audPayload === 'string') { + return audOption.includes(audPayload); + } + if (Array.isArray(audPayload)) { + return audOption.some(Set.prototype.has.bind(new Set(audPayload))); + } + return false; +}; +export function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { + let payload; + try { + payload = JSON.parse(decoder.decode(encodedPayload)); + } + catch { + } + if (!isObject(payload)) { + throw new JWTInvalid('JWT Claims Set must be a top-level JSON object'); + } + const { typ } = options; + if (typ && + (typeof protectedHeader.typ !== 'string' || + normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { + throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed'); + } + const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; + const presenceCheck = [...requiredClaims]; + if (maxTokenAge !== undefined) + presenceCheck.push('iat'); + if (audience !== undefined) + presenceCheck.push('aud'); + if (subject !== undefined) + presenceCheck.push('sub'); + if (issuer !== undefined) + presenceCheck.push('iss'); + for (const claim of new Set(presenceCheck.reverse())) { + if (!(claim in payload)) { + throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing'); + } + } + if (issuer && + !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { + throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed'); + } + if (subject && payload.sub !== subject) { + throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed'); + } + if (audience && + !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) { + throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed'); + } + let tolerance; + switch (typeof options.clockTolerance) { + case 'string': + tolerance = secs(options.clockTolerance); + break; + case 'number': + tolerance = options.clockTolerance; + break; + case 'undefined': + tolerance = 0; + break; + default: + throw new TypeError('Invalid clockTolerance option type'); + } + const { currentDate } = options; + const now = epoch(currentDate || new Date()); + if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') { + throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid'); + } + if (payload.nbf !== undefined) { + if (typeof payload.nbf !== 'number') { + throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid'); + } + if (payload.nbf > now + tolerance) { + throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed'); + } + } + if (payload.exp !== undefined) { + if (typeof payload.exp !== 'number') { + throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid'); + } + if (payload.exp <= now - tolerance) { + throw new JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed'); + } + } + if (maxTokenAge) { + const age = now - payload.iat; + const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge); + if (age - tolerance > max) { + throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed'); + } + if (age < 0 - tolerance) { + throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed'); + } + } + return payload; +} +export class JWTClaimsBuilder { + #payload; + constructor(payload) { + if (!isObject(payload)) { + throw new TypeError('JWT Claims Set MUST be an object'); + } + this.#payload = structuredClone(payload); + } + data() { + return encoder.encode(JSON.stringify(this.#payload)); + } + get iss() { + return this.#payload.iss; + } + set iss(value) { + this.#payload.iss = value; + } + get sub() { + return this.#payload.sub; + } + set sub(value) { + this.#payload.sub = value; + } + get aud() { + return this.#payload.aud; + } + set aud(value) { + this.#payload.aud = value; + } + set jti(value) { + this.#payload.jti = value; + } + set nbf(value) { + if (typeof value === 'number') { + this.#payload.nbf = validateInput('setNotBefore', value); + } + else if (value instanceof Date) { + this.#payload.nbf = validateInput('setNotBefore', epoch(value)); + } + else { + this.#payload.nbf = epoch(new Date()) + secs(value); + } + } + set exp(value) { + if (typeof value === 'number') { + this.#payload.exp = validateInput('setExpirationTime', value); + } + else if (value instanceof Date) { + this.#payload.exp = validateInput('setExpirationTime', epoch(value)); + } + else { + this.#payload.exp = epoch(new Date()) + secs(value); + } + } + set iat(value) { + if (value === undefined) { + this.#payload.iat = epoch(new Date()); + } + else if (value instanceof Date) { + this.#payload.iat = validateInput('setIssuedAt', epoch(value)); + } + else if (typeof value === 'string') { + this.#payload.iat = validateInput('setIssuedAt', epoch(new Date()) + secs(value)); + } + else { + this.#payload.iat = validateInput('setIssuedAt', value); + } + } +} diff --git a/node_modules/jose/dist/webapi/lib/key_to_jwk.js b/node_modules/jose/dist/webapi/lib/key_to_jwk.js new file mode 100644 index 000000000..a236d25fb --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/key_to_jwk.js @@ -0,0 +1,31 @@ +import { invalidKeyInput } from './invalid_key_input.js'; +import { encode as b64u } from '../util/base64url.js'; +import { isCryptoKey, isKeyObject } from './is_key_like.js'; +export async function keyToJWK(key) { + if (isKeyObject(key)) { + if (key.type === 'secret') { + key = key.export(); + } + else { + return key.export({ format: 'jwk' }); + } + } + if (key instanceof Uint8Array) { + return { + kty: 'oct', + k: b64u(key), + }; + } + if (!isCryptoKey(key)) { + throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'Uint8Array')); + } + if (!key.extractable) { + throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK'); + } + const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key); + if (jwk.kty === 'AKP') { + ; + jwk.alg = alg; + } + return jwk; +} diff --git a/node_modules/jose/dist/webapi/lib/normalize_key.js b/node_modules/jose/dist/webapi/lib/normalize_key.js new file mode 100644 index 000000000..fa8b709ef --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/normalize_key.js @@ -0,0 +1,176 @@ +import { isJWK } from './is_jwk.js'; +import { decode } from '../util/base64url.js'; +import { jwkToKey } from './jwk_to_key.js'; +import { isCryptoKey, isKeyObject } from './is_key_like.js'; +let cache; +const handleJWK = async (key, jwk, alg, freeze = false) => { + cache ||= new WeakMap(); + let cached = cache.get(key); + if (cached?.[alg]) { + return cached[alg]; + } + const cryptoKey = await jwkToKey({ ...jwk, alg }); + if (freeze) + Object.freeze(key); + if (!cached) { + cache.set(key, { [alg]: cryptoKey }); + } + else { + cached[alg] = cryptoKey; + } + return cryptoKey; +}; +const handleKeyObject = (keyObject, alg) => { + cache ||= new WeakMap(); + let cached = cache.get(keyObject); + if (cached?.[alg]) { + return cached[alg]; + } + const isPublic = keyObject.type === 'public'; + const extractable = isPublic ? true : false; + let cryptoKey; + if (keyObject.asymmetricKeyType === 'x25519') { + switch (alg) { + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': + break; + default: + throw new TypeError('given KeyObject instance cannot be used for this algorithm'); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ['deriveBits']); + } + if (keyObject.asymmetricKeyType === 'ed25519') { + if (alg !== 'EdDSA' && alg !== 'Ed25519') { + throw new TypeError('given KeyObject instance cannot be used for this algorithm'); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ + isPublic ? 'verify' : 'sign', + ]); + } + switch (keyObject.asymmetricKeyType) { + case 'ml-dsa-44': + case 'ml-dsa-65': + case 'ml-dsa-87': { + if (alg !== keyObject.asymmetricKeyType.toUpperCase()) { + throw new TypeError('given KeyObject instance cannot be used for this algorithm'); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ + isPublic ? 'verify' : 'sign', + ]); + } + } + if (keyObject.asymmetricKeyType === 'rsa') { + let hash; + switch (alg) { + case 'RSA-OAEP': + hash = 'SHA-1'; + break; + case 'RS256': + case 'PS256': + case 'RSA-OAEP-256': + hash = 'SHA-256'; + break; + case 'RS384': + case 'PS384': + case 'RSA-OAEP-384': + hash = 'SHA-384'; + break; + case 'RS512': + case 'PS512': + case 'RSA-OAEP-512': + hash = 'SHA-512'; + break; + default: + throw new TypeError('given KeyObject instance cannot be used for this algorithm'); + } + if (alg.startsWith('RSA-OAEP')) { + return keyObject.toCryptoKey({ + name: 'RSA-OAEP', + hash, + }, extractable, isPublic ? ['encrypt'] : ['decrypt']); + } + cryptoKey = keyObject.toCryptoKey({ + name: alg.startsWith('PS') ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5', + hash, + }, extractable, [isPublic ? 'verify' : 'sign']); + } + if (keyObject.asymmetricKeyType === 'ec') { + const nist = new Map([ + ['prime256v1', 'P-256'], + ['secp384r1', 'P-384'], + ['secp521r1', 'P-521'], + ]); + const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve); + if (!namedCurve) { + throw new TypeError('given KeyObject instance cannot be used for this algorithm'); + } + if (alg === 'ES256' && namedCurve === 'P-256') { + cryptoKey = keyObject.toCryptoKey({ + name: 'ECDSA', + namedCurve, + }, extractable, [isPublic ? 'verify' : 'sign']); + } + if (alg === 'ES384' && namedCurve === 'P-384') { + cryptoKey = keyObject.toCryptoKey({ + name: 'ECDSA', + namedCurve, + }, extractable, [isPublic ? 'verify' : 'sign']); + } + if (alg === 'ES512' && namedCurve === 'P-521') { + cryptoKey = keyObject.toCryptoKey({ + name: 'ECDSA', + namedCurve, + }, extractable, [isPublic ? 'verify' : 'sign']); + } + if (alg.startsWith('ECDH-ES')) { + cryptoKey = keyObject.toCryptoKey({ + name: 'ECDH', + namedCurve, + }, extractable, isPublic ? [] : ['deriveBits']); + } + } + if (!cryptoKey) { + throw new TypeError('given KeyObject instance cannot be used for this algorithm'); + } + if (!cached) { + cache.set(keyObject, { [alg]: cryptoKey }); + } + else { + cached[alg] = cryptoKey; + } + return cryptoKey; +}; +export async function normalizeKey(key, alg) { + if (key instanceof Uint8Array) { + return key; + } + if (isCryptoKey(key)) { + return key; + } + if (isKeyObject(key)) { + if (key.type === 'secret') { + return key.export(); + } + if ('toCryptoKey' in key && typeof key.toCryptoKey === 'function') { + try { + return handleKeyObject(key, alg); + } + catch (err) { + if (err instanceof TypeError) { + throw err; + } + } + } + let jwk = key.export({ format: 'jwk' }); + return handleJWK(key, jwk, alg); + } + if (isJWK(key)) { + if (key.k) { + return decode(key.k); + } + return handleJWK(key, key, alg, true); + } + throw new Error('unreachable'); +} diff --git a/node_modules/jose/dist/webapi/lib/pbes2kw.js b/node_modules/jose/dist/webapi/lib/pbes2kw.js new file mode 100644 index 000000000..2b0c20c0a --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/pbes2kw.js @@ -0,0 +1,39 @@ +import { encode as b64u } from '../util/base64url.js'; +import * as aeskw from './aeskw.js'; +import { checkEncCryptoKey } from './crypto_key.js'; +import { concat, encode } from './buffer_utils.js'; +import { JWEInvalid } from '../util/errors.js'; +function getCryptoKey(key, alg) { + if (key instanceof Uint8Array) { + return crypto.subtle.importKey('raw', key, 'PBKDF2', false, [ + 'deriveBits', + ]); + } + checkEncCryptoKey(key, alg, 'deriveBits'); + return key; +} +const concatSalt = (alg, p2sInput) => concat(encode(alg), Uint8Array.of(0x00), p2sInput); +async function deriveKey(p2s, alg, p2c, key) { + if (!(p2s instanceof Uint8Array) || p2s.length < 8) { + throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets'); + } + const salt = concatSalt(alg, p2s); + const keylen = parseInt(alg.slice(13, 16), 10); + const subtleAlg = { + hash: `SHA-${alg.slice(8, 11)}`, + iterations: p2c, + name: 'PBKDF2', + salt, + }; + const cryptoKey = await getCryptoKey(key, alg); + return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); +} +export async function wrap(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) { + const derived = await deriveKey(p2s, alg, p2c, key); + const encryptedKey = await aeskw.wrap(alg.slice(-6), derived, cek); + return { encryptedKey, p2c, p2s: b64u(p2s) }; +} +export async function unwrap(alg, key, encryptedKey, p2c, p2s) { + const derived = await deriveKey(p2s, alg, p2c, key); + return aeskw.unwrap(alg.slice(-6), derived, encryptedKey); +} diff --git a/node_modules/jose/dist/webapi/lib/private_symbols.js b/node_modules/jose/dist/webapi/lib/private_symbols.js new file mode 100644 index 000000000..fce302b11 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/private_symbols.js @@ -0,0 +1 @@ +export const unprotected = Symbol(); diff --git a/node_modules/jose/dist/webapi/lib/rsaes.js b/node_modules/jose/dist/webapi/lib/rsaes.js new file mode 100644 index 000000000..a1f48fa4c --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/rsaes.js @@ -0,0 +1,24 @@ +import { checkEncCryptoKey } from './crypto_key.js'; +import { checkKeyLength } from './check_key_length.js'; +import { JOSENotSupported } from '../util/errors.js'; +const subtleAlgorithm = (alg) => { + switch (alg) { + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + return 'RSA-OAEP'; + default: + throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } +}; +export async function encrypt(alg, key, cek) { + checkEncCryptoKey(key, alg, 'encrypt'); + checkKeyLength(alg, key); + return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek)); +} +export async function decrypt(alg, key, encryptedKey) { + checkEncCryptoKey(key, alg, 'decrypt'); + checkKeyLength(alg, key); + return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey)); +} diff --git a/node_modules/jose/dist/webapi/lib/sign.js b/node_modules/jose/dist/webapi/lib/sign.js new file mode 100644 index 000000000..baf41d1e7 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/sign.js @@ -0,0 +1,9 @@ +import { subtleAlgorithm } from './subtle_dsa.js'; +import { checkKeyLength } from './check_key_length.js'; +import { getSigKey } from './get_sign_verify_key.js'; +export async function sign(alg, key, data) { + const cryptoKey = await getSigKey(alg, key, 'sign'); + checkKeyLength(alg, cryptoKey); + const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data); + return new Uint8Array(signature); +} diff --git a/node_modules/jose/dist/webapi/lib/subtle_dsa.js b/node_modules/jose/dist/webapi/lib/subtle_dsa.js new file mode 100644 index 000000000..0c72c2914 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/subtle_dsa.js @@ -0,0 +1,31 @@ +import { JOSENotSupported } from '../util/errors.js'; +export function subtleAlgorithm(alg, algorithm) { + const hash = `SHA-${alg.slice(-3)}`; + switch (alg) { + case 'HS256': + case 'HS384': + case 'HS512': + return { hash, name: 'HMAC' }; + case 'PS256': + case 'PS384': + case 'PS512': + return { hash, name: 'RSA-PSS', saltLength: parseInt(alg.slice(-3), 10) >> 3 }; + case 'RS256': + case 'RS384': + case 'RS512': + return { hash, name: 'RSASSA-PKCS1-v1_5' }; + case 'ES256': + case 'ES384': + case 'ES512': + return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve }; + case 'Ed25519': + case 'EdDSA': + return { name: 'Ed25519' }; + case 'ML-DSA-44': + case 'ML-DSA-65': + case 'ML-DSA-87': + return { name: alg }; + default: + throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } +} diff --git a/node_modules/jose/dist/webapi/lib/validate_algorithms.js b/node_modules/jose/dist/webapi/lib/validate_algorithms.js new file mode 100644 index 000000000..3417f3f56 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/validate_algorithms.js @@ -0,0 +1,10 @@ +export function validateAlgorithms(option, algorithms) { + if (algorithms !== undefined && + (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) { + throw new TypeError(`"${option}" option must be an array of strings`); + } + if (!algorithms) { + return undefined; + } + return new Set(algorithms); +} diff --git a/node_modules/jose/dist/webapi/lib/validate_crit.js b/node_modules/jose/dist/webapi/lib/validate_crit.js new file mode 100644 index 000000000..44e77e322 --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/validate_crit.js @@ -0,0 +1,33 @@ +import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.js'; +export function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { + if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) { + throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); + } + if (!protectedHeader || protectedHeader.crit === undefined) { + return new Set(); + } + if (!Array.isArray(protectedHeader.crit) || + protectedHeader.crit.length === 0 || + protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) { + throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); + } + let recognized; + if (recognizedOption !== undefined) { + recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); + } + else { + recognized = recognizedDefault; + } + for (const parameter of protectedHeader.crit) { + if (!recognized.has(parameter)) { + throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); + } + if (joseHeader[parameter] === undefined) { + throw new Err(`Extension Header Parameter "${parameter}" is missing`); + } + if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { + throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); + } + } + return new Set(protectedHeader.crit); +} diff --git a/node_modules/jose/dist/webapi/lib/verify.js b/node_modules/jose/dist/webapi/lib/verify.js new file mode 100644 index 000000000..9470af5bb --- /dev/null +++ b/node_modules/jose/dist/webapi/lib/verify.js @@ -0,0 +1,14 @@ +import { subtleAlgorithm } from './subtle_dsa.js'; +import { checkKeyLength } from './check_key_length.js'; +import { getSigKey } from './get_sign_verify_key.js'; +export async function verify(alg, key, signature, data) { + const cryptoKey = await getSigKey(alg, key, 'verify'); + checkKeyLength(alg, cryptoKey); + const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm); + try { + return await crypto.subtle.verify(algorithm, cryptoKey, signature, data); + } + catch { + return false; + } +} diff --git a/node_modules/jose/dist/webapi/util/base64url.js b/node_modules/jose/dist/webapi/util/base64url.js new file mode 100644 index 000000000..d18f1f594 --- /dev/null +++ b/node_modules/jose/dist/webapi/util/base64url.js @@ -0,0 +1,30 @@ +import { encoder, decoder } from '../lib/buffer_utils.js'; +import { encodeBase64, decodeBase64 } from '../lib/base64.js'; +export function decode(input) { + if (Uint8Array.fromBase64) { + return Uint8Array.fromBase64(typeof input === 'string' ? input : decoder.decode(input), { + alphabet: 'base64url', + }); + } + let encoded = input; + if (encoded instanceof Uint8Array) { + encoded = decoder.decode(encoded); + } + encoded = encoded.replace(/-/g, '+').replace(/_/g, '/'); + try { + return decodeBase64(encoded); + } + catch { + throw new TypeError('The input to be decoded is not correctly encoded.'); + } +} +export function encode(input) { + let unencoded = input; + if (typeof unencoded === 'string') { + unencoded = encoder.encode(unencoded); + } + if (Uint8Array.prototype.toBase64) { + return unencoded.toBase64({ alphabet: 'base64url', omitPadding: true }); + } + return encodeBase64(unencoded).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); +} diff --git a/node_modules/jose/dist/webapi/util/decode_jwt.js b/node_modules/jose/dist/webapi/util/decode_jwt.js new file mode 100644 index 000000000..93d84f04b --- /dev/null +++ b/node_modules/jose/dist/webapi/util/decode_jwt.js @@ -0,0 +1,32 @@ +import { decode as b64u } from './base64url.js'; +import { decoder } from '../lib/buffer_utils.js'; +import { isObject } from '../lib/is_object.js'; +import { JWTInvalid } from './errors.js'; +export function decodeJwt(jwt) { + if (typeof jwt !== 'string') + throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string'); + const { 1: payload, length } = jwt.split('.'); + if (length === 5) + throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded'); + if (length !== 3) + throw new JWTInvalid('Invalid JWT'); + if (!payload) + throw new JWTInvalid('JWTs must contain a payload'); + let decoded; + try { + decoded = b64u(payload); + } + catch { + throw new JWTInvalid('Failed to base64url decode the payload'); + } + let result; + try { + result = JSON.parse(decoder.decode(decoded)); + } + catch { + throw new JWTInvalid('Failed to parse the decoded payload as JSON'); + } + if (!isObject(result)) + throw new JWTInvalid('Invalid JWT Claims Set'); + return result; +} diff --git a/node_modules/jose/dist/webapi/util/decode_protected_header.js b/node_modules/jose/dist/webapi/util/decode_protected_header.js new file mode 100644 index 000000000..a6da5a63e --- /dev/null +++ b/node_modules/jose/dist/webapi/util/decode_protected_header.js @@ -0,0 +1,34 @@ +import { decode as b64u } from './base64url.js'; +import { decoder } from '../lib/buffer_utils.js'; +import { isObject } from '../lib/is_object.js'; +export function decodeProtectedHeader(token) { + let protectedB64u; + if (typeof token === 'string') { + const parts = token.split('.'); + if (parts.length === 3 || parts.length === 5) { + ; + [protectedB64u] = parts; + } + } + else if (typeof token === 'object' && token) { + if ('protected' in token) { + protectedB64u = token.protected; + } + else { + throw new TypeError('Token does not contain a Protected Header'); + } + } + try { + if (typeof protectedB64u !== 'string' || !protectedB64u) { + throw new Error(); + } + const result = JSON.parse(decoder.decode(b64u(protectedB64u))); + if (!isObject(result)) { + throw new Error(); + } + return result; + } + catch { + throw new TypeError('Invalid Token or Protected Header formatting'); + } +} diff --git a/node_modules/jose/dist/webapi/util/errors.js b/node_modules/jose/dist/webapi/util/errors.js new file mode 100644 index 000000000..6fa9568dd --- /dev/null +++ b/node_modules/jose/dist/webapi/util/errors.js @@ -0,0 +1,99 @@ +export class JOSEError extends Error { + static code = 'ERR_JOSE_GENERIC'; + code = 'ERR_JOSE_GENERIC'; + constructor(message, options) { + super(message, options); + this.name = this.constructor.name; + Error.captureStackTrace?.(this, this.constructor); + } +} +export class JWTClaimValidationFailed extends JOSEError { + static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; + code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; + claim; + reason; + payload; + constructor(message, payload, claim = 'unspecified', reason = 'unspecified') { + super(message, { cause: { claim, reason, payload } }); + this.claim = claim; + this.reason = reason; + this.payload = payload; + } +} +export class JWTExpired extends JOSEError { + static code = 'ERR_JWT_EXPIRED'; + code = 'ERR_JWT_EXPIRED'; + claim; + reason; + payload; + constructor(message, payload, claim = 'unspecified', reason = 'unspecified') { + super(message, { cause: { claim, reason, payload } }); + this.claim = claim; + this.reason = reason; + this.payload = payload; + } +} +export class JOSEAlgNotAllowed extends JOSEError { + static code = 'ERR_JOSE_ALG_NOT_ALLOWED'; + code = 'ERR_JOSE_ALG_NOT_ALLOWED'; +} +export class JOSENotSupported extends JOSEError { + static code = 'ERR_JOSE_NOT_SUPPORTED'; + code = 'ERR_JOSE_NOT_SUPPORTED'; +} +export class JWEDecryptionFailed extends JOSEError { + static code = 'ERR_JWE_DECRYPTION_FAILED'; + code = 'ERR_JWE_DECRYPTION_FAILED'; + constructor(message = 'decryption operation failed', options) { + super(message, options); + } +} +export class JWEInvalid extends JOSEError { + static code = 'ERR_JWE_INVALID'; + code = 'ERR_JWE_INVALID'; +} +export class JWSInvalid extends JOSEError { + static code = 'ERR_JWS_INVALID'; + code = 'ERR_JWS_INVALID'; +} +export class JWTInvalid extends JOSEError { + static code = 'ERR_JWT_INVALID'; + code = 'ERR_JWT_INVALID'; +} +export class JWKInvalid extends JOSEError { + static code = 'ERR_JWK_INVALID'; + code = 'ERR_JWK_INVALID'; +} +export class JWKSInvalid extends JOSEError { + static code = 'ERR_JWKS_INVALID'; + code = 'ERR_JWKS_INVALID'; +} +export class JWKSNoMatchingKey extends JOSEError { + static code = 'ERR_JWKS_NO_MATCHING_KEY'; + code = 'ERR_JWKS_NO_MATCHING_KEY'; + constructor(message = 'no applicable key found in the JSON Web Key Set', options) { + super(message, options); + } +} +export class JWKSMultipleMatchingKeys extends JOSEError { + [Symbol.asyncIterator]; + static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; + code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; + constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) { + super(message, options); + } +} +export class JWKSTimeout extends JOSEError { + static code = 'ERR_JWKS_TIMEOUT'; + code = 'ERR_JWKS_TIMEOUT'; + constructor(message = 'request timed out', options) { + super(message, options); + } +} +export class JWSSignatureVerificationFailed extends JOSEError { + static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; + code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; + constructor(message = 'signature verification failed', options) { + super(message, options); + } +} diff --git a/node_modules/jose/package.json b/node_modules/jose/package.json new file mode 100644 index 000000000..e3ad85d96 --- /dev/null +++ b/node_modules/jose/package.json @@ -0,0 +1,200 @@ +{ + "name": "jose", + "version": "6.1.3", + "description": "JWA, JWS, JWE, JWT, JWK, JWKS for Node.js, Browser, Cloudflare Workers, Deno, Bun, and other Web-interoperable runtimes", + "keywords": [ + "akp", + "browser", + "bun", + "cloudflare", + "compact", + "decode", + "decrypt", + "deno", + "detached", + "ec", + "ecdsa", + "ed25519", + "eddsa", + "edge", + "electron", + "embedded", + "encrypt", + "flattened", + "general", + "jose", + "json web token", + "jsonwebtoken", + "jwa", + "jwe", + "jwk", + "jwks", + "jws", + "jwt-decode", + "jwt", + "ml-dsa", + "netlify", + "next", + "nextjs", + "oct", + "okp", + "payload", + "pem", + "pkcs8", + "rsa", + "sign", + "signature", + "spki", + "validate", + "vercel", + "verify", + "webcrypto", + "workerd", + "workers", + "x509" + ], + "homepage": "https://github.com/panva/jose", + "repository": "panva/jose", + "funding": { + "url": "https://github.com/sponsors/panva" + }, + "license": "MIT", + "author": "Filip Skokan ", + "sideEffects": false, + "type": "module", + "exports": { + ".": { + "types": "./dist/types/index.d.ts", + "default": "./dist/webapi/index.js" + }, + "./jwk/embedded": { + "types": "./dist/types/jwk/embedded.d.ts", + "default": "./dist/webapi/jwk/embedded.js" + }, + "./jwk/thumbprint": { + "types": "./dist/types/jwk/thumbprint.d.ts", + "default": "./dist/webapi/jwk/thumbprint.js" + }, + "./key/import": { + "types": "./dist/types/key/import.d.ts", + "default": "./dist/webapi/key/import.js" + }, + "./key/export": { + "types": "./dist/types/key/export.d.ts", + "default": "./dist/webapi/key/export.js" + }, + "./key/generate/keypair": { + "types": "./dist/types/key/generate_key_pair.d.ts", + "default": "./dist/webapi/key/generate_key_pair.js" + }, + "./key/generate/secret": { + "types": "./dist/types/key/generate_secret.d.ts", + "default": "./dist/webapi/key/generate_secret.js" + }, + "./jwks/remote": { + "types": "./dist/types/jwks/remote.d.ts", + "default": "./dist/webapi/jwks/remote.js" + }, + "./jwks/local": { + "types": "./dist/types/jwks/local.d.ts", + "default": "./dist/webapi/jwks/local.js" + }, + "./jwt/sign": { + "types": "./dist/types/jwt/sign.d.ts", + "default": "./dist/webapi/jwt/sign.js" + }, + "./jwt/verify": { + "types": "./dist/types/jwt/verify.d.ts", + "default": "./dist/webapi/jwt/verify.js" + }, + "./jwt/encrypt": { + "types": "./dist/types/jwt/encrypt.d.ts", + "default": "./dist/webapi/jwt/encrypt.js" + }, + "./jwt/decrypt": { + "types": "./dist/types/jwt/decrypt.d.ts", + "default": "./dist/webapi/jwt/decrypt.js" + }, + "./jwt/unsecured": { + "types": "./dist/types/jwt/unsecured.d.ts", + "default": "./dist/webapi/jwt/unsecured.js" + }, + "./jwt/decode": { + "types": "./dist/types/util/decode_jwt.d.ts", + "default": "./dist/webapi/util/decode_jwt.js" + }, + "./decode/protected_header": { + "types": "./dist/types/util/decode_protected_header.d.ts", + "default": "./dist/webapi/util/decode_protected_header.js" + }, + "./jws/compact/sign": { + "types": "./dist/types/jws/compact/sign.d.ts", + "default": "./dist/webapi/jws/compact/sign.js" + }, + "./jws/compact/verify": { + "types": "./dist/types/jws/compact/verify.d.ts", + "default": "./dist/webapi/jws/compact/verify.js" + }, + "./jws/flattened/sign": { + "types": "./dist/types/jws/flattened/sign.d.ts", + "default": "./dist/webapi/jws/flattened/sign.js" + }, + "./jws/flattened/verify": { + "types": "./dist/types/jws/flattened/verify.d.ts", + "default": "./dist/webapi/jws/flattened/verify.js" + }, + "./jws/general/sign": { + "types": "./dist/types/jws/general/sign.d.ts", + "default": "./dist/webapi/jws/general/sign.js" + }, + "./jws/general/verify": { + "types": "./dist/types/jws/general/verify.d.ts", + "default": "./dist/webapi/jws/general/verify.js" + }, + "./jwe/compact/encrypt": { + "types": "./dist/types/jwe/compact/encrypt.d.ts", + "default": "./dist/webapi/jwe/compact/encrypt.js" + }, + "./jwe/compact/decrypt": { + "types": "./dist/types/jwe/compact/decrypt.d.ts", + "default": "./dist/webapi/jwe/compact/decrypt.js" + }, + "./jwe/flattened/encrypt": { + "types": "./dist/types/jwe/flattened/encrypt.d.ts", + "default": "./dist/webapi/jwe/flattened/encrypt.js" + }, + "./jwe/flattened/decrypt": { + "types": "./dist/types/jwe/flattened/decrypt.d.ts", + "default": "./dist/webapi/jwe/flattened/decrypt.js" + }, + "./jwe/general/encrypt": { + "types": "./dist/types/jwe/general/encrypt.d.ts", + "default": "./dist/webapi/jwe/general/encrypt.js" + }, + "./jwe/general/decrypt": { + "types": "./dist/types/jwe/general/decrypt.d.ts", + "default": "./dist/webapi/jwe/general/decrypt.js" + }, + "./errors": { + "types": "./dist/types/util/errors.d.ts", + "default": "./dist/webapi/util/errors.js" + }, + "./base64url": { + "types": "./dist/types/util/base64url.d.ts", + "default": "./dist/webapi/util/base64url.js" + }, + "./package.json": "./package.json" + }, + "main": "./dist/webapi/index.js", + "types": "./dist/types/index.d.ts", + "files": [ + "dist/webapi/**/*.js", + "dist/types/**/*.d.ts", + "!dist/**/*.bundle.js", + "!dist/**/*.umd.js", + "!dist/**/*.min.js", + "!dist/types/runtime/*", + "!dist/types/lib/*", + "!dist/deno/**/*" + ] +} diff --git a/node_modules/json-schema-traverse/.eslintrc.yml b/node_modules/json-schema-traverse/.eslintrc.yml new file mode 100644 index 000000000..618559ab6 --- /dev/null +++ b/node_modules/json-schema-traverse/.eslintrc.yml @@ -0,0 +1,27 @@ +extends: eslint:recommended +env: + node: true + browser: true +rules: + block-scoped-var: 2 + complexity: [2, 15] + curly: [2, multi-or-nest, consistent] + dot-location: [2, property] + dot-notation: 2 + indent: [2, 2, SwitchCase: 1] + linebreak-style: [2, unix] + new-cap: 2 + no-console: [2, allow: [warn, error]] + no-else-return: 2 + no-eq-null: 2 + no-fallthrough: 2 + no-invalid-this: 2 + no-return-assign: 2 + no-shadow: 1 + no-trailing-spaces: 2 + no-use-before-define: [2, nofunc] + quotes: [2, single, avoid-escape] + semi: [2, always] + strict: [2, global] + valid-jsdoc: [2, requireReturn: false] + no-control-regex: 0 diff --git a/node_modules/json-schema-traverse/.github/FUNDING.yml b/node_modules/json-schema-traverse/.github/FUNDING.yml new file mode 100644 index 000000000..44f80f417 --- /dev/null +++ b/node_modules/json-schema-traverse/.github/FUNDING.yml @@ -0,0 +1,2 @@ +github: epoberezkin +tidelift: "npm/json-schema-traverse" diff --git a/node_modules/json-schema-traverse/.github/workflows/build.yml b/node_modules/json-schema-traverse/.github/workflows/build.yml new file mode 100644 index 000000000..f8ef5ba80 --- /dev/null +++ b/node_modules/json-schema-traverse/.github/workflows/build.yml @@ -0,0 +1,28 @@ +name: build + +on: + push: + branches: [master] + pull_request: + branches: ["*"] + +jobs: + build: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [10.x, 12.x, 14.x] + + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - run: npm install + - run: npm test + - name: Coveralls + uses: coverallsapp/github-action@master + with: + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/node_modules/json-schema-traverse/.github/workflows/publish.yml b/node_modules/json-schema-traverse/.github/workflows/publish.yml new file mode 100644 index 000000000..924825b12 --- /dev/null +++ b/node_modules/json-schema-traverse/.github/workflows/publish.yml @@ -0,0 +1,27 @@ +name: publish + +on: + release: + types: [published] + +jobs: + publish-npm: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v1 + with: + node-version: 14 + registry-url: https://registry.npmjs.org/ + - run: npm install + - run: npm test + - name: Publish beta version to npm + if: "github.event.release.prerelease" + run: npm publish --tag beta + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + - name: Publish to npm + if: "!github.event.release.prerelease" + run: npm publish + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/node_modules/json-schema-traverse/LICENSE b/node_modules/json-schema-traverse/LICENSE new file mode 100644 index 000000000..7f1543566 --- /dev/null +++ b/node_modules/json-schema-traverse/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +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/json-schema-traverse/README.md b/node_modules/json-schema-traverse/README.md new file mode 100644 index 000000000..f3e60073a --- /dev/null +++ b/node_modules/json-schema-traverse/README.md @@ -0,0 +1,95 @@ +# json-schema-traverse +Traverse JSON Schema passing each schema object to callback + +[![build](https://github.com/epoberezkin/json-schema-traverse/workflows/build/badge.svg)](https://github.com/epoberezkin/json-schema-traverse/actions?query=workflow%3Abuild) +[![npm](https://img.shields.io/npm/v/json-schema-traverse)](https://www.npmjs.com/package/json-schema-traverse) +[![coverage](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) + + +## Install + +``` +npm install json-schema-traverse +``` + + +## Usage + +```javascript +const traverse = require('json-schema-traverse'); +const schema = { + properties: { + foo: {type: 'string'}, + bar: {type: 'integer'} + } +}; + +traverse(schema, {cb}); +// cb is called 3 times with: +// 1. root schema +// 2. {type: 'string'} +// 3. {type: 'integer'} + +// Or: + +traverse(schema, {cb: {pre, post}}); +// pre is called 3 times with: +// 1. root schema +// 2. {type: 'string'} +// 3. {type: 'integer'} +// +// post is called 3 times with: +// 1. {type: 'string'} +// 2. {type: 'integer'} +// 3. root schema + +``` + +Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. + +Callback is passed these parameters: + +- _schema_: the current schema object +- _JSON pointer_: from the root schema to the current schema object +- _root schema_: the schema passed to `traverse` object +- _parent JSON pointer_: from the root schema to the parent schema object (see below) +- _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) +- _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema +- _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` + + +## Traverse objects in all unknown keywords + +```javascript +const traverse = require('json-schema-traverse'); +const schema = { + mySchema: { + minimum: 1, + maximum: 2 + } +}; + +traverse(schema, {allKeys: true, cb}); +// cb is called 2 times with: +// 1. root schema +// 2. mySchema +``` + +Without option `allKeys: true` callback will be called only with root schema. + + +## Enterprise support + +json-schema-traverse package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-json-schema-traverse?utm_source=npm-json-schema-traverse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. + + +## Security contact + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. + + +## License + +[MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) diff --git a/node_modules/json-schema-traverse/index.d.ts b/node_modules/json-schema-traverse/index.d.ts new file mode 100644 index 000000000..0772daedb --- /dev/null +++ b/node_modules/json-schema-traverse/index.d.ts @@ -0,0 +1,40 @@ +declare function traverse( + schema: traverse.SchemaObject, + opts: traverse.Options, + cb?: traverse.Callback +): void; + +declare function traverse( + schema: traverse.SchemaObject, + cb: traverse.Callback +): void; + +declare namespace traverse { + interface SchemaObject { + $id?: string; + $schema?: string; + [x: string]: any; + } + + type Callback = ( + schema: SchemaObject, + jsonPtr: string, + rootSchema: SchemaObject, + parentJsonPtr?: string, + parentKeyword?: string, + parentSchema?: SchemaObject, + keyIndex?: string | number + ) => void; + + interface Options { + allKeys?: boolean; + cb?: + | Callback + | { + pre?: Callback; + post?: Callback; + }; + } +} + +export = traverse; diff --git a/node_modules/json-schema-traverse/index.js b/node_modules/json-schema-traverse/index.js new file mode 100644 index 000000000..e521bfa85 --- /dev/null +++ b/node_modules/json-schema-traverse/index.js @@ -0,0 +1,93 @@ +'use strict'; + +var traverse = module.exports = function (schema, opts, cb) { + // Legacy support for v0.3.1 and earlier. + if (typeof opts == 'function') { + cb = opts; + opts = {}; + } + + cb = opts.cb || cb; + var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + + _traverse(opts, pre, post, schema, '', schema); +}; + + +traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true +}; + +traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; + +traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true +}; + +traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; + + +function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == 'object' && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i=0; i + +All JSON Schema documentation and descriptions are copyright (c): + +2009 [draft-0] IETF Trust , Kris Zyp , +and SitePen (USA) . + +2009 [draft-1] IETF Trust , Kris Zyp , +and SitePen (USA) . + +2010 [draft-2] IETF Trust , Kris Zyp , +and SitePen (USA) . + +2010 [draft-3] IETF Trust , Kris Zyp , +Gary Court , and SitePen (USA) . + +2013 [draft-4] IETF Trust ), Francis Galiegue +, Kris Zyp , Gary Court +, and SitePen (USA) . + +2018 [draft-7] IETF Trust , Austin Wright , +Henry Andrews , Geraint Luff , and +Cloudflare, Inc. . + +2019 [draft-2019-09] IETF Trust , Austin Wright +, Henry Andrews , Ben Hutton +, and Greg Dennis . + +2020 [draft-2020-12] IETF Trust , Austin Wright +, Henry Andrews , Ben Hutton +, and Greg Dennis . + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/json-schema-typed/README.md b/node_modules/json-schema-typed/README.md new file mode 100644 index 000000000..91b643b00 --- /dev/null +++ b/node_modules/json-schema-typed/README.md @@ -0,0 +1,108 @@ +[![npm](https://img.shields.io/npm/v/json-schema-typed.svg?style=flat-square)](https://npmjs.org/package/json-schema-typed) +[![downloads-per-month](https://img.shields.io/npm/dm/json-schema-typed.svg?style=flat-square&label=npm%20downloads)](https://npmjs.org/package/json-schema-typed) +[![License](https://img.shields.io/badge/license-BSD--2--Clause-blue.svg?style=flat-square)][license] + +# JSON Schema Typed + +JSON Schema TypeScript definitions with complete inline documentation. + +**NOTE:** This library only supports defining schemas. You will need a separate +library for data validation. + +There are 3 JSON Schema drafts included in this package: + +- `draft-07` +- `draft-2019-09` +- `draft-2020-12` + +## Install + +```sh +npm install json-schema-typed +``` + +## Usage + +1. Chose which draft you'd like to import. + +- The main package export points to the latest supported stable draft, currently + `draft-2020-12`. Future releases that point the main package export to a new + draft will always incur a bump to the major semantic version. + + ```ts + import { type JSONSchema } from "json-schema-typed"; + ``` + +- Or you can specify the exact draft you need. + ```ts + import { type JSONSchema } from "json-schema-typed/draft-2020-12"; + ``` + +2. Define a schema + + ```ts + import { Format, type JSONSchema } from "json-schema-typed"; + + const schema: JSONSchema = { + properties: { + email: { + format: Format.Email, + type: "string", + }, + }, + type: "object", + }; + + // The JSONSchema namespace also provides type-specific narrowed interfaces + const stringSchema: JSONSchema.String = { + // Only { type: "string" } and common keywords are allowed + maxLength: 100, + type: "string", + }; + ``` + +## Upgrading + +Version `8.0.0` has breaking changes from the previous release. + +- Now a + [pure ESM package](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). +- Many exports were renamed. The table below reflects the new export names. + These are considered final and unlikely to change in future releases. +- The `JSONSchema` type was changed from an `interface` to a `type` which is a + mixed union that allows `boolean` values in order to properly align with the + JSON Schema spec. If you were previously extending the `JSONSchema` interface, + you can access the `interface` directly with `JSONSchema.Interface`. +- The previous main package export pointed to Draft 7. Import it directly if you + need to continue using it: + ```ts + import { type JSONSchema } from "json-schema-typed/draft-07"; + ``` + +## Exports supported in each draft module + +| Name | Type | Purpose | +| ----------------- | --------------- | ------------------------------------------------------------------ | +| `$schema` | `string` | Draft meta schema URL that can be used with the `$schema` keyword. | +| `ContentEncoding` | Enum object | String content encoding strategies. | +| `draft` | `string` | Draft version. | +| `Format` | Enum object | String formats. | +| `JSONSchema` | TypeScript Type | Used to define a JSON Schema. | +| `keywords` | `string[]` | All the keywords for the imported draft. | +| `TypeName` | Enum object | Simple type names for the `type` keyword. | + +## Versioning + +This library follows [semantic versioning](https://semver.org). + +--- + +## Maintainers + +- [Remy Rylan](https://github.com/RemyRylan) + +## License + +[BSD-2-Clause][license] + +[license]: https://github.com/RemyRylan/json-schema-typed/blob/main/dist/node/LICENSE.md diff --git a/node_modules/json-schema-typed/draft_07.d.ts b/node_modules/json-schema-typed/draft_07.d.ts new file mode 100644 index 000000000..0fdcea03c --- /dev/null +++ b/node_modules/json-schema-typed/draft_07.d.ts @@ -0,0 +1,882 @@ +export declare const draft: "7"; +export declare const $schema: "https://json-schema.org/draft-07/schema"; +type MaybeReadonlyArray = Array | ReadonlyArray; +type ValueOf = T[keyof T]; +/** + * JSON Schema [Draft 7](https://json-schema.org/draft-07/json-schema-validation.html) + */ +export type JSONSchema ? "object" : JSONSchema.TypeValue> = boolean | { + /** + * This keyword is reserved for comments from schema authors to readers or + * maintainers of the schema. The value of this keyword MUST be a string. + * Implementations MUST NOT present this string to end users. Tools for + * editing schemas SHOULD support displaying and editing this keyword. + * + * The value of this keyword MAY be used in debug or error output which is + * intended for developers making use of schemas. Schema vocabularies + * SHOULD allow `comment` within any object containing vocabulary + * keywords. + * + * Implementations MAY assume `comment` is allowed unless the vocabulary + * specifically forbids it. Vocabularies MUST NOT specify any effect of + * `comment` beyond what is described in this specification. Tools that + * translate other media types or programming languages to and from + * `application/schema+json` MAY choose to convert that media type or + * programming language's native comments to or from `comment` values. + * + * The behavior of such translation when both native comments and + * `comment` properties are present is implementation-dependent. + * Implementations SHOULD treat `comment` identically to an unknown + * extension keyword. + * + * They MAY strip `comment` values at any point during processing. In + * particular, this allows for shortening schemas when the size of deployed + * schemas is a concern. Implementations MUST NOT take any other action + * based on the presence, absence, or contents of `comment` properties. + */ + $comment?: string; + /** + * The `$id` keyword defines a URI for the schema, and the base URI that + * other URI references within the schema are resolved against. A + * subschema's `$id` is resolved against the base URI of its parent + * schema. If no parent sets an explicit base with `$id`, the base URI is + * that of the entire document, as determined per + * [RFC 3986 section 5][RFC3986]. + * + * If present, the value for this keyword MUST be a string, and MUST + * represent a valid [URI-reference][RFC3986]. This value SHOULD be + * normalized, and SHOULD NOT be an empty fragment `#` or an empty string. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + * + * @format "uri-reference" + */ + $id?: string; + /** + * The `$ref` keyword is used to reference a schema, and provides the + * ability to validate recursive structures through self-reference. + * + * An object schema with a `$ref` property MUST be interpreted as a + * `$ref` reference. The value of the `$ref` property MUST be a URI + * Reference. Resolved against the current URI base, it identifies the URI + * of a schema to use. All other properties in a `$ref` object MUST be + * ignored. + * + * The URI is not a network locator, only an identifier. A schema need not + * be downloadable from the address if it is a network-addressable URL, and + * implementations SHOULD NOT assume they should perform a network + * operation when they encounter a network-addressable URI. + * + * A schema MUST NOT be run into an infinite loop against a schema. For + * example, if two schemas `"#alice"` and `"#bob"` both have an + * `allOf` property that refers to the other, a naive validator might get + * stuck in an infinite recursive loop trying to validate the instance. + * Schemas SHOULD NOT make use of infinite recursive nesting like this; the + * behavior is undefined. + * + * @format "uri-reference" + */ + $ref?: string; + /** + * The `$schema` keyword is both used as a JSON Schema version identifier + * and the location of a resource which is itself a JSON Schema, which + * describes any schema written for this particular version. + * + * The value of this keyword MUST be a [URI][RFC3986] (containing a scheme) + * and this URI MUST be normalized. The current schema MUST be valid + * against the meta-schema identified by this URI. + * + * If this URI identifies a retrievable resource, that resource SHOULD be + * of media type `application/schema+json`. + * + * The `$schema` keyword SHOULD be used in a root schema. It MUST NOT + * appear in subschemas. + * + * Values for this property are defined in other documents and by other + * parties. JSON Schema implementations SHOULD implement support for + * current and previous published drafts of JSON Schema vocabularies as + * deemed reasonable. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + * + * @format "uri" + */ + $schema?: string; + /** + * The value of `additionalItems` MUST be a valid JSON Schema. + * + * This keyword determines how child instances validate for arrays, and + * does not directly validate the immediate instance itself. + * + * If `items` is an array of schemas, validation succeeds if every + * instance element at a position greater than the size of `items` + * validates against `additionalItems`. + * + * Otherwise, `additionalItems` MUST be ignored, as the `items` schema + * (possibly the default value of an empty schema) is applied to all + * elements. + * + * Omitting this keyword has the same behavior as an empty schema. + */ + additionalItems?: JSONSchema; + /** + * The value of `additionalProperties` MUST be a valid JSON Schema. + * + * This keyword determines how child instances validate for objects, and + * does not directly validate the immediate instance itself. + * + * Validation with `additionalProperties` applies only to the child + * values of instance names that do not match any names in `properties`, + * and do not match any regular expression in `patternProperties`. + * + * For all such properties, validation succeeds if the child instance + * validates against the `additionalProperties` schema. + * + * Omitting this keyword has the same behavior as an empty schema. + */ + additionalProperties?: JSONSchema; + /** + * This keyword's value MUST be a non-empty array. Each item of the array + * MUST be a valid JSON Schema. + * + * An instance validates successfully against this keyword if it validates + * successfully against all schemas defined by this keyword's value. + */ + allOf?: MaybeReadonlyArray>; + /** + * This keyword's value MUST be a non-empty array. Each item of the array + * MUST be a valid JSON Schema. + * + * An instance validates successfully against this keyword if it validates + * successfully against at least one schema defined by this keyword's + * value. + */ + anyOf?: MaybeReadonlyArray>; + /** + * An instance validates successfully against this keyword if its value is + * equal to the value of the keyword. + * + * Use of this keyword is functionally equivalent to the `enum` keyword + * with a single value. + */ + const?: Value; + /** + * The value of this keyword MUST be a valid JSON Schema. + * + * An array instance is valid against `contains` if at least one of its + * elements is valid against the given schema. + */ + contains?: JSONSchema; + /** + * If the instance value is a string, this property defines that the + * string SHOULD be interpreted as binary data and decoded using the + * encoding named by this property. [RFC 2045, Sec 6.1][RFC2045] lists the + * possible values for this property. + * + * The value of this property SHOULD be ignored if the instance described + * is not a string. + * + * [RFC2045]: https://datatracker.ietf.org/doc/html/rfc2045#section-6.1 + */ + contentEncoding?: "7bit" | "8bit" | "base64" | "binary" | "ietf-token" | "quoted-printable" | "x-token"; + /** + * The value of this property must be a media type, as defined by + * [RFC 2046][RFC2046]. This property defines the media type of instances + * which this schema defines. + * + * The value of this property SHOULD be ignored if the instance described + * is not a string. + * + * If the `contentEncoding` property is not present, but the instance + * value is a string, then the value of this property SHOULD specify a text + * document type, and the character set SHOULD be the character set into + * which the JSON string value was decoded (for which the default is + * Unicode). + * + * [RFC2046]: https://datatracker.ietf.org/doc/html/rfc2046 + */ + contentMediaType?: string; + /** + * This keyword can be used to supply a default JSON value associated with + * a particular schema. It is RECOMMENDED that a `default` value be valid + * against the associated schema. + */ + default?: Value; + /** + * The `definitions` keywords provides a standardized location for schema + * authors to inline re-usable JSON Schemas into a more general schema. The + * keyword does not directly affect the validation result. + * + * This keyword's value MUST be an object. Each member value of this object + * MUST be a valid JSON Schema. + */ + definitions?: Record; + /** + * This keyword specifies rules that are evaluated if the instance is an + * object and contains a certain property. + * + * This keyword's value MUST be an object. Each property specifies a + * dependency. Each dependency value MUST be an array or a valid JSON + * Schema. + * + * If the dependency value is a subschema, and the dependency key is a + * property in the instance, the entire instance must validate against the + * dependency value. + * + * If the dependency value is an array, each element in the array, if any, + * MUST be a string, and MUST be unique. If the dependency key is a + * property in the instance, each of the items in the dependency value must + * be a property that exists in the instance. + * + * Omitting this keyword has the same behavior as an empty object. + */ + dependencies?: Record | JSONSchema>; + /** + * Can be used to decorate a user interface with explanation or information + * about the data produced. + */ + description?: string; + /** + * This keyword's value MUST be a valid JSON Schema. + * + * When `if` is present, and the instance fails to validate against its + * subschema, then validation succeeds against this keyword if the instance + * successfully validates against this keyword's subschema. + * + * This keyword has no effect when `if` is absent, or when the instance + * successfully validates against its subschema. Implementations MUST NOT + * evaluate the instance against this keyword, for either validation or + * annotation collection purposes, in such cases. + */ + else?: JSONSchema; + /** + * The value of this keyword MUST be an array. This array SHOULD have at + * least one element. Elements in the array SHOULD be unique. + * + * An instance validates successfully against this keyword if its value is + * equal to one of the elements in this keyword's array value. + * + * Elements in the array might be of any type, including `null`. + */ + enum?: MaybeReadonlyArray; + /** + * The value of this keyword MUST be an array. When multiple occurrences of + * this keyword are applicable to a single sub-instance, implementations + * MUST provide a flat array of all values rather than an array of arrays. + * + * This keyword can be used to provide sample JSON values associated with a + * particular schema, for the purpose of illustrating usage. It is + * RECOMMENDED that these values be valid against the associated schema. + * + * Implementations MAY use the value(s) of `default`, if present, as an + * additional example. If `examples` is absent, `default` MAY still be + * used in this manner. + */ + examples?: MaybeReadonlyArray; + /** + * The value of `exclusiveMaximum` MUST be a number, representing an + * exclusive upper limit for a numeric instance. + * + * If the instance is a number, then the instance is valid only if it has a + * value strictly less than (not equal to) `exclusiveMaximum`. + */ + exclusiveMaximum?: number; + /** + * The value of `exclusiveMinimum` MUST be a number, representing an + * exclusive lower limit for a numeric instance. + * + * If the instance is a number, then the instance is valid only if it has a + * value strictly greater than (not equal to) `exclusiveMinimum`. + */ + exclusiveMinimum?: number; + /** + * The `format` keyword functions as both an [annotation][annotation] and + * as an [assertion][assertion]. While no special effort is required to + * implement it as an annotation conveying semantic meaning, implementing + * validation is non-trivial. + * + * Implementations MAY support the `format` keyword as a validation + * assertion. + * + * Implementations MAY add custom `format` attributes. Save for agreement + * between parties, schema authors SHALL NOT expect a peer implementation + * to support this keyword and/or custom `format` attributes. + * + * [annotation]: https://json-schema.org/draft-07/json-schema-validation.html#annotations + * [assertion]: https://json-schema.org/draft-07/json-schema-validation.html#assertions + */ + format?: string; + /** + * This keyword's value MUST be a valid JSON Schema. + * + * This validation outcome of this keyword's subschema has no direct effect + * on the overall validation result. Rather, it controls which of the + * `then` or `else` keywords are evaluated. + * + * Instances that successfully validate against this keyword's subschema + * MUST also be valid against the subschema value of the `then` keyword, + * if present. + * + * Instances that fail to validate against this keyword's subschema MUST + * also be valid against the subschema value of the `else` keyword, if + * present. + * + * If [annotations][annotations] are being collected, they are collected + * from this keyword's subschema in the usual way, including when the + * keyword is present without either `then` or `else`. + * + * [annotations]: https://json-schema.org/draft-07/json-schema-validation.html#annotations + */ + if?: JSONSchema; + /** + * The value of `items` MUST be either a valid JSON Schema or an array of + * valid JSON Schemas. + * + * This keyword determines how child instances validate for arrays, and + * does not directly validate the immediate instance itself. + * + * If `items` is a schema, validation succeeds if all elements in the + * array successfully validate against that schema. + * + * If `items` is an array of schemas, validation succeeds if each element + * of the instance validates against the schema at the same position, if + * any. + * + * Omitting this keyword has the same behavior as an empty schema. + */ + items?: MaybeReadonlyArray | JSONSchema; + /** + * The value of `maximum` MUST be a number, representing an inclusive + * upper limit for a numeric instance. + * + * If the instance is a number, then this keyword validates only if the + * instance is less than or exactly equal to `maximum`. + */ + maximum?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An array instance is valid against `maxItems` if its size is less + * than, or equal to, the value of this keyword. + * + * @minimum 0 + */ + maxItems?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * A string instance is valid against this keyword if its length is less + * than, or equal to, the value of this keyword. + * + * The length of a string instance is defined as the number of its + * characters as defined by [RFC 7159][RFC7159]. + * + * [RFC7159]: https://datatracker.ietf.org/doc/html/rfc7159 + * + * @minimum 0 + */ + maxLength?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An object instance is valid against `maxProperties` if its number of + * `properties` is less than, or equal to, the value of this keyword. + * + * @minimum 0 + */ + maxProperties?: number; + /** + * The value of `minimum` MUST be a number, representing an inclusive + * lower limit for a numeric instance. + * + * If the instance is a number, then this keyword validates only if the + * instance is greater than or exactly equal to `minimum`. + */ + minimum?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An array instance is valid against `minItems` if its size is greater + * than, or equal to, the value of this keyword. + * + * Omitting this keyword has the same behavior as a value of `0`. + * + * @default 0 + * @minimum 0 + */ + minItems?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * A string instance is valid against this keyword if its length is greater + * than, or equal to, the value of this keyword. + * + * The length of a string instance is defined as the number of its + * characters as defined by [RFC 7159][RFC7159]. + * + * Omitting this keyword has the same behavior as a value of `0`. + * + * [RFC7159]: https://datatracker.ietf.org/doc/html/rfc7159 + * + * @default 0 + * @minimum 0 + */ + minLength?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An object instance is valid against `minProperties` if its number of + * `properties` is greater than, or equal to, the value of this keyword. + * + * Omitting this keyword has the same behavior as a value of `0`. + * + * @default 0 + * @minimum 0 + */ + minProperties?: number; + /** + * The value of `multipleOf` MUST be a number, strictly greater than + * `0`. + * + * A numeric instance is valid only if division by this keyword's value + * results in an integer. + * + * @exclusiveMinimum 0 + */ + multipleOf?: number; + /** + * This keyword's value MUST be a valid JSON Schema. + * + * An instance is valid against this keyword if it fails to validate + * successfully against the schema defined by this keyword. + */ + not?: JSONSchema; + /** + * This keyword's value MUST be a non-empty array. Each item of the array + * MUST be a valid JSON Schema. + * + * An instance validates successfully against this keyword if it validates + * successfully against exactly one schema defined by this keyword's value. + */ + oneOf?: MaybeReadonlyArray>; + /** + * The value of this keyword MUST be a string. This string SHOULD be a + * valid regular expression, according to the [ECMA-262][ecma262] regular + * expression dialect. + * + * A string instance is considered valid if the regular expression matches + * the instance successfully. Recall: regular expressions are not + * implicitly anchored. + * + * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ + * + * @format "regex" + */ + pattern?: string; + /** + * The value of `patternProperties` MUST be an object. Each property name + * of this object SHOULD be a valid regular expression, according to the + * [ECMA-262][ecma262] regular expression dialect. Each property value of + * this object MUST be a valid JSON Schema. + * + * This keyword determines how child instances validate for objects, and + * does not directly validate the immediate instance itself. Validation of + * the primitive instance type against this keyword always succeeds. + * + * Validation succeeds if, for each instance name that matches any regular + * expressions that appear as a property name in this keyword's value, the + * child instance for that name successfully validates against each schema + * that corresponds to a matching regular expression. + * + * Omitting this keyword has the same behavior as an empty object. + * + * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ + */ + patternProperties?: Record; + /** + * The value of `properties` MUST be an object. Each value of this object + * MUST be a valid JSON Schema. + * + * This keyword determines how child instances validate for objects, and + * does not directly validate the immediate instance itself. + * + * Validation succeeds if, for each name that appears in both the instance + * and as a name within this keyword's value, the child instance for that + * name successfully validates against the corresponding schema. + * + * Omitting this keyword has the same behavior as an empty object. + */ + properties?: Record; + /** + * The value of `propertyNames` MUST be a valid JSON Schema. + * + * If the instance is an object, this keyword validates if every property + * name in the instance validates against the provided schema. Note the + * property name that the schema is testing will always be a string. + * + * Omitting this keyword has the same behavior as an empty schema. + */ + propertyNames?: JSONSchema; + /** + * The value of this keyword MUST be a boolean. When multiple occurrences + * of this keyword are applicable to a single sub-instance, the resulting + * value MUST be `true` if any occurrence specifies a `true` value, and + * MUST be `false` otherwise. + * + * If `readOnly` has a value of boolean `true`, it indicates that the + * value of the instance is managed exclusively by the owning authority, + * and attempts by an application to modify the value of this property are + * expected to be ignored or rejected by that owning authority. + * + * An instance document that is marked as `readOnly` for the entire + * document MAY be ignored if sent to the owning authority, or MAY result + * in an error, at the authority's discretion. + * + * For example, `readOnly` would be used to mark a database-generated + * serial number as read-only. + * + * This keyword can be used to assist in user interface instance + * generation. + * + * @default false + */ + readOnly?: boolean; + /** + * The value of this keyword MUST be an array. Elements of this array, if + * any, MUST be strings, and MUST be unique. + * + * An object instance is valid against this keyword if every item in the + * array is the name of a property in the instance. + * + * Omitting this keyword has the same behavior as an empty array. + */ + required?: MaybeReadonlyArray; + /** + * This keyword's value MUST be a valid JSON Schema. + * + * When `if` is present, and the instance successfully validates against + * its subschema, then validation succeeds against this keyword if the + * instance also successfully validates against this keyword's subschema. + * + * This keyword has no effect when `if` is absent, or when the instance + * fails to validate against its subschema. Implementations MUST NOT + * evaluate the instance against this keyword, for either validation or + * annotation collection purposes, in such cases. + */ + then?: JSONSchema; + /** + * Can be used to decorate a user interface with a short label about the + * data produced. + */ + title?: string; + /** + * The value of this keyword MUST be either a string or an array. If it is + * an array, elements of the array MUST be strings and MUST be unique. + * + * String values MUST be one of the six primitive types (`"null"`, + * `"boolean"`, `"object"`, `"array"`, `"number"`, or + * `"string"`), or `"integer"` which matches any number with a zero + * fractional part. + * + * An instance validates if and only if the instance is in any of the sets + * listed for this keyword. + */ + type?: SchemaType; + /** + * The value of this keyword MUST be a boolean. + * + * If this keyword has boolean value `false`, the instance validates + * successfully. If it has boolean value `true`, the instance validates + * successfully if all of its elements are unique. + * + * Omitting this keyword has the same behavior as a value of `false`. + * + * @default false + */ + uniqueItems?: boolean; + /** + * The value of this keyword MUST be a boolean. When multiple occurrences + * of this keyword is applicable to a single sub-instance, the resulting + * value MUST be `true` if any occurrence specifies a `true` value, and + * MUST be `false` otherwise. + * + * If `writeOnly` has a value of boolean `true`, it indicates that the + * value is never present when the instance is retrieved from the owning + * authority. It can be present when sent to the owning authority to update + * or create the document (or the resource it represents), but it will not + * be included in any updated or newly created version of the instance. + * + * An instance document that is marked as `writeOnly` for the entire + * document MAY be returned as a blank document of some sort, or MAY + * produce an error upon retrieval, or have the retrieval request ignored, + * at the authority's discretion. + * + * For example, `writeOnly` would be used to mark a password input field. + * + * These keywords can be used to assist in user interface instance + * generation. In particular, an application MAY choose to use a widget + * that hides input values as they are typed for write-only fields. + * + * @default false + */ + writeOnly?: boolean; +}; +export declare namespace JSONSchema { + type TypeValue = ValueOf | TypeName | Array | TypeName> | ReadonlyArray | TypeName>; + /** + * JSON Schema interface + */ + type Interface = Exclude, boolean>; + type Array = Pick, KeywordByType.Any | KeywordByType.Array>; + type Boolean = Pick, KeywordByType.Any>; + type Integer = Pick, KeywordByType.Any | KeywordByType.Number>; + type Number = Pick, KeywordByType.Any | KeywordByType.Number>; + type Null = Pick, KeywordByType.Any>; + type Object = Pick, KeywordByType.Any | KeywordByType.Object>; + type String = Pick, KeywordByType.Any | KeywordByType.String>; +} +declare namespace KeywordByType { + type Any = "$comment" | "$id" | "$ref" | "$schema" | "allOf" | "anyOf" | "const" | "default" | "definitions" | "description" | "else" | "enum" | "examples" | "if" | "not" | "oneOf" | "readOnly" | "then" | "title" | "type" | "writeOnly"; + type Array = "additionalItems" | "contains" | "items" | "maxItems" | "minItems" | "uniqueItems"; + type Number = "exclusiveMaximum" | "exclusiveMinimum" | "maximum" | "minimum" | "multipleOf"; + type Object = "additionalProperties" | "dependencies" | "maxProperties" | "minProperties" | "patternProperties" | "properties" | "propertyNames" | "required"; + type String = "contentEncoding" | "contentMediaType" | "format" | "maxLength" | "minLength" | "pattern"; +} +/** + * Content encoding strategy enum. + * + * - [Content-Transfer-Encoding Syntax](https://datatracker.ietf.org/doc/html/rfc2045#section-6.1) + * - [7bit vs 8bit encoding](https://stackoverflow.com/questions/25710599/content-transfer-encoding-7bit-or-8-bit/28531705#28531705) + */ +export declare enum ContentEncoding { + /** + * Only US-ASCII characters, which use the lower 7 bits for each character. + * + * Each line must be less than 1,000 characters. + */ + "7bit" = "7bit", + /** + * Allow extended ASCII characters which can use the 8th (highest) bit to + * indicate special characters not available in 7bit. + * + * Each line must be less than 1,000 characters. + */ + "8bit" = "8bit", + /** + * Useful for data that is mostly non-text. + */ + Base64 = "base64", + /** + * Same character set as 8bit, with no line length restriction. + */ + Binary = "binary", + /** + * An extension token defined by a standards-track RFC and registered with + * IANA. + */ + IETFToken = "ietf-token", + /** + * Lines are limited to 76 characters, and line breaks are represented using + * special characters that are escaped. + */ + QuotedPrintable = "quoted-printable", + /** + * The two characters "X-" or "x-" followed, with no intervening white space, + * by any token. + */ + XToken = "x-token" +} +/** + * This enum provides well-known formats that apply to strings. + */ +export declare enum Format { + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "full-date" production in + * [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Date = "date", + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "date-time" production in + * [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + DateTime = "date-time", + /** + * A string instance is valid against this attribute if it is a valid Internet + * email address as defined by [RFC 5322, section 3.4.1][RFC5322]. + * + * [RFC5322]: https://datatracker.ietf.org/doc/html/rfc5322 + */ + Email = "email", + /** + * As defined by [RFC 1034, section 3.1][RFC1034], including host names + * produced using the Punycode algorithm specified in + * [RFC 5891, section 4.4][RFC5891]. + * + * [RFC1034]: https://datatracker.ietf.org/doc/html/rfc1034 + * [RFC5891]: https://datatracker.ietf.org/doc/html/rfc5891 + */ + Hostname = "hostname", + /** + * A string instance is valid against this attribute if it is a valid Internet + * email address as defined by [RFC 6531][RFC6531]. + * + * [RFC6531]: https://datatracker.ietf.org/doc/html/rfc6531 + */ + IDNEmail = "idn-email", + /** + * As defined by either [RFC 1034, section 3.1][RFC1034] as for hostname, or + * an internationalized hostname as defined by + * [RFC 5890, section 2.3.2.3][RFC5890]. + * + * [RFC1034]: https://datatracker.ietf.org/doc/html/rfc1034 + * [RFC5890]: https://datatracker.ietf.org/doc/html/rfc5890 + */ + IDNHostname = "idn-hostname", + /** + * An IPv4 address according to the "dotted-quad" ABNF syntax as defined in + * [RFC 2673, section 3.2][RFC2673]. + * + * [RFC2673]: https://datatracker.ietf.org/doc/html/rfc2673 + */ + IPv4 = "ipv4", + /** + * An IPv6 address as defined in [RFC 4291, section 2.2][RFC4291]. + * + * [RFC4291]: https://datatracker.ietf.org/doc/html/rfc4291 + */ + IPv6 = "ipv6", + /** + * A string instance is valid against this attribute if it is a valid IRI, + * according to [RFC 3987][RFC3987]. + * + * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 + */ + IRI = "iri", + /** + * A string instance is valid against this attribute if it is a valid IRI + * Reference (either an IRI or a relative-reference), according to + * [RFC 3987][RFC3987]. + * + * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 + */ + IRIReference = "iri-reference", + /** + * A string instance is valid against this attribute if it is a valid JSON + * string representation of a JSON Pointer, according to + * [RFC 6901, section 5][RFC6901]. + * + * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 + */ + JSONPointer = "json-pointer", + /** + * A string instance is valid against this attribute if it is a valid JSON + * string representation of a JSON Pointer fragment, according to + * [RFC 6901, section 5][RFC6901]. + * + * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 + */ + JSONPointerURIFragment = "json-pointer-uri-fragment", + /** + * This attribute applies to string instances. + * + * A regular expression, which SHOULD be valid according to the + * [ECMA-262][ecma262] regular expression dialect. + * + * Implementations that validate formats MUST accept at least the subset of + * [ECMA-262][ecma262] defined in the [Regular Expressions][regexInterop] + * section of this specification, and SHOULD accept all valid + * [ECMA-262][ecma262] expressions. + * + * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ + * [regexInterop]: https://json-schema.org/draft-07/json-schema-validation.html#regexInterop + */ + RegEx = "regex", + /** + * A string instance is valid against this attribute if it is a valid + * [Relative JSON Pointer][relative-json-pointer]. + * + * [relative-json-pointer]: https://datatracker.ietf.org/doc/html/draft-handrews-relative-json-pointer-01 + */ + RelativeJSONPointer = "relative-json-pointer", + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "time" production in [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Time = "time", + /** + * A string instance is valid against this attribute if it is a valid URI, + * according to [RFC3986][RFC3986]. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + */ + URI = "uri", + /** + * A string instance is valid against this attribute if it is a valid URI + * Reference (either a URI or a relative-reference), according to + * [RFC3986][RFC3986]. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + */ + URIReference = "uri-reference", + /** + * A string instance is valid against this attribute if it is a valid URI + * Template (of any level), according to [RFC6570][RFC6570]. + * + * Note that URI Templates may be used for IRIs; there is no separate IRI + * Template specification. + * + * [RFC6570]: https://datatracker.ietf.org/doc/html/rfc6570 + */ + URITemplate = "uri-template", + /** + * UUID + */ + UUID = "uuid" +} +/** + * Enum consisting of simple type names for the `type` keyword + */ +export declare enum TypeName { + /** + * Value MUST be an array. + */ + Array = "array", + /** + * Value MUST be a boolean. + */ + Boolean = "boolean", + /** + * Value MUST be an integer, no floating point numbers are allowed. This is a + * subset of the number type. + */ + Integer = "integer", + /** + * Value MUST be null. Note this is mainly for purpose of being able use union + * types to define nullability. If this type is not included in a union, null + * values are not allowed (the primitives listed above do not allow nulls on + * their own). + */ + Null = "null", + /** + * Value MUST be a number, floating point numbers are allowed. + */ + Number = "number", + /** + * Value MUST be an object. + */ + Object = "object", + /** + * Value MUST be a string. + */ + String = "string" +} +export declare const keywords: readonly ["$comment", "$id", "$ref", "$schema", "additionalItems", "additionalProperties", "allOf", "anyOf", "const", "contains", "contentEncoding", "contentMediaType", "default", "definitions", "dependencies", "description", "else", "enum", "examples", "exclusiveMaximum", "exclusiveMinimum", "format", "if", "items", "maximum", "maxItems", "maxLength", "maxProperties", "minimum", "minItems", "minLength", "minProperties", "multipleOf", "not", "oneOf", "pattern", "patternProperties", "properties", "propertyNames", "readOnly", "required", "then", "title", "type", "uniqueItems", "writeOnly"]; +export {}; diff --git a/node_modules/json-schema-typed/draft_07.js b/node_modules/json-schema-typed/draft_07.js new file mode 100644 index 000000000..55ef88a94 --- /dev/null +++ b/node_modules/json-schema-typed/draft_07.js @@ -0,0 +1,328 @@ +// @generated +// This code is automatically generated. Manual editing is not recommended. +/* + * BSD-2-Clause License + * + * Original source code is copyright (c) 2019-2025 Remy Rylan + * + * + * Documentation and keyword descriptions are copyright (c) 2018 IETF Trust + * , Austin Wright , Henry Andrews + * , Geraint Luff , and Cloudflare, + * Inc. . All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +export const draft = "7"; +export const $schema = "https://json-schema.org/draft-07/schema"; +// ----------------------------------------------------------------------------- +/** + * Content encoding strategy enum. + * + * - [Content-Transfer-Encoding Syntax](https://datatracker.ietf.org/doc/html/rfc2045#section-6.1) + * - [7bit vs 8bit encoding](https://stackoverflow.com/questions/25710599/content-transfer-encoding-7bit-or-8-bit/28531705#28531705) + */ +export var ContentEncoding; +(function (ContentEncoding) { + /** + * Only US-ASCII characters, which use the lower 7 bits for each character. + * + * Each line must be less than 1,000 characters. + */ + ContentEncoding["7bit"] = "7bit"; + /** + * Allow extended ASCII characters which can use the 8th (highest) bit to + * indicate special characters not available in 7bit. + * + * Each line must be less than 1,000 characters. + */ + ContentEncoding["8bit"] = "8bit"; + /** + * Useful for data that is mostly non-text. + */ + ContentEncoding["Base64"] = "base64"; + /** + * Same character set as 8bit, with no line length restriction. + */ + ContentEncoding["Binary"] = "binary"; + /** + * An extension token defined by a standards-track RFC and registered with + * IANA. + */ + ContentEncoding["IETFToken"] = "ietf-token"; + /** + * Lines are limited to 76 characters, and line breaks are represented using + * special characters that are escaped. + */ + ContentEncoding["QuotedPrintable"] = "quoted-printable"; + /** + * The two characters "X-" or "x-" followed, with no intervening white space, + * by any token. + */ + ContentEncoding["XToken"] = "x-token"; +})(ContentEncoding || (ContentEncoding = {})); +/** + * This enum provides well-known formats that apply to strings. + */ +export var Format; +(function (Format) { + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "full-date" production in + * [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Format["Date"] = "date"; + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "date-time" production in + * [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Format["DateTime"] = "date-time"; + /** + * A string instance is valid against this attribute if it is a valid Internet + * email address as defined by [RFC 5322, section 3.4.1][RFC5322]. + * + * [RFC5322]: https://datatracker.ietf.org/doc/html/rfc5322 + */ + Format["Email"] = "email"; + /** + * As defined by [RFC 1034, section 3.1][RFC1034], including host names + * produced using the Punycode algorithm specified in + * [RFC 5891, section 4.4][RFC5891]. + * + * [RFC1034]: https://datatracker.ietf.org/doc/html/rfc1034 + * [RFC5891]: https://datatracker.ietf.org/doc/html/rfc5891 + */ + Format["Hostname"] = "hostname"; + /** + * A string instance is valid against this attribute if it is a valid Internet + * email address as defined by [RFC 6531][RFC6531]. + * + * [RFC6531]: https://datatracker.ietf.org/doc/html/rfc6531 + */ + Format["IDNEmail"] = "idn-email"; + /** + * As defined by either [RFC 1034, section 3.1][RFC1034] as for hostname, or + * an internationalized hostname as defined by + * [RFC 5890, section 2.3.2.3][RFC5890]. + * + * [RFC1034]: https://datatracker.ietf.org/doc/html/rfc1034 + * [RFC5890]: https://datatracker.ietf.org/doc/html/rfc5890 + */ + Format["IDNHostname"] = "idn-hostname"; + /** + * An IPv4 address according to the "dotted-quad" ABNF syntax as defined in + * [RFC 2673, section 3.2][RFC2673]. + * + * [RFC2673]: https://datatracker.ietf.org/doc/html/rfc2673 + */ + Format["IPv4"] = "ipv4"; + /** + * An IPv6 address as defined in [RFC 4291, section 2.2][RFC4291]. + * + * [RFC4291]: https://datatracker.ietf.org/doc/html/rfc4291 + */ + Format["IPv6"] = "ipv6"; + /** + * A string instance is valid against this attribute if it is a valid IRI, + * according to [RFC 3987][RFC3987]. + * + * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 + */ + Format["IRI"] = "iri"; + /** + * A string instance is valid against this attribute if it is a valid IRI + * Reference (either an IRI or a relative-reference), according to + * [RFC 3987][RFC3987]. + * + * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 + */ + Format["IRIReference"] = "iri-reference"; + /** + * A string instance is valid against this attribute if it is a valid JSON + * string representation of a JSON Pointer, according to + * [RFC 6901, section 5][RFC6901]. + * + * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 + */ + Format["JSONPointer"] = "json-pointer"; + /** + * A string instance is valid against this attribute if it is a valid JSON + * string representation of a JSON Pointer fragment, according to + * [RFC 6901, section 5][RFC6901]. + * + * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 + */ + Format["JSONPointerURIFragment"] = "json-pointer-uri-fragment"; + /** + * This attribute applies to string instances. + * + * A regular expression, which SHOULD be valid according to the + * [ECMA-262][ecma262] regular expression dialect. + * + * Implementations that validate formats MUST accept at least the subset of + * [ECMA-262][ecma262] defined in the [Regular Expressions][regexInterop] + * section of this specification, and SHOULD accept all valid + * [ECMA-262][ecma262] expressions. + * + * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ + * [regexInterop]: https://json-schema.org/draft-07/json-schema-validation.html#regexInterop + */ + Format["RegEx"] = "regex"; + /** + * A string instance is valid against this attribute if it is a valid + * [Relative JSON Pointer][relative-json-pointer]. + * + * [relative-json-pointer]: https://datatracker.ietf.org/doc/html/draft-handrews-relative-json-pointer-01 + */ + Format["RelativeJSONPointer"] = "relative-json-pointer"; + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "time" production in [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Format["Time"] = "time"; + /** + * A string instance is valid against this attribute if it is a valid URI, + * according to [RFC3986][RFC3986]. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + */ + Format["URI"] = "uri"; + /** + * A string instance is valid against this attribute if it is a valid URI + * Reference (either a URI or a relative-reference), according to + * [RFC3986][RFC3986]. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + */ + Format["URIReference"] = "uri-reference"; + /** + * A string instance is valid against this attribute if it is a valid URI + * Template (of any level), according to [RFC6570][RFC6570]. + * + * Note that URI Templates may be used for IRIs; there is no separate IRI + * Template specification. + * + * [RFC6570]: https://datatracker.ietf.org/doc/html/rfc6570 + */ + Format["URITemplate"] = "uri-template"; + /** + * UUID + */ + Format["UUID"] = "uuid"; +})(Format || (Format = {})); +/** + * Enum consisting of simple type names for the `type` keyword + */ +export var TypeName; +(function (TypeName) { + /** + * Value MUST be an array. + */ + TypeName["Array"] = "array"; + /** + * Value MUST be a boolean. + */ + TypeName["Boolean"] = "boolean"; + /** + * Value MUST be an integer, no floating point numbers are allowed. This is a + * subset of the number type. + */ + TypeName["Integer"] = "integer"; + /** + * Value MUST be null. Note this is mainly for purpose of being able use union + * types to define nullability. If this type is not included in a union, null + * values are not allowed (the primitives listed above do not allow nulls on + * their own). + */ + TypeName["Null"] = "null"; + /** + * Value MUST be a number, floating point numbers are allowed. + */ + TypeName["Number"] = "number"; + /** + * Value MUST be an object. + */ + TypeName["Object"] = "object"; + /** + * Value MUST be a string. + */ + TypeName["String"] = "string"; +})(TypeName || (TypeName = {})); +// ----------------------------------------------------------------------------- +// Keywords +// ----------------------------------------------------------------------------- +export const keywords = [ + "$comment", + "$id", + "$ref", + "$schema", + "additionalItems", + "additionalProperties", + "allOf", + "anyOf", + "const", + "contains", + "contentEncoding", + "contentMediaType", + "default", + "definitions", + "dependencies", + "description", + "else", + "enum", + "examples", + "exclusiveMaximum", + "exclusiveMinimum", + "format", + "if", + "items", + "maximum", + "maxItems", + "maxLength", + "maxProperties", + "minimum", + "minItems", + "minLength", + "minProperties", + "multipleOf", + "not", + "oneOf", + "pattern", + "patternProperties", + "properties", + "propertyNames", + "readOnly", + "required", + "then", + "title", + "type", + "uniqueItems", + "writeOnly", +]; diff --git a/node_modules/json-schema-typed/draft_2019_09.d.ts b/node_modules/json-schema-typed/draft_2019_09.d.ts new file mode 100644 index 000000000..b3368c7ef --- /dev/null +++ b/node_modules/json-schema-typed/draft_2019_09.d.ts @@ -0,0 +1,1247 @@ +export declare const draft: "2019-09"; +export declare const $schema: "https://json-schema.org/draft/2019-09/schema"; +type MaybeReadonlyArray = Array | ReadonlyArray; +type ValueOf = T[keyof T]; +/** + * JSON Schema [Draft 2019-09](https://json-schema.org/draft/2019-09/json-schema-validation.html) + */ +export type JSONSchema ? "object" : JSONSchema.TypeValue> = boolean | { + /** + * Using JSON Pointer fragments requires knowledge of the structure of the + * schema. When writing schema documents with the intention to provide + * re-usable schemas, it may be preferable to use a plain name fragment + * that is not tied to any particular structural location. This allows a + * subschema to be relocated without requiring JSON Pointer references to + * be updated. + * + * The `$anchor` keyword is used to specify such a fragment. It is an + * identifier keyword that can only be used to create plain name fragments. + * + * If present, the value of this keyword MUST be a string, which MUST start + * with a letter `[A-Za-z]`, followed by any number of letters, digits + * `[0-9]`, hyphens `-`, underscores `_`, colons `:`, + * or periods `.`. + * + * Note that the anchor string does not include the `#` character, + * as it is not a URI-reference. An `{"$anchor": "foo"}` becomes the + * fragment `#foo` when used in a URI. + * + * The base URI to which the resulting fragment is appended is determined + * by the `$id` keyword as explained in the previous section. + * Two `$anchor` keywords in the same schema document MAY have the same + * value if they apply to different base URIs, as the resulting full URIs + * will be distinct. However, the effect of two `$anchor` keywords + * with the same value and the same base URI is undefined. Implementations + * MAY raise an error if such usage is detected. + */ + $anchor?: string; + /** + * This keyword reserves a location for comments from schema authors + * to readers or maintainers of the schema. + * + * The value of this keyword MUST be a string. Implementations MUST NOT + * present this string to end users. Tools for editing schemas SHOULD + * support displaying and editing this keyword. The value of this keyword + * MAY be used in debug or error output which is intended for developers + * making use of schemas. + * + * Schema vocabularies SHOULD allow `$comment` within any object + * containing vocabulary keywords. Implementations MAY assume `$comment` + * is allowed unless the vocabulary specifically forbids it. Vocabularies + * MUST NOT specify any effect of `$comment` beyond what is described in + * this specification. + * + * Tools that translate other media types or programming languages + * to and from `application/schema+json` MAY choose to convert that media + * type or programming language's native comments to or from `$comment` + * values. The behavior of such translation when both native comments and + * `$comment` properties are present is implementation-dependent. + * + * Implementations SHOULD treat `$comment` identically to an unknown + * extension keyword. They MAY strip `$comment` values at any point + * during processing. In particular, this allows for shortening schemas + * when the size of deployed schemas is a concern. + * + * Implementations MUST NOT take any other action based on the presence, + * absence, or contents of `$comment` properties. In particular, the + * value of `$comment` MUST NOT be collected as an annotation result. + */ + $comment?: string; + /** + * The `$defs` keywords provides a standardized location for schema + * authors to inline re-usable JSON Schemas into a more general schema. The + * keyword does not directly affect the validation result. + * + * This keyword's value MUST be an object. Each member value of this object + * MUST be a valid JSON Schema. + */ + $defs?: Record; + /** + * The `$id` keyword identifies a schema resource with its + * [canonical][[RFC6596]] URI. + * + * Note that this URI is an identifier and not necessarily a network + * locator. In the case of a network-addressable URL, a schema need not be + * downloadable from its canonical URI. + * + * If present, the value for this keyword MUST be a string, and MUST + * represent a valid [URI-reference][RFC3986]. This URI-reference SHOULD + * be normalized, and MUST resolve to an [absolute-URI][RFC3986] (without a + * fragment). Therefore, `$id` MUST NOT contain a non-empty fragment, + * and SHOULD NOT contain an empty fragment. + * + * Since an empty fragment in the context of the + * `application/schema+json` media type refers to the same resource as + * the base URI without a fragment, an implementation MAY normalize a URI + * ending with an empty fragment by removing the fragment. However, schema + * authors SHOULD NOT rely on this behavior across implementations. + * + * This URI also serves as the base URI for relative URI-references in + * keywords within the schema resource, in accordance with + * [RFC 3986][RFC3986] section 5.1.1 regarding base URIs embedded in + * content. + * + * The presence of `$id` in a subschema indicates that the subschema + * constitutes a distinct schema resource within a single schema document. + * Furthermore, in accordance with [RFC 3986][RFC3986] section 5.1.2 + * regarding encapsulating entities, if an `$id` in a subschema is a + * relative URI-reference, the base URI for resolving that reference is the + * URI of the parent schema resource. + * + * If no parent schema object explicitly identifies itself as a resource + * with `$id`, the base URI is that of the entire document. + * + * The root schema of a JSON Schema document SHOULD contain an `$id` + * keyword with an [absolute-URI][RFC3986] (containing a scheme, but no + * fragment). + * + * [RFC6596]: https://datatracker.ietf.org/doc/html/rfc6596 + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + * + * @format "uri-reference" + */ + $id?: string; + /** + * The value of the `$recursiveAnchor` property MUST be a boolean. + * + * `$recursiveAnchor` is used to dynamically identify a base URI at + * runtime for `$recursiveRef` by marking where such a calculation can + * start, and where it stops. This keyword MUST NOT affect the base URI of + * other keywords, unless they are explicitly defined to rely on it. + * + * If set to `true`, then when the containing schema object is used as a + * target of `$recursiveRef`, a new base URI is determined by examining + * the [dynamic scope][scopes] for the outermost schema that also contains + * `$recursiveAnchor` with a value of `true`. The base URI of that + * schema is then used as the dynamic base URI. + * + * - If no such schema exists, then the base URI is unchanged. + * - If this keyword is set to `false`, the base URI is unchanged. + * + * Omitting this keyword has the same behavior as a value of `false`. + * + * [scopes]: https://json-schema.org/draft/2019-09/json-schema-core.html#scopes + */ + $recursiveAnchor?: boolean; + /** + * The value of the `$recursiveRef` property MUST be a string which is + * a URI-reference. It is a by-reference applicator that uses a + * dynamically calculated base URI to resolve its value. + * + * The behavior of this keyword is defined only for the value `"#"`. + * Implementations MAY choose to consider other values to be errors. + * + * The value of `$recursiveRef` is initially resolved against the + * current base URI, in the same manner as for `$ref`. + * + * The schema identified by the resulting URI is examined for the + * presence of `$recursiveAnchor`, and a new base URI is calculated. + * + * Finally, the value of `$recursiveRef` is resolved against the new base + * URI determined according to `$recursiveAnchor` producing the final + * resolved reference URI. + * + * Note that in the absence of `$recursiveAnchor` (and in some cases + * when it is present), `$recursiveRef`'s behavior is identical to + * that of `$ref`. + * + * As with `$ref`, the results of this keyword are the results of the + * referenced schema. + * + * @format "uri-reference" + */ + $recursiveRef?: string; + /** + * The `$ref` keyword is an applicator that is used to reference a + * statically identified schema. Its results are the results of the + * referenced schema. Other keywords can appear alongside of `$ref` in + * the same schema object. + * + * The value of the `$ref` property MUST be a string which is a + * URI-Reference. Resolved against the current URI base, it produces the + * URI of the schema to apply. + * + * @format "uri-reference" + */ + $ref?: string; + /** + * The `$schema` keyword is both used as a JSON Schema version identifier + * and the location of a resource which is itself a JSON Schema, which + * describes any schema written for this particular version. + * + * The value of this keyword MUST be a [URI][RFC3986] (containing a scheme) + * and this URI MUST be normalized. The current schema MUST be valid + * against the meta-schema identified by this URI. + * + * If this URI identifies a retrievable resource, that resource SHOULD be + * of media type `application/schema+json`. + * + * The `$schema` keyword SHOULD be used in a resource root schema. + * It MUST NOT appear in resource subschemas. If absent from the root + * schema, the resulting behavior is implementation-defined. + * + * If multiple schema resources are present in a single document, then all + * schema resources SHOULD Have the same value for `$schema`. The result + * of differing values for "$schema" within the same schema document is + * implementation-defined. + * + * Values for this property are defined elsewhere in this and other + * documents, and by other parties. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + * + * @format "uri" + */ + $schema?: string; + /** + * The `$vocabulary` keyword is used in meta-schemas to identify the + * vocabularies available for use in schemas described by that meta-schema. + * It is also used to indicate whether each vocabulary is required or + * optional, in the sense that an implementation MUST understand the + * required vocabularies in order to successfully process the schema. + * + * The value of this keyword MUST be an object. The property names in the + * object MUST be URIs (containing a scheme) and this URI MUST be + * normalized. Each URI that appears as a property name identifies a + * specific set of keywords and their semantics. + * + * The URI MAY be a URL, but the nature of the retrievable resource is + * currently undefined, and reserved for future use. Vocabulary authors + * MAY use the URL of the vocabulary specification, in a human-readable + * media type such as `text/html` or `text/plain`, as the vocabulary + * URI. + * + * The values of the object properties MUST be booleans. + * If the value is `true`, then implementations that do not recognize + * the vocabulary MUST refuse to process any schemas that declare + * this meta-schema with "$schema". If the value is `false`, + * implementations that do not recognize the vocabulary SHOULD proceed with + * processing such schemas. + * + * Unrecognized keywords SHOULD be ignored. This remains the case for + * keywords defined by unrecognized vocabularies. It is not currently + * possible to distinguish between unrecognized keywords that are defined + * in vocabularies from those that are not part of any vocabulary. + * + * The `$vocabulary` keyword SHOULD be used in the root schema of any + * schema document intended for use as a meta-schema. It MUST NOT appear + * in subschemas. + * + * The `$vocabulary` keyword MUST be ignored in schema documents that are + * not being processed as a meta-schema. + */ + $vocabulary?: Record; + /** + * The value of `additionalItems` MUST be a valid JSON Schema. + * + * The behavior of this keyword depends on the presence and annotation + * result of `items` within the same schema object. + * If `items` is present, and its annotation result is a number, + * validation succeeds if every instance element at an index greater than + * that number validates against `additionalItems`. + * + * Otherwise, if `items` is absent or its annotation result is the + * boolean `true`, `additionalItems` MUST be ignored. + * + * If the `additionalItems` subschema is applied to any positions within + * the instance array, it produces an annotation result of boolean + * `true`, analogous to the single schema behavior of `items`. If any + * `additionalItems` keyword from any subschema applied to the same + * instance location produces an annotation value of `true`, then the + * combined result from these keywords is also `true`. + * + * Omitting this keyword has the same assertion behavior as an empty + * schema. + * + * Implementations MAY choose to implement or optimize this keyword in + * another way that produces the same effect, such as by directly + * checking for the presence and size of an `items` array. + */ + additionalItems?: JSONSchema; + /** + * The value of `additionalProperties` MUST be a valid JSON Schema. + * + * The behavior of this keyword depends on the presence and annotation + * results of `properties` and `patternProperties` within the same + * schema object. Validation with `additionalProperties` applies only to + * the child values of instance names that do not appear in the annotation + * results of either `properties` or `patternProperties`. + * + * For all such properties, validation succeeds if the child instance + * validates against the `additionalProperties` schema. + * + * The annotation result of this keyword is the set of instance property + * names validated by this keyword's subschema. Annotation results for + * `additionalProperties` keywords from multiple schemas applied to the + * same instance location are combined by taking the union of the sets. + * + * Omitting this keyword has the same assertion behavior as an empty + * schema. + * + * Implementations MAY choose to implement or optimize this keyword in + * another way that produces the same effect, such as by directly checking + * the names in `properties` and the patterns in `patternProperties` + * against the instance property set. + */ + additionalProperties?: JSONSchema; + /** + * This keyword's value MUST be a non-empty array. Each item of the array + * MUST be a valid JSON Schema. + * + * An instance validates successfully against this keyword if it validates + * successfully against all schemas defined by this keyword's value. + */ + allOf?: MaybeReadonlyArray>; + /** + * This keyword's value MUST be a non-empty array. Each item of the array + * MUST be a valid JSON Schema. + * + * An instance validates successfully against this keyword if it validates + * successfully against at least one schema defined by this keyword's + * value. + */ + anyOf?: MaybeReadonlyArray>; + /** + * An instance validates successfully against this keyword if its value is + * equal to the value of the keyword. + * + * Use of this keyword is functionally equivalent to the `enum` keyword + * with a single value. + */ + const?: Value; + /** + * An array instance is valid against `contains` if at least one of + * its elements is valid against the given schema. Note that when + * collecting annotations, the subschema MUST be applied to every + * array element even after the first match has been found. This + * is to ensure that all possible annotations are collected. + */ + contains?: JSONSchema; + /** + * If the instance value is a string, this property defines that the + * string SHOULD be interpreted as binary data and decoded using the + * encoding named by this property. [RFC 2045, Sec 6.1][RFC2045] lists the + * possible values for this property. + * + * The value of this property SHOULD be ignored if the instance described + * is not a string. + * + * If this keyword is absent, but `contentMediaType` is present, this + * indicates that the media type could be encoded into `UTF-8` like any + * other JSON string value, and does not require additional decoding. + * + * The value of this property MUST be a string. + * + * [RFC2045]: https://datatracker.ietf.org/doc/html/rfc2045#section-6.1 + */ + contentEncoding?: "7bit" | "8bit" | "base64" | "binary" | "ietf-token" | "quoted-printable" | "x-token"; + /** + * If the instance is a string, this property indicates the media type + * of the contents of the string. If `contentEncoding` is present, + * this property describes the decoded string. + * + * The value of this property must be a media type, as defined by + * [RFC 2046][RFC2046]. This property defines the media type of instances + * which this schema defines. + * + * The value of this property SHOULD be ignored if the instance described + * is not a string. + * + * If the `contentEncoding` property is not present, but the instance + * value is a string, then the value of this property SHOULD specify a text + * document type, and the character set SHOULD be the character set into + * which the JSON string value was decoded (for which the default is + * Unicode). + * + * [RFC2046]: https://datatracker.ietf.org/doc/html/rfc2046 + */ + contentMediaType?: string; + /** + * If the instance is a string, and if `contentMediaType` is present, + * this property contains a schema which describes the structure of the + * string. + * + * This keyword MAY be used with any media type that can be mapped into + * JSON Schema's data model. + * + * The value of this property SHOULD be ignored if `contentMediaType` is + * not present. + */ + contentSchema?: JSONSchema; + /** + * This keyword can be used to supply a default JSON value associated with + * a particular schema. It is RECOMMENDED that a `default` value be valid + * against the associated schema. + */ + default?: Value; + /** + * @deprecated `definitions` has been renamed to `$defs`. + */ + definitions?: Record; + /** + * @deprecated `dependencies` has been split into two keywords: + * `dependentSchemas` and `dependentRequired`. + */ + dependencies?: Record | JSONSchema>; + /** + * The value of this keyword MUST be an object. Properties in + * this object, if any, MUST be arrays. Elements in each array, + * if any, MUST be strings, and MUST be unique. + * + * This keyword specifies properties that are required if a specific + * other property is present. Their requirement is dependent on the + * presence of the other property. + * + * Validation succeeds if, for each name that appears in both + * the instance and as a name within this keyword's value, every + * item in the corresponding array is also the name of a property + * in the instance. + * + * Omitting this keyword has the same behavior as an empty object. + */ + dependentRequired?: Record>; + /** + * This keyword specifies subschemas that are evaluated if the instance is + * an object and contains a certain property. + * + * This keyword's value MUST be an object. Each value in the object MUST be + * a valid JSON Schema. + * + * If the object key is a property in the instance, the entire instance + * must validate against the subschema. Its use is dependent on the + * presence of the property. + * + * Omitting this keyword has the same behavior as an empty object. + */ + dependentSchemas?: Record; + /** + * The value of this keyword MUST be a boolean. When multiple occurrences + * of this keyword are applicable to a single sub-instance, applications + * SHOULD consider the instance location to be deprecated if any occurrence + * specifies a `true` value. + * + * If `deprecated` has a value of boolean `true`, it indicates that + * applications SHOULD refrain from usage of the declared property. It MAY + * mean the property is going to be removed in the future. + * + * A root schema containing `deprecated` with a value of `true` + * indicates that the entire resource being described MAY be removed in the + * future. + * + * When the `deprecated` keyword is applied to an item in an array by + * means of `items`, if `items` is a single schema, the deprecation + * relates to the whole array, while if `items` is an array of schemas, + * the deprecation relates to the corresponding item according to the + * subschemas position. + * + * Omitting this keyword has the same behavior as a value of `false`. + */ + deprecated?: boolean; + /** + * Can be used to decorate a user interface with explanation or information + * about the data produced. + */ + description?: string; + /** + * This keyword's value MUST be a valid JSON Schema. + * + * When `if` is present, and the instance fails to validate against its + * subschema, then validation succeeds against this keyword if the instance + * successfully validates against this keyword's subschema. + * + * This keyword has no effect when `if` is absent, or when the instance + * successfully validates against its subschema. Implementations MUST NOT + * evaluate the instance against this keyword, for either validation or + * annotation collection purposes, in such cases. + */ + else?: JSONSchema; + /** + * The value of this keyword MUST be an array. This array SHOULD have at + * least one element. Elements in the array SHOULD be unique. + * + * An instance validates successfully against this keyword if its value is + * equal to one of the elements in this keyword's array value. + * + * Elements in the array might be of any type, including `null`. + */ + enum?: MaybeReadonlyArray; + /** + * The value of this keyword MUST be an array. When multiple occurrences of + * this keyword are applicable to a single sub-instance, implementations + * MUST provide a flat array of all values rather than an array of arrays. + * + * This keyword can be used to provide sample JSON values associated with a + * particular schema, for the purpose of illustrating usage. It is + * RECOMMENDED that these values be valid against the associated schema. + * + * Implementations MAY use the value(s) of `default`, if present, as an + * additional example. If `examples` is absent, `default` MAY still be + * used in this manner. + */ + examples?: MaybeReadonlyArray; + /** + * The value of `exclusiveMaximum` MUST be a number, representing an + * exclusive upper limit for a numeric instance. + * + * If the instance is a number, then the instance is valid only if it has a + * value strictly less than (not equal to) `exclusiveMaximum`. + */ + exclusiveMaximum?: number; + /** + * The value of `exclusiveMinimum` MUST be a number, representing an + * exclusive lower limit for a numeric instance. + * + * If the instance is a number, then the instance is valid only if it has a + * value strictly greater than (not equal to) `exclusiveMinimum`. + */ + exclusiveMinimum?: number; + /** + * Implementations MAY treat `format` as an assertion in addition to an + * annotation, and attempt to validate the value's conformance to the + * specified semantics. + * + * The value of this keyword is called a format attribute. It MUST be a + * string. A format attribute can generally only validate a given set + * of instance types. If the type of the instance to validate is not in + * this set, validation for this format attribute and instance SHOULD + * succeed. Format attributes are most often applied to strings, but can + * be specified to apply to any type. + * + * Implementations MAY support custom format attributes. Save for agreement + * between parties, schema authors SHALL NOT expect a peer implementation + * to support such custom format attributes. An implementation MUST NOT + * fail validation or cease processing due to an unknown format attribute. + * When treating `format` as an annotation, implementations SHOULD + * collect both known and unknown format attribute values. + */ + format?: string; + /** + * This keyword's value MUST be a valid JSON Schema. + * + * This validation outcome of this keyword's subschema has no direct effect + * on the overall validation result. Rather, it controls which of the + * `then` or `else` keywords are evaluated. + * + * Instances that successfully validate against this keyword's subschema + * MUST also be valid against the subschema value of the `then` keyword, + * if present. + * + * Instances that fail to validate against this keyword's subschema MUST + * also be valid against the subschema value of the `else` keyword, if + * present. + * + * If annotations are being collected, they are collected + * from this keyword's subschema in the usual way, including when the + * keyword is present without either `then` or `else`. + */ + if?: JSONSchema; + /** + * The value of `items` MUST be either a valid JSON Schema or an array of + * valid JSON Schemas. + * + * If `items` is a schema, validation succeeds if all elements in the + * array successfully validate against that schema. + * + * If `items` is an array of schemas, validation succeeds if each element + * of the instance validates against the schema at the same position, if + * any. + * + * This keyword produces an annotation value which is the largest index to + * which this keyword applied a subschema. The value MAY be a boolean + * `true` if a subschema was applied to every index of the instance, such + * as when `items` is a schema. + * + * Annotation results for `items` keywords from multiple schemas applied + * to the same instance location are combined by setting the combined + * result to `true` if any of the values are `true`, and otherwise + * retaining the largest numerical value. + * + * Omitting this keyword has the same assertion behavior as an empty + * schema. + */ + items?: MaybeReadonlyArray | JSONSchema; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An array instance is valid against `maxContains` if the number of + * elements that are valid against the schema for + * `contains` is less than, or equal to, the value of this keyword. + * + * If `contains` is not present within the same schema object, then this + * keyword has no effect. + */ + maxContains?: number; + /** + * The value of `maximum` MUST be a number, representing an inclusive + * upper limit for a numeric instance. + * + * If the instance is a number, then this keyword validates only if the + * instance is less than or exactly equal to `maximum`. + */ + maximum?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An array instance is valid against `maxItems` if its size is less + * than, or equal to, the value of this keyword. + * + * @minimum 0 + */ + maxItems?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * A string instance is valid against this keyword if its length is less + * than, or equal to, the value of this keyword. + * + * The length of a string instance is defined as the number of its + * characters as defined by [RFC 8259][RFC8259]. + * + * [RFC8259]: https://datatracker.ietf.org/doc/html/rfc8259 + * + * @minimum 0 + */ + maxLength?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An object instance is valid against `maxProperties` if its number of + * `properties` is less than, or equal to, the value of this keyword. + * + * @minimum 0 + */ + maxProperties?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An array instance is valid against `minContains` if the number of + * elements that are valid against the schema for `contains` is + * greater than, or equal to, the value of this keyword. + * + * A value of `0` is allowed, but is only useful for setting a range + * of occurrences from `0` to the value of `maxContains`. A value of + * `0` with no `maxContains` causes `contains` to always pass + * validation. + * + * If `contains` is not present within the same schema object, then this + * keyword has no effect. + * + * Omitting this keyword has the same behavior as a value of `1`. + * + * @default 1 + */ + minContains?: number; + /** + * The value of `minimum` MUST be a number, representing an inclusive + * lower limit for a numeric instance. + * + * If the instance is a number, then this keyword validates only if the + * instance is greater than or exactly equal to `minimum`. + */ + minimum?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An array instance is valid against `minItems` if its size is greater + * than, or equal to, the value of this keyword. + * + * Omitting this keyword has the same behavior as a value of `0`. + * + * @default 0 + * @minimum 0 + */ + minItems?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * A string instance is valid against this keyword if its length is greater + * than, or equal to, the value of this keyword. + * + * The length of a string instance is defined as the number of its + * characters as defined by [RFC 8259][RFC8259]. + * + * Omitting this keyword has the same behavior as a value of `0`. + * + * [RFC8259]: https://datatracker.ietf.org/doc/html/rfc8259 + * + * @default 0 + * @minimum 0 + */ + minLength?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An object instance is valid against `minProperties` if its number of + * `properties` is greater than, or equal to, the value of this keyword. + * + * Omitting this keyword has the same behavior as a value of `0`. + * + * @default 0 + * @minimum 0 + */ + minProperties?: number; + /** + * The value of `multipleOf` MUST be a number, strictly greater than + * `0`. + * + * A numeric instance is valid only if division by this keyword's value + * results in an integer. + * + * @exclusiveMinimum 0 + */ + multipleOf?: number; + /** + * This keyword's value MUST be a valid JSON Schema. + * + * An instance is valid against this keyword if it fails to validate + * successfully against the schema defined by this keyword. + */ + not?: JSONSchema; + /** + * This keyword's value MUST be a non-empty array. Each item of the array + * MUST be a valid JSON Schema. + * + * An instance validates successfully against this keyword if it validates + * successfully against exactly one schema defined by this keyword's value. + */ + oneOf?: MaybeReadonlyArray>; + /** + * The value of this keyword MUST be a string. This string SHOULD be a + * valid regular expression, according to the [ECMA-262][ecma262] regular + * expression dialect. + * + * A string instance is considered valid if the regular expression matches + * the instance successfully. Recall: regular expressions are not + * implicitly anchored. + * + * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ + * + * @format "regex" + */ + pattern?: string; + /** + * The value of `patternProperties` MUST be an object. Each property name + * of this object SHOULD be a valid regular expression, according to the + * [ECMA-262][ecma262] regular expression dialect. Each property value of + * this object MUST be a valid JSON Schema. + * + * Validation succeeds if, for each instance name that matches any regular + * expressions that appear as a property name in this keyword's value, + * the child instance for that name successfully validates against each + * schema that corresponds to a matching regular expression. + * + * The annotation result of this keyword is the set of instance property + * names matched by this keyword. Annotation results for + * `patternProperties` keywords from multiple schemas applied to the same + * instance location are combined by taking the union of the sets. + * + * Omitting this keyword has the same assertion behavior as an empty + * object. + * + * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ + */ + patternProperties?: Record; + /** + * The value of `properties` MUST be an object. Each value of this object + * MUST be a valid JSON Schema. + * + * Validation succeeds if, for each name that appears in both the instance + * and as a name within this keyword's value, the child instance for that + * name successfully validates against the corresponding schema. + * + * The annotation result of this keyword is the set of instance property + * names matched by this keyword. Annotation results for `properties` + * keywords from multiple schemas applied to the same instance location are + * combined by taking the union of the sets. + * + * Omitting this keyword has the same assertion behavior as an empty + * object. + */ + properties?: Record; + /** + * The value of `propertyNames` MUST be a valid JSON Schema. + * + * If the instance is an object, this keyword validates if every property + * name in the instance validates against the provided schema. + * Note the property name that the schema is testing will always be a + * string. + * + * Omitting this keyword has the same behavior as an empty schema. + */ + propertyNames?: JSONSchema; + /** + * The value of this keyword MUST be a boolean. When multiple occurrences + * of this keyword are applicable to a single sub-instance, the resulting + * value MUST be `true` if any occurrence specifies a `true` value, and + * MUST be `false` otherwise. + * + * If `readOnly` has a value of boolean `true`, it indicates that the + * value of the instance is managed exclusively by the owning authority, + * and attempts by an application to modify the value of this property are + * expected to be ignored or rejected by that owning authority. + * + * An instance document that is marked as `readOnly` for the entire + * document MAY be ignored if sent to the owning authority, or MAY result + * in an error, at the authority's discretion. + * + * For example, `readOnly` would be used to mark a database-generated + * serial number as read-only. + * + * This keyword can be used to assist in user interface instance + * generation. + * + * @default false + */ + readOnly?: boolean; + /** + * The value of this keyword MUST be an array. Elements of this array, if + * any, MUST be strings, and MUST be unique. + * + * An object instance is valid against this keyword if every item in the + * array is the name of a property in the instance. + * + * Omitting this keyword has the same behavior as an empty array. + */ + required?: MaybeReadonlyArray; + /** + * This keyword's value MUST be a valid JSON Schema. + * + * When `if` is present, and the instance successfully validates against + * its subschema, then validation succeeds against this keyword if the + * instance also successfully validates against this keyword's subschema. + * + * This keyword has no effect when `if` is absent, or when the instance + * fails to validate against its subschema. Implementations MUST NOT + * evaluate the instance against this keyword, for either validation or + * annotation collection purposes, in such cases. + */ + then?: JSONSchema; + /** + * Can be used to decorate a user interface with a short label about the + * data produced. + */ + title?: string; + /** + * The value of this keyword MUST be either a string or an array. If it is + * an array, elements of the array MUST be strings and MUST be unique. + * + * String values MUST be one of the six primitive types (`"null"`, + * `"boolean"`, `"object"`, `"array"`, `"number"`, or + * `"string"`), or `"integer"` which matches any number with a zero + * fractional part. + * + * An instance validates if and only if the instance is in any of the sets + * listed for this keyword. + */ + type?: SchemaType; + /** + * The value of `unevaluatedItems` MUST be a valid JSON Schema. + * + * The behavior of this keyword depends on the annotation results of + * adjacent keywords that apply to the instance location being validated. + * Specifically, the annotations from `items` and `additionalItems`, + * which can come from those keywords when they are adjacent to the + * `unevaluatedItems` keyword. Those two annotations, as well as + * `unevaluatedItems`, can also result from any and all adjacent + * [in-place applicator][in-place-applicator] keywords. + * + * If an `items` annotation is present, and its annotation result is a + * number, and no "additionalItems" or `unevaluatedItems` annotation is + * present, then validation succeeds if every instance element at an index + * greater than the `items` annotation validates against + * `unevaluatedItems`. + * + * Otherwise, if any `items`, `additionalItems`, or + * `unevaluatedItems` annotations are present with a value of boolean + * `true`, then `unevaluatedItems` MUST be ignored. However, if none + * of these annotations are present, `unevaluatedItems` MUST be applied + * to all locations in the array. + * + * This means that `items`, `additionalItems`, and all in-place + * applicators MUST be evaluated before this keyword can be evaluated. + * Authors of extension keywords MUST NOT define an in-place applicator + * that would need to be evaluated before this keyword. + * + * If the `unevaluatedItems` subschema is applied to any positions within + * the instance array, it produces an annotation result of boolean + * `true`, analogous to the single schema behavior of `items`. If any + * `unevaluatedItems` keyword from any subschema applied to the same + * instance location produces an annotation value of `true`, then the + * combined result from these keywords is also `true`. + * + * Omitting this keyword has the same assertion behavior as an empty + * schema. + * + * Implementations that do not collect annotations MUST raise an error + * upon encountering this keyword. + * + * [in-place-applicator]: https://json-schema.org/draft/2019-09/json-schema-core.html#in-place + */ + unevaluatedItems?: JSONSchema; + /** + * The value of `unevaluatedProperties` MUST be a valid JSON Schema. + * + * The behavior of this keyword depends on the annotation results of + * adjacent keywords that apply to the instance location being validated. + * Specifically, the annotations from `properties`, + * `patternProperties`, and `additionalProperties`, which can come from + * those keywords when they are adjacent to the `unevaluatedProperties` + * keyword. Those three annotations, as well as `unevaluatedProperties`, + * can also result from any and all adjacent + * [in-place applicator][in-place-applicator] keywords. + * + * Validation with `unevaluatedProperties` applies only to the child + * values of instance names that do not appear in the `properties`, + * `patternProperties`, `additionalProperties`, or + * `unevaluatedProperties` annotation results that apply to the + * instance location being validated. + * + * For all such properties, validation succeeds if the child instance + * validates against the "unevaluatedProperties" schema. + * + * This means that `properties`, `patternProperties`, + * `additionalProperties`, and all in-place applicators MUST be evaluated + * before this keyword can be evaluated. Authors of extension keywords + * MUST NOT define an in-place applicator that would need to be evaluated + * before this keyword. + * + * The annotation result of this keyword is the set of instance property + * names validated by this keyword's subschema. Annotation results for + * `unevaluatedProperties` keywords from multiple schemas applied to the + * same instance location are combined by taking the union of the sets. + * + * Omitting this keyword has the same assertion behavior as an empty + * schema. + * + * Implementations that do not collect annotations MUST raise an error upon + * encountering this keyword. + * + * [in-place-applicator]: https://json-schema.org/draft/2019-09/json-schema-core.html#in-place + */ + unevaluatedProperties?: JSONSchema; + /** + * The value of this keyword MUST be a boolean. + * + * If this keyword has boolean value `false`, the instance validates + * successfully. If it has boolean value `true`, the instance validates + * successfully if all of its elements are unique. + * + * Omitting this keyword has the same behavior as a value of `false`. + * + * @default false + */ + uniqueItems?: boolean; + /** + * The value of this keyword MUST be a boolean. When multiple occurrences + * of this keyword is applicable to a single sub-instance, the resulting + * value MUST be `true` if any occurrence specifies a `true` value, and + * MUST be `false` otherwise. + * + * If `writeOnly` has a value of boolean `true`, it indicates that the + * value is never present when the instance is retrieved from the owning + * authority. It can be present when sent to the owning authority to update + * or create the document (or the resource it represents), but it will not + * be included in any updated or newly created version of the instance. + * + * An instance document that is marked as `writeOnly` for the entire + * document MAY be returned as a blank document of some sort, or MAY + * produce an error upon retrieval, or have the retrieval request ignored, + * at the authority's discretion. + * + * For example, `writeOnly` would be used to mark a password input field. + * + * These keywords can be used to assist in user interface instance + * generation. In particular, an application MAY choose to use a widget + * that hides input values as they are typed for write-only fields. + * + * @default false + */ + writeOnly?: boolean; +}; +export declare namespace JSONSchema { + type TypeValue = ValueOf | TypeName | Array | TypeName> | ReadonlyArray | TypeName>; + /** + * JSON Schema interface + */ + type Interface = Exclude, boolean>; + type Array = Pick, KeywordByType.Any | KeywordByType.Array>; + type Boolean = Pick, KeywordByType.Any>; + type Integer = Pick, KeywordByType.Any | KeywordByType.Number>; + type Number = Pick, KeywordByType.Any | KeywordByType.Number>; + type Null = Pick, KeywordByType.Any>; + type Object = Pick, KeywordByType.Any | KeywordByType.Object>; + type String = Pick, KeywordByType.Any | KeywordByType.String>; +} +declare namespace KeywordByType { + type Any = "$anchor" | "$comment" | "$defs" | "$id" | "$recursiveAnchor" | "$recursiveRef" | "$ref" | "$schema" | "$vocabulary" | "allOf" | "anyOf" | "const" | "default" | "definitions" | "deprecated" | "description" | "else" | "enum" | "examples" | "format" | "if" | "not" | "oneOf" | "readOnly" | "then" | "title" | "type" | "writeOnly"; + type Array = "additionalItems" | "contains" | "items" | "maxContains" | "maxItems" | "minContains" | "minItems" | "unevaluatedItems" | "uniqueItems"; + type Number = "exclusiveMaximum" | "exclusiveMinimum" | "maximum" | "minimum" | "multipleOf"; + type Object = "additionalProperties" | "dependencies" | "dependentRequired" | "dependentSchemas" | "maxProperties" | "minProperties" | "patternProperties" | "properties" | "propertyNames" | "required" | "unevaluatedProperties"; + type String = "contentEncoding" | "contentMediaType" | "contentSchema" | "maxLength" | "minLength" | "pattern"; +} +/** + * Content encoding strategy enum. + * + * - [Content-Transfer-Encoding Syntax](https://datatracker.ietf.org/doc/html/rfc2045#section-6.1) + * - [7bit vs 8bit encoding](https://stackoverflow.com/questions/25710599/content-transfer-encoding-7bit-or-8-bit/28531705#28531705) + */ +export declare enum ContentEncoding { + /** + * Only US-ASCII characters, which use the lower 7 bits for each character. + * + * Each line must be less than 1,000 characters. + */ + "7bit" = "7bit", + /** + * Allow extended ASCII characters which can use the 8th (highest) bit to + * indicate special characters not available in 7bit. + * + * Each line must be less than 1,000 characters. + */ + "8bit" = "8bit", + /** + * Useful for data that is mostly non-text. + */ + Base64 = "base64", + /** + * Same character set as 8bit, with no line length restriction. + */ + Binary = "binary", + /** + * An extension token defined by a standards-track RFC and registered with + * IANA. + */ + IETFToken = "ietf-token", + /** + * Lines are limited to 76 characters, and line breaks are represented using + * special characters that are escaped. + */ + QuotedPrintable = "quoted-printable", + /** + * The two characters "X-" or "x-" followed, with no intervening white space, + * by any token. + */ + XToken = "x-token" +} +/** + * This enum provides well-known formats that apply to strings. + */ +export declare enum Format { + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "full-date" production in + * [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Date = "date", + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "date-time" production in + * [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + DateTime = "date-time", + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "duration" production. + */ + Duration = "duration", + /** + * A string instance is valid against this attribute if it is a valid Internet + * email address as defined by [RFC 5322, section 3.4.1][RFC5322]. + * + * [RFC5322]: https://datatracker.ietf.org/doc/html/rfc5322 + */ + Email = "email", + /** + * As defined by [RFC 1123, section 2.1][RFC1123], including host names + * produced using the Punycode algorithm specified in + * [RFC 5891, section 4.4][RFC5891]. + * + * [RFC1123]: https://datatracker.ietf.org/doc/html/rfc1123 + * [RFC5891]: https://datatracker.ietf.org/doc/html/rfc5891 + */ + Hostname = "hostname", + /** + * A string instance is valid against this attribute if it is a valid Internet + * email address as defined by [RFC 6531][RFC6531]. + * + * [RFC6531]: https://datatracker.ietf.org/doc/html/rfc6531 + */ + IDNEmail = "idn-email", + /** + * As defined by either [RFC 1123, section 2.1][RFC1123] as for hostname, or + * an internationalized hostname as defined by + * [RFC 5890, section 2.3.2.3][RFC5890]. + * + * [RFC1123]: https://datatracker.ietf.org/doc/html/rfc1123 + * [RFC5890]: https://datatracker.ietf.org/doc/html/rfc5890 + */ + IDNHostname = "idn-hostname", + /** + * An IPv4 address according to the "dotted-quad" ABNF syntax as defined in + * [RFC 2673, section 3.2][RFC2673]. + * + * [RFC2673]: https://datatracker.ietf.org/doc/html/rfc2673 + */ + IPv4 = "ipv4", + /** + * An IPv6 address as defined in [RFC 4291, section 2.2][RFC4291]. + * + * [RFC4291]: https://datatracker.ietf.org/doc/html/rfc4291 + */ + IPv6 = "ipv6", + /** + * A string instance is valid against this attribute if it is a valid IRI, + * according to [RFC 3987][RFC3987]. + * + * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 + */ + IRI = "iri", + /** + * A string instance is valid against this attribute if it is a valid IRI + * Reference (either an IRI or a relative-reference), according to + * [RFC 3987][RFC3987]. + * + * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 + */ + IRIReference = "iri-reference", + /** + * A string instance is valid against this attribute if it is a valid JSON + * string representation of a JSON Pointer, according to + * [RFC 6901, section 5][RFC6901]. + * + * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 + */ + JSONPointer = "json-pointer", + /** + * A string instance is valid against this attribute if it is a valid JSON + * string representation of a JSON Pointer fragment, according to + * [RFC 6901, section 5][RFC6901]. + * + * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 + */ + JSONPointerURIFragment = "json-pointer-uri-fragment", + /** + * This attribute applies to string instances. + * + * A regular expression, which SHOULD be valid according to the + * [ECMA-262][ecma262] regular expression dialect. + * + * Implementations that validate formats MUST accept at least the subset of + * [ECMA-262][ecma262] defined in the [Regular Expressions][regexInterop] + * section of this specification, and SHOULD accept all valid + * [ECMA-262][ecma262] expressions. + * + * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ + * [regexInterop]: https://json-schema.org/draft/2019-09/json-schema-validation.html#regexInterop + */ + RegEx = "regex", + /** + * A string instance is valid against this attribute if it is a valid + * [Relative JSON Pointer][relative-json-pointer]. + * + * [relative-json-pointer]: https://datatracker.ietf.org/doc/html/draft-handrews-relative-json-pointer-01 + */ + RelativeJSONPointer = "relative-json-pointer", + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "time" production in [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Time = "time", + /** + * A string instance is valid against this attribute if it is a valid URI, + * according to [RFC3986][RFC3986]. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + */ + URI = "uri", + /** + * A string instance is valid against this attribute if it is a valid URI + * Reference (either a URI or a relative-reference), according to + * [RFC3986][RFC3986]. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + */ + URIReference = "uri-reference", + /** + * A string instance is valid against this attribute if it is a valid URI + * Template (of any level), according to [RFC 6570][RFC6570]. + * + * Note that URI Templates may be used for IRIs; there is no separate IRI + * Template specification. + * + * [RFC6570]: https://datatracker.ietf.org/doc/html/rfc6570 + */ + URITemplate = "uri-template", + /** + * A string instance is valid against this attribute if it is a valid string + * representation of a UUID, according to [RFC 4122][RFC4122]. + * + * [RFC4122]: https://datatracker.ietf.org/doc/html/rfc4122 + */ + UUID = "uuid" +} +/** + * Enum consisting of simple type names for the `type` keyword + */ +export declare enum TypeName { + /** + * Value MUST be an array. + */ + Array = "array", + /** + * Value MUST be a boolean. + */ + Boolean = "boolean", + /** + * Value MUST be an integer, no floating point numbers are allowed. This is a + * subset of the number type. + */ + Integer = "integer", + /** + * Value MUST be null. Note this is mainly for purpose of being able use union + * types to define nullability. If this type is not included in a union, null + * values are not allowed (the primitives listed above do not allow nulls on + * their own). + */ + Null = "null", + /** + * Value MUST be a number, floating point numbers are allowed. + */ + Number = "number", + /** + * Value MUST be an object. + */ + Object = "object", + /** + * Value MUST be a string. + */ + String = "string" +} +export declare const keywords: readonly ["$anchor", "$comment", "$defs", "$id", "$recursiveAnchor", "$recursiveRef", "$ref", "$schema", "$vocabulary", "additionalItems", "additionalProperties", "allOf", "anyOf", "const", "contains", "contentEncoding", "contentMediaType", "contentSchema", "default", "definitions", "dependencies", "dependentRequired", "dependentSchemas", "deprecated", "description", "else", "enum", "examples", "exclusiveMaximum", "exclusiveMinimum", "format", "if", "items", "maxContains", "maximum", "maxItems", "maxLength", "maxProperties", "minContains", "minimum", "minItems", "minLength", "minProperties", "multipleOf", "not", "oneOf", "pattern", "patternProperties", "properties", "propertyNames", "readOnly", "required", "then", "title", "type", "unevaluatedItems", "unevaluatedProperties", "uniqueItems", "writeOnly"]; +export {}; diff --git a/node_modules/json-schema-typed/draft_2019_09.js b/node_modules/json-schema-typed/draft_2019_09.js new file mode 100644 index 000000000..a488571d9 --- /dev/null +++ b/node_modules/json-schema-typed/draft_2019_09.js @@ -0,0 +1,349 @@ +// @generated +// This code is automatically generated. Manual editing is not recommended. +/* + * BSD-2-Clause License + * + * Original source code is copyright (c) 2025 Remy Rylan + * + * + * Documentation and keyword descriptions are copyright (c) 2019 IETF Trust + * , Austin Wright , Henry Andrews + * , Ben Hutton , and Greg Dennis + * . All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +export const draft = "2019-09"; +export const $schema = "https://json-schema.org/draft/2019-09/schema"; +// ----------------------------------------------------------------------------- +/** + * Content encoding strategy enum. + * + * - [Content-Transfer-Encoding Syntax](https://datatracker.ietf.org/doc/html/rfc2045#section-6.1) + * - [7bit vs 8bit encoding](https://stackoverflow.com/questions/25710599/content-transfer-encoding-7bit-or-8-bit/28531705#28531705) + */ +export var ContentEncoding; +(function (ContentEncoding) { + /** + * Only US-ASCII characters, which use the lower 7 bits for each character. + * + * Each line must be less than 1,000 characters. + */ + ContentEncoding["7bit"] = "7bit"; + /** + * Allow extended ASCII characters which can use the 8th (highest) bit to + * indicate special characters not available in 7bit. + * + * Each line must be less than 1,000 characters. + */ + ContentEncoding["8bit"] = "8bit"; + /** + * Useful for data that is mostly non-text. + */ + ContentEncoding["Base64"] = "base64"; + /** + * Same character set as 8bit, with no line length restriction. + */ + ContentEncoding["Binary"] = "binary"; + /** + * An extension token defined by a standards-track RFC and registered with + * IANA. + */ + ContentEncoding["IETFToken"] = "ietf-token"; + /** + * Lines are limited to 76 characters, and line breaks are represented using + * special characters that are escaped. + */ + ContentEncoding["QuotedPrintable"] = "quoted-printable"; + /** + * The two characters "X-" or "x-" followed, with no intervening white space, + * by any token. + */ + ContentEncoding["XToken"] = "x-token"; +})(ContentEncoding || (ContentEncoding = {})); +/** + * This enum provides well-known formats that apply to strings. + */ +export var Format; +(function (Format) { + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "full-date" production in + * [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Format["Date"] = "date"; + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "date-time" production in + * [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Format["DateTime"] = "date-time"; + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "duration" production. + */ + Format["Duration"] = "duration"; + /** + * A string instance is valid against this attribute if it is a valid Internet + * email address as defined by [RFC 5322, section 3.4.1][RFC5322]. + * + * [RFC5322]: https://datatracker.ietf.org/doc/html/rfc5322 + */ + Format["Email"] = "email"; + /** + * As defined by [RFC 1123, section 2.1][RFC1123], including host names + * produced using the Punycode algorithm specified in + * [RFC 5891, section 4.4][RFC5891]. + * + * [RFC1123]: https://datatracker.ietf.org/doc/html/rfc1123 + * [RFC5891]: https://datatracker.ietf.org/doc/html/rfc5891 + */ + Format["Hostname"] = "hostname"; + /** + * A string instance is valid against this attribute if it is a valid Internet + * email address as defined by [RFC 6531][RFC6531]. + * + * [RFC6531]: https://datatracker.ietf.org/doc/html/rfc6531 + */ + Format["IDNEmail"] = "idn-email"; + /** + * As defined by either [RFC 1123, section 2.1][RFC1123] as for hostname, or + * an internationalized hostname as defined by + * [RFC 5890, section 2.3.2.3][RFC5890]. + * + * [RFC1123]: https://datatracker.ietf.org/doc/html/rfc1123 + * [RFC5890]: https://datatracker.ietf.org/doc/html/rfc5890 + */ + Format["IDNHostname"] = "idn-hostname"; + /** + * An IPv4 address according to the "dotted-quad" ABNF syntax as defined in + * [RFC 2673, section 3.2][RFC2673]. + * + * [RFC2673]: https://datatracker.ietf.org/doc/html/rfc2673 + */ + Format["IPv4"] = "ipv4"; + /** + * An IPv6 address as defined in [RFC 4291, section 2.2][RFC4291]. + * + * [RFC4291]: https://datatracker.ietf.org/doc/html/rfc4291 + */ + Format["IPv6"] = "ipv6"; + /** + * A string instance is valid against this attribute if it is a valid IRI, + * according to [RFC 3987][RFC3987]. + * + * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 + */ + Format["IRI"] = "iri"; + /** + * A string instance is valid against this attribute if it is a valid IRI + * Reference (either an IRI or a relative-reference), according to + * [RFC 3987][RFC3987]. + * + * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 + */ + Format["IRIReference"] = "iri-reference"; + /** + * A string instance is valid against this attribute if it is a valid JSON + * string representation of a JSON Pointer, according to + * [RFC 6901, section 5][RFC6901]. + * + * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 + */ + Format["JSONPointer"] = "json-pointer"; + /** + * A string instance is valid against this attribute if it is a valid JSON + * string representation of a JSON Pointer fragment, according to + * [RFC 6901, section 5][RFC6901]. + * + * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 + */ + Format["JSONPointerURIFragment"] = "json-pointer-uri-fragment"; + /** + * This attribute applies to string instances. + * + * A regular expression, which SHOULD be valid according to the + * [ECMA-262][ecma262] regular expression dialect. + * + * Implementations that validate formats MUST accept at least the subset of + * [ECMA-262][ecma262] defined in the [Regular Expressions][regexInterop] + * section of this specification, and SHOULD accept all valid + * [ECMA-262][ecma262] expressions. + * + * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ + * [regexInterop]: https://json-schema.org/draft/2019-09/json-schema-validation.html#regexInterop + */ + Format["RegEx"] = "regex"; + /** + * A string instance is valid against this attribute if it is a valid + * [Relative JSON Pointer][relative-json-pointer]. + * + * [relative-json-pointer]: https://datatracker.ietf.org/doc/html/draft-handrews-relative-json-pointer-01 + */ + Format["RelativeJSONPointer"] = "relative-json-pointer"; + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "time" production in [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Format["Time"] = "time"; + /** + * A string instance is valid against this attribute if it is a valid URI, + * according to [RFC3986][RFC3986]. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + */ + Format["URI"] = "uri"; + /** + * A string instance is valid against this attribute if it is a valid URI + * Reference (either a URI or a relative-reference), according to + * [RFC3986][RFC3986]. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + */ + Format["URIReference"] = "uri-reference"; + /** + * A string instance is valid against this attribute if it is a valid URI + * Template (of any level), according to [RFC 6570][RFC6570]. + * + * Note that URI Templates may be used for IRIs; there is no separate IRI + * Template specification. + * + * [RFC6570]: https://datatracker.ietf.org/doc/html/rfc6570 + */ + Format["URITemplate"] = "uri-template"; + /** + * A string instance is valid against this attribute if it is a valid string + * representation of a UUID, according to [RFC 4122][RFC4122]. + * + * [RFC4122]: https://datatracker.ietf.org/doc/html/rfc4122 + */ + Format["UUID"] = "uuid"; +})(Format || (Format = {})); +/** + * Enum consisting of simple type names for the `type` keyword + */ +export var TypeName; +(function (TypeName) { + /** + * Value MUST be an array. + */ + TypeName["Array"] = "array"; + /** + * Value MUST be a boolean. + */ + TypeName["Boolean"] = "boolean"; + /** + * Value MUST be an integer, no floating point numbers are allowed. This is a + * subset of the number type. + */ + TypeName["Integer"] = "integer"; + /** + * Value MUST be null. Note this is mainly for purpose of being able use union + * types to define nullability. If this type is not included in a union, null + * values are not allowed (the primitives listed above do not allow nulls on + * their own). + */ + TypeName["Null"] = "null"; + /** + * Value MUST be a number, floating point numbers are allowed. + */ + TypeName["Number"] = "number"; + /** + * Value MUST be an object. + */ + TypeName["Object"] = "object"; + /** + * Value MUST be a string. + */ + TypeName["String"] = "string"; +})(TypeName || (TypeName = {})); +// ----------------------------------------------------------------------------- +// Keywords +// ----------------------------------------------------------------------------- +export const keywords = [ + "$anchor", + "$comment", + "$defs", + "$id", + "$recursiveAnchor", + "$recursiveRef", + "$ref", + "$schema", + "$vocabulary", + "additionalItems", + "additionalProperties", + "allOf", + "anyOf", + "const", + "contains", + "contentEncoding", + "contentMediaType", + "contentSchema", + "default", + "definitions", + "dependencies", + "dependentRequired", + "dependentSchemas", + "deprecated", + "description", + "else", + "enum", + "examples", + "exclusiveMaximum", + "exclusiveMinimum", + "format", + "if", + "items", + "maxContains", + "maximum", + "maxItems", + "maxLength", + "maxProperties", + "minContains", + "minimum", + "minItems", + "minLength", + "minProperties", + "multipleOf", + "not", + "oneOf", + "pattern", + "patternProperties", + "properties", + "propertyNames", + "readOnly", + "required", + "then", + "title", + "type", + "unevaluatedItems", + "unevaluatedProperties", + "uniqueItems", + "writeOnly", +]; diff --git a/node_modules/json-schema-typed/draft_2020_12.d.ts b/node_modules/json-schema-typed/draft_2020_12.d.ts new file mode 100644 index 000000000..c2024fb8f --- /dev/null +++ b/node_modules/json-schema-typed/draft_2020_12.d.ts @@ -0,0 +1,1239 @@ +export declare const draft: "2020-12"; +export declare const $schema: "https://json-schema.org/draft/2020-12/schema"; +type MaybeReadonlyArray = Array | ReadonlyArray; +type ValueOf = T[keyof T]; +/** + * JSON Schema [Draft 2020-12](https://json-schema.org/draft/2020-12/json-schema-validation.html) + */ +export type JSONSchema ? "object" : JSONSchema.TypeValue> = boolean | { + /** + * Using JSON Pointer fragments requires knowledge of the structure of the + * schema. When writing schema documents with the intention to provide + * re-usable schemas, it may be preferable to use a plain name fragment + * that is not tied to any particular structural location. This allows a + * subschema to be relocated without requiring JSON Pointer references to + * be updated. + * + * The `$anchor` keyword is used to specify such a fragment. It is an + * identifier keyword that can only be used to create plain name fragments. + * + * If present, the value of this keyword MUST be a string, which MUST start + * with a letter `[A-Za-z]`, followed by any number of letters, digits + * `[0-9]`, hyphens `-`, underscores `_`, colons `:`, + * or periods `.`. + * + * Note that the anchor string does not include the `#` character, + * as it is not a URI-reference. An `{"$anchor": "foo"}` becomes the + * fragment `#foo` when used in a URI. + * + * The base URI to which the resulting fragment is appended is determined + * by the `$id` keyword as explained in the previous section. + * Two `$anchor` keywords in the same schema document MAY have the same + * value if they apply to different base URIs, as the resulting full URIs + * will be distinct. However, the effect of two `$anchor` keywords + * with the same value and the same base URI is undefined. Implementations + * MAY raise an error if such usage is detected. + */ + $anchor?: string; + /** + * This keyword reserves a location for comments from schema authors to + * readers or maintainers of the schema. + * + * The value of this keyword MUST be a string. Implementations MUST NOT + * present this string to end users. Tools for editing schemas SHOULD + * support displaying and editing this keyword. The value of this keyword + * MAY be used in debug or error output which is intended for developers + * making use of schemas. + * + * Schema vocabularies SHOULD allow `$comment` within any object + * containing vocabulary keywords. Implementations MAY assume `$comment` + * is allowed unless the vocabulary specifically forbids it. Vocabularies + * MUST NOT specify any effect of `$comment` beyond what is described in + * this specification. + * + * Tools that translate other media types or programming languages + * to and from `application/schema+json` MAY choose to convert that media + * type or programming language's native comments to or from `$comment` + * values. The behavior of such translation when both native comments and + * `$comment` properties are present is implementation-dependent. + * + * Implementations MAY strip `$comment` values at any point during + * processing. In particular, this allows for shortening schemas when the + * size of deployed schemas is a concern. + * + * Implementations MUST NOT take any other action based on the presence, + * absence, or contents of `$comment` properties. In particular, the + * value of `$comment` MUST NOT be collected as an annotation result. + */ + $comment?: string; + /** + * The `$defs` keyword reserves a location for schema authors to inline + * re-usable JSON Schemas into a more general schema. The keyword does not + * directly affect the validation result. + * + * This keyword's value MUST be an object. Each member value of this object + * MUST be a valid JSON Schema. + */ + $defs?: Record; + /** + * "The `$dynamicAnchor` indicates that the fragment is an extension + * point when used with the `$dynamicRef` keyword. This low-level, + * advanced feature makes it easier to extend recursive schemas such as the + * meta-schemas, without imposing any particular semantics on that + * extension. See `$dynamicRef` for more details. + */ + $dynamicAnchor?: string; + /** + * The `$dynamicRef` keyword is an applicator that allows for deferring + * the full resolution until runtime, at which point it is resolved each + * time it is encountered while evaluating an instance. + * + * Together with `$dynamicAnchor`, `$dynamicRef` implements a + * cooperative extension mechanism that is primarily useful with recursive + * schemas (schemas that reference themselves). Both the extension point + * and the runtime-determined extension target are defined with + * `$dynamicAnchor`, and only exhibit runtime dynamic behavior when + * referenced with `$dynamicRef`. + * + * The value of the `$dynamicRef` property MUST be a string which is + * a URI-Reference. Resolved against the current URI base, it produces + * the URI used as the starting point for runtime resolution. This initial + * resolution is safe to perform on schema load. + * + * If the initially resolved starting point URI includes a fragment that + * was created by the `$dynamicAnchor` keyword, the initial URI MUST be + * replaced by the URI (including the fragment) for the outermost schema + * resource in the [dynamic scope][scopes] that defines + * an identically named fragment with `$dynamicAnchor`. + * + * Otherwise, its behavior is identical to `$ref`, and no runtime + * resolution is needed. + * + * [scopes]: https://json-schema.org/draft/2020-12/json-schema-core.html#scopes + * + * @format "uri-reference" + */ + $dynamicRef?: string; + /** + * The `$id` keyword identifies a schema resource with its + * [canonical][[RFC6596]] URI. + * + * Note that this URI is an identifier and not necessarily a network + * locator. In the case of a network-addressable URL, a schema need not be + * downloadable from its canonical URI. + * + * If present, the value for this keyword MUST be a string, and MUST + * represent a valid [URI-reference][RFC3986]. This URI-reference SHOULD + * be normalized, and MUST resolve to an [absolute-URI][RFC3986] (without a + * fragment). Therefore, `$id` MUST NOT contain a non-empty fragment, + * and SHOULD NOT contain an empty fragment. + * + * Since an empty fragment in the context of the + * `application/schema+json` media type refers to the same resource as + * the base URI without a fragment, an implementation MAY normalize a URI + * ending with an empty fragment by removing the fragment. However, schema + * authors SHOULD NOT rely on this behavior across implementations. + * + * This URI also serves as the base URI for relative URI-references in + * keywords within the schema resource, in accordance with + * [RFC 3986][RFC3986] section 5.1.1 regarding base URIs embedded in + * content. + * + * The presence of `$id` in a subschema indicates that the subschema + * constitutes a distinct schema resource within a single schema document. + * Furthermore, in accordance with [RFC 3986][RFC3986] section 5.1.2 + * regarding encapsulating entities, if an `$id` in a subschema is a + * relative URI-reference, the base URI for resolving that reference is the + * URI of the parent schema resource. + * + * If no parent schema object explicitly identifies itself as a resource + * with `$id`, the base URI is that of the entire document. + * + * The root schema of a JSON Schema document SHOULD contain an `$id` + * keyword with an [absolute-URI][RFC3986] (containing a scheme, but no + * fragment). + * + * [RFC6596]: https://datatracker.ietf.org/doc/html/rfc6596 + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + * + * @format "uri-reference" + */ + $id?: string; + /** + * The `$ref` keyword is an applicator that is used to reference a + * statically identified schema. Its results are the results of the + * referenced schema. Other keywords can appear alongside of `$ref` in + * the same schema object. + * + * The value of the `$ref` property MUST be a string which is a + * URI-Reference. Resolved against the current URI base, it produces the + * URI of the schema to apply. + * + * @format "uri-reference" + */ + $ref?: string; + /** + * The `$schema` keyword is both used as a JSON Schema dialect identifier + * and as the identifier of a resource which is itself a JSON Schema, which + * describes the set of valid schemas written for this particular dialect. + * + * The value of this keyword MUST be a [URI][RFC3986] (containing a scheme) + * and this URI MUST be normalized. The current schema MUST be valid + * against the meta-schema identified by this URI. + * + * If this URI identifies a retrievable resource, that resource SHOULD be + * of media type `application/schema+json`. + * + * The `$schema` keyword SHOULD be used in the document root schema + * object, and MAY be used in the root schema objects of embedded schema + * resources. It MUST NOT appear in non-resource root schema objects. If + * absent from the document root schema, the resulting behavior is + * implementation-defined. + * + * Values for this property are defined elsewhere in this and other + * documents, and by other parties. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + * + * @format "uri" + */ + $schema?: string; + /** + * The `$vocabulary` keyword is used in meta-schemas to identify the + * vocabularies available for use in schemas described by that meta-schema. + * It is also used to indicate whether each vocabulary is required or + * optional, in the sense that an implementation MUST understand the + * required vocabularies in order to successfully process the schema. + * Together, this information forms a dialect. Any vocabulary that is + * understood by the implementation MUST be processed in a manner + * consistent with the semantic definitions contained within the + * vocabulary. + * + * The value of this keyword MUST be an object. The property names in the + * object MUST be URIs (containing a scheme) and this URI MUST be + * normalized. Each URI that appears as a property name identifies a + * specific set of keywords and their semantics. + * + * The URI MAY be a URL, but the nature of the retrievable resource is + * currently undefined, and reserved for future use. Vocabulary authors + * MAY use the URL of the vocabulary specification, in a human-readable + * media type such as `text/html` or `text/plain`, as the vocabulary + * URI. + * + * The values of the object properties MUST be booleans. If the value is + * `true`, then implementations that do not recognize the vocabulary MUST + * refuse to process any schemas that declare this meta-schema with + * `$schema`. If the value is `false`, implementations that do not + * recognize the vocabulary SHOULD proceed with processing such schemas. + * The value has no impact if the implementation understands the + * vocabulary. + * + * Unrecognized keywords SHOULD be ignored. This remains the case for + * keywords defined by unrecognized vocabularies. It is not currently + * possible to distinguish between unrecognized keywords that are defined + * in vocabularies from those that are not part of any vocabulary. + * + * The `$vocabulary` keyword SHOULD be used in the root schema of any + * schema document intended for use as a meta-schema. It MUST NOT appear + * in subschemas. + * + * The `$vocabulary` keyword MUST be ignored in schema documents that are + * not being processed as a meta-schema. + */ + $vocabulary?: Record; + /** + * @deprecated `additionalItems` has been deprecated in favor of `prefixItems` + * paired with `items`. + */ + additionalItems?: JSONSchema; + /** + * The value of `additionalProperties` MUST be a valid JSON Schema. + * + * The behavior of this keyword depends on the presence and annotation + * results of `properties` and `patternProperties` within the same + * schema object. Validation with `additionalProperties` applies only to + * the child values of instance names that do not appear in the annotation + * results of either `properties` or `patternProperties`. + * + * For all such properties, validation succeeds if the child instance + * validates against the `additionalProperties` schema. + * + * The annotation result of this keyword is the set of instance property + * names validated by this keyword's subschema. Annotation results for + * `additionalProperties` keywords from multiple schemas applied to the + * same instance location are combined by taking the union of the sets. + * + * Omitting this keyword has the same assertion behavior as an empty + * schema. + * + * Implementations MAY choose to implement or optimize this keyword in + * another way that produces the same effect, such as by directly checking + * the names in `properties` and the patterns in `patternProperties` + * against the instance property set. + */ + additionalProperties?: JSONSchema; + /** + * This keyword's value MUST be a non-empty array. Each item of the array + * MUST be a valid JSON Schema. + * + * An instance validates successfully against this keyword if it validates + * successfully against all schemas defined by this keyword's value. + */ + allOf?: MaybeReadonlyArray>; + /** + * This keyword's value MUST be a non-empty array. Each item of the array + * MUST be a valid JSON Schema. + * + * An instance validates successfully against this keyword if it validates + * successfully against at least one schema defined by this keyword's + * value. + */ + anyOf?: MaybeReadonlyArray>; + /** + * An instance validates successfully against this keyword if its value is + * equal to the value of the keyword. + * + * Use of this keyword is functionally equivalent to the `enum` keyword + * with a single value. + */ + const?: Value; + /** + * The value of this keyword MUST be a valid JSON Schema. + * + * An array instance is valid against `contains` if at least one of its + * elements is valid against the given schema. The subschema MUST be + * applied to every array element even after the first match has been + * found, in order to collect annotations for use by other keywords. + * This is to ensure that all possible annotations are collected. + * + * Logically, the validation result of applying the value subschema to each + * item in the array MUST be OR'ed with `false`, resulting in an overall + * validation result. + * + * This keyword produces an annotation value which is an array of the + * indexes to which this keyword validates successfully when applying its + * subschema, in ascending order. The value MAY be a boolean `true` if + * the subschema validates successfully when applied to every index of the + * instance. The annotation MUST be present if the instance array to which + * this keyword's schema applies is empty. + */ + contains?: JSONSchema; + /** + * If the instance value is a string, this property defines that the + * string SHOULD be interpreted as binary data and decoded using the + * encoding named by this property. [RFC 2045, Sec 6.1][RFC2045] lists the + * possible values for this property. + * + * The value of this property SHOULD be ignored if the instance described + * is not a string. + * + * If this keyword is absent, but `contentMediaType` is present, this + * indicates that the media type could be encoded into `UTF-8` like any + * other JSON string value, and does not require additional decoding. + * + * The value of this property MUST be a string. + * + * [RFC2045]: https://datatracker.ietf.org/doc/html/rfc2045#section-6.1 + */ + contentEncoding?: "7bit" | "8bit" | "base64" | "binary" | "ietf-token" | "quoted-printable" | "x-token"; + /** + * If the instance is a string, this property indicates the media type + * of the contents of the string. If `contentEncoding` is present, + * this property describes the decoded string. + * + * The value of this property must be a media type, as defined by + * [RFC 2046][RFC2046]. This property defines the media type of instances + * which this schema defines. + * + * The value of this property SHOULD be ignored if the instance described + * is not a string. + * + * If the `contentEncoding` property is not present, but the instance + * value is a string, then the value of this property SHOULD specify a text + * document type, and the character set SHOULD be the character set into + * which the JSON string value was decoded (for which the default is + * Unicode). + * + * [RFC2046]: https://datatracker.ietf.org/doc/html/rfc2046 + */ + contentMediaType?: string; + /** + * If the instance is a string, and if `contentMediaType` is present, + * this property contains a schema which describes the structure of the + * string. + * + * This keyword MAY be used with any media type that can be mapped into + * JSON Schema's data model. + * + * The value of this property MUST be a valid JSON schema. It SHOULD be + * ignored if `contentMediaType` is not present. + */ + contentSchema?: JSONSchema; + /** + * This keyword can be used to supply a default JSON value associated with + * a particular schema. It is RECOMMENDED that a `default` value be valid + * against the associated schema. + */ + default?: Value; + /** + * @deprecated `definitions` has been renamed to `$defs`. + */ + definitions?: Record; + /** + * @deprecated `dependencies` has been split into two keywords: + * `dependentSchemas` and `dependentRequired`. + */ + dependencies?: Record | JSONSchema>; + /** + * The value of this keyword MUST be an object. Properties in + * this object, if any, MUST be arrays. Elements in each array, + * if any, MUST be strings, and MUST be unique. + * + * This keyword specifies properties that are required if a specific + * other property is present. Their requirement is dependent on the + * presence of the other property. + * + * Validation succeeds if, for each name that appears in both + * the instance and as a name within this keyword's value, every + * item in the corresponding array is also the name of a property + * in the instance. + * + * Omitting this keyword has the same behavior as an empty object. + */ + dependentRequired?: Record>; + /** + * This keyword specifies subschemas that are evaluated if the instance is + * an object and contains a certain property. + * + * This keyword's value MUST be an object. Each value in the object MUST be + * a valid JSON Schema. + * + * If the object key is a property in the instance, the entire instance + * must validate against the subschema. Its use is dependent on the + * presence of the property. + * + * Omitting this keyword has the same behavior as an empty object. + */ + dependentSchemas?: Record; + /** + * The value of this keyword MUST be a boolean. When multiple occurrences + * of this keyword are applicable to a single sub-instance, applications + * SHOULD consider the instance location to be deprecated if any occurrence + * specifies a `true` value. + * + * If `deprecated` has a value of boolean `true`, it indicates that + * applications SHOULD refrain from usage of the declared property. It MAY + * mean the property is going to be removed in the future. + * + * A root schema containing `deprecated` with a value of `true` + * indicates that the entire resource being described MAY be removed in the + * future. + * + * The `deprecated` keyword applies to each instance location to which + * the schema object containing the keyword successfully applies. This can + * result in scenarios where every array item or object property is + * deprecated even though the containing array or object is not. + * + * Omitting this keyword has the same behavior as a value of `false`. + */ + deprecated?: boolean; + /** + * Can be used to decorate a user interface with explanation or information + * about the data produced. + */ + description?: string; + /** + * This keyword's value MUST be a valid JSON Schema. + * + * When `if` is present, and the instance fails to validate against its + * subschema, then validation succeeds against this keyword if the instance + * successfully validates against this keyword's subschema. + * + * This keyword has no effect when `if` is absent, or when the instance + * successfully validates against its subschema. Implementations MUST NOT + * evaluate the instance against this keyword, for either validation or + * annotation collection purposes, in such cases. + */ + else?: JSONSchema; + /** + * The value of this keyword MUST be an array. This array SHOULD have at + * least one element. Elements in the array SHOULD be unique. + * + * An instance validates successfully against this keyword if its value is + * equal to one of the elements in this keyword's array value. + * + * Elements in the array might be of any type, including `null`. + */ + enum?: MaybeReadonlyArray; + /** + * The value of this keyword MUST be an array. When multiple occurrences of + * this keyword are applicable to a single sub-instance, implementations + * MUST provide a flat array of all values rather than an array of arrays. + * + * This keyword can be used to provide sample JSON values associated with a + * particular schema, for the purpose of illustrating usage. It is + * RECOMMENDED that these values be valid against the associated schema. + * + * Implementations MAY use the value(s) of `default`, if present, as an + * additional example. If `examples` is absent, `default` MAY still be + * used in this manner. + */ + examples?: MaybeReadonlyArray; + /** + * The value of `exclusiveMaximum` MUST be a number, representing an + * exclusive upper limit for a numeric instance. + * + * If the instance is a number, then the instance is valid only if it has a + * value strictly less than (not equal to) `exclusiveMaximum`. + */ + exclusiveMaximum?: number; + /** + * The value of `exclusiveMinimum` MUST be a number, representing an + * exclusive lower limit for a numeric instance. + * + * If the instance is a number, then the instance is valid only if it has a + * value strictly greater than (not equal to) `exclusiveMinimum`. + */ + exclusiveMinimum?: number; + /** + * Implementations MAY treat `format` as an assertion in addition to an + * annotation, and attempt to validate the value's conformance to the + * specified semantics. + * + * The value of this keyword is called a format attribute. It MUST be a + * string. A format attribute can generally only validate a given set + * of instance types. If the type of the instance to validate is not in + * this set, validation for this format attribute and instance SHOULD + * succeed. Format attributes are most often applied to strings, but can + * be specified to apply to any type. + * + * Implementations MAY support custom format attributes. Save for agreement + * between parties, schema authors SHALL NOT expect a peer implementation + * to support such custom format attributes. An implementation MUST NOT + * fail validation or cease processing due to an unknown format attribute. + * When treating `format` as an annotation, implementations SHOULD + * collect both known and unknown format attribute values. + */ + format?: string; + /** + * This keyword's value MUST be a valid JSON Schema. + * + * This validation outcome of this keyword's subschema has no direct effect + * on the overall validation result. Rather, it controls which of the + * `then` or `else` keywords are evaluated. + * + * Instances that successfully validate against this keyword's subschema + * MUST also be valid against the subschema value of the `then` keyword, + * if present. + * + * Instances that fail to validate against this keyword's subschema MUST + * also be valid against the subschema value of the `else` keyword, if + * present. + * + * If annotations are being collected, they are collected + * from this keyword's subschema in the usual way, including when the + * keyword is present without either `then` or `else`. + */ + if?: JSONSchema; + /** + * The value of `items` MUST be a valid JSON Schema. + * + * This keyword applies its subschema to all instance elements at indexes + * greater than the length of the `prefixItems` array in the same schema + * object, as reported by the annotation result of that `prefixItems` + * keyword. If no such annotation result exists, `items` applies its + * subschema to all instance array elements. + * + * Note that the behavior of `items` without `prefixItems` is identical + * to that of the schema form of `items` in prior drafts. + * + * When `prefixItems` is present, the behavior of `items` is identical + * to the former `additionalItems` keyword. + * + * If the `items` subschema is applied to any positions within the + * instance array, it produces an annotation result of boolean `true`, + * indicating that all remaining array elements have been evaluated against + * this keyword's subschema. + * + * Omitting this keyword has the same assertion behavior as an empty + * schema. + * + * Implementations MAY choose to implement or optimize this keyword + * in another way that produces the same effect, such as by directly + * checking for the presence and size of a `prefixItems` array. + */ + items?: JSONSchema; + /** + * The value of this keyword MUST be a non-negative integer. + * + * If `contains` is not present within the same schema object, then this + * keyword has no effect. + * + * An instance array is valid against `maxContains` in two ways, + * depending on the form of the annotation result of an adjacent + * `contains` keyword. The first way is if the annotation result is an + * array and the length of that array is less than or equal to the + * `maxContains` value. The second way is if the annotation result is a + * boolean `true` and the instance array length is less than or equal to + * the `maxContains` value. + */ + maxContains?: number; + /** + * The value of `maximum` MUST be a number, representing an inclusive + * upper limit for a numeric instance. + * + * If the instance is a number, then this keyword validates only if the + * instance is less than or exactly equal to `maximum`. + */ + maximum?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An array instance is valid against `maxItems` if its size is less + * than, or equal to, the value of this keyword. + * + * @minimum 0 + */ + maxItems?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * A string instance is valid against this keyword if its length is less + * than, or equal to, the value of this keyword. + * + * The length of a string instance is defined as the number of its + * characters as defined by [RFC 8259][RFC8259]. + * + * [RFC8259]: https://datatracker.ietf.org/doc/html/rfc8259 + * + * @minimum 0 + */ + maxLength?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An object instance is valid against `maxProperties` if its number of + * `properties` is less than, or equal to, the value of this keyword. + * + * @minimum 0 + */ + maxProperties?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * If `contains` is not present within the same schema object, then this + * keyword has no effect. + * + * An instance array is valid against `minContains` in two ways, + * depending on the form of the annotation result of an adjacent + * `contains` keyword. The first way is if the annotation result is an + * array and the length of that array is greater than or equal to the + * `minContains` value. The second way is if the annotation result is a + * boolean `true` and the instance array length is greater than or equal + * to the `minContains` value. + * + * A value of `0` is allowed, but is only useful for setting a range + * of occurrences from `0` to the value of `maxContains`. A value of + * `0` with no `maxContains` causes `contains` to always pass + * validation. + * + * Omitting this keyword has the same behavior as a value of `1`. + * + * @default 1 + */ + minContains?: number; + /** + * The value of `minimum` MUST be a number, representing an inclusive + * lower limit for a numeric instance. + * + * If the instance is a number, then this keyword validates only if the + * instance is greater than or exactly equal to `minimum`. + */ + minimum?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An array instance is valid against `minItems` if its size is greater + * than, or equal to, the value of this keyword. + * + * Omitting this keyword has the same behavior as a value of `0`. + * + * @default 0 + * @minimum 0 + */ + minItems?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * A string instance is valid against this keyword if its length is greater + * than, or equal to, the value of this keyword. + * + * The length of a string instance is defined as the number of its + * characters as defined by [RFC 8259][RFC8259]. + * + * Omitting this keyword has the same behavior as a value of `0`. + * + * [RFC8259]: https://datatracker.ietf.org/doc/html/rfc8259 + * + * @default 0 + * @minimum 0 + */ + minLength?: number; + /** + * The value of this keyword MUST be a non-negative integer. + * + * An object instance is valid against `minProperties` if its number of + * `properties` is greater than, or equal to, the value of this keyword. + * + * Omitting this keyword has the same behavior as a value of `0`. + * + * @default 0 + * @minimum 0 + */ + minProperties?: number; + /** + * The value of `multipleOf` MUST be a number, strictly greater than + * `0`. + * + * A numeric instance is valid only if division by this keyword's value + * results in an integer. + * + * @exclusiveMinimum 0 + */ + multipleOf?: number; + /** + * This keyword's value MUST be a valid JSON Schema. + * + * An instance is valid against this keyword if it fails to validate + * successfully against the schema defined by this keyword. + */ + not?: JSONSchema; + /** + * This keyword's value MUST be a non-empty array. Each item of the array + * MUST be a valid JSON Schema. + * + * An instance validates successfully against this keyword if it validates + * successfully against exactly one schema defined by this keyword's value. + */ + oneOf?: MaybeReadonlyArray>; + /** + * The value of this keyword MUST be a string. This string SHOULD be a + * valid regular expression, according to the [ECMA-262][ecma262] regular + * expression dialect. + * + * A string instance is considered valid if the regular expression matches + * the instance successfully. Recall: regular expressions are not + * implicitly anchored. + * + * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ + * + * @format "regex" + */ + pattern?: string; + /** + * The value of `patternProperties` MUST be an object. Each property name + * of this object SHOULD be a valid regular expression, according to the + * [ECMA-262][ecma262] regular expression dialect. Each property value of + * this object MUST be a valid JSON Schema. + * + * Validation succeeds if, for each instance name that matches any regular + * expressions that appear as a property name in this keyword's value, + * the child instance for that name successfully validates against each + * schema that corresponds to a matching regular expression. + * + * The annotation result of this keyword is the set of instance property + * names matched by this keyword. Omitting this keyword has the same + * assertion behavior as an empty object. + * + * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ + */ + patternProperties?: Record; + /** + * The value of `prefixItems` MUST be a non-empty array of valid JSON + * Schemas. + * + * Validation succeeds if each element of the instance validates against + * the schema at the same position, if any. This keyword does not + * constrain the length of the array. If the array is longer than this + * keyword's value, this keyword validates only the prefix of matching + * length. + * + * This keyword produces an annotation value which is the largest index to + * which this keyword applied a subschema. The value MAY be a boolean + * `true` if a subschema was applied to every index of the instance, such + * as is produced by the `items` keyword. + * This annotation affects the behavior of `items` and + * `unevaluatedItems`. + * + * Omitting this keyword has the same assertion behavior as an empty array. + */ + prefixItems?: MaybeReadonlyArray | JSONSchema; + /** + * The value of `properties` MUST be an object. Each value of this object + * MUST be a valid JSON Schema. + * + * Validation succeeds if, for each name that appears in both the instance + * and as a name within this keyword's value, the child instance for that + * name successfully validates against the corresponding schema. + * + * The annotation result of this keyword is the set of instance property + * names matched by this keyword. + * + * Omitting this keyword has the same assertion behavior as an empty + * object. + */ + properties?: Record; + /** + * The value of `propertyNames` MUST be a valid JSON Schema. + * + * If the instance is an object, this keyword validates if every property + * name in the instance validates against the provided schema. + * Note the property name that the schema is testing will always be a + * string. + * + * Omitting this keyword has the same behavior as an empty schema. + */ + propertyNames?: JSONSchema; + /** + * The value of this keyword MUST be a boolean. When multiple occurrences + * of this keyword are applicable to a single sub-instance, the resulting + * value MUST be `true` if any occurrence specifies a `true` value, and + * MUST be `false` otherwise. + * + * If `readOnly` has a value of boolean `true`, it indicates that the + * value of the instance is managed exclusively by the owning authority, + * and attempts by an application to modify the value of this property are + * expected to be ignored or rejected by that owning authority. + * + * An instance document that is marked as `readOnly` for the entire + * document MAY be ignored if sent to the owning authority, or MAY result + * in an error, at the authority's discretion. + * + * For example, `readOnly` would be used to mark a database-generated + * serial number as read-only. + * + * This keyword can be used to assist in user interface instance + * generation. + * + * @default false + */ + readOnly?: boolean; + /** + * The value of this keyword MUST be an array. Elements of this array, if + * any, MUST be strings, and MUST be unique. + * + * An object instance is valid against this keyword if every item in the + * array is the name of a property in the instance. + * + * Omitting this keyword has the same behavior as an empty array. + */ + required?: MaybeReadonlyArray; + /** + * This keyword's value MUST be a valid JSON Schema. + * + * When `if` is present, and the instance successfully validates against + * its subschema, then validation succeeds against this keyword if the + * instance also successfully validates against this keyword's subschema. + * + * This keyword has no effect when `if` is absent, or when the instance + * fails to validate against its subschema. Implementations MUST NOT + * evaluate the instance against this keyword, for either validation or + * annotation collection purposes, in such cases. + */ + then?: JSONSchema; + /** + * Can be used to decorate a user interface with a short label about the + * data produced. + */ + title?: string; + /** + * The value of this keyword MUST be either a string or an array. If it is + * an array, elements of the array MUST be strings and MUST be unique. + * + * String values MUST be one of the six primitive types (`"null"`, + * `"boolean"`, `"object"`, `"array"`, `"number"`, or + * `"string"`), or `"integer"` which matches any number with a zero + * fractional part. + * + * An instance validates if and only if the instance is in any of the sets + * listed for this keyword. + */ + type?: SchemaType; + /** + * The value of `unevaluatedItems` MUST be a valid JSON Schema. + * + * The behavior of this keyword depends on the annotation results of + * adjacent keywords that apply to the instance location being validated. + * Specifically, the annotations from `prefixItems`, `items`, and + * `contains`, which can come from those keywords when they are adjacent + * to the `unevaluatedItems` keyword. Those three annotations, as well as + * `unevaluatedItems`, can also result from any and all adjacent + * [in-place applicator][in-place-applicator] keywords. + * + * If no relevant annotations are present, the `unevaluatedItems` + * subschema MUST be applied to all locations in the array. + * If a boolean `true` value is present from any of the relevant + * annotations, `unevaluatedItems` MUST be ignored. Otherwise, the + * subschema MUST be applied to any index greater than the largest + * annotation value for `prefixItems`, which does not appear in any + * annotation value for `contains`. + * + * This means that `prefixItems`, `items`, `contains`, and all + * in-place applicators MUST be evaluated before this keyword can be + * evaluated. Authors of extension keywords MUST NOT define an in-place + * applicator that would need to be evaluated after this keyword. + * + * If the `unevaluatedItems` subschema is applied to any positions within + * the instance array, it produces an annotation result of boolean + * `true`, analogous to the behavior of `items`. + * + * Omitting this keyword has the same assertion behavior as an empty + * schema. + * + * [in-place-applicator]: https://json-schema.org/draft/2020-12/json-schema-core.html#in-place + */ + unevaluatedItems?: JSONSchema; + /** + * The value of `unevaluatedProperties` MUST be a valid JSON Schema. + * + * The behavior of this keyword depends on the annotation results of + * adjacent keywords that apply to the instance location being validated. + * Specifically, the annotations from `properties`, + * `patternProperties`, and `additionalProperties`, which can come from + * those keywords when they are adjacent to the `unevaluatedProperties` + * keyword. Those three annotations, as well as `unevaluatedProperties`, + * can also result from any and all adjacent + * [in-place applicator][in-place-applicator] keywords. + * + * Validation with `unevaluatedProperties` applies only to the child + * values of instance names that do not appear in the `properties`, + * `patternProperties`, `additionalProperties`, or + * `unevaluatedProperties` annotation results that apply to the + * instance location being validated. + * + * For all such properties, validation succeeds if the child instance + * validates against the "unevaluatedProperties" schema. + * + * This means that `properties`, `patternProperties`, + * `additionalProperties`, and all in-place applicators MUST be evaluated + * before this keyword can be evaluated. Authors of extension keywords + * MUST NOT define an in-place applicator that would need to be evaluated + * after this keyword. + * + * The annotation result of this keyword is the set of instance property + * names validated by this keyword's subschema. + * + * Omitting this keyword has the same assertion behavior as an empty + * schema. + * + * [in-place-applicator]: https://json-schema.org/draft/2020-12/json-schema-core.html#in-place + */ + unevaluatedProperties?: JSONSchema; + /** + * The value of this keyword MUST be a boolean. + * + * If this keyword has boolean value `false`, the instance validates + * successfully. If it has boolean value `true`, the instance validates + * successfully if all of its elements are unique. + * + * Omitting this keyword has the same behavior as a value of `false`. + * + * @default false + */ + uniqueItems?: boolean; + /** + * The value of this keyword MUST be a boolean. When multiple occurrences + * of this keyword is applicable to a single sub-instance, the resulting + * value MUST be `true` if any occurrence specifies a `true` value, and + * MUST be `false` otherwise. + * + * If `writeOnly` has a value of boolean `true`, it indicates that the + * value is never present when the instance is retrieved from the owning + * authority. It can be present when sent to the owning authority to update + * or create the document (or the resource it represents), but it will not + * be included in any updated or newly created version of the instance. + * + * An instance document that is marked as `writeOnly` for the entire + * document MAY be returned as a blank document of some sort, or MAY + * produce an error upon retrieval, or have the retrieval request ignored, + * at the authority's discretion. + * + * For example, `writeOnly` would be used to mark a password input field. + * + * These keywords can be used to assist in user interface instance + * generation. In particular, an application MAY choose to use a widget + * that hides input values as they are typed for write-only fields. + * + * @default false + */ + writeOnly?: boolean; +}; +export declare namespace JSONSchema { + type TypeValue = ValueOf | TypeName | Array | TypeName> | ReadonlyArray | TypeName>; + /** + * JSON Schema interface + */ + type Interface = Exclude, boolean>; + type Array = Pick, KeywordByType.Any | KeywordByType.Array>; + type Boolean = Pick, KeywordByType.Any>; + type Integer = Pick, KeywordByType.Any | KeywordByType.Number>; + type Number = Pick, KeywordByType.Any | KeywordByType.Number>; + type Null = Pick, KeywordByType.Any>; + type Object = Pick, KeywordByType.Any | KeywordByType.Object>; + type String = Pick, KeywordByType.Any | KeywordByType.String>; +} +declare namespace KeywordByType { + type Any = "$anchor" | "$comment" | "$defs" | "$dynamicAnchor" | "$dynamicRef" | "$id" | "$ref" | "$schema" | "$vocabulary" | "allOf" | "anyOf" | "const" | "default" | "definitions" | "deprecated" | "description" | "else" | "enum" | "examples" | "format" | "if" | "not" | "oneOf" | "readOnly" | "then" | "title" | "type" | "writeOnly"; + type Array = "additionalItems" | "contains" | "items" | "maxContains" | "maxItems" | "minContains" | "minItems" | "prefixItems" | "unevaluatedItems" | "uniqueItems"; + type Number = "exclusiveMaximum" | "exclusiveMinimum" | "maximum" | "minimum" | "multipleOf"; + type Object = "additionalProperties" | "dependencies" | "dependentRequired" | "dependentSchemas" | "maxProperties" | "minProperties" | "patternProperties" | "properties" | "propertyNames" | "required" | "unevaluatedProperties"; + type String = "contentEncoding" | "contentMediaType" | "contentSchema" | "maxLength" | "minLength" | "pattern"; +} +/** + * Content encoding strategy enum. + * + * - [Content-Transfer-Encoding Syntax](https://datatracker.ietf.org/doc/html/rfc2045#section-6.1) + * - [7bit vs 8bit encoding](https://stackoverflow.com/questions/25710599/content-transfer-encoding-7bit-or-8-bit/28531705#28531705) + */ +export declare enum ContentEncoding { + /** + * Only US-ASCII characters, which use the lower 7 bits for each character. + * + * Each line must be less than 1,000 characters. + */ + "7bit" = "7bit", + /** + * Allow extended ASCII characters which can use the 8th (highest) bit to + * indicate special characters not available in 7bit. + * + * Each line must be less than 1,000 characters. + */ + "8bit" = "8bit", + /** + * Useful for data that is mostly non-text. + */ + Base64 = "base64", + /** + * Same character set as 8bit, with no line length restriction. + */ + Binary = "binary", + /** + * An extension token defined by a standards-track RFC and registered with + * IANA. + */ + IETFToken = "ietf-token", + /** + * Lines are limited to 76 characters, and line breaks are represented using + * special characters that are escaped. + */ + QuotedPrintable = "quoted-printable", + /** + * The two characters "X-" or "x-" followed, with no intervening white space, + * by any token. + */ + XToken = "x-token" +} +/** + * This enum provides well-known formats that apply to strings. + */ +export declare enum Format { + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "full-date" production in + * [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Date = "date", + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "date-time" production in + * [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + DateTime = "date-time", + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "duration" production. + */ + Duration = "duration", + /** + * A string instance is valid against this attribute if it is a valid Internet + * email address as defined by by the "Mailbox" ABNF rule in [RFC + * 5321][RFC5322], section 4.1.2. + * + * [RFC5321]: https://datatracker.ietf.org/doc/html/rfc5321 + */ + Email = "email", + /** + * As defined by [RFC 1123, section 2.1][RFC1123], including host names + * produced using the Punycode algorithm specified in + * [RFC 5891, section 4.4][RFC5891]. + * + * [RFC1123]: https://datatracker.ietf.org/doc/html/rfc1123 + * [RFC5891]: https://datatracker.ietf.org/doc/html/rfc5891 + */ + Hostname = "hostname", + /** + * A string instance is valid against this attribute if it is a valid Internet + * email address as defined by the extended "Mailbox" ABNF rule in + * [RFC 6531][RFC6531], section 3.3. + * + * [RFC6531]: https://datatracker.ietf.org/doc/html/rfc6531 + */ + IDNEmail = "idn-email", + /** + * As defined by either [RFC 1123, section 2.1][RFC1123] as for hostname, or + * an internationalized hostname as defined by + * [RFC 5890, section 2.3.2.3][RFC5890]. + * + * [RFC1123]: https://datatracker.ietf.org/doc/html/rfc1123 + * [RFC5890]: https://datatracker.ietf.org/doc/html/rfc5890 + */ + IDNHostname = "idn-hostname", + /** + * An IPv4 address according to the "dotted-quad" ABNF syntax as defined in + * [RFC 2673, section 3.2][RFC2673]. + * + * [RFC2673]: https://datatracker.ietf.org/doc/html/rfc2673 + */ + IPv4 = "ipv4", + /** + * An IPv6 address as defined in [RFC 4291, section 2.2][RFC4291]. + * + * [RFC4291]: https://datatracker.ietf.org/doc/html/rfc4291 + */ + IPv6 = "ipv6", + /** + * A string instance is valid against this attribute if it is a valid IRI, + * according to [RFC 3987][RFC3987]. + * + * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 + */ + IRI = "iri", + /** + * A string instance is valid against this attribute if it is a valid IRI + * Reference (either an IRI or a relative-reference), according to + * [RFC 3987][RFC3987]. + * + * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 + */ + IRIReference = "iri-reference", + /** + * A string instance is valid against this attribute if it is a valid JSON + * string representation of a JSON Pointer, according to + * [RFC 6901, section 5][RFC6901]. + * + * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 + */ + JSONPointer = "json-pointer", + /** + * A string instance is valid against this attribute if it is a valid JSON + * string representation of a JSON Pointer fragment, according to + * [RFC 6901, section 5][RFC6901]. + * + * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 + */ + JSONPointerURIFragment = "json-pointer-uri-fragment", + /** + * This attribute applies to string instances. + * + * A regular expression, which SHOULD be valid according to the + * [ECMA-262][ecma262] regular expression dialect. + * + * Implementations that validate formats MUST accept at least the subset of + * [ECMA-262][ecma262] defined in the [Regular Expressions][regexInterop] + * section of this specification, and SHOULD accept all valid + * [ECMA-262][ecma262] expressions. + * + * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ + * [regexInterop]: https://json-schema.org/draft/2020-12/json-schema-validation.html#regexInterop + */ + RegEx = "regex", + /** + * A string instance is valid against this attribute if it is a valid + * [Relative JSON Pointer][relative-json-pointer]. + * + * [relative-json-pointer]: https://datatracker.ietf.org/doc/html/draft-handrews-relative-json-pointer-01 + */ + RelativeJSONPointer = "relative-json-pointer", + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "time" production in [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Time = "time", + /** + * A string instance is valid against this attribute if it is a valid URI, + * according to [RFC3986][RFC3986]. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + */ + URI = "uri", + /** + * A string instance is valid against this attribute if it is a valid URI + * Reference (either a URI or a relative-reference), according to + * [RFC3986][RFC3986]. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + */ + URIReference = "uri-reference", + /** + * A string instance is valid against this attribute if it is a valid URI + * Template (of any level), according to [RFC 6570][RFC6570]. + * + * Note that URI Templates may be used for IRIs; there is no separate IRI + * Template specification. + * + * [RFC6570]: https://datatracker.ietf.org/doc/html/rfc6570 + */ + URITemplate = "uri-template", + /** + * A string instance is valid against this attribute if it is a valid string + * representation of a UUID, according to [RFC 4122][RFC4122]. + * + * [RFC4122]: https://datatracker.ietf.org/doc/html/rfc4122 + */ + UUID = "uuid" +} +/** + * Enum consisting of simple type names for the `type` keyword + */ +export declare enum TypeName { + /** + * Value MUST be an array. + */ + Array = "array", + /** + * Value MUST be a boolean. + */ + Boolean = "boolean", + /** + * Value MUST be an integer, no floating point numbers are allowed. This is a + * subset of the number type. + */ + Integer = "integer", + /** + * Value MUST be null. Note this is mainly for purpose of being able use union + * types to define nullability. If this type is not included in a union, null + * values are not allowed (the primitives listed above do not allow nulls on + * their own). + */ + Null = "null", + /** + * Value MUST be a number, floating point numbers are allowed. + */ + Number = "number", + /** + * Value MUST be an object. + */ + Object = "object", + /** + * Value MUST be a string. + */ + String = "string" +} +export declare const keywords: readonly ["$anchor", "$comment", "$defs", "$dynamicAnchor", "$dynamicRef", "$id", "$ref", "$schema", "$vocabulary", "additionalItems", "additionalProperties", "allOf", "anyOf", "const", "contains", "contentEncoding", "contentMediaType", "contentSchema", "default", "definitions", "dependencies", "dependentRequired", "dependentSchemas", "deprecated", "description", "else", "enum", "examples", "exclusiveMaximum", "exclusiveMinimum", "format", "if", "items", "maxContains", "maximum", "maxItems", "maxLength", "maxProperties", "minContains", "minimum", "minItems", "minLength", "minProperties", "multipleOf", "not", "oneOf", "pattern", "patternProperties", "prefixItems", "properties", "propertyNames", "readOnly", "required", "then", "title", "type", "unevaluatedItems", "unevaluatedProperties", "uniqueItems", "writeOnly"]; +export {}; diff --git a/node_modules/json-schema-typed/draft_2020_12.js b/node_modules/json-schema-typed/draft_2020_12.js new file mode 100644 index 000000000..67130c0f3 --- /dev/null +++ b/node_modules/json-schema-typed/draft_2020_12.js @@ -0,0 +1,352 @@ +// @generated +// This code is automatically generated. Manual editing is not recommended. +/* + * BSD-2-Clause License + * + * Original source code is copyright (c) 2025 Remy Rylan + * + * + * Documentation and keyword descriptions are copyright (c) 2020 IETF Trust + * , Austin Wright , Henry Andrews + * , Ben Hutton , and Greg Dennis + * . All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +export const draft = "2020-12"; +export const $schema = "https://json-schema.org/draft/2020-12/schema"; +// ----------------------------------------------------------------------------- +/** + * Content encoding strategy enum. + * + * - [Content-Transfer-Encoding Syntax](https://datatracker.ietf.org/doc/html/rfc2045#section-6.1) + * - [7bit vs 8bit encoding](https://stackoverflow.com/questions/25710599/content-transfer-encoding-7bit-or-8-bit/28531705#28531705) + */ +export var ContentEncoding; +(function (ContentEncoding) { + /** + * Only US-ASCII characters, which use the lower 7 bits for each character. + * + * Each line must be less than 1,000 characters. + */ + ContentEncoding["7bit"] = "7bit"; + /** + * Allow extended ASCII characters which can use the 8th (highest) bit to + * indicate special characters not available in 7bit. + * + * Each line must be less than 1,000 characters. + */ + ContentEncoding["8bit"] = "8bit"; + /** + * Useful for data that is mostly non-text. + */ + ContentEncoding["Base64"] = "base64"; + /** + * Same character set as 8bit, with no line length restriction. + */ + ContentEncoding["Binary"] = "binary"; + /** + * An extension token defined by a standards-track RFC and registered with + * IANA. + */ + ContentEncoding["IETFToken"] = "ietf-token"; + /** + * Lines are limited to 76 characters, and line breaks are represented using + * special characters that are escaped. + */ + ContentEncoding["QuotedPrintable"] = "quoted-printable"; + /** + * The two characters "X-" or "x-" followed, with no intervening white space, + * by any token. + */ + ContentEncoding["XToken"] = "x-token"; +})(ContentEncoding || (ContentEncoding = {})); +/** + * This enum provides well-known formats that apply to strings. + */ +export var Format; +(function (Format) { + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "full-date" production in + * [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Format["Date"] = "date"; + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "date-time" production in + * [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Format["DateTime"] = "date-time"; + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "duration" production. + */ + Format["Duration"] = "duration"; + /** + * A string instance is valid against this attribute if it is a valid Internet + * email address as defined by by the "Mailbox" ABNF rule in [RFC + * 5321][RFC5322], section 4.1.2. + * + * [RFC5321]: https://datatracker.ietf.org/doc/html/rfc5321 + */ + Format["Email"] = "email"; + /** + * As defined by [RFC 1123, section 2.1][RFC1123], including host names + * produced using the Punycode algorithm specified in + * [RFC 5891, section 4.4][RFC5891]. + * + * [RFC1123]: https://datatracker.ietf.org/doc/html/rfc1123 + * [RFC5891]: https://datatracker.ietf.org/doc/html/rfc5891 + */ + Format["Hostname"] = "hostname"; + /** + * A string instance is valid against this attribute if it is a valid Internet + * email address as defined by the extended "Mailbox" ABNF rule in + * [RFC 6531][RFC6531], section 3.3. + * + * [RFC6531]: https://datatracker.ietf.org/doc/html/rfc6531 + */ + Format["IDNEmail"] = "idn-email"; + /** + * As defined by either [RFC 1123, section 2.1][RFC1123] as for hostname, or + * an internationalized hostname as defined by + * [RFC 5890, section 2.3.2.3][RFC5890]. + * + * [RFC1123]: https://datatracker.ietf.org/doc/html/rfc1123 + * [RFC5890]: https://datatracker.ietf.org/doc/html/rfc5890 + */ + Format["IDNHostname"] = "idn-hostname"; + /** + * An IPv4 address according to the "dotted-quad" ABNF syntax as defined in + * [RFC 2673, section 3.2][RFC2673]. + * + * [RFC2673]: https://datatracker.ietf.org/doc/html/rfc2673 + */ + Format["IPv4"] = "ipv4"; + /** + * An IPv6 address as defined in [RFC 4291, section 2.2][RFC4291]. + * + * [RFC4291]: https://datatracker.ietf.org/doc/html/rfc4291 + */ + Format["IPv6"] = "ipv6"; + /** + * A string instance is valid against this attribute if it is a valid IRI, + * according to [RFC 3987][RFC3987]. + * + * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 + */ + Format["IRI"] = "iri"; + /** + * A string instance is valid against this attribute if it is a valid IRI + * Reference (either an IRI or a relative-reference), according to + * [RFC 3987][RFC3987]. + * + * [RFC3987]: https://datatracker.ietf.org/doc/html/rfc3987 + */ + Format["IRIReference"] = "iri-reference"; + /** + * A string instance is valid against this attribute if it is a valid JSON + * string representation of a JSON Pointer, according to + * [RFC 6901, section 5][RFC6901]. + * + * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 + */ + Format["JSONPointer"] = "json-pointer"; + /** + * A string instance is valid against this attribute if it is a valid JSON + * string representation of a JSON Pointer fragment, according to + * [RFC 6901, section 5][RFC6901]. + * + * [RFC6901]: https://datatracker.ietf.org/doc/html/rfc6901 + */ + Format["JSONPointerURIFragment"] = "json-pointer-uri-fragment"; + /** + * This attribute applies to string instances. + * + * A regular expression, which SHOULD be valid according to the + * [ECMA-262][ecma262] regular expression dialect. + * + * Implementations that validate formats MUST accept at least the subset of + * [ECMA-262][ecma262] defined in the [Regular Expressions][regexInterop] + * section of this specification, and SHOULD accept all valid + * [ECMA-262][ecma262] expressions. + * + * [ecma262]: https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ + * [regexInterop]: https://json-schema.org/draft/2020-12/json-schema-validation.html#regexInterop + */ + Format["RegEx"] = "regex"; + /** + * A string instance is valid against this attribute if it is a valid + * [Relative JSON Pointer][relative-json-pointer]. + * + * [relative-json-pointer]: https://datatracker.ietf.org/doc/html/draft-handrews-relative-json-pointer-01 + */ + Format["RelativeJSONPointer"] = "relative-json-pointer"; + /** + * A string instance is valid against this attribute if it is a valid + * representation according to the "time" production in [RFC 3339][RFC3339]. + * + * [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339 + */ + Format["Time"] = "time"; + /** + * A string instance is valid against this attribute if it is a valid URI, + * according to [RFC3986][RFC3986]. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + */ + Format["URI"] = "uri"; + /** + * A string instance is valid against this attribute if it is a valid URI + * Reference (either a URI or a relative-reference), according to + * [RFC3986][RFC3986]. + * + * [RFC3986]: https://datatracker.ietf.org/doc/html/rfc3986 + */ + Format["URIReference"] = "uri-reference"; + /** + * A string instance is valid against this attribute if it is a valid URI + * Template (of any level), according to [RFC 6570][RFC6570]. + * + * Note that URI Templates may be used for IRIs; there is no separate IRI + * Template specification. + * + * [RFC6570]: https://datatracker.ietf.org/doc/html/rfc6570 + */ + Format["URITemplate"] = "uri-template"; + /** + * A string instance is valid against this attribute if it is a valid string + * representation of a UUID, according to [RFC 4122][RFC4122]. + * + * [RFC4122]: https://datatracker.ietf.org/doc/html/rfc4122 + */ + Format["UUID"] = "uuid"; +})(Format || (Format = {})); +/** + * Enum consisting of simple type names for the `type` keyword + */ +export var TypeName; +(function (TypeName) { + /** + * Value MUST be an array. + */ + TypeName["Array"] = "array"; + /** + * Value MUST be a boolean. + */ + TypeName["Boolean"] = "boolean"; + /** + * Value MUST be an integer, no floating point numbers are allowed. This is a + * subset of the number type. + */ + TypeName["Integer"] = "integer"; + /** + * Value MUST be null. Note this is mainly for purpose of being able use union + * types to define nullability. If this type is not included in a union, null + * values are not allowed (the primitives listed above do not allow nulls on + * their own). + */ + TypeName["Null"] = "null"; + /** + * Value MUST be a number, floating point numbers are allowed. + */ + TypeName["Number"] = "number"; + /** + * Value MUST be an object. + */ + TypeName["Object"] = "object"; + /** + * Value MUST be a string. + */ + TypeName["String"] = "string"; +})(TypeName || (TypeName = {})); +// ----------------------------------------------------------------------------- +// Keywords +// ----------------------------------------------------------------------------- +export const keywords = [ + "$anchor", + "$comment", + "$defs", + "$dynamicAnchor", + "$dynamicRef", + "$id", + "$ref", + "$schema", + "$vocabulary", + "additionalItems", + "additionalProperties", + "allOf", + "anyOf", + "const", + "contains", + "contentEncoding", + "contentMediaType", + "contentSchema", + "default", + "definitions", + "dependencies", + "dependentRequired", + "dependentSchemas", + "deprecated", + "description", + "else", + "enum", + "examples", + "exclusiveMaximum", + "exclusiveMinimum", + "format", + "if", + "items", + "maxContains", + "maximum", + "maxItems", + "maxLength", + "maxProperties", + "minContains", + "minimum", + "minItems", + "minLength", + "minProperties", + "multipleOf", + "not", + "oneOf", + "pattern", + "patternProperties", + "prefixItems", + "properties", + "propertyNames", + "readOnly", + "required", + "then", + "title", + "type", + "unevaluatedItems", + "unevaluatedProperties", + "uniqueItems", + "writeOnly", +]; diff --git a/node_modules/json-schema-typed/package.json b/node_modules/json-schema-typed/package.json new file mode 100644 index 000000000..b5d791cf2 --- /dev/null +++ b/node_modules/json-schema-typed/package.json @@ -0,0 +1,44 @@ +{ + "name": "json-schema-typed", + "description": "JSON Schema TypeScript definitions with complete inline documentation.", + "license": "BSD-2-Clause", + "version": "8.0.2", + "homepage": "https://github.com/RemyRylan/json-schema-typed/tree/main/dist/node", + "repository": { + "type": "git", + "url": "https://github.com/RemyRylan/json-schema-typed.git" + }, + "author": { + "name": "Remy Rylan", + "url": "https://github.com/RemyRylan" + }, + "main": "./draft_2020_12.js", + "types": "./draft_2020_12.d.ts", + "type": "module", + "exports": { + ".": { + "types": "./draft_2020_12.d.ts", + "default": "./draft_2020_12.js" + }, + "./draft-07": { + "types": "./draft_07.d.ts", + "default": "./draft_07.js" + }, + "./draft-2019-09": { + "types": "./draft_2019_09.d.ts", + "default": "./draft_2019_09.js" + }, + "./draft-2020-12": { + "types": "./draft_2020_12.d.ts", + "default": "./draft_2020_12.js" + } + }, + "keywords": [ + "jsonschema", + "typescript", + "types", + "definitions", + "json", + "schema" + ] +} diff --git a/node_modules/math-intrinsics/.eslintrc b/node_modules/math-intrinsics/.eslintrc new file mode 100644 index 000000000..d90a1bc65 --- /dev/null +++ b/node_modules/math-intrinsics/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "eqeqeq": ["error", "allow-null"], + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "RequireObjectCoercible", + "ToObject", + ], + }], + }, +} diff --git a/node_modules/math-intrinsics/.github/FUNDING.yml b/node_modules/math-intrinsics/.github/FUNDING.yml new file mode 100644 index 000000000..868f4ff48 --- /dev/null +++ b/node_modules/math-intrinsics/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/math-intrinsics +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/math-intrinsics/CHANGELOG.md b/node_modules/math-intrinsics/CHANGELOG.md new file mode 100644 index 000000000..9cf48f5a1 --- /dev/null +++ b/node_modules/math-intrinsics/CHANGELOG.md @@ -0,0 +1,24 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.0](https://github.com/es-shims/math-intrinsics/compare/v1.0.0...v1.1.0) - 2024-12-18 + +### Commits + +- [New] add `round` [`7cfb044`](https://github.com/es-shims/math-intrinsics/commit/7cfb04460c0fbdf1ca101eecbac3f59d11994130) +- [Tests] add attw [`e96be8f`](https://github.com/es-shims/math-intrinsics/commit/e96be8fbf58449eafe976446a0470e6ea561ad8d) +- [Dev Deps] update `@types/tape` [`30d0023`](https://github.com/es-shims/math-intrinsics/commit/30d00234ce8a3fa0094a61cd55d6686eb91e36ec) + +## v1.0.0 - 2024-12-11 + +### Commits + +- Initial implementation, tests, readme, types [`b898caa`](https://github.com/es-shims/math-intrinsics/commit/b898caae94e9994a94a42b8740f7bbcfd0a868fe) +- Initial commit [`02745b0`](https://github.com/es-shims/math-intrinsics/commit/02745b03a62255af8a332771987b55d127538d9c) +- [New] add `constants/maxArrayLength`, `mod` [`b978178`](https://github.com/es-shims/math-intrinsics/commit/b978178a57685bd23ed1c7efe2137f3784f5fcc5) +- npm init [`a39fc57`](https://github.com/es-shims/math-intrinsics/commit/a39fc57e5639a645d0bd52a0dc56202480223be2) +- Only apps should have lockfiles [`9451580`](https://github.com/es-shims/math-intrinsics/commit/94515800fb34db4f3cc7e99290042d45609ac7bd) diff --git a/node_modules/math-intrinsics/LICENSE b/node_modules/math-intrinsics/LICENSE new file mode 100644 index 000000000..34995e79d --- /dev/null +++ b/node_modules/math-intrinsics/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 ECMAScript Shims + +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/math-intrinsics/README.md b/node_modules/math-intrinsics/README.md new file mode 100644 index 000000000..4a66dcf24 --- /dev/null +++ b/node_modules/math-intrinsics/README.md @@ -0,0 +1,50 @@ +# math-intrinsics [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +ES Math-related intrinsics and helpers, robustly cached. + + - `abs` + - `floor` + - `isFinite` + - `isInteger` + - `isNaN` + - `isNegativeZero` + - `max` + - `min` + - `mod` + - `pow` + - `round` + - `sign` + - `constants/maxArrayLength` + - `constants/maxSafeInteger` + - `constants/maxValue` + + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/math-intrinsics +[npm-version-svg]: https://versionbadg.es/es-shims/math-intrinsics.svg +[deps-svg]: https://david-dm.org/es-shims/math-intrinsics.svg +[deps-url]: https://david-dm.org/es-shims/math-intrinsics +[dev-deps-svg]: https://david-dm.org/es-shims/math-intrinsics/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/math-intrinsics#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/math-intrinsics.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/math-intrinsics.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-object.svg +[downloads-url]: https://npm-stat.com/charts.html?package=math-intrinsics +[codecov-image]: https://codecov.io/gh/es-shims/math-intrinsics/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/math-intrinsics/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/es-shims/math-intrinsics +[actions-url]: https://github.com/es-shims/math-intrinsics/actions diff --git a/node_modules/math-intrinsics/abs.d.ts b/node_modules/math-intrinsics/abs.d.ts new file mode 100644 index 000000000..14ad9c699 --- /dev/null +++ b/node_modules/math-intrinsics/abs.d.ts @@ -0,0 +1 @@ +export = Math.abs; \ No newline at end of file diff --git a/node_modules/math-intrinsics/abs.js b/node_modules/math-intrinsics/abs.js new file mode 100644 index 000000000..a751424cd --- /dev/null +++ b/node_modules/math-intrinsics/abs.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./abs')} */ +module.exports = Math.abs; diff --git a/node_modules/math-intrinsics/constants/maxArrayLength.d.ts b/node_modules/math-intrinsics/constants/maxArrayLength.d.ts new file mode 100644 index 000000000..b92d46be2 --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxArrayLength.d.ts @@ -0,0 +1,3 @@ +declare const MAX_ARRAY_LENGTH: 4294967295; + +export = MAX_ARRAY_LENGTH; \ No newline at end of file diff --git a/node_modules/math-intrinsics/constants/maxArrayLength.js b/node_modules/math-intrinsics/constants/maxArrayLength.js new file mode 100644 index 000000000..cfc6affd0 --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxArrayLength.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./maxArrayLength')} */ +module.exports = 4294967295; // Math.pow(2, 32) - 1; diff --git a/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts b/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts new file mode 100644 index 000000000..fee3f621e --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts @@ -0,0 +1,3 @@ +declare const MAX_SAFE_INTEGER: 9007199254740991; + +export = MAX_SAFE_INTEGER; \ No newline at end of file diff --git a/node_modules/math-intrinsics/constants/maxSafeInteger.js b/node_modules/math-intrinsics/constants/maxSafeInteger.js new file mode 100644 index 000000000..b568ad393 --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxSafeInteger.js @@ -0,0 +1,5 @@ +'use strict'; + +/** @type {import('./maxSafeInteger')} */ +// eslint-disable-next-line no-extra-parens +module.exports = /** @type {import('./maxSafeInteger')} */ (Number.MAX_SAFE_INTEGER) || 9007199254740991; // Math.pow(2, 53) - 1; diff --git a/node_modules/math-intrinsics/constants/maxValue.d.ts b/node_modules/math-intrinsics/constants/maxValue.d.ts new file mode 100644 index 000000000..292cb8271 --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxValue.d.ts @@ -0,0 +1,3 @@ +declare const MAX_VALUE: 1.7976931348623157e+308; + +export = MAX_VALUE; diff --git a/node_modules/math-intrinsics/constants/maxValue.js b/node_modules/math-intrinsics/constants/maxValue.js new file mode 100644 index 000000000..a2202dc39 --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxValue.js @@ -0,0 +1,5 @@ +'use strict'; + +/** @type {import('./maxValue')} */ +// eslint-disable-next-line no-extra-parens +module.exports = /** @type {import('./maxValue')} */ (Number.MAX_VALUE) || 1.7976931348623157e+308; diff --git a/node_modules/math-intrinsics/floor.d.ts b/node_modules/math-intrinsics/floor.d.ts new file mode 100644 index 000000000..9265236f2 --- /dev/null +++ b/node_modules/math-intrinsics/floor.d.ts @@ -0,0 +1 @@ +export = Math.floor; \ No newline at end of file diff --git a/node_modules/math-intrinsics/floor.js b/node_modules/math-intrinsics/floor.js new file mode 100644 index 000000000..ab0e5d7dc --- /dev/null +++ b/node_modules/math-intrinsics/floor.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./floor')} */ +module.exports = Math.floor; diff --git a/node_modules/math-intrinsics/isFinite.d.ts b/node_modules/math-intrinsics/isFinite.d.ts new file mode 100644 index 000000000..6daae331f --- /dev/null +++ b/node_modules/math-intrinsics/isFinite.d.ts @@ -0,0 +1,3 @@ +declare function isFinite(x: unknown): x is number | bigint; + +export = isFinite; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isFinite.js b/node_modules/math-intrinsics/isFinite.js new file mode 100644 index 000000000..b201a5a52 --- /dev/null +++ b/node_modules/math-intrinsics/isFinite.js @@ -0,0 +1,12 @@ +'use strict'; + +var $isNaN = require('./isNaN'); + +/** @type {import('./isFinite')} */ +module.exports = function isFinite(x) { + return (typeof x === 'number' || typeof x === 'bigint') + && !$isNaN(x) + && x !== Infinity + && x !== -Infinity; +}; + diff --git a/node_modules/math-intrinsics/isInteger.d.ts b/node_modules/math-intrinsics/isInteger.d.ts new file mode 100644 index 000000000..13935a8cc --- /dev/null +++ b/node_modules/math-intrinsics/isInteger.d.ts @@ -0,0 +1,3 @@ +declare function isInteger(argument: unknown): argument is number; + +export = isInteger; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isInteger.js b/node_modules/math-intrinsics/isInteger.js new file mode 100644 index 000000000..4b1b9a56d --- /dev/null +++ b/node_modules/math-intrinsics/isInteger.js @@ -0,0 +1,16 @@ +'use strict'; + +var $abs = require('./abs'); +var $floor = require('./floor'); + +var $isNaN = require('./isNaN'); +var $isFinite = require('./isFinite'); + +/** @type {import('./isInteger')} */ +module.exports = function isInteger(argument) { + if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) { + return false; + } + var absValue = $abs(argument); + return $floor(absValue) === absValue; +}; diff --git a/node_modules/math-intrinsics/isNaN.d.ts b/node_modules/math-intrinsics/isNaN.d.ts new file mode 100644 index 000000000..c1d4c5524 --- /dev/null +++ b/node_modules/math-intrinsics/isNaN.d.ts @@ -0,0 +1 @@ +export = Number.isNaN; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isNaN.js b/node_modules/math-intrinsics/isNaN.js new file mode 100644 index 000000000..e36475cf8 --- /dev/null +++ b/node_modules/math-intrinsics/isNaN.js @@ -0,0 +1,6 @@ +'use strict'; + +/** @type {import('./isNaN')} */ +module.exports = Number.isNaN || function isNaN(a) { + return a !== a; +}; diff --git a/node_modules/math-intrinsics/isNegativeZero.d.ts b/node_modules/math-intrinsics/isNegativeZero.d.ts new file mode 100644 index 000000000..7ad88193e --- /dev/null +++ b/node_modules/math-intrinsics/isNegativeZero.d.ts @@ -0,0 +1,3 @@ +declare function isNegativeZero(x: unknown): boolean; + +export = isNegativeZero; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isNegativeZero.js b/node_modules/math-intrinsics/isNegativeZero.js new file mode 100644 index 000000000..b69adcc5a --- /dev/null +++ b/node_modules/math-intrinsics/isNegativeZero.js @@ -0,0 +1,6 @@ +'use strict'; + +/** @type {import('./isNegativeZero')} */ +module.exports = function isNegativeZero(x) { + return x === 0 && 1 / x === 1 / -0; +}; diff --git a/node_modules/math-intrinsics/max.d.ts b/node_modules/math-intrinsics/max.d.ts new file mode 100644 index 000000000..ad6f43e35 --- /dev/null +++ b/node_modules/math-intrinsics/max.d.ts @@ -0,0 +1 @@ +export = Math.max; \ No newline at end of file diff --git a/node_modules/math-intrinsics/max.js b/node_modules/math-intrinsics/max.js new file mode 100644 index 000000000..edb55dfbc --- /dev/null +++ b/node_modules/math-intrinsics/max.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./max')} */ +module.exports = Math.max; diff --git a/node_modules/math-intrinsics/min.d.ts b/node_modules/math-intrinsics/min.d.ts new file mode 100644 index 000000000..fd90f2d50 --- /dev/null +++ b/node_modules/math-intrinsics/min.d.ts @@ -0,0 +1 @@ +export = Math.min; \ No newline at end of file diff --git a/node_modules/math-intrinsics/min.js b/node_modules/math-intrinsics/min.js new file mode 100644 index 000000000..5a4a7c714 --- /dev/null +++ b/node_modules/math-intrinsics/min.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./min')} */ +module.exports = Math.min; diff --git a/node_modules/math-intrinsics/mod.d.ts b/node_modules/math-intrinsics/mod.d.ts new file mode 100644 index 000000000..549dbd46e --- /dev/null +++ b/node_modules/math-intrinsics/mod.d.ts @@ -0,0 +1,3 @@ +declare function mod(number: number, modulo: number): number; + +export = mod; \ No newline at end of file diff --git a/node_modules/math-intrinsics/mod.js b/node_modules/math-intrinsics/mod.js new file mode 100644 index 000000000..4a98362ba --- /dev/null +++ b/node_modules/math-intrinsics/mod.js @@ -0,0 +1,9 @@ +'use strict'; + +var $floor = require('./floor'); + +/** @type {import('./mod')} */ +module.exports = function mod(number, modulo) { + var remain = number % modulo; + return $floor(remain >= 0 ? remain : remain + modulo); +}; diff --git a/node_modules/math-intrinsics/package.json b/node_modules/math-intrinsics/package.json new file mode 100644 index 000000000..067627354 --- /dev/null +++ b/node_modules/math-intrinsics/package.json @@ -0,0 +1,86 @@ +{ + "name": "math-intrinsics", + "version": "1.1.0", + "description": "ES Math-related intrinsics and helpers, robustly cached.", + "main": false, + "exports": { + "./abs": "./abs.js", + "./floor": "./floor.js", + "./isFinite": "./isFinite.js", + "./isInteger": "./isInteger.js", + "./isNaN": "./isNaN.js", + "./isNegativeZero": "./isNegativeZero.js", + "./max": "./max.js", + "./min": "./min.js", + "./mod": "./mod.js", + "./pow": "./pow.js", + "./sign": "./sign.js", + "./round": "./round.js", + "./constants/maxArrayLength": "./constants/maxArrayLength.js", + "./constants/maxSafeInteger": "./constants/maxSafeInteger.js", + "./constants/maxValue": "./constants/maxValue.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "npx npm@'>= 10.2' audit --production", + "prelint": "evalmd README.md && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc && attw -P", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/es-shims/math-intrinsics.git" + }, + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/es-shims/math-intrinsics/issues" + }, + "homepage": "https://github.com/es-shims/math-intrinsics#readme", + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/for-each": "^0.3.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.8.0", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "es-value-fixtures": "^1.5.0", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.3", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/math-intrinsics/pow.d.ts b/node_modules/math-intrinsics/pow.d.ts new file mode 100644 index 000000000..5873c441e --- /dev/null +++ b/node_modules/math-intrinsics/pow.d.ts @@ -0,0 +1 @@ +export = Math.pow; \ No newline at end of file diff --git a/node_modules/math-intrinsics/pow.js b/node_modules/math-intrinsics/pow.js new file mode 100644 index 000000000..c0a410381 --- /dev/null +++ b/node_modules/math-intrinsics/pow.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./pow')} */ +module.exports = Math.pow; diff --git a/node_modules/math-intrinsics/round.d.ts b/node_modules/math-intrinsics/round.d.ts new file mode 100644 index 000000000..da1fde3f6 --- /dev/null +++ b/node_modules/math-intrinsics/round.d.ts @@ -0,0 +1 @@ +export = Math.round; \ No newline at end of file diff --git a/node_modules/math-intrinsics/round.js b/node_modules/math-intrinsics/round.js new file mode 100644 index 000000000..b79215663 --- /dev/null +++ b/node_modules/math-intrinsics/round.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./round')} */ +module.exports = Math.round; diff --git a/node_modules/math-intrinsics/sign.d.ts b/node_modules/math-intrinsics/sign.d.ts new file mode 100644 index 000000000..c49cecaa2 --- /dev/null +++ b/node_modules/math-intrinsics/sign.d.ts @@ -0,0 +1,3 @@ +declare function sign(x: number): number; + +export = sign; \ No newline at end of file diff --git a/node_modules/math-intrinsics/sign.js b/node_modules/math-intrinsics/sign.js new file mode 100644 index 000000000..9e5173c80 --- /dev/null +++ b/node_modules/math-intrinsics/sign.js @@ -0,0 +1,11 @@ +'use strict'; + +var $isNaN = require('./isNaN'); + +/** @type {import('./sign')} */ +module.exports = function sign(number) { + if ($isNaN(number) || number === 0) { + return number; + } + return number < 0 ? -1 : +1; +}; diff --git a/node_modules/math-intrinsics/test/index.js b/node_modules/math-intrinsics/test/index.js new file mode 100644 index 000000000..0f90a5dc0 --- /dev/null +++ b/node_modules/math-intrinsics/test/index.js @@ -0,0 +1,192 @@ +'use strict'; + +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); +var inspect = require('object-inspect'); + +var abs = require('../abs'); +var floor = require('../floor'); +var isFinite = require('../isFinite'); +var isInteger = require('../isInteger'); +var isNaN = require('../isNaN'); +var isNegativeZero = require('../isNegativeZero'); +var max = require('../max'); +var min = require('../min'); +var mod = require('../mod'); +var pow = require('../pow'); +var round = require('../round'); +var sign = require('../sign'); + +var maxArrayLength = require('../constants/maxArrayLength'); +var maxSafeInteger = require('../constants/maxSafeInteger'); +var maxValue = require('../constants/maxValue'); + +test('abs', function (t) { + t.equal(abs(-1), 1, 'abs(-1) === 1'); + t.equal(abs(+1), 1, 'abs(+1) === 1'); + t.equal(abs(+0), +0, 'abs(+0) === +0'); + t.equal(abs(-0), +0, 'abs(-0) === +0'); + + t.end(); +}); + +test('floor', function (t) { + t.equal(floor(-1.1), -2, 'floor(-1.1) === -2'); + t.equal(floor(+1.1), 1, 'floor(+1.1) === 1'); + t.equal(floor(+0), +0, 'floor(+0) === +0'); + t.equal(floor(-0), -0, 'floor(-0) === -0'); + t.equal(floor(-Infinity), -Infinity, 'floor(-Infinity) === -Infinity'); + t.equal(floor(Number(Infinity)), Number(Infinity), 'floor(+Infinity) === +Infinity'); + t.equal(floor(NaN), NaN, 'floor(NaN) === NaN'); + t.equal(floor(0), +0, 'floor(0) === +0'); + t.equal(floor(-0), -0, 'floor(-0) === -0'); + t.equal(floor(1), 1, 'floor(1) === 1'); + t.equal(floor(-1), -1, 'floor(-1) === -1'); + t.equal(floor(1.1), 1, 'floor(1.1) === 1'); + t.equal(floor(-1.1), -2, 'floor(-1.1) === -2'); + t.equal(floor(maxValue), maxValue, 'floor(maxValue) === maxValue'); + t.equal(floor(maxSafeInteger), maxSafeInteger, 'floor(maxSafeInteger) === maxSafeInteger'); + + t.end(); +}); + +test('isFinite', function (t) { + t.equal(isFinite(0), true, 'isFinite(+0) === true'); + t.equal(isFinite(-0), true, 'isFinite(-0) === true'); + t.equal(isFinite(1), true, 'isFinite(1) === true'); + t.equal(isFinite(Infinity), false, 'isFinite(Infinity) === false'); + t.equal(isFinite(-Infinity), false, 'isFinite(-Infinity) === false'); + t.equal(isFinite(NaN), false, 'isFinite(NaN) === false'); + + forEach(v.nonNumbers, function (nonNumber) { + t.equal(isFinite(nonNumber), false, 'isFinite(' + inspect(nonNumber) + ') === false'); + }); + + t.end(); +}); + +test('isInteger', function (t) { + forEach([].concat( + // @ts-expect-error TS sucks with concat + v.nonNumbers, + v.nonIntegerNumbers + ), function (nonInteger) { + t.equal(isInteger(nonInteger), false, 'isInteger(' + inspect(nonInteger) + ') === false'); + }); + + t.end(); +}); + +test('isNaN', function (t) { + forEach([].concat( + // @ts-expect-error TS sucks with concat + v.nonNumbers, + v.infinities, + v.zeroes, + v.integerNumbers + ), function (nonNaN) { + t.equal(isNaN(nonNaN), false, 'isNaN(' + inspect(nonNaN) + ') === false'); + }); + + t.equal(isNaN(NaN), true, 'isNaN(NaN) === true'); + + t.end(); +}); + +test('isNegativeZero', function (t) { + t.equal(isNegativeZero(-0), true, 'isNegativeZero(-0) === true'); + t.equal(isNegativeZero(+0), false, 'isNegativeZero(+0) === false'); + t.equal(isNegativeZero(1), false, 'isNegativeZero(1) === false'); + t.equal(isNegativeZero(-1), false, 'isNegativeZero(-1) === false'); + t.equal(isNegativeZero(NaN), false, 'isNegativeZero(NaN) === false'); + t.equal(isNegativeZero(Infinity), false, 'isNegativeZero(Infinity) === false'); + t.equal(isNegativeZero(-Infinity), false, 'isNegativeZero(-Infinity) === false'); + + forEach(v.nonNumbers, function (nonNumber) { + t.equal(isNegativeZero(nonNumber), false, 'isNegativeZero(' + inspect(nonNumber) + ') === false'); + }); + + t.end(); +}); + +test('max', function (t) { + t.equal(max(1, 2), 2, 'max(1, 2) === 2'); + t.equal(max(1, 2, 3), 3, 'max(1, 2, 3) === 3'); + t.equal(max(1, 2, 3, 4), 4, 'max(1, 2, 3, 4) === 4'); + t.equal(max(1, 2, 3, 4, 5), 5, 'max(1, 2, 3, 4, 5) === 5'); + t.equal(max(1, 2, 3, 4, 5, 6), 6, 'max(1, 2, 3, 4, 5, 6) === 6'); + t.equal(max(1, 2, 3, 4, 5, 6, 7), 7, 'max(1, 2, 3, 4, 5, 6, 7) === 7'); + + t.end(); +}); + +test('min', function (t) { + t.equal(min(1, 2), 1, 'min(1, 2) === 1'); + t.equal(min(1, 2, 3), 1, 'min(1, 2, 3) === 1'); + t.equal(min(1, 2, 3, 4), 1, 'min(1, 2, 3, 4) === 1'); + t.equal(min(1, 2, 3, 4, 5), 1, 'min(1, 2, 3, 4, 5) === 1'); + t.equal(min(1, 2, 3, 4, 5, 6), 1, 'min(1, 2, 3, 4, 5, 6) === 1'); + + t.end(); +}); + +test('mod', function (t) { + t.equal(mod(1, 2), 1, 'mod(1, 2) === 1'); + t.equal(mod(2, 2), 0, 'mod(2, 2) === 0'); + t.equal(mod(3, 2), 1, 'mod(3, 2) === 1'); + t.equal(mod(4, 2), 0, 'mod(4, 2) === 0'); + t.equal(mod(5, 2), 1, 'mod(5, 2) === 1'); + t.equal(mod(6, 2), 0, 'mod(6, 2) === 0'); + t.equal(mod(7, 2), 1, 'mod(7, 2) === 1'); + t.equal(mod(8, 2), 0, 'mod(8, 2) === 0'); + t.equal(mod(9, 2), 1, 'mod(9, 2) === 1'); + t.equal(mod(10, 2), 0, 'mod(10, 2) === 0'); + t.equal(mod(11, 2), 1, 'mod(11, 2) === 1'); + + t.end(); +}); + +test('pow', function (t) { + t.equal(pow(2, 2), 4, 'pow(2, 2) === 4'); + t.equal(pow(2, 3), 8, 'pow(2, 3) === 8'); + t.equal(pow(2, 4), 16, 'pow(2, 4) === 16'); + t.equal(pow(2, 5), 32, 'pow(2, 5) === 32'); + t.equal(pow(2, 6), 64, 'pow(2, 6) === 64'); + t.equal(pow(2, 7), 128, 'pow(2, 7) === 128'); + t.equal(pow(2, 8), 256, 'pow(2, 8) === 256'); + t.equal(pow(2, 9), 512, 'pow(2, 9) === 512'); + t.equal(pow(2, 10), 1024, 'pow(2, 10) === 1024'); + + t.end(); +}); + +test('round', function (t) { + t.equal(round(1.1), 1, 'round(1.1) === 1'); + t.equal(round(1.5), 2, 'round(1.5) === 2'); + t.equal(round(1.9), 2, 'round(1.9) === 2'); + + t.end(); +}); + +test('sign', function (t) { + t.equal(sign(-1), -1, 'sign(-1) === -1'); + t.equal(sign(+1), +1, 'sign(+1) === +1'); + t.equal(sign(+0), +0, 'sign(+0) === +0'); + t.equal(sign(-0), -0, 'sign(-0) === -0'); + t.equal(sign(NaN), NaN, 'sign(NaN) === NaN'); + t.equal(sign(Infinity), +1, 'sign(Infinity) === +1'); + t.equal(sign(-Infinity), -1, 'sign(-Infinity) === -1'); + t.equal(sign(maxValue), +1, 'sign(maxValue) === +1'); + t.equal(sign(maxSafeInteger), +1, 'sign(maxSafeInteger) === +1'); + + t.end(); +}); + +test('constants', function (t) { + t.equal(typeof maxArrayLength, 'number', 'typeof maxArrayLength === "number"'); + t.equal(typeof maxSafeInteger, 'number', 'typeof maxSafeInteger === "number"'); + t.equal(typeof maxValue, 'number', 'typeof maxValue === "number"'); + + t.end(); +}); diff --git a/node_modules/math-intrinsics/tsconfig.json b/node_modules/math-intrinsics/tsconfig.json new file mode 100644 index 000000000..b13100079 --- /dev/null +++ b/node_modules/math-intrinsics/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "@ljharb/tsconfig", +} diff --git a/node_modules/media-typer/HISTORY.md b/node_modules/media-typer/HISTORY.md new file mode 100644 index 000000000..538ade14f --- /dev/null +++ b/node_modules/media-typer/HISTORY.md @@ -0,0 +1,50 @@ +1.1.0 / 2019-04-24 +================== + + * Add `test(string)` function + +1.0.2 / 2019-04-19 +================== + + * Fix JSDoc comment for `parse` function + +1.0.1 / 2018-10-20 +================== + + * Remove left over `parameters` property from class + +1.0.0 / 2018-10-20 +================== + +This major release brings the module back to it's RFC 6838 roots. If you want +a module to parse the `Content-Type` or similar HTTP headers, use the +`content-type` module instead. + + * Drop support for Node.js below 0.8 + * Remove parameter handling, which is outside RFC 6838 scope + * Remove `parse(req)` and `parse(res)` signatures + * perf: enable strict mode + * perf: use a class for object creation + +0.3.0 / 2014-09-07 +================== + + * Support Node.js 0.6 + * Throw error when parameter format invalid on parse + +0.2.0 / 2014-06-18 +================== + + * Add `typer.format()` to format media types + +0.1.0 / 2014-06-17 +================== + + * Accept `req` as argument to `parse` + * Accept `res` as argument to `parse` + * Parse media type with extra LWS between type and first parameter + +0.0.0 / 2014-06-13 +================== + + * Initial implementation diff --git a/node_modules/media-typer/LICENSE b/node_modules/media-typer/LICENSE new file mode 100644 index 000000000..84441fbb5 --- /dev/null +++ b/node_modules/media-typer/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 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/media-typer/README.md b/node_modules/media-typer/README.md new file mode 100644 index 000000000..37edad16f --- /dev/null +++ b/node_modules/media-typer/README.md @@ -0,0 +1,93 @@ +# media-typer + +[![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][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Simple RFC 6838 media type parser. + +This module will parse a given media type into it's component parts, like type, +subtype, and suffix. A formatter is also provided to put them back together and +the two can be combined to normalize media types into a canonical form. + +If you are looking to parse the string that represents a media type and it's +parameters in HTTP (for example, the `Content-Type` header), use the +[content-type module](https://www.npmjs.com/package/content-type). + +## 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 media-typer +``` + +## API + + + +```js +var typer = require('media-typer') +``` + +### typer.parse(string) + + + +```js +var obj = typer.parse('image/svg+xml') +``` + +Parse a media type string. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The type of the media type (always lower case). Example: `'image'` + + - `subtype`: The subtype of the media type (always lower case). Example: `'svg'` + + - `suffix`: The suffix of the media type (always lower case). Example: `'xml'` + +If the given type string is invalid, then a `TypeError` is thrown. + +### typer.format(obj) + + + +```js +var obj = typer.format({ type: 'image', subtype: 'svg', suffix: 'xml' }) +``` + +Format an object into a media type string. This will return a string of the +mime type for the given object. For the properties of the object, see the +documentation for `typer.parse(string)`. + +If any of the given object values are invalid, then a `TypeError` is thrown. + +### typer.test(string) + + + +```js +var valid = typer.test('image/svg+xml') +``` + +Validate a media type string. This will return `true` is the string is a well- +formatted media type, or `false` otherwise. + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/media-typer/master +[coveralls-url]: https://coveralls.io/r/jshttp/media-typer?branch=master +[node-version-image]: https://badgen.net/npm/node/media-typer +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/media-typer +[npm-url]: https://npmjs.org/package/media-typer +[npm-version-image]: https://badgen.net/npm/v/media-typer +[travis-image]: https://badgen.net/travis/jshttp/media-typer/master +[travis-url]: https://travis-ci.org/jshttp/media-typer diff --git a/node_modules/media-typer/index.js b/node_modules/media-typer/index.js new file mode 100644 index 000000000..897cae157 --- /dev/null +++ b/node_modules/media-typer/index.js @@ -0,0 +1,143 @@ +/*! + * media-typer + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to match type in RFC 6838 + * + * type-name = restricted-name + * subtype-name = restricted-name + * restricted-name = restricted-name-first *126restricted-name-chars + * restricted-name-first = ALPHA / DIGIT + * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / + * "$" / "&" / "-" / "^" / "_" + * restricted-name-chars =/ "." ; Characters before first dot always + * ; specify a facet name + * restricted-name-chars =/ "+" ; Characters after last plus always + * ; specify a structured syntax suffix + * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z + * DIGIT = %x30-39 ; 0-9 + */ +var SUBTYPE_NAME_REGEXP = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ +var TYPE_NAME_REGEXP = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ +var TYPE_REGEXP = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/ + +/** + * Module exports. + */ + +exports.format = format +exports.parse = parse +exports.test = test + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var subtype = obj.subtype + var suffix = obj.suffix + var type = obj.type + + if (!type || !TYPE_NAME_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + if (!subtype || !SUBTYPE_NAME_REGEXP.test(subtype)) { + throw new TypeError('invalid subtype') + } + + // format as type/subtype + var string = type + '/' + subtype + + // append +suffix + if (suffix) { + if (!TYPE_NAME_REGEXP.test(suffix)) { + throw new TypeError('invalid suffix') + } + + string += '+' + suffix + } + + return string +} + +/** + * Test media type. + * + * @param {string} string + * @return {object} + * @public + */ + +function test (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + if (typeof string !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + return TYPE_REGEXP.test(string.toLowerCase()) +} + +/** + * Parse media type to object. + * + * @param {string} string + * @return {object} + * @public + */ + +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + if (typeof string !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var match = TYPE_REGEXP.exec(string.toLowerCase()) + + if (!match) { + throw new TypeError('invalid media type') + } + + var type = match[1] + var subtype = match[2] + var suffix + + // suffix after last + + var index = subtype.lastIndexOf('+') + if (index !== -1) { + suffix = subtype.substr(index + 1) + subtype = subtype.substr(0, index) + } + + return new MediaType(type, subtype, suffix) +} + +/** + * Class for MediaType object. + * @public + */ + +function MediaType (type, subtype, suffix) { + this.type = type + this.subtype = subtype + this.suffix = suffix +} diff --git a/node_modules/media-typer/package.json b/node_modules/media-typer/package.json new file mode 100644 index 000000000..1dca712ee --- /dev/null +++ b/node_modules/media-typer/package.json @@ -0,0 +1,33 @@ +{ + "name": "media-typer", + "description": "Simple RFC 6838 media type parser and formatter", + "version": "1.1.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "jshttp/media-typer", + "devDependencies": { + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "mocha": "6.1.4", + "nyc": "14.0.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test" + } +} diff --git a/node_modules/merge-descriptors/index.d.ts b/node_modules/merge-descriptors/index.d.ts new file mode 100644 index 000000000..df8f91f44 --- /dev/null +++ b/node_modules/merge-descriptors/index.d.ts @@ -0,0 +1,11 @@ +/** +Merges "own" properties from a source to a destination object, including non-enumerable and accessor-defined properties. It retains original values and descriptors, ensuring the destination receives a complete and accurate copy of the source's properties. + +@param destination - The object to receive properties. +@param source - The object providing properties. +@param overwrite - Optional boolean to control overwriting of existing properties. Defaults to true. +@returns The modified destination object. +*/ +declare function mergeDescriptors(destination: T, source: U, overwrite?: boolean): T & U; + +export = mergeDescriptors; diff --git a/node_modules/merge-descriptors/index.js b/node_modules/merge-descriptors/index.js new file mode 100644 index 000000000..51228e5ce --- /dev/null +++ b/node_modules/merge-descriptors/index.js @@ -0,0 +1,26 @@ +'use strict'; + +function mergeDescriptors(destination, source, overwrite = true) { + if (!destination) { + throw new TypeError('The `destination` argument is required.'); + } + + if (!source) { + throw new TypeError('The `source` argument is required.'); + } + + for (const name of Object.getOwnPropertyNames(source)) { + if (!overwrite && Object.hasOwn(destination, name)) { + // Skip descriptor + continue; + } + + // Copy descriptor + const descriptor = Object.getOwnPropertyDescriptor(source, name); + Object.defineProperty(destination, name, descriptor); + } + + return destination; +} + +module.exports = mergeDescriptors; diff --git a/node_modules/merge-descriptors/license b/node_modules/merge-descriptors/license new file mode 100644 index 000000000..c509d4557 --- /dev/null +++ b/node_modules/merge-descriptors/license @@ -0,0 +1,11 @@ +MIT License + +Copyright (c) Jonathan Ong +Copyright (c) Douglas Christopher Wilson +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/merge-descriptors/package.json b/node_modules/merge-descriptors/package.json new file mode 100644 index 000000000..9bedb250b --- /dev/null +++ b/node_modules/merge-descriptors/package.json @@ -0,0 +1,50 @@ +{ + "name": "merge-descriptors", + "version": "2.0.0", + "description": "Merge objects using their property descriptors", + "license": "MIT", + "repository": "sindresorhus/merge-descriptors", + "funding": "https://github.com/sponsors/sindresorhus", + "contributors": [ + "Jonathan Ong ", + "Douglas Christopher Wilson ", + "Mike Grabowski ", + "Sindre Sorhus " + ], + "exports": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "main": "./index.js", + "types": "./index.d.ts", + "sideEffects": false, + "engines": { + "node": ">=18" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "merge", + "descriptors", + "object", + "property", + "properties", + "merging", + "getter", + "setter" + ], + "devDependencies": { + "ava": "^5.3.1", + "xo": "^0.56.0" + }, + "xo": { + "rules": { + "unicorn/prefer-module": "off" + } + } +} diff --git a/node_modules/merge-descriptors/readme.md b/node_modules/merge-descriptors/readme.md new file mode 100644 index 000000000..1dee67d84 --- /dev/null +++ b/node_modules/merge-descriptors/readme.md @@ -0,0 +1,55 @@ +# merge-descriptors + +> Merge objects using their property descriptors + +## Install + +```sh +npm install merge-descriptors +``` + +## Usage + +```js +import mergeDescriptors from 'merge-descriptors'; + +const thing = { + get name() { + return 'John' + } +} + +const animal = {}; + +mergeDescriptors(animal, thing); + +console.log(animal.name); +//=> 'John' +``` + +## API + +### merge(destination, source, overwrite?) + +Merges "own" properties from a source to a destination object, including non-enumerable and accessor-defined properties. It retains original values and descriptors, ensuring the destination receives a complete and accurate copy of the source's properties. + +Returns the modified destination object. + +#### destination + +Type: `object` + +The object to receive properties. + +#### source + +Type: `object` + +The object providing properties. + +#### overwrite + +Type: `boolean`\ +Default: `true` + +A boolean to control overwriting of existing properties. diff --git a/node_modules/mime-db/HISTORY.md b/node_modules/mime-db/HISTORY.md new file mode 100644 index 000000000..fb35becca --- /dev/null +++ b/node_modules/mime-db/HISTORY.md @@ -0,0 +1,541 @@ +1.54.0 / 2025-03-17 +=================== + + * Update mime type for DCM format (#362) + * mark application/octet-stream as compressible (#163) + * Fix typo in application/x-zip-compressed mimetype (#359) + * Add mime-type for Jupyter notebooks (#282) + * Add Google Drive MIME types (#311) + * Add .blend file type (#338) + * Add support for the FBX file extension (#342) + * Add Adobe DNG file (#340) + * Add Procreate Brush and Brush Set file Types (#339) + * Add support for Procreate Dreams (#341) + * replace got with undici (#352) + * Added extensions list for model/step (#293) + * Add m4b as a type of audio/mp4 (#357) + * windows 11 application/x-zip-compressed (#346) + * add dotLottie mime type (#351) + * Add some MS-related extensions and types (#336) + +1.53.0 / 2024-07-12 +=================== + + * Add extension `.sql` to `application/sql` + * Add extensions `.aac` and `.adts` to `audio/aac` + * Add extensions `.js` and `.mjs` to `text/javascript` + * Add extensions for `application/mp4` from IANA + * Add extensions from IANA for more MIME types + * Add Microsoft app installer types and extensions + * Add new upstream MIME types + * Fix extensions for `text/markdown` to match IANA + * Remove extension `.mjs` from `application/javascript` + * Remove obsolete MIME types from IANA data + +1.52.0 / 2022-02-21 +=================== + + * Add extensions from IANA for more `image/*` types + * Add extension `.asc` to `application/pgp-keys` + * Add extensions to various XML types + * Add new upstream MIME types + +1.51.0 / 2021-11-08 +=================== + + * Add new upstream MIME types + * Mark `image/vnd.microsoft.icon` as compressible + * Mark `image/vnd.ms-dds` as compressible + +1.50.0 / 2021-09-15 +=================== + + * Add deprecated iWorks mime types and extensions + * Add new upstream MIME types + +1.49.0 / 2021-07-26 +=================== + + * Add extension `.trig` to `application/trig` + * Add new upstream MIME types + +1.48.0 / 2021-05-30 +=================== + + * Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + * Add new upstream MIME types + * Mark `text/yaml` as compressible + +1.47.0 / 2021-04-01 +=================== + + * Add new upstream MIME types + * Remove ambiguous extensions from IANA for `application/*+xml` types + * Update primary extension to `.es` for `application/ecmascript` + +1.46.0 / 2021-02-13 +=================== + + * Add extension `.amr` to `audio/amr` + * Add extension `.m4s` to `video/iso.segment` + * Add extension `.opus` to `audio/ogg` + * Add new upstream MIME types + +1.45.0 / 2020-09-22 +=================== + + * Add `application/ubjson` with extension `.ubj` + * Add `image/avif` with extension `.avif` + * Add `image/ktx2` with extension `.ktx2` + * Add extension `.dbf` to `application/vnd.dbf` + * Add extension `.rar` to `application/vnd.rar` + * Add extension `.td` to `application/urc-targetdesc+xml` + * Add new upstream MIME types + * Fix extension of `application/vnd.apple.keynote` to be `.key` + +1.44.0 / 2020-04-22 +=================== + + * Add charsets from IANA + * Add extension `.cjs` to `application/node` + * Add new upstream MIME types + +1.43.0 / 2020-01-05 +=================== + + * Add `application/x-keepass2` with extension `.kdbx` + * Add extension `.mxmf` to `audio/mobile-xmf` + * Add extensions from IANA for `application/*+xml` types + * Add new upstream MIME types + +1.42.0 / 2019-09-25 +=================== + + * Add `image/vnd.ms-dds` with extension `.dds` + * Add new upstream MIME types + * Remove compressible from `multipart/mixed` + +1.41.0 / 2019-08-30 +=================== + + * Add new upstream MIME types + * Add `application/toml` with extension `.toml` + * Mark `font/ttf` as compressible + +1.40.0 / 2019-04-20 +=================== + + * Add extensions from IANA for `model/*` types + * Add `text/mdx` with extension `.mdx` + +1.39.0 / 2019-04-04 +=================== + + * Add extensions `.siv` and `.sieve` to `application/sieve` + * Add new upstream MIME types + +1.38.0 / 2019-02-04 +=================== + + * Add extension `.nq` to `application/n-quads` + * Add extension `.nt` to `application/n-triples` + * Add new upstream MIME types + * Mark `text/less` as compressible + +1.37.0 / 2018-10-19 +=================== + + * Add extensions to HEIC image types + * Add new upstream MIME types + +1.36.0 / 2018-08-20 +=================== + + * Add Apple file extensions from IANA + * Add extensions from IANA for `image/*` types + * Add new upstream MIME types + +1.35.0 / 2018-07-15 +=================== + + * Add extension `.owl` to `application/rdf+xml` + * Add new upstream MIME types + - Removes extension `.woff` from `application/font-woff` + +1.34.0 / 2018-06-03 +=================== + + * Add extension `.csl` to `application/vnd.citationstyles.style+xml` + * Add extension `.es` to `application/ecmascript` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/turtle` + * Mark all XML-derived types as compressible + +1.33.0 / 2018-02-15 +=================== + + * Add extensions from IANA for `message/*` types + * Add new upstream MIME types + * Fix some incorrect OOXML types + * Remove `application/font-woff2` + +1.32.0 / 2017-11-29 +=================== + + * Add new upstream MIME types + * Update `text/hjson` to registered `application/hjson` + * Add `text/shex` with extension `.shex` + +1.31.0 / 2017-10-25 +=================== + + * Add `application/raml+yaml` with extension `.raml` + * Add `application/wasm` with extension `.wasm` + * Add new `font` type from IANA + * Add new upstream font extensions + * Add new upstream MIME types + * Add extensions for JPEG-2000 images + +1.30.0 / 2017-08-27 +=================== + + * Add `application/vnd.ms-outlook` + * Add `application/x-arj` + * Add extension `.mjs` to `application/javascript` + * Add glTF types and extensions + * Add new upstream MIME types + * Add `text/x-org` + * Add VirtualBox MIME types + * Fix `source` records for `video/*` types that are IANA + * Update `font/opentype` to registered `font/otf` + +1.29.0 / 2017-07-10 +=================== + + * Add `application/fido.trusted-apps+json` + * Add extension `.wadl` to `application/vnd.sun.wadl+xml` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/css` + +1.28.0 / 2017-05-14 +=================== + + * Add new upstream MIME types + * Add extension `.gz` to `application/gzip` + * Update extensions `.md` and `.markdown` to be `text/markdown` + +1.27.0 / 2017-03-16 +=================== + + * Add new upstream MIME types + * Add `image/apng` with extension `.apng` + +1.26.0 / 2017-01-14 +=================== + + * Add new upstream MIME types + * Add extension `.geojson` to `application/geo+json` + +1.25.0 / 2016-11-11 +=================== + + * Add new upstream MIME types + +1.24.0 / 2016-09-18 +=================== + + * Add `audio/mp3` + * Add new upstream MIME types + +1.23.0 / 2016-05-01 +=================== + + * Add new upstream MIME types + * Add extension `.3gpp` to `audio/3gpp` + +1.22.0 / 2016-02-15 +=================== + + * Add `text/slim` + * Add extension `.rng` to `application/xml` + * Add new upstream MIME types + * Fix extension of `application/dash+xml` to be `.mpd` + * Update primary extension to `.m4a` for `audio/mp4` + +1.21.0 / 2016-01-06 +=================== + + * Add Google document types + * Add new upstream MIME types + +1.20.0 / 2015-11-10 +=================== + + * Add `text/x-suse-ymp` + * Add new upstream MIME types + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.apple.pkpass` + * Add new upstream MIME types + +1.18.0 / 2015-09-03 +=================== + + * Add new upstream MIME types + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + +1.8.0 / 2015-03-13 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/node_modules/mime-db/LICENSE b/node_modules/mime-db/LICENSE new file mode 100644 index 000000000..0751cb10e --- /dev/null +++ b/node_modules/mime-db/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015-2022 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/mime-db/README.md b/node_modules/mime-db/README.md new file mode 100644 index 000000000..ee93fa00a --- /dev/null +++ b/node_modules/mime-db/README.md @@ -0,0 +1,109 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a large database of mime types and information about them. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +It aggregates data from the following sources: + +- https://www.iana.org/assignments/media-types/media-types.xhtml +- https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- https://hg.nginx.org/nginx/raw-file/default/conf/mime.types + +## Installation + +```bash +npm install mime-db +``` + +### Database Download + +If you intend to use this in a web browser, you can conveniently access the JSON file via [jsDelivr](https://www.jsdelivr.com/), a popular CDN (Content Delivery Network). To ensure stability and compatibility, it is advisable to specify [a release tag](https://github.com/jshttp/mime-db/tags) instead of using the 'master' branch. This is because the JSON file's format might change in future updates, and relying on a specific release tag will prevent potential issues arising from these changes. + +``` +https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json +``` + +## Usage + +```js +var db = require('mime-db') + +// grab data on .js files +var data = db['application/javascript'] +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + If not set, it's probably a custom media type. + - `apache` - [Apache common media types](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + - `iana` - [IANA-defined media types](https://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](https://hg.nginx.org/nginx/raw-file/default/conf/mime.types) +- `.extensions[]` - known extensions associated with this mime type. +- `.compressible` - whether a file of this type can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Note on MIME Type Data and Semver + +This package considers the programmatic api as the semver compatibility. This means the MIME type resolution is *not* considered +in the semver bumps. This means that if you want to pin your `mime-db` data you will need to do it in your application. While +this expectation was not set in docs until now, it is how the pacakge operated, so we do not feel this is a breaking change. + +## Contributing + +The primary way to contribute to this database is by updating the data in +one of the upstream sources. The database is updated from the upstreams +periodically and will pull in any changes. + +### Registering Media Types + +The best way to get new media types included in this library is to register +them with the IANA. The community registration procedure is outlined in +[RFC 6838 section 5](https://tools.ietf.org/html/rfc6838#section-5). Types +registered with the IANA are automatically pulled into this library. + +### Direct Inclusion + +If that is not possible / feasible, they can be added directly here as a +"custom" type. To do this, it is required to have a primary source that +definitively lists the media type. If an extension is going to be listed as +associated with this media type, the source must definitively link the +media type and extension as well. + +To edit the database, only make PRs against `src/custom-types.json` or +`src/custom-suffix.json`. + +The `src/custom-types.json` file is a JSON object with the MIME type as the +keys and the values being an object with the following keys: + +- `compressible` - leave out if you don't know, otherwise `true`/`false` to + indicate whether the data represented by the type is typically compressible. +- `extensions` - include an array of file extensions that are associated with + the type. +- `notes` - human-readable notes about the type, typically what the type is. +- `sources` - include an array of URLs of where the MIME type and the associated + extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); + links to type aggregating sites and Wikipedia are _not acceptable_. + +To update the build, run `npm run build`. + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci +[ci-url]: https://github.com/jshttp/mime-db/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master +[node-image]: https://badgen.net/npm/node/mime-db +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-db +[npm-url]: https://npmjs.org/package/mime-db +[npm-version-image]: https://badgen.net/npm/v/mime-db diff --git a/node_modules/mime-db/db.json b/node_modules/mime-db/db.json new file mode 100644 index 000000000..7e7473302 --- /dev/null +++ b/node_modules/mime-db/db.json @@ -0,0 +1,9342 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/3gpp-ims+xml": { + "source": "iana", + "compressible": true + }, + "application/3gpphal+json": { + "source": "iana", + "compressible": true + }, + "application/3gpphalforms+json": { + "source": "iana", + "compressible": true + }, + "application/a2l": { + "source": "iana" + }, + "application/ace+cbor": { + "source": "iana" + }, + "application/ace+json": { + "source": "iana", + "compressible": true + }, + "application/ace-groupcomm+cbor": { + "source": "iana" + }, + "application/ace-trl+cbor": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/activity+json": { + "source": "iana", + "compressible": true + }, + "application/aif+cbor": { + "source": "iana" + }, + "application/aif+json": { + "source": "iana", + "compressible": true + }, + "application/alto-cdni+json": { + "source": "iana", + "compressible": true + }, + "application/alto-cdnifilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-propmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-propmapparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-tips+json": { + "source": "iana", + "compressible": true + }, + "application/alto-tipsparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamcontrol+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamparams+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/appinstaller": { + "compressible": false, + "extensions": ["appinstaller"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/appx": { + "compressible": false, + "extensions": ["appx"] + }, + "application/appxbundle": { + "compressible": false, + "extensions": ["appxbundle"] + }, + "application/at+jwt": { + "source": "iana" + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomdeleted"] + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomsvc"] + }, + "application/atsc-dwd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dwd"] + }, + "application/atsc-dynamic-event-message": { + "source": "iana" + }, + "application/atsc-held+xml": { + "source": "iana", + "compressible": true, + "extensions": ["held"] + }, + "application/atsc-rdt+json": { + "source": "iana", + "compressible": true + }, + "application/atsc-rsat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsat"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana", + "compressible": true + }, + "application/automationml-aml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["aml"] + }, + "application/automationml-amlx+zip": { + "source": "iana", + "compressible": false, + "extensions": ["amlx"] + }, + "application/bacnet-xdd+zip": { + "source": "iana", + "compressible": false + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/bufr": { + "source": "iana" + }, + "application/c2pa": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xcs"] + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/captive+json": { + "source": "iana", + "compressible": true + }, + "application/cbor": { + "source": "iana" + }, + "application/cbor-seq": { + "source": "iana" + }, + "application/cccex": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana", + "compressible": true + }, + "application/ccxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ccxml"] + }, + "application/cda+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/cdfx+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdfx"] + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/ce+cbor": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana", + "compressible": true + }, + "application/cellml+xml": { + "source": "iana", + "compressible": true + }, + "application/cfw": { + "source": "iana" + }, + "application/cid-edhoc+cbor-seq": { + "source": "iana" + }, + "application/city+json": { + "source": "iana", + "compressible": true + }, + "application/city+json-seq": { + "source": "iana" + }, + "application/clr": { + "source": "iana" + }, + "application/clue+xml": { + "source": "iana", + "compressible": true + }, + "application/clue_info+xml": { + "source": "iana", + "compressible": true + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana", + "compressible": true + }, + "application/coap-eap": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/coap-payload": { + "source": "iana" + }, + "application/commonground": { + "source": "iana" + }, + "application/concise-problem-details+cbor": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/cose": { + "source": "iana" + }, + "application/cose-key": { + "source": "iana" + }, + "application/cose-key-set": { + "source": "iana" + }, + "application/cose-x509": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cpl"] + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana", + "compressible": true + }, + "application/cstadata+xml": { + "source": "iana", + "compressible": true + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cwl": { + "source": "iana", + "extensions": ["cwl"] + }, + "application/cwl+json": { + "source": "iana", + "compressible": true + }, + "application/cwl+yaml": { + "source": "iana" + }, + "application/cwt": { + "source": "iana" + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpd"] + }, + "application/dash-patch+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "compressible": true, + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana", + "compressible": true + }, + "application/dicom": { + "source": "iana", + "extensions": ["dcm"] + }, + "application/dicom+json": { + "source": "iana", + "compressible": true + }, + "application/dicom+xml": { + "source": "iana", + "compressible": true + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/dns+json": { + "source": "iana", + "compressible": true + }, + "application/dns-message": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dbk"] + }, + "application/dots+cbor": { + "source": "iana" + }, + "application/dpop+jwt": { + "source": "iana" + }, + "application/dskpp+xml": { + "source": "iana", + "compressible": true + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/eat+cwt": { + "source": "iana" + }, + "application/eat+jwt": { + "source": "iana" + }, + "application/eat-bun+cbor": { + "source": "iana" + }, + "application/eat-bun+json": { + "source": "iana", + "compressible": true + }, + "application/eat-ucs+cbor": { + "source": "iana" + }, + "application/eat-ucs+json": { + "source": "iana", + "compressible": true + }, + "application/ecmascript": { + "source": "apache", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edhoc+cbor-seq": { + "source": "iana" + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/efi": { + "source": "iana" + }, + "application/elm+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/elm+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.cap+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/emergencycalldata.comment+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.control+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.ecall.msd": { + "source": "iana" + }, + "application/emergencycalldata.legacyesn+json": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.veds+xml": { + "source": "iana", + "compressible": true + }, + "application/emma+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emotionml"] + }, + "application/encaprtp": { + "source": "iana" + }, + "application/entity-statement+jwt": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana", + "compressible": true + }, + "application/epub+zip": { + "source": "iana", + "compressible": false, + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/expect-ct-report+json": { + "source": "iana", + "compressible": true + }, + "application/express": { + "source": "iana", + "extensions": ["exp"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/fdt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fdt"] + }, + "application/fhir+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fhir+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fido.trusted-apps+json": { + "compressible": true + }, + "application/fits": { + "source": "iana" + }, + "application/flexfec": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false + }, + "application/framework-attributes+xml": { + "source": "iana", + "compressible": true + }, + "application/geo+json": { + "source": "iana", + "compressible": true, + "extensions": ["geojson"] + }, + "application/geo+json-seq": { + "source": "iana" + }, + "application/geopackage+sqlite3": { + "source": "iana" + }, + "application/geopose+json": { + "source": "iana", + "compressible": true + }, + "application/geoxacml+json": { + "source": "iana", + "compressible": true + }, + "application/geoxacml+xml": { + "source": "iana", + "compressible": true + }, + "application/gltf-buffer": { + "source": "iana" + }, + "application/gml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["gml"] + }, + "application/gnap-binding-jws": { + "source": "iana" + }, + "application/gnap-binding-jwsd": { + "source": "iana" + }, + "application/gnap-binding-rotation-jws": { + "source": "iana" + }, + "application/gnap-binding-rotation-jwsd": { + "source": "iana" + }, + "application/gpx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["gpx"] + }, + "application/grib": { + "source": "iana" + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false, + "extensions": ["gz"] + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana", + "compressible": true + }, + "application/hjson": { + "extensions": ["hjson"] + }, + "application/hl7v2+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pkg-reply+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana", + "compressible": true, + "extensions": ["its"] + }, + "application/java-archive": { + "source": "iana", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "apache", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jf2feed+json": { + "source": "iana", + "compressible": true + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/jscalendar+json": { + "source": "iana", + "compressible": true + }, + "application/jscontact+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jsonpath": { + "source": "iana" + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+jwt": { + "source": "iana" + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana", + "compressible": true + }, + "application/kpml-response+xml": { + "source": "iana", + "compressible": true + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/lgr+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lgr"] + }, + "application/link-format": { + "source": "iana" + }, + "application/linkset": { + "source": "iana" + }, + "application/linkset+json": { + "source": "iana", + "compressible": true + }, + "application/load-control+xml": { + "source": "iana", + "compressible": true + }, + "application/logout+jwt": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana", + "compressible": true + }, + "application/lpf+zip": { + "source": "iana", + "compressible": false + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mads"] + }, + "application/manifest+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana", + "compressible": true + }, + "application/mathml-presentation+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-deregister+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-envelope+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-protection-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-reception-report+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-user-service-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpf"] + }, + "application/media_control+xml": { + "source": "iana", + "compressible": true + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "compressible": true, + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "compressible": true, + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mipc": { + "source": "iana" + }, + "application/missing-blocks+cbor-seq": { + "source": "iana" + }, + "application/mmt-aei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["maei"] + }, + "application/mmt-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musd"] + }, + "application/mods+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4","mpg4","mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana", + "compressible": true + }, + "application/mrb-publish+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-ivr+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msc-mixer+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msix": { + "compressible": false, + "extensions": ["msix"] + }, + "application/msixbundle": { + "compressible": false, + "extensions": ["msixbundle"] + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mud+json": { + "source": "iana", + "compressible": true + }, + "application/multipart-core": { + "source": "iana" + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/n-quads": { + "source": "iana", + "extensions": ["nq"] + }, + "application/n-triples": { + "source": "iana", + "extensions": ["nt"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-groupinfo": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana", + "compressible": true + }, + "application/node": { + "source": "iana", + "extensions": ["cjs"] + }, + "application/nss": { + "source": "iana" + }, + "application/oauth-authz-req+jwt": { + "source": "iana" + }, + "application/oblivious-dns-message": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": true, + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] + }, + "application/oda": { + "source": "iana", + "extensions": ["oda"] + }, + "application/odm+xml": { + "source": "iana", + "compressible": true + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/ohttp-keys": { + "source": "iana" + }, + "application/omdoc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg","one","onea"] + }, + "application/opc-nodeset+xml": { + "source": "iana", + "compressible": true + }, + "application/oscore": { + "source": "iana" + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p21": { + "source": "iana" + }, + "application/p21+zip": { + "source": "iana", + "compressible": false + }, + "application/p2p-overlay+xml": { + "source": "iana", + "compressible": true, + "extensions": ["relo"] + }, + "application/parityfec": { + "source": "iana" + }, + "application/passport": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pem-certificate-chain": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana", + "extensions": ["asc"] + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["sig","asc"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pidf-diff+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkcs8-encrypted": { + "source": "iana" + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/ppsp-tracker+json": { + "source": "iana", + "compressible": true + }, + "application/private-token-issuer-directory": { + "source": "iana" + }, + "application/private-token-request": { + "source": "iana" + }, + "application/private-token-response": { + "source": "iana" + }, + "application/problem+json": { + "source": "iana", + "compressible": true + }, + "application/problem+xml": { + "source": "iana", + "compressible": true + }, + "application/provenance+xml": { + "source": "iana", + "compressible": true, + "extensions": ["provx"] + }, + "application/provided-claims+jwt": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.cyn": { + "source": "iana", + "charset": "7-BIT" + }, + "application/prs.hpub+zip": { + "source": "iana", + "compressible": false + }, + "application/prs.implied-document+xml": { + "source": "iana", + "compressible": true + }, + "application/prs.implied-executable": { + "source": "iana" + }, + "application/prs.implied-object+json": { + "source": "iana", + "compressible": true + }, + "application/prs.implied-object+json-seq": { + "source": "iana" + }, + "application/prs.implied-object+yaml": { + "source": "iana" + }, + "application/prs.implied-structure": { + "source": "iana" + }, + "application/prs.mayfile": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.vcfbzip2": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsf"] + }, + "application/pskc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pskcxml"] + }, + "application/pvd+json": { + "source": "iana", + "compressible": true + }, + "application/qsig": { + "source": "iana" + }, + "application/raml+yaml": { + "compressible": true, + "extensions": ["raml"] + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf","owl"] + }, + "application/reginfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "apache" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resolve-response+jwt": { + "source": "iana" + }, + "application/resource-lists+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana", + "compressible": true + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana", + "compressible": true + }, + "application/rls-services+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rs"] + }, + "application/route-apd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rapd"] + }, + "application/route-s-tsid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sls"] + }, + "application/route-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rusd"] + }, + "application/rpki-checklist": { + "source": "iana" + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-publication": { + "source": "iana" + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-signed-tal": { + "source": "iana" + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana", + "compressible": true + }, + "application/samlmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/sarif+json": { + "source": "iana", + "compressible": true + }, + "application/sarif-external-properties+json": { + "source": "iana", + "compressible": true + }, + "application/sbe": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana", + "compressible": true + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/secevent+jwt": { + "source": "iana" + }, + "application/senml+cbor": { + "source": "iana" + }, + "application/senml+json": { + "source": "iana", + "compressible": true + }, + "application/senml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["senmlx"] + }, + "application/senml-etch+cbor": { + "source": "iana" + }, + "application/senml-etch+json": { + "source": "iana", + "compressible": true + }, + "application/senml-exi": { + "source": "iana" + }, + "application/sensml+cbor": { + "source": "iana" + }, + "application/sensml+json": { + "source": "iana", + "compressible": true + }, + "application/sensml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sensmlx"] + }, + "application/sensml-exi": { + "source": "iana" + }, + "application/sep+xml": { + "source": "iana", + "compressible": true + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana", + "extensions": ["siv","sieve"] + }, + "application/simple-filter+xml": { + "source": "iana", + "compressible": true + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/sipc": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "apache" + }, + "application/smil+xml": { + "source": "iana", + "compressible": true, + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "compressible": true, + "extensions": ["srx"] + }, + "application/spdx+json": { + "source": "iana", + "compressible": true + }, + "application/spirits-event+xml": { + "source": "iana", + "compressible": true + }, + "application/sql": { + "source": "iana", + "extensions": ["sql"] + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ssdl"] + }, + "application/sslkeylogfile": { + "source": "iana" + }, + "application/ssml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ssml"] + }, + "application/st2110-41": { + "source": "iana" + }, + "application/stix+json": { + "source": "iana", + "compressible": true + }, + "application/stratum": { + "source": "iana" + }, + "application/swid+cbor": { + "source": "iana" + }, + "application/swid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["swidtag"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/taxii+json": { + "source": "iana", + "compressible": true + }, + "application/td+json": { + "source": "iana", + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tei","teicorpus"] + }, + "application/tetra_isi": { + "source": "iana" + }, + "application/thraud+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/tlsrpt+gzip": { + "source": "iana" + }, + "application/tlsrpt+json": { + "source": "iana", + "compressible": true + }, + "application/tm+json": { + "source": "iana", + "compressible": true + }, + "application/tnauthlist": { + "source": "iana" + }, + "application/toc+cbor": { + "source": "iana" + }, + "application/token-introspection+jwt": { + "source": "iana" + }, + "application/toml": { + "source": "iana", + "compressible": true, + "extensions": ["toml"] + }, + "application/trickle-ice-sdpfrag": { + "source": "iana" + }, + "application/trig": { + "source": "iana", + "extensions": ["trig"] + }, + "application/trust-chain+json": { + "source": "iana", + "compressible": true + }, + "application/trust-mark+jwt": { + "source": "iana" + }, + "application/trust-mark-delegation+jwt": { + "source": "iana" + }, + "application/ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ttml"] + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/tzif": { + "source": "iana" + }, + "application/tzif-leap": { + "source": "iana" + }, + "application/ubjson": { + "compressible": false, + "extensions": ["ubj"] + }, + "application/uccs+cbor": { + "source": "iana" + }, + "application/ujcs+json": { + "source": "iana", + "compressible": true + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-ressheet+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsheet"] + }, + "application/urc-targetdesc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["td"] + }, + "application/urc-uisocketdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/vc": { + "source": "iana" + }, + "application/vc+cose": { + "source": "iana" + }, + "application/vc+jwt": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana", + "compressible": true + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + "source": "iana", + "compressible": true, + "extensions": ["1km"] + }, + "application/vnd.1ob": { + "source": "iana" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3a+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ach+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc8+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-v2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gnas": { + "source": "iana" + }, + "application/vnd.3gpp.5gsa2x": { + "source": "iana" + }, + "application/vnd.3gpp.5gsa2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gsv2x": { + "source": "iana" + }, + "application/vnd.3gpp.5gsv2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.crs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.current-location-discovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gmop+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gtpc": { + "source": "iana" + }, + "application/vnd.3gpp.interworking-data": { + "source": "iana" + }, + "application/vnd.3gpp.lpp": { + "source": "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-msgstore-ctrl-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-payload": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-regroup+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-signalling": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-regroup+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-regroup+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ngap": { + "source": "iana" + }, + "application/vnd.3gpp.pfcp": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.pinapp-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.s1ap": { + "source": "iana" + }, + "application/vnd.3gpp.seal-group-doc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-network-qos-management-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-ue-config-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-unicast-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-user-profile-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.sms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.v2x": { + "source": "iana" + }, + "application/vnd.3gpp.vae-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + "source": "iana" + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acm.addressxfer+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.acm.chatbot+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "compressible": false, + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "apache", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + "source": "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + "source": "iana" + }, + "application/vnd.afpc.foca-charset": { + "source": "iana" + }, + "application/vnd.afpc.foca-codedfont": { + "source": "iana" + }, + "application/vnd.afpc.foca-codepage": { + "source": "iana" + }, + "application/vnd.afpc.modca": { + "source": "iana" + }, + "application/vnd.afpc.modca-cmtable": { + "source": "iana" + }, + "application/vnd.afpc.modca-formdef": { + "source": "iana" + }, + "application/vnd.afpc.modca-mediummap": { + "source": "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + "source": "iana" + }, + "application/vnd.afpc.modca-overlay": { + "source": "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + "source": "iana" + }, + "application/vnd.age": { + "source": "iana", + "extensions": ["age"] + }, + "application/vnd.ah-barcode": { + "source": "apache" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amadeus+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + "source": "iana" + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.android.ota": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.arrow.file": { + "source": "iana" + }, + "application/vnd.apache.arrow.stream": { + "source": "iana" + }, + "application/vnd.apache.parquet": { + "source": "iana" + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.apexlang": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.aplextor.warrp+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apothekende.reservation+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpkg"] + }, + "application/vnd.apple.keynote": { + "source": "iana", + "extensions": ["key"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.numbers": { + "source": "iana", + "extensions": ["numbers"] + }, + "application/vnd.apple.pages": { + "source": "iana", + "extensions": ["pages"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "apache" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artisan+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autodesk.fbx": { + "extensions": ["fbx"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avalon+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.avistar+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.banana-accounting": { + "source": "iana" + }, + "application/vnd.bbf.usp.error": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.belightsoft.lhzd+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.belightsoft.lhzl+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.bint.med-content": { + "source": "iana" + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.blink-idb-value-wrapper": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.bpf": { + "source": "iana" + }, + "application/vnd.bpf3": { + "source": "iana" + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.byu.uapi+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bzip3": { + "source": "iana" + }, + "application/vnd.c3voc.schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.capasystems-pg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdxml"] + }, + "application/vnd.chess-pgn": { + "source": "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.ciedi": { + "source": "iana" + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana", + "compressible": true, + "extensions": ["csl"] + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.cncf.helm.chart.content.v1.tar+gzip": { + "source": "iana" + }, + "application/vnd.cncf.helm.chart.provenance.v1.prov": { + "source": "iana" + }, + "application/vnd.cncf.helm.config.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.comicbook+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.comicbook-rar": { + "source": "iana" + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.crypto-shade-file": { + "source": "iana" + }, + "application/vnd.cryptomator.encrypted": { + "source": "iana" + }, + "application/vnd.cryptomator.vault": { + "source": "iana" + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.cyclonedx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cyclonedx+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.d3m-dataset": { + "source": "iana" + }, + "application/vnd.d3m-problem": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.datalog": { + "source": "iana" + }, + "application/vnd.datapackage+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dataresource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dbf": { + "source": "iana", + "extensions": ["dbf"] + }, + "application/vnd.dcmp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dcmp"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume.movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecip.rlp": { + "source": "iana" + }, + "application/vnd.eclipse.ditto+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.efi.img": { + "source": "iana" + }, + "application/vnd.efi.iso": { + "source": "iana" + }, + "application/vnd.eln+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.erofs": { + "source": "iana" + }, + "application/vnd.espass-espass+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "compressible": true, + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.cug+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.sci+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eu.kasparian.car+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.evolv.ecig.profile": { + "source": "iana" + }, + "application/vnd.evolv.ecig.settings": { + "source": "iana" + }, + "application/vnd.evolv.ecig.theme": { + "source": "iana" + }, + "application/vnd.exstream-empower+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.exstream-package": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "apache", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.fdsn.stationxml+xml": { + "source": "iana", + "charset": "XML-BASED", + "compressible": true + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.ficlab.flb+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.freelog.comic": { + "source": "iana" + }, + "application/vnd.frogans.fnc": { + "source": "apache", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "apache", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.futoin+cbor": { + "source": "iana" + }, + "application/vnd.futoin+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.ga4gh.passport+jwt": { + "source": "iana" + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.genozip": { + "source": "iana" + }, + "application/vnd.gentics.grd+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.gentoo.catmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gentoo.ebuild": { + "source": "iana" + }, + "application/vnd.gentoo.eclass": { + "source": "iana" + }, + "application/vnd.gentoo.gpkg": { + "source": "iana" + }, + "application/vnd.gentoo.manifest": { + "source": "iana" + }, + "application/vnd.gentoo.pkgmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gentoo.xpak": { + "source": "iana" + }, + "application/vnd.geo+json": { + "source": "apache", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.pinboard": { + "source": "iana" + }, + "application/vnd.geogebra.slides": { + "source": "iana", + "extensions": ["ggs"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.gnu.taler.exchange+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.gnu.taler.merchant+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.google-apps.audio": {}, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.drawing": { + "compressible": false, + "extensions": ["gdraw"] + }, + "application/vnd.google-apps.drive-sdk": { + "compressible": false + }, + "application/vnd.google-apps.file": {}, + "application/vnd.google-apps.folder": { + "compressible": false + }, + "application/vnd.google-apps.form": { + "compressible": false, + "extensions": ["gform"] + }, + "application/vnd.google-apps.fusiontable": {}, + "application/vnd.google-apps.jam": { + "compressible": false, + "extensions": ["gjam"] + }, + "application/vnd.google-apps.mail-layout": {}, + "application/vnd.google-apps.map": { + "compressible": false, + "extensions": ["gmap"] + }, + "application/vnd.google-apps.photo": {}, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.script": { + "compressible": false, + "extensions": ["gscript"] + }, + "application/vnd.google-apps.shortcut": {}, + "application/vnd.google-apps.site": { + "compressible": false, + "extensions": ["gsite"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-apps.unknown": {}, + "application/vnd.google-apps.video": {}, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdcf"] + }, + "application/vnd.gpxsee.map+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "compressible": true, + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.hdt": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.hsl": { + "source": "iana" + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyper-item+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "apache" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "apache", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.imagemeter.image+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.informix-visionary": { + "source": "apache" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.ipfs.ipns-record": { + "source": "iana" + }, + "application/vnd.ipld.car": { + "source": "iana" + }, + "application/vnd.ipld.dag-cbor": { + "source": "iana" + }, + "application/vnd.ipld.dag-json": { + "source": "iana" + }, + "application/vnd.ipld.raw": { + "source": "iana" + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kdl": { + "source": "iana" + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.keyman.kmp+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.keyman.kmx": { + "source": "iana" + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las": { + "source": "iana" + }, + "application/vnd.las.las+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.las.las+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lasxml"] + }, + "application/vnd.laszip": { + "source": "iana" + }, + "application/vnd.ldev.productlicensing": { + "source": "iana" + }, + "application/vnd.leap+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.liberty-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.loom": { + "source": "iana" + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana", + "extensions": ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxar.archive.3tz+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.mdl": { + "source": "iana" + }, + "application/vnd.mdl-mbsdf": { + "source": "iana" + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.medicalholodeck.recordxr": { + "source": "iana" + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mermaid": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.modl": { + "source": "iana" + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-outlook": { + "compressible": false, + "extensions": ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-printschematicket+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-visio.viewer": { + "extensions": ["vdx"] + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msgpack": { + "source": "iana" + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nato.bindingdataobject+cbor": { + "source": "iana" + }, + "application/vnd.nato.bindingdataobject+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nato.bindingdataobject+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bdo"] + }, + "application/vnd.nato.openxmlformats-package.iepd+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nearst.inv+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nebumind.line": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nimn": { + "source": "iana" + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "apache", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oai.workflows": { + "source": "iana" + }, + "application/vnd.oai.workflows+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oai.workflows+yaml": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.base": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "apache", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-master-template": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.ocf+cbor": { + "source": "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+cbor": { + "source": "iana" + }, + "application/vnd.oma.lwm2m+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+tlv": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-email+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-file+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-folder+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.onepager": { + "source": "iana" + }, + "application/vnd.onepagertamp": { + "source": "iana" + }, + "application/vnd.onepagertamx": { + "source": "iana" + }, + "application/vnd.onepagertat": { + "source": "iana" + }, + "application/vnd.onepagertatp": { + "source": "iana" + }, + "application/vnd.onepagertatx": { + "source": "iana" + }, + "application/vnd.onvif.metadata": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana", + "compressible": true, + "extensions": ["obgx"] + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osm"] + }, + "application/vnd.opentimestamps.ots": { + "source": "iana" + }, + "application/vnd.openvpi.dspx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "iana", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "iana", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "iana", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "iana" + }, + "application/vnd.patentdive": { + "source": "iana" + }, + "application/vnd.patientecommsdoc": { + "source": "iana" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.procrate.brushset": { + "extensions": ["brushset"] + }, + "application/vnd.procreate.brush": { + "extensions": ["brush"] + }, + "application/vnd.procreate.dream": { + "extensions": ["drm"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.psfs": { + "source": "iana" + }, + "application/vnd.pt.mundusmundi": { + "source": "iana" + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtm"] + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quarantainenet": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.rar": { + "source": "iana", + "extensions": ["rar"] + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musicxml"] + }, + "application/vnd.relpipe": { + "source": "iana" + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.resilient.logic": { + "source": "iana" + }, + "application/vnd.restful+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "compressible": true, + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sar": { + "source": "iana" + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.seis+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shade-save-file": { + "source": "iana" + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.shootproof+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shopkick+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shp": { + "source": "iana" + }, + "application/vnd.shx": { + "source": "iana" + }, + "application/vnd.sigrok.session": { + "source": "iana" + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sketchometry": { + "source": "iana" + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.smintio.portals.archive": { + "source": "iana" + }, + "application/vnd.snesdev-page-table": { + "source": "iana" + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sqlite3": { + "source": "iana" + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wadl"] + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.sybyl.mol2": { + "source": "iana" + }, + "application/vnd.sycle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syft+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tableschema+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.tri.onesource": { + "source": "iana" + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uic.osdm+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uoml","uo"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.vel+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veraison.tsm-report+cbor": { + "source": "iana" + }, + "application/vnd.veraison.tsm-report+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.veritone.aion+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veryant.thin": { + "source": "iana" + }, + "application/vnd.ves.encrypted": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw","vsdx","vtx"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vocalshaper.vsp4": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.wasmflow.wafl": { + "source": "iana" + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.dpp": { + "source": "iana" + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordlift": { + "source": "iana" + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.wv.ssp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xarin.cpj": { + "source": "iana" + }, + "application/vnd.xecrets-encrypted": { + "source": "iana" + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["vxml"] + }, + "application/voucher-cms+json": { + "source": "iana", + "compressible": true + }, + "application/voucher-jws+json": { + "source": "iana", + "compressible": true + }, + "application/vp": { + "source": "iana" + }, + "application/vp+cose": { + "source": "iana" + }, + "application/vp+jwt": { + "source": "iana" + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/wasm": { + "source": "iana", + "compressible": true, + "extensions": ["wasm"] + }, + "application/watcherinfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wif"] + }, + "application/webpush-options+json": { + "source": "iana", + "compressible": true + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-arj": { + "compressible": false, + "extensions": ["arj"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blender": { + "extensions": ["blend"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-compressed": { + "extensions": ["rar"] + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "compressible": true, + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-ipynb+json": { + "compressible": true, + "extensions": ["ipynb"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + "extensions": ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + "extensions": ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + "extensions": ["pages"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-keepass2": { + "extensions": ["kdbx"] + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "source": "apache", + "extensions": ["nc","cdf"] + }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, + "application/x-nzb": { + "source": "apache", + "extensions": ["nzb"] + }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, + "application/x-pkcs12": { + "source": "apache", + "compressible": false, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-pki-message": { + "source": "iana" + }, + "application/x-rar-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["rar"] + }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, + "application/x-research-info-systems": { + "source": "apache", + "extensions": ["ris"] + }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, + "application/x-sh": { + "source": "apache", + "compressible": true, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-virtualbox-hdd": { + "compressible": true, + "extensions": ["hdd"] + }, + "application/x-virtualbox-ova": { + "compressible": true, + "extensions": ["ova"] + }, + "application/x-virtualbox-ovf": { + "compressible": true, + "extensions": ["ovf"] + }, + "application/x-virtualbox-vbox": { + "compressible": true, + "extensions": ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + "compressible": false, + "extensions": ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + "compressible": true, + "extensions": ["vdi"] + }, + "application/x-virtualbox-vhd": { + "compressible": true, + "extensions": ["vhd"] + }, + "application/x-virtualbox-vmdk": { + "compressible": true, + "extensions": ["vmdk"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "iana", + "extensions": ["der","crt","pem"] + }, + "application/x-x509-ca-ra-cert": { + "source": "iana" + }, + "application/x-x509-next-ca-cert": { + "source": "iana" + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zip-compressed": { + "extensions": ["zip"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana", + "compressible": true + }, + "application/xaml+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xav"] + }, + "application/xcap-caps+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xca"] + }, + "application/xcap-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xel"] + }, + "application/xcap-error+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-ns+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xns"] + }, + "application/xcon-conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/xenc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xenc"] + }, + "application/xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache", + "compressible": true + }, + "application/xliff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xlf"] + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd","rng"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/xmpp+xml": { + "source": "iana", + "compressible": true + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsl","xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yaml": { + "source": "iana" + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yang-data+cbor": { + "source": "iana" + }, + "application/yang-data+json": { + "source": "iana", + "compressible": true + }, + "application/yang-data+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+json": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-sid+json": { + "source": "iana", + "compressible": true + }, + "application/yin+xml": { + "source": "iana", + "compressible": true, + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zip+dotlottie": { + "extensions": ["lottie"] + }, + "application/zlib": { + "source": "iana" + }, + "application/zstd": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana", + "compressible": false, + "extensions": ["3gpp"] + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/aac": { + "source": "iana", + "extensions": ["adts","aac"] + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana", + "extensions": ["amr"] + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/flac": { + "source": "iana" + }, + "audio/flexfec": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/matroska": { + "source": "iana" + }, + "audio/melp": { + "source": "iana" + }, + "audio/melp1200": { + "source": "iana" + }, + "audio/melp2400": { + "source": "iana" + }, + "audio/melp600": { + "source": "iana" + }, + "audio/mhas": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/midi-clip": { + "source": "iana" + }, + "audio/mobile-xmf": { + "source": "iana", + "extensions": ["mxmf"] + }, + "audio/mp3": { + "compressible": false, + "extensions": ["mp3"] + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["m4a","mp4a","m4b"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx","opus"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/scip": { + "source": "iana" + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sofa": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tetra_acelp": { + "source": "iana" + }, + "audio/tetra_acelp_bb": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/tsvcis": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/usac": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dts.uhd": { + "source": "iana" + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.presonus.multitrack": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "apache" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/collection": { + "source": "iana", + "extensions": ["ttc"] + }, + "font/otf": { + "source": "iana", + "compressible": true, + "extensions": ["otf"] + }, + "font/sfnt": { + "source": "iana" + }, + "font/ttf": { + "source": "iana", + "compressible": true, + "extensions": ["ttf"] + }, + "font/woff": { + "source": "iana", + "extensions": ["woff"] + }, + "font/woff2": { + "source": "iana", + "extensions": ["woff2"] + }, + "image/aces": { + "source": "iana", + "extensions": ["exr"] + }, + "image/apng": { + "source": "iana", + "compressible": false, + "extensions": ["apng"] + }, + "image/avci": { + "source": "iana", + "extensions": ["avci"] + }, + "image/avcs": { + "source": "iana", + "extensions": ["avcs"] + }, + "image/avif": { + "source": "iana", + "compressible": false, + "extensions": ["avif"] + }, + "image/bmp": { + "source": "iana", + "compressible": true, + "extensions": ["bmp","dib"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/dicom-rle": { + "source": "iana", + "extensions": ["drle"] + }, + "image/dpx": { + "source": "iana", + "extensions": ["dpx"] + }, + "image/emf": { + "source": "iana", + "extensions": ["emf"] + }, + "image/fits": { + "source": "iana", + "extensions": ["fits"] + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/heic": { + "source": "iana", + "extensions": ["heic"] + }, + "image/heic-sequence": { + "source": "iana", + "extensions": ["heics"] + }, + "image/heif": { + "source": "iana", + "extensions": ["heif"] + }, + "image/heif-sequence": { + "source": "iana", + "extensions": ["heifs"] + }, + "image/hej2k": { + "source": "iana", + "extensions": ["hej2"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/j2c": { + "source": "iana" + }, + "image/jaii": { + "source": "iana", + "extensions": ["jaii"] + }, + "image/jais": { + "source": "iana", + "extensions": ["jais"] + }, + "image/jls": { + "source": "iana", + "extensions": ["jls"] + }, + "image/jp2": { + "source": "iana", + "compressible": false, + "extensions": ["jp2","jpg2"] + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpg","jpeg","jpe"] + }, + "image/jph": { + "source": "iana", + "extensions": ["jph"] + }, + "image/jphc": { + "source": "iana", + "extensions": ["jhc"] + }, + "image/jpm": { + "source": "iana", + "compressible": false, + "extensions": ["jpm","jpgm"] + }, + "image/jpx": { + "source": "iana", + "compressible": false, + "extensions": ["jpx","jpf"] + }, + "image/jxl": { + "source": "iana", + "extensions": ["jxl"] + }, + "image/jxr": { + "source": "iana", + "extensions": ["jxr"] + }, + "image/jxra": { + "source": "iana", + "extensions": ["jxra"] + }, + "image/jxrs": { + "source": "iana", + "extensions": ["jxrs"] + }, + "image/jxs": { + "source": "iana", + "extensions": ["jxs"] + }, + "image/jxsc": { + "source": "iana", + "extensions": ["jxsc"] + }, + "image/jxsi": { + "source": "iana", + "extensions": ["jxsi"] + }, + "image/jxss": { + "source": "iana", + "extensions": ["jxss"] + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/ktx2": { + "source": "iana", + "extensions": ["ktx2"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false, + "extensions": ["jfif"] + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif","btf"] + }, + "image/prs.pti": { + "source": "iana", + "extensions": ["pti"] + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana", + "extensions": ["t38"] + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tif","tiff"] + }, + "image/tiff-fx": { + "source": "iana", + "extensions": ["tfx"] + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana", + "extensions": ["azv"] + }, + "image/vnd.clip": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana", + "compressible": true, + "extensions": ["ico"] + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-dds": { + "compressible": true, + "extensions": ["dds"] + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.pco.b16": { + "source": "iana", + "extensions": ["b16"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana", + "extensions": ["tap"] + }, + "image/vnd.valve.source.texture": { + "source": "iana", + "extensions": ["vtf"] + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana", + "extensions": ["pcx"] + }, + "image/webp": { + "source": "iana", + "extensions": ["webp"] + }, + "image/wmf": { + "source": "iana", + "extensions": ["wmf"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-adobe-dng": { + "extensions": ["dng"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-emf": { + "source": "iana" + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "compressible": true, + "extensions": ["ico"] + }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, + "image/x-mrsid-image": { + "source": "apache", + "extensions": ["sid"] + }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, + "image/x-pcx": { + "source": "apache", + "extensions": ["pcx"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-wmf": { + "source": "iana" + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/bhttp": { + "source": "iana" + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana", + "extensions": [ + "disposition-notification" + ] + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana", + "extensions": ["u8msg"] + }, + "message/global-delivery-status": { + "source": "iana", + "extensions": ["u8dsn"] + }, + "message/global-disposition-notification": { + "source": "iana", + "extensions": ["u8mdn"] + }, + "message/global-headers": { + "source": "iana", + "extensions": ["u8hdr"] + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/mls": { + "source": "iana" + }, + "message/news": { + "source": "apache" + }, + "message/ohttp-req": { + "source": "iana" + }, + "message/ohttp-res": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime","mht","mhtml"] + }, + "message/s-http": { + "source": "apache" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "apache" + }, + "message/vnd.wfa.wsc": { + "source": "iana", + "extensions": ["wsc"] + }, + "model/3mf": { + "source": "iana", + "extensions": ["3mf"] + }, + "model/e57": { + "source": "iana" + }, + "model/gltf+json": { + "source": "iana", + "compressible": true, + "extensions": ["gltf"] + }, + "model/gltf-binary": { + "source": "iana", + "compressible": true, + "extensions": ["glb"] + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/jt": { + "source": "iana", + "extensions": ["jt"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/mtl": { + "source": "iana", + "extensions": ["mtl"] + }, + "model/obj": { + "source": "iana", + "extensions": ["obj"] + }, + "model/prc": { + "source": "iana", + "extensions": ["prc"] + }, + "model/step": { + "source": "iana", + "extensions": ["step","stp","stpnc","p21","210"] + }, + "model/step+xml": { + "source": "iana", + "compressible": true, + "extensions": ["stpx"] + }, + "model/step+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpz"] + }, + "model/step-xml+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpxz"] + }, + "model/stl": { + "source": "iana", + "extensions": ["stl"] + }, + "model/u3d": { + "source": "iana", + "extensions": ["u3d"] + }, + "model/vnd.bary": { + "source": "iana", + "extensions": ["bary"] + }, + "model/vnd.cld": { + "source": "iana", + "extensions": ["cld"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana", + "compressible": true + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana", + "extensions": ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana", + "extensions": ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana", + "extensions": ["x_t"] + }, + "model/vnd.pytha.pyox": { + "source": "iana", + "extensions": ["pyo","pyox"] + }, + "model/vnd.rosette.annotated-data-model": { + "source": "iana" + }, + "model/vnd.sap.vds": { + "source": "iana", + "extensions": ["vds"] + }, + "model/vnd.usda": { + "source": "iana", + "extensions": ["usda"] + }, + "model/vnd.usdz+zip": { + "source": "iana", + "compressible": false, + "extensions": ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana", + "extensions": ["bsp"] + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana", + "extensions": ["x3db"] + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana", + "extensions": ["x3dv"] + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana" + }, + "multipart/multilingual": { + "source": "iana" + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/vnd.bint.med-plus": { + "source": "iana" + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/cql": { + "source": "iana" + }, + "text/cql-expression": { + "source": "iana" + }, + "text/cql-identifier": { + "source": "iana" + }, + "text/css": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "apache" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fhirpath": { + "source": "iana" + }, + "text/flexfec": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/gff3": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hl7v2": { + "source": "iana" + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js","mjs"] + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "compressible": true, + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana", + "compressible": true, + "extensions": ["md","markdown"] + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mdx": { + "compressible": true, + "extensions": ["mdx"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana", + "charset": "UTF-8" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana", + "charset": "UTF-8" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/prs.prop.logic": { + "source": "iana" + }, + "text/prs.texi": { + "source": "iana" + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/shaclc": { + "source": "iana" + }, + "text/shex": { + "source": "iana", + "extensions": ["shex"] + }, + "text/slim": { + "extensions": ["slim","slm"] + }, + "text/spdx": { + "source": "iana", + "extensions": ["spdx"] + }, + "text/strings": { + "source": "iana" + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.ascii-art": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.exchangeable": { + "source": "iana" + }, + "text/vnd.familysearch.gedcom": { + "source": "iana", + "extensions": ["ged"] + }, + "text/vnd.ficlab.flt": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.gml": { + "source": "iana" + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.hans": { + "source": "iana" + }, + "text/vnd.hgl": { + "source": "iana" + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.senx.warpscript": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "apache" + }, + "text/vnd.sosi": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.vcf": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vnd.zoo.kcl": { + "source": "iana" + }, + "text/vtt": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/wgsl": { + "source": "iana", + "extensions": ["wgsl"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-org": { + "compressible": true, + "extensions": ["org"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "compressible": true, + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "iana" + }, + "video/3gpp": { + "source": "iana", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "iana" + }, + "video/3gpp2": { + "source": "iana", + "extensions": ["3g2"] + }, + "video/av1": { + "source": "iana" + }, + "video/bmpeg": { + "source": "iana" + }, + "video/bt656": { + "source": "iana" + }, + "video/celb": { + "source": "iana" + }, + "video/dv": { + "source": "iana" + }, + "video/encaprtp": { + "source": "iana" + }, + "video/evc": { + "source": "iana" + }, + "video/ffv1": { + "source": "iana" + }, + "video/flexfec": { + "source": "iana" + }, + "video/h261": { + "source": "iana", + "extensions": ["h261"] + }, + "video/h263": { + "source": "iana", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "iana" + }, + "video/h263-2000": { + "source": "iana" + }, + "video/h264": { + "source": "iana", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "iana" + }, + "video/h264-svc": { + "source": "iana" + }, + "video/h265": { + "source": "iana" + }, + "video/h266": { + "source": "iana" + }, + "video/iso.segment": { + "source": "iana", + "extensions": ["m4s"] + }, + "video/jpeg": { + "source": "iana", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "iana" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/jxsv": { + "source": "iana" + }, + "video/lottie+json": { + "source": "iana", + "compressible": true + }, + "video/matroska": { + "source": "iana" + }, + "video/matroska-3d": { + "source": "iana" + }, + "video/mj2": { + "source": "iana", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "iana" + }, + "video/mp2p": { + "source": "iana" + }, + "video/mp2t": { + "source": "iana", + "extensions": ["ts","m2t","m2ts","mts"] + }, + "video/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "iana" + }, + "video/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "iana" + }, + "video/mpv": { + "source": "iana" + }, + "video/nv": { + "source": "iana" + }, + "video/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "iana" + }, + "video/pointer": { + "source": "iana" + }, + "video/quicktime": { + "source": "iana", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raptorfec": { + "source": "iana" + }, + "video/raw": { + "source": "iana" + }, + "video/rtp-enc-aescm128": { + "source": "iana" + }, + "video/rtploopback": { + "source": "iana" + }, + "video/rtx": { + "source": "iana" + }, + "video/scip": { + "source": "iana" + }, + "video/smpte291": { + "source": "iana" + }, + "video/smpte292m": { + "source": "iana" + }, + "video/ulpfec": { + "source": "iana" + }, + "video/vc1": { + "source": "iana" + }, + "video/vc2": { + "source": "iana" + }, + "video/vnd.cctv": { + "source": "iana" + }, + "video/vnd.dece.hd": { + "source": "iana", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "iana", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "iana" + }, + "video/vnd.dece.pd": { + "source": "iana", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "iana", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "iana", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "iana" + }, + "video/vnd.directv.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dvb.file": { + "source": "iana", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "iana", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "iana" + }, + "video/vnd.motorola.video": { + "source": "iana" + }, + "video/vnd.motorola.videop": { + "source": "iana" + }, + "video/vnd.mpegurl": { + "source": "iana", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "iana", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "iana" + }, + "video/vnd.nokia.mp4vr": { + "source": "iana" + }, + "video/vnd.nokia.videovoip": { + "source": "iana" + }, + "video/vnd.objectvideo": { + "source": "iana" + }, + "video/vnd.planar": { + "source": "iana" + }, + "video/vnd.radgamettools.bink": { + "source": "iana" + }, + "video/vnd.radgamettools.smacker": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "iana" + }, + "video/vnd.sealed.mpeg4": { + "source": "iana" + }, + "video/vnd.sealed.swf": { + "source": "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "iana" + }, + "video/vnd.uvvu.mp4": { + "source": "iana", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "iana", + "extensions": ["viv"] + }, + "video/vnd.youtube.yt": { + "source": "iana" + }, + "video/vp8": { + "source": "iana" + }, + "video/vp9": { + "source": "iana" + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/node_modules/mime-db/index.js b/node_modules/mime-db/index.js new file mode 100644 index 000000000..ec2be30de --- /dev/null +++ b/node_modules/mime-db/index.js @@ -0,0 +1,12 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/node_modules/mime-db/package.json b/node_modules/mime-db/package.json new file mode 100644 index 000000000..289a370c8 --- /dev/null +++ b/node_modules/mime-db/package.json @@ -0,0 +1,56 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.54.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "Robert Kieffer (http://github.com/broofa)" + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": "jshttp/mime-db", + "devDependencies": { + "csv-parse": "4.16.3", + "eslint": "8.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-markdown": "3.0.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.1.1", + "eslint-plugin-standard": "4.1.0", + "media-typer": "1.1.0", + "mocha": "10.2.0", + "nyc": "15.1.0", + "stream-to-array": "2.3.0", + "undici": "7.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "fetch": "node scripts/fetch-apache && node scripts/fetch-iana && node scripts/fetch-nginx", + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/mime-types/HISTORY.md b/node_modules/mime-types/HISTORY.md new file mode 100644 index 000000000..9ba2dc077 --- /dev/null +++ b/node_modules/mime-types/HISTORY.md @@ -0,0 +1,428 @@ +3.0.2 / 2025-11-20 +=================== + +* Fix: update JSDoc to reflect that functions return only `false` or `string`, not `boolean|string`. +* Fix: refined mime-score logic so `.mp4` resolves correctly +* Fix:reflect the current Node.js version supported to ≥ 18 (See 3.0.0 for more details). + +3.0.1 / 2025-03-26 +=================== + +* deps: mime-db@1.54.0 + +3.0.0 / 2024-08-31 +=================== + +* Drop support for node <18 +* deps: mime-db@1.53.0 +* resolve extension conflicts with mime-score (#119) + * asc -> application/pgp-signature is now application/pgp-keys + * mpp -> application/vnd.ms-project is now application/dash-patch+xml + * ac -> application/vnd.nokia.n-gage.ac+xml is now application/pkix-attr-cert + * bdoc -> application/x-bdoc is now application/bdoc + * wmz -> application/x-msmetafile is now application/x-ms-wmz + * xsl -> application/xslt+xml is now application/xml + * wav -> audio/wave is now audio/wav + * rtf -> text/rtf is now application/rtf + * xml -> text/xml is now application/xml + * mp4 -> video/mp4 is now application/mp4 + * mpg4 -> video/mp4 is now application/mp4 + + +2.1.35 / 2022-03-12 +=================== + + * deps: mime-db@1.52.0 + - Add extensions from IANA for more `image/*` types + - Add extension `.asc` to `application/pgp-keys` + - Add extensions to various XML types + - Add new upstream MIME types + +2.1.34 / 2021-11-08 +=================== + + * deps: mime-db@1.51.0 + - Add new upstream MIME types + +2.1.33 / 2021-10-01 +=================== + + * deps: mime-db@1.50.0 + - Add deprecated iWorks mime types and extensions + - Add new upstream MIME types + +2.1.32 / 2021-07-27 +=================== + + * deps: mime-db@1.49.0 + - Add extension `.trig` to `application/trig` + - Add new upstream MIME types + +2.1.31 / 2021-06-01 +=================== + + * deps: mime-db@1.48.0 + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add new upstream MIME types + +2.1.30 / 2021-04-02 +=================== + + * deps: mime-db@1.47.0 + - Add extension `.amr` to `audio/amr` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +2.1.29 / 2021-02-17 +=================== + + * deps: mime-db@1.46.0 + - Add extension `.amr` to `audio/amr` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.opus` to `audio/ogg` + - Add new upstream MIME types + +2.1.28 / 2021-01-01 +=================== + + * deps: mime-db@1.45.0 + - Add `application/ubjson` with extension `.ubj` + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + +2.1.27 / 2020-04-23 +=================== + + * deps: mime-db@1.44.0 + - Add charsets from IANA + - Add extension `.cjs` to `application/node` + - Add new upstream MIME types + +2.1.26 / 2020-01-05 +=================== + + * deps: mime-db@1.43.0 + - Add `application/x-keepass2` with extension `.kdbx` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extensions from IANA for `application/*+xml` types + - Add new upstream MIME types + +2.1.25 / 2019-11-12 +=================== + + * deps: mime-db@1.42.0 + - Add new upstream MIME types + - Add `application/toml` with extension `.toml` + - Add `image/vnd.ms-dds` with extension `.dds` + +2.1.24 / 2019-04-20 +=================== + + * deps: mime-db@1.40.0 + - Add extensions from IANA for `model/*` types + - Add `text/mdx` with extension `.mdx` + +2.1.23 / 2019-04-17 +=================== + + * deps: mime-db@~1.39.0 + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add new upstream MIME types + +2.1.22 / 2019-02-14 +=================== + + * deps: mime-db@~1.38.0 + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add new upstream MIME types + +2.1.21 / 2018-10-19 +=================== + + * deps: mime-db@~1.37.0 + - Add extensions to HEIC image types + - Add new upstream MIME types + +2.1.20 / 2018-08-26 +=================== + + * deps: mime-db@~1.36.0 + - Add Apple file extensions from IANA + - Add extensions from IANA for `image/*` types + - Add new upstream MIME types + +2.1.19 / 2018-07-17 +=================== + + * deps: mime-db@~1.35.0 + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.owl` to `application/rdf+xml` + - Add new upstream MIME types + - Add UTF-8 as default charset for `text/turtle` + +2.1.18 / 2018-02-16 +=================== + + * deps: mime-db@~1.33.0 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add new upstream MIME types + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +2.1.17 / 2017-09-01 +=================== + + * deps: mime-db@~1.30.0 + - Add `application/vnd.ms-outlook` + - Add `application/x-arj` + - Add extension `.mjs` to `application/javascript` + - Add glTF types and extensions + - Add new upstream MIME types + - Add `text/x-org` + - Add VirtualBox MIME types + - Fix `source` records for `video/*` types that are IANA + - Update `font/opentype` to registered `font/otf` + +2.1.16 / 2017-07-24 +=================== + + * deps: mime-db@~1.29.0 + - Add `application/fido.trusted-apps+json` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add new upstream MIME types + - Update extensions `.md` and `.markdown` to be `text/markdown` + +2.1.15 / 2017-03-23 +=================== + + * deps: mime-db@~1.27.0 + - Add new mime types + - Add `image/apng` + +2.1.14 / 2017-01-14 +=================== + + * deps: mime-db@~1.26.0 + - Add new mime types + +2.1.13 / 2016-11-18 +=================== + + * deps: mime-db@~1.25.0 + - Add new mime types + +2.1.12 / 2016-09-18 +=================== + + * deps: mime-db@~1.24.0 + - Add new mime types + - Add `audio/mp3` + +2.1.11 / 2016-05-01 +=================== + + * deps: mime-db@~1.23.0 + - Add new mime types + +2.1.10 / 2016-02-15 +=================== + + * deps: mime-db@~1.22.0 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + +2.0.10 / 2015-03-13 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/node_modules/mime-types/LICENSE b/node_modules/mime-types/LICENSE new file mode 100644 index 000000000..06166077b --- /dev/null +++ b/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +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/mime-types/README.md b/node_modules/mime-types/README.md new file mode 100644 index 000000000..222d2b58a --- /dev/null +++ b/node_modules/mime-types/README.md @@ -0,0 +1,126 @@ +# mime-types + +[![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][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +The ultimate javascript content-type utility. + +Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, + `mime-types` simply returns `false`, so do + `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- No `.define()` functionality +- Bug fixes for `.lookup(path)` + +Otherwise, the API is compatible with `mime` 1.x. + +## Install + +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 mime-types +``` + +## Note on MIME Type Data and Semver + +This package considers the programmatic api as the semver compatibility. Additionally, the package which provides the MIME data +for this package (`mime-db`) *also* considers it's programmatic api as the semver contract. This means the MIME type resolution is *not* considered +in the semver bumps. + +In the past the version of `mime-db` was pinned to give two decision points when adopting MIME data changes. This is no longer true. We still update the +`mime-db` package here as a `minor` release when necessary, but will use a `^` range going forward. This means that if you want to pin your `mime-db` data +you will need to do it in your application. While this expectation was not set in docs until now, it is how the pacakge operated, so we do not feel this is +a breaking change. + +If you wish to pin your `mime-db` version you can do that with overrides via your package manager of choice. See their documentation for how to correctly configure that. + +## Adding Types + +All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. +When given an extension, `mime.lookup` is used to get the matching +content-type, otherwise the given content-type is used. Then if the +content-type does not already have a `charset` parameter, `mime.charset` +is used to get the default charset and add to the returned content-type. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' +mime.contentType('text/html') // 'text/html; charset=utf-8' +mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci +[ci-url]: https://github.com/jshttp/mime-types/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master +[node-version-image]: https://badgen.net/npm/node/mime-types +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-types +[npm-url]: https://npmjs.org/package/mime-types +[npm-version-image]: https://badgen.net/npm/v/mime-types diff --git a/node_modules/mime-types/index.js b/node_modules/mime-types/index.js new file mode 100644 index 000000000..9725ddf3d --- /dev/null +++ b/node_modules/mime-types/index.js @@ -0,0 +1,211 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var db = require('mime-db') +var extname = require('path').extname +var mimeScore = require('./mimeScore') + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) +exports._extensionConflicts = [] + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {false|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {false|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 ? exports.lookup(str) : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {false|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {false|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .slice(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + types[extension] = _preferredType(extension, types[extension], type) + + // DELETE (eventually): Capture extension->type maps that change as a + // result of switching to mime-score. This is just to help make reviewing + // PR #119 easier, and can be removed once that PR is approved. + const legacyType = _preferredTypeLegacy( + extension, + types[extension], + type + ) + if (legacyType !== types[extension]) { + exports._extensionConflicts.push([extension, legacyType, types[extension]]) + } + } + }) +} + +// Resolve type conflict using mime-score +function _preferredType (ext, type0, type1) { + var score0 = type0 ? mimeScore(type0, db[type0].source) : 0 + var score1 = type1 ? mimeScore(type1, db[type1].source) : 0 + + return score0 > score1 ? type0 : type1 +} + +// Resolve type conflict using pre-mime-score logic +function _preferredTypeLegacy (ext, type0, type1) { + var SOURCE_RANK = ['nginx', 'apache', undefined, 'iana'] + + var score0 = type0 ? SOURCE_RANK.indexOf(db[type0].source) : 0 + var score1 = type1 ? SOURCE_RANK.indexOf(db[type1].source) : 0 + + if ( + exports.types[extension] !== 'application/octet-stream' && + (score0 > score1 || + (score0 === score1 && + exports.types[extension]?.slice(0, 12) === 'application/')) + ) { + return type0 + } + + return score0 > score1 ? type0 : type1 +} diff --git a/node_modules/mime-types/mimeScore.js b/node_modules/mime-types/mimeScore.js new file mode 100644 index 000000000..fc2e6657a --- /dev/null +++ b/node_modules/mime-types/mimeScore.js @@ -0,0 +1,57 @@ +// 'mime-score' back-ported to CommonJS + +// Score RFC facets (see https://tools.ietf.org/html/rfc6838#section-3) +var FACET_SCORES = { + 'prs.': 100, + 'x-': 200, + 'x.': 300, + 'vnd.': 400, + default: 900 +} + +// Score mime source (Logic originally from `jshttp/mime-types` module) +var SOURCE_SCORES = { + nginx: 10, + apache: 20, + iana: 40, + default: 30 // definitions added by `jshttp/mime-db` project? +} + +var TYPE_SCORES = { + // prefer application/xml over text/xml + // prefer application/rtf over text/rtf + application: 1, + + // prefer font/woff over application/font-woff + font: 2, + + // prefer video/mp4 over audio/mp4 over application/mp4 + // See https://www.rfc-editor.org/rfc/rfc4337.html#section-2 + audio: 2, + video: 3, + + default: 0 +} + +/** + * Get each component of the score for a mime type. The sum of these is the + * total score. The higher the score, the more "official" the type. + */ +module.exports = function mimeScore (mimeType, source = 'default') { + if (mimeType === 'application/octet-stream') { + return 0 + } + + const [type, subtype] = mimeType.split('/') + + const facet = subtype.replace(/(\.|x-).*/, '$1') + + const facetScore = FACET_SCORES[facet] || FACET_SCORES.default + const sourceScore = SOURCE_SCORES[source] || SOURCE_SCORES.default + const typeScore = TYPE_SCORES[type] || TYPE_SCORES.default + + // All else being equal prefer shorter types + const lengthScore = 1 - mimeType.length / 100 + + return facetScore + sourceScore + typeScore + lengthScore +} diff --git a/node_modules/mime-types/package.json b/node_modules/mime-types/package.json new file mode 100644 index 000000000..6c58c27af --- /dev/null +++ b/node_modules/mime-types/package.json @@ -0,0 +1,49 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "3.0.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jeremiah Senkpiel (https://searchbeam.jit.su)", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": "jshttp/mime-types", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "dependencies": { + "mime-db": "^1.54.0" + }, + "devDependencies": { + "eslint": "8.33.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.32.0", + "eslint-plugin-markdown": "3.0.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.6.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "10.8.2", + "nyc": "15.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js", + "mimeScore.js" + ], + "engines": { + "node": ">=18" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec test/test.js", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 000000000..ea734fb73 --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 000000000..fa5d39b62 --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 000000000..49971890d --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,38 @@ +{ + "name": "ms", + "version": "2.1.3", + "description": "Tiny millisecond conversion utility", + "repository": "vercel/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.18.2", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1", + "prettier": "2.0.5" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 000000000..0fc1abb3b --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,59 @@ +# ms + +![CI](https://github.com/vercel/ms/workflows/CI/badge.svg) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/negotiator/HISTORY.md b/node_modules/negotiator/HISTORY.md new file mode 100644 index 000000000..63d537d3f --- /dev/null +++ b/node_modules/negotiator/HISTORY.md @@ -0,0 +1,114 @@ +1.0.0 / 2024-08-31 +================== + + * Drop support for node <18 + * Added an option preferred encodings array #59 + +0.6.3 / 2022-01-22 +================== + + * Revert "Lazy-load modules from main entry point" + +0.6.2 / 2019-04-29 +================== + + * Fix sorting charset, encoding, and language with extra parameters + +0.6.1 / 2016-05-02 +================== + + * perf: improve `Accept` parsing speed + * perf: improve `Accept-Charset` parsing speed + * perf: improve `Accept-Encoding` parsing speed + * perf: improve `Accept-Language` parsing speed + +0.6.0 / 2015-09-29 +================== + + * Fix including type extensions in parameters in `Accept` parsing + * Fix parsing `Accept` parameters with quoted equals + * Fix parsing `Accept` parameters with quoted semicolons + * Lazy-load modules from main entry point + * perf: delay type concatenation until needed + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove closures getting spec properties + * perf: remove a closure from media type parsing + * perf: remove property delete from media type parsing + +0.5.3 / 2015-05-10 +================== + + * Fix media type parameter matching to be case-insensitive + +0.5.2 / 2015-05-06 +================== + + * Fix comparing media types with quoted values + * Fix splitting media types with quoted commas + +0.5.1 / 2015-02-14 +================== + + * Fix preference sorting to be stable for long acceptable lists + +0.5.0 / 2014-12-18 +================== + + * Fix list return order when large accepted list + * Fix missing identity encoding when q=0 exists + * Remove dynamic building of Negotiator class + +0.4.9 / 2014-10-14 +================== + + * Fix error when media type has invalid parameter + +0.4.8 / 2014-09-28 +================== + + * Fix all negotiations to be case-insensitive + * Stable sort preferences of same quality according to client order + * Support Node.js 0.6 + +0.4.7 / 2014-06-24 +================== + + * Handle invalid provided languages + * Handle invalid provided media types + +0.4.6 / 2014-06-11 +================== + + * Order by specificity when quality is the same + +0.4.5 / 2014-05-29 +================== + + * Fix regression in empty header handling + +0.4.4 / 2014-05-29 +================== + + * Fix behaviors when headers are not present + +0.4.3 / 2014-04-16 +================== + + * Handle slashes on media params correctly + +0.4.2 / 2014-02-28 +================== + + * Fix media type sorting + * Handle media types params strictly + +0.4.1 / 2014-01-16 +================== + + * Use most specific matches + +0.4.0 / 2014-01-09 +================== + + * Remove preferred prefix from methods diff --git a/node_modules/negotiator/LICENSE b/node_modules/negotiator/LICENSE new file mode 100644 index 000000000..ea6b9e2e9 --- /dev/null +++ b/node_modules/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Federico Romero +Copyright (c) 2012-2014 Isaac Z. Schlueter +Copyright (c) 2014-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/negotiator/README.md b/node_modules/negotiator/README.md new file mode 100644 index 000000000..6fb7f2db3 --- /dev/null +++ b/node_modules/negotiator/README.md @@ -0,0 +1,212 @@ +# negotiator + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-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] + +An HTTP content negotiator for Node.js + +## Installation + +```sh +$ npm install negotiator +``` + +## API + +```js +var Negotiator = require('negotiator') +``` + +### Accept Negotiation + +```js +availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + +// The negotiator constructor receives a request object +negotiator = new Negotiator(request) + +// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + +negotiator.mediaTypes() +// -> ['text/html', 'image/jpeg', 'application/*'] + +negotiator.mediaTypes(availableMediaTypes) +// -> ['text/html', 'application/json'] + +negotiator.mediaType(availableMediaTypes) +// -> 'text/html' +``` + +You can check a working example at `examples/accept.js`. + +#### Methods + +##### mediaType() + +Returns the most preferred media type from the client. + +##### mediaType(availableMediaType) + +Returns the most preferred media type from a list of available media types. + +##### mediaTypes() + +Returns an array of preferred media types ordered by the client preference. + +##### mediaTypes(availableMediaTypes) + +Returns an array of preferred media types ordered by priority from a list of +available media types. + +### Accept-Language Negotiation + +```js +negotiator = new Negotiator(request) + +availableLanguages = ['en', 'es', 'fr'] + +// Let's say Accept-Language header is 'en;q=0.8, es, pt' + +negotiator.languages() +// -> ['es', 'pt', 'en'] + +negotiator.languages(availableLanguages) +// -> ['es', 'en'] + +language = negotiator.language(availableLanguages) +// -> 'es' +``` + +You can check a working example at `examples/language.js`. + +#### Methods + +##### language() + +Returns the most preferred language from the client. + +##### language(availableLanguages) + +Returns the most preferred language from a list of available languages. + +##### languages() + +Returns an array of preferred languages ordered by the client preference. + +##### languages(availableLanguages) + +Returns an array of preferred languages ordered by priority from a list of +available languages. + +### Accept-Charset Negotiation + +```js +availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + +negotiator.charsets() +// -> ['utf-8', 'iso-8859-1', 'utf-7'] + +negotiator.charsets(availableCharsets) +// -> ['utf-8', 'iso-8859-1'] + +negotiator.charset(availableCharsets) +// -> 'utf-8' +``` + +You can check a working example at `examples/charset.js`. + +#### Methods + +##### charset() + +Returns the most preferred charset from the client. + +##### charset(availableCharsets) + +Returns the most preferred charset from a list of available charsets. + +##### charsets() + +Returns an array of preferred charsets ordered by the client preference. + +##### charsets(availableCharsets) + +Returns an array of preferred charsets ordered by priority from a list of +available charsets. + +### Accept-Encoding Negotiation + +```js +availableEncodings = ['identity', 'gzip'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + +negotiator.encodings() +// -> ['gzip', 'identity', 'compress'] + +negotiator.encodings(availableEncodings) +// -> ['gzip', 'identity'] + +negotiator.encoding(availableEncodings) +// -> 'gzip' +``` + +You can check a working example at `examples/encoding.js`. + +#### Methods + +##### encoding() + +Returns the most preferred encoding from the client. + +##### encoding(availableEncodings) + +Returns the most preferred encoding from a list of available encodings. + +##### encoding(availableEncodings, { preferred }) + +Returns the most preferred encoding from a list of available encodings, while prioritizing based on `preferred` array between same-quality encodings. + +##### encodings() + +Returns an array of preferred encodings ordered by the client preference. + +##### encodings(availableEncodings) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings. + +##### encodings(availableEncodings, { preferred }) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings, while prioritizing based on `preferred` array between same-quality encodings. + +## See Also + +The [accepts](https://npmjs.org/package/accepts#readme) module builds on +this module and provides an alternative interface, mime type validation, +and more. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/negotiator.svg +[npm-url]: https://npmjs.org/package/negotiator +[node-version-image]: https://img.shields.io/node/v/negotiator.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master +[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg +[downloads-url]: https://npmjs.org/package/negotiator +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/jshttp/negotiator/ci/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/negotiator/actions/workflows/ci.yml diff --git a/node_modules/negotiator/index.js b/node_modules/negotiator/index.js new file mode 100644 index 000000000..4f51315d6 --- /dev/null +++ b/node_modules/negotiator/index.js @@ -0,0 +1,83 @@ +/*! + * negotiator + * Copyright(c) 2012 Federico Romero + * Copyright(c) 2012-2014 Isaac Z. Schlueter + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +var preferredCharsets = require('./lib/charset') +var preferredEncodings = require('./lib/encoding') +var preferredLanguages = require('./lib/language') +var preferredMediaTypes = require('./lib/mediaType') + +/** + * Module exports. + * @public + */ + +module.exports = Negotiator; +module.exports.Negotiator = Negotiator; + +/** + * Create a Negotiator instance from a request. + * @param {object} request + * @public + */ + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available, opts) { + var set = this.encodings(available, opts); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available, options) { + var opts = options || {}; + return preferredEncodings(this.request.headers['accept-encoding'], available, opts.preferred); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; diff --git a/node_modules/negotiator/lib/charset.js b/node_modules/negotiator/lib/charset.js new file mode 100644 index 000000000..cdd014803 --- /dev/null +++ b/node_modules/negotiator/lib/charset.js @@ -0,0 +1,169 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredCharsets; +module.exports.preferredCharsets = preferredCharsets; + +/** + * Module variables. + * @private + */ + +var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Charset header. + * @private + */ + +function parseAcceptCharset(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var charset = parseCharset(accepts[i].trim(), i); + + if (charset) { + accepts[j++] = charset; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a charset from the Accept-Charset header. + * @private + */ + +function parseCharset(str, i) { + var match = simpleCharsetRegExp.exec(str); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +/** + * Get the priority of a charset. + * @private + */ + +function getCharsetPriority(charset, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(charset, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the charset. + * @private + */ + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +/** + * Get the preferred charsets from an Accept-Charset header. + * @public + */ + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all charsets + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullCharset); + } + + var priorities = provided.map(function getPriority(type, index) { + return getCharsetPriority(type, accepts, index); + }); + + // sorted list of accepted charsets + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full charset string. + * @private + */ + +function getFullCharset(spec) { + return spec.charset; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/encoding.js b/node_modules/negotiator/lib/encoding.js new file mode 100644 index 000000000..9ebb633d6 --- /dev/null +++ b/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,205 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredEncodings; +module.exports.preferredEncodings = preferredEncodings; + +/** + * Module variables. + * @private + */ + +var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Encoding header. + * @private + */ + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + for (var i = 0, j = 0; i < accepts.length; i++) { + var encoding = parseEncoding(accepts[i].trim(), i); + + if (encoding) { + accepts[j++] = encoding; + hasIdentity = hasIdentity || specify('identity', encoding); + minQuality = Math.min(minQuality, encoding.q || 1); + } + } + + if (!hasIdentity) { + /* + * If identity doesn't explicitly appear in the accept-encoding header, + * it's added to the list of acceptable encoding with the lowest q + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse an encoding from the Accept-Encoding header. + * @private + */ + +function parseEncoding(str, i) { + var match = simpleEncodingRegExp.exec(str); + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +/** + * Get the priority of an encoding. + * @private + */ + +function getEncodingPriority(encoding, accepted, index) { + var priority = {encoding: encoding, o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(encoding, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the encoding. + * @private + */ + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + encoding: encoding, + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred encodings from an Accept-Encoding header. + * @public + */ + +function preferredEncodings(accept, provided, preferred) { + var accepts = parseAcceptEncoding(accept || ''); + + var comparator = preferred ? function comparator (a, b) { + if (a.q !== b.q) { + return b.q - a.q // higher quality first + } + + var aPreferred = preferred.indexOf(a.encoding) + var bPreferred = preferred.indexOf(b.encoding) + + if (aPreferred === -1 && bPreferred === -1) { + // consider the original specifity/order + return (b.s - a.s) || (a.o - b.o) || (a.i - b.i) + } + + if (aPreferred !== -1 && bPreferred !== -1) { + return aPreferred - bPreferred // consider the preferred order + } + + return aPreferred === -1 ? 1 : -1 // preferred first + } : compareSpecs; + + if (!provided) { + // sorted list of all encodings + return accepts + .filter(isQuality) + .sort(comparator) + .map(getFullEncoding); + } + + var priorities = provided.map(function getPriority(type, index) { + return getEncodingPriority(type, accepts, index); + }); + + // sorted list of accepted encodings + return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i); +} + +/** + * Get full encoding string. + * @private + */ + +function getFullEncoding(spec) { + return spec.encoding; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/language.js b/node_modules/negotiator/lib/language.js new file mode 100644 index 000000000..a23167252 --- /dev/null +++ b/node_modules/negotiator/lib/language.js @@ -0,0 +1,179 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredLanguages; +module.exports.preferredLanguages = preferredLanguages; + +/** + * Module variables. + * @private + */ + +var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Language header. + * @private + */ + +function parseAcceptLanguage(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var language = parseLanguage(accepts[i].trim(), i); + + if (language) { + accepts[j++] = language; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a language from the Accept-Language header. + * @private + */ + +function parseLanguage(str, i) { + var match = simpleLanguageRegExp.exec(str); + if (!match) return null; + + var prefix = match[1] + var suffix = match[2] + var full = prefix + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +/** + * Get the priority of a language. + * @private + */ + +function getLanguagePriority(language, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(language, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the language. + * @private + */ + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred languages from an Accept-Language header. + * @public + */ + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all languages + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullLanguage); + } + + var priorities = provided.map(function getPriority(type, index) { + return getLanguagePriority(type, accepts, index); + }); + + // sorted list of accepted languages + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full language string. + * @private + */ + +function getFullLanguage(spec) { + return spec.full; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/mediaType.js b/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 000000000..8e402ea88 --- /dev/null +++ b/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,294 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredMediaTypes; +module.exports.preferredMediaTypes = preferredMediaTypes; + +/** + * Module variables. + * @private + */ + +var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept header. + * @private + */ + +function parseAccept(accept) { + var accepts = splitMediaTypes(accept); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var mediaType = parseMediaType(accepts[i].trim(), i); + + if (mediaType) { + accepts[j++] = mediaType; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a media type from the Accept header. + * @private + */ + +function parseMediaType(str, i) { + var match = simpleMediaTypeRegExp.exec(str); + if (!match) return null; + + var params = Object.create(null); + var q = 1; + var subtype = match[2]; + var type = match[1]; + + if (match[3]) { + var kvps = splitParameters(match[3]).map(splitKeyValuePair); + + for (var j = 0; j < kvps.length; j++) { + var pair = kvps[j]; + var key = pair[0].toLowerCase(); + var val = pair[1]; + + // get the value, unwrapping quotes + var value = val && val[0] === '"' && val[val.length - 1] === '"' + ? val.slice(1, -1) + : val; + + if (key === 'q') { + q = parseFloat(value); + break; + } + + // store parameter + params[key] = value; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i + }; +} + +/** + * Get the priority of a media type. + * @private + */ + +function getMediaTypePriority(type, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(type, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the media type. + * @private + */ + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } +} + +/** + * Get the preferred media types from an Accept header. + * @public + */ + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + if (!provided) { + // sorted list of all types + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullType); + } + + var priorities = provided.map(function getPriority(type, index) { + return getMediaTypePriority(type, accepts, index); + }); + + // sorted list of accepted types + return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full type string. + * @private + */ + +function getFullType(spec) { + return spec.type + '/' + spec.subtype; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} + +/** + * Count the number of quotes in a string. + * @private + */ + +function quoteCount(string) { + var count = 0; + var index = 0; + + while ((index = string.indexOf('"', index)) !== -1) { + count++; + index++; + } + + return count; +} + +/** + * Split a key value pair. + * @private + */ + +function splitKeyValuePair(str) { + var index = str.indexOf('='); + var key; + var val; + + if (index === -1) { + key = str; + } else { + key = str.slice(0, index); + val = str.slice(index + 1); + } + + return [key, val]; +} + +/** + * Split an Accept header into media types. + * @private + */ + +function splitMediaTypes(accept) { + var accepts = accept.split(','); + + for (var i = 1, j = 0; i < accepts.length; i++) { + if (quoteCount(accepts[j]) % 2 == 0) { + accepts[++j] = accepts[i]; + } else { + accepts[j] += ',' + accepts[i]; + } + } + + // trim accepts + accepts.length = j + 1; + + return accepts; +} + +/** + * Split a string of parameters. + * @private + */ + +function splitParameters(str) { + var parameters = str.split(';'); + + for (var i = 1, j = 0; i < parameters.length; i++) { + if (quoteCount(parameters[j]) % 2 == 0) { + parameters[++j] = parameters[i]; + } else { + parameters[j] += ';' + parameters[i]; + } + } + + // trim parameters + parameters.length = j + 1; + + for (var i = 0; i < parameters.length; i++) { + parameters[i] = parameters[i].trim(); + } + + return parameters; +} diff --git a/node_modules/negotiator/package.json b/node_modules/negotiator/package.json new file mode 100644 index 000000000..e4bdc1ef4 --- /dev/null +++ b/node_modules/negotiator/package.json @@ -0,0 +1,43 @@ +{ + "name": "negotiator", + "description": "HTTP content negotiation", + "version": "1.0.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Federico Romero ", + "Isaac Z. Schlueter (http://blog.izs.me/)" + ], + "license": "MIT", + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "repository": "jshttp/negotiator", + "devDependencies": { + "eslint": "7.32.0", + "eslint-plugin-markdown": "2.2.1", + "mocha": "9.1.3", + "nyc": "15.1.0" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test:debug": "mocha --reporter spec --check-leaks --inspect --inspect-brk test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/object-assign/index.js b/node_modules/object-assign/index.js new file mode 100644 index 000000000..0930cf889 --- /dev/null +++ b/node_modules/object-assign/index.js @@ -0,0 +1,90 @@ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; diff --git a/node_modules/object-assign/license b/node_modules/object-assign/license new file mode 100644 index 000000000..654d0bfe9 --- /dev/null +++ b/node_modules/object-assign/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/object-assign/package.json b/node_modules/object-assign/package.json new file mode 100644 index 000000000..503eb1e6d --- /dev/null +++ b/node_modules/object-assign/package.json @@ -0,0 +1,42 @@ +{ + "name": "object-assign", + "version": "4.1.1", + "description": "ES2015 `Object.assign()` ponyfill", + "license": "MIT", + "repository": "sindresorhus/object-assign", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava", + "bench": "matcha bench.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "object", + "assign", + "extend", + "properties", + "es2015", + "ecmascript", + "harmony", + "ponyfill", + "prollyfill", + "polyfill", + "shim", + "browser" + ], + "devDependencies": { + "ava": "^0.16.0", + "lodash": "^4.16.4", + "matcha": "^0.7.0", + "xo": "^0.16.0" + } +} diff --git a/node_modules/object-assign/readme.md b/node_modules/object-assign/readme.md new file mode 100644 index 000000000..1be09d35c --- /dev/null +++ b/node_modules/object-assign/readme.md @@ -0,0 +1,61 @@ +# object-assign [![Build Status](https://travis-ci.org/sindresorhus/object-assign.svg?branch=master)](https://travis-ci.org/sindresorhus/object-assign) + +> ES2015 [`Object.assign()`](http://www.2ality.com/2014/01/object-assign.html) [ponyfill](https://ponyfill.com) + + +## Use the built-in + +Node.js 4 and up, as well as every evergreen browser (Chrome, Edge, Firefox, Opera, Safari), +support `Object.assign()` :tada:. If you target only those environments, then by all +means, use `Object.assign()` instead of this package. + + +## Install + +``` +$ npm install --save object-assign +``` + + +## Usage + +```js +const objectAssign = require('object-assign'); + +objectAssign({foo: 0}, {bar: 1}); +//=> {foo: 0, bar: 1} + +// multiple sources +objectAssign({foo: 0}, {bar: 1}, {baz: 2}); +//=> {foo: 0, bar: 1, baz: 2} + +// overwrites equal keys +objectAssign({foo: 0}, {foo: 1}, {foo: 2}); +//=> {foo: 2} + +// ignores null and undefined sources +objectAssign({foo: 0}, null, {bar: 1}, undefined); +//=> {foo: 0, bar: 1} +``` + + +## API + +### objectAssign(target, [source, ...]) + +Assigns enumerable own properties of `source` objects to the `target` object and returns the `target` object. Additional `source` objects will overwrite previous ones. + + +## Resources + +- [ES2015 spec - Object.assign](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign) + + +## Related + +- [deep-assign](https://github.com/sindresorhus/deep-assign) - Recursive `Object.assign()` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/object-inspect/.eslintrc b/node_modules/object-inspect/.eslintrc new file mode 100644 index 000000000..21f903923 --- /dev/null +++ b/node_modules/object-inspect/.eslintrc @@ -0,0 +1,53 @@ +{ + "root": true, + "extends": "@ljharb", + "rules": { + "complexity": 0, + "func-style": [2, "declaration"], + "indent": [2, 4], + "max-lines": 1, + "max-lines-per-function": 1, + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "no-param-reassign": 1, + "strict": 0, // TODO + }, + "overrides": [ + { + "files": ["test/**", "test-*", "example/**"], + "extends": "@ljharb/eslint-config/tests", + "rules": { + "id-length": 0, + }, + }, + { + "files": ["example/**"], + "rules": { + "no-console": 0, + }, + }, + { + "files": ["test/browser/**"], + "env": { + "browser": true, + }, + }, + { + "files": ["test/bigint*"], + "rules": { + "new-cap": [2, { "capIsNewExceptions": ["BigInt"] }], + }, + }, + { + "files": "index.js", + "globals": { + "HTMLElement": false, + }, + "rules": { + "no-use-before-define": 1, + }, + }, + ], +} diff --git a/node_modules/object-inspect/.github/FUNDING.yml b/node_modules/object-inspect/.github/FUNDING.yml new file mode 100644 index 000000000..730276bd1 --- /dev/null +++ b/node_modules/object-inspect/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/object-inspect +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/object-inspect/.nycrc b/node_modules/object-inspect/.nycrc new file mode 100644 index 000000000..58a5db783 --- /dev/null +++ b/node_modules/object-inspect/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "instrumentation": false, + "sourceMap": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "example", + "test", + "test-core-js.js" + ] +} diff --git a/node_modules/object-inspect/CHANGELOG.md b/node_modules/object-inspect/CHANGELOG.md new file mode 100644 index 000000000..bdf900274 --- /dev/null +++ b/node_modules/object-inspect/CHANGELOG.md @@ -0,0 +1,424 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.13.4](https://github.com/inspect-js/object-inspect/compare/v1.13.3...v1.13.4) - 2025-02-04 + +### Commits + +- [Fix] avoid being fooled by a `Symbol.toStringTag` [`fa5870d`](https://github.com/inspect-js/object-inspect/commit/fa5870da468a525d2f20193700f70752f506cbf7) +- [Tests] fix tests in node v6.0 - v6.4 [`2abfe1b`](https://github.com/inspect-js/object-inspect/commit/2abfe1bc3c69f9293c07c5cd65a9d7d87a628b84) +- [Dev Deps] update `es-value-fixtures`, `for-each`, `has-symbols` [`3edfb01`](https://github.com/inspect-js/object-inspect/commit/3edfb01cc8cce220fba0dfdfe2dc8bc955758cdd) + +## [v1.13.3](https://github.com/inspect-js/object-inspect/compare/v1.13.2...v1.13.3) - 2024-11-09 + +### Commits + +- [actions] split out node 10-20, and 20+ [`44395a8`](https://github.com/inspect-js/object-inspect/commit/44395a8fc1deda6718a5e125e86b9ffcaa1c7580) +- [Fix] `quoteStyle`: properly escape only the containing quotes [`5137f8f`](https://github.com/inspect-js/object-inspect/commit/5137f8f7bea69a7fc671bb683fd35f244f38fc52) +- [Refactor] clean up `quoteStyle` code [`450680c`](https://github.com/inspect-js/object-inspect/commit/450680cd50de4e689ee3b8e1d6db3a1bcf3fc18c) +- [Tests] add `quoteStyle` escaping tests [`e997c59`](https://github.com/inspect-js/object-inspect/commit/e997c595aeaea84fd98ca35d7e1c3b5ab3ae26e0) +- [Dev Deps] update `auto-changelog`, `es-value-fixtures`, `tape` [`d5a469c`](https://github.com/inspect-js/object-inspect/commit/d5a469c99ec07ccaeafc36ac4b36a93285086d48) +- [Tests] replace `aud` with `npm audit` [`fb7815f`](https://github.com/inspect-js/object-inspect/commit/fb7815f9b72cae277a04f65bbb0543f85b88be62) +- [Dev Deps] update `mock-property` [`11c817b`](https://github.com/inspect-js/object-inspect/commit/11c817bf10392aa017755962ba6bc89d731359ee) + +## [v1.13.2](https://github.com/inspect-js/object-inspect/compare/v1.13.1...v1.13.2) - 2024-06-21 + +### Commits + +- [readme] update badges [`8a51e6b`](https://github.com/inspect-js/object-inspect/commit/8a51e6bedaf389ec40cc4659e9df53e8543d176e) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`ef05f58`](https://github.com/inspect-js/object-inspect/commit/ef05f58c9761a41416ab907299bf0fa79517014b) +- [Dev Deps] update `error-cause`, `has-tostringtag`, `tape` [`c0c6c26`](https://github.com/inspect-js/object-inspect/commit/c0c6c26c44cee6671f7c5d43d2b91d27c5c00d90) +- [Fix] Don't throw when `global` is not defined [`d4d0965`](https://github.com/inspect-js/object-inspect/commit/d4d096570f7dbd0e03266a96de11d05eb7b63e0f) +- [meta] add missing `engines.node` [`17a352a`](https://github.com/inspect-js/object-inspect/commit/17a352af6fe1ba6b70a19081674231eb1a50c940) +- [Dev Deps] update `globalthis` [`9c08884`](https://github.com/inspect-js/object-inspect/commit/9c08884aa662a149e2f11403f413927736b97da7) +- [Dev Deps] update `error-cause` [`6af352d`](https://github.com/inspect-js/object-inspect/commit/6af352d7c3929a4cc4c55768c27bf547a5e900f4) +- [Dev Deps] update `npmignore` [`94e617d`](https://github.com/inspect-js/object-inspect/commit/94e617d38831722562fa73dff4c895746861d267) +- [Dev Deps] update `mock-property` [`2ac24d7`](https://github.com/inspect-js/object-inspect/commit/2ac24d7e58cd388ad093c33249e413e05bbfd6c3) +- [Dev Deps] update `tape` [`46125e5`](https://github.com/inspect-js/object-inspect/commit/46125e58f1d1dcfb170ed3d1ea69da550ea8d77b) + +## [v1.13.1](https://github.com/inspect-js/object-inspect/compare/v1.13.0...v1.13.1) - 2023-10-19 + +### Commits + +- [Fix] in IE 8, global can !== window despite them being prototypes of each other [`30d0859`](https://github.com/inspect-js/object-inspect/commit/30d0859dc4606cf75c2410edcd5d5c6355f8d372) + +## [v1.13.0](https://github.com/inspect-js/object-inspect/compare/v1.12.3...v1.13.0) - 2023-10-14 + +### Commits + +- [New] add special handling for the global object [`431bab2`](https://github.com/inspect-js/object-inspect/commit/431bab21a490ee51d35395966a504501e8c685da) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`fd4f619`](https://github.com/inspect-js/object-inspect/commit/fd4f6193562b4b0e95dcf5c0201b4e8cbbc4f58d) +- [Dev Deps] update `mock-property`, `tape` [`b453f6c`](https://github.com/inspect-js/object-inspect/commit/b453f6ceeebf8a1b738a1029754092e0367a4134) +- [Dev Deps] update `error-cause` [`e8ffc57`](https://github.com/inspect-js/object-inspect/commit/e8ffc577d73b92bb6a4b00c44f14e3319e374888) +- [Dev Deps] update `tape` [`054b8b9`](https://github.com/inspect-js/object-inspect/commit/054b8b9b98633284cf989e582450ebfbbe53503c) +- [Dev Deps] temporarily remove `aud` due to breaking change in transitive deps [`2476845`](https://github.com/inspect-js/object-inspect/commit/2476845e0678dd290c541c81cd3dec8420782c52) +- [Dev Deps] pin `glob`, since v10.3.8+ requires a broken `jackspeak` [`383fa5e`](https://github.com/inspect-js/object-inspect/commit/383fa5eebc0afd705cc778a4b49d8e26452e49a8) +- [Dev Deps] pin `jackspeak` since 2.1.2+ depends on npm aliases, which kill the install process in npm < 6 [`68c244c`](https://github.com/inspect-js/object-inspect/commit/68c244c5174cdd877e5dcb8ee90aa3f44b2f25be) + +## [v1.12.3](https://github.com/inspect-js/object-inspect/compare/v1.12.2...v1.12.3) - 2023-01-12 + +### Commits + +- [Fix] in eg FF 24, collections lack forEach [`75fc226`](https://github.com/inspect-js/object-inspect/commit/75fc22673c82d45f28322b1946bb0eb41b672b7f) +- [actions] update rebase action to use reusable workflow [`250a277`](https://github.com/inspect-js/object-inspect/commit/250a277a095e9dacc029ab8454dcfc15de549dcd) +- [Dev Deps] update `aud`, `es-value-fixtures`, `tape` [`66a19b3`](https://github.com/inspect-js/object-inspect/commit/66a19b3209ccc3c5ef4b34c3cb0160e65d1ce9d5) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `error-cause` [`c43d332`](https://github.com/inspect-js/object-inspect/commit/c43d3324b48384a16fd3dc444e5fc589d785bef3) +- [Tests] add `@pkgjs/support` to `postlint` [`e2618d2`](https://github.com/inspect-js/object-inspect/commit/e2618d22a7a3fa361b6629b53c1752fddc9c4d80) + +## [v1.12.2](https://github.com/inspect-js/object-inspect/compare/v1.12.1...v1.12.2) - 2022-05-26 + +### Commits + +- [Fix] use `util.inspect` for a custom inspection symbol method [`e243bf2`](https://github.com/inspect-js/object-inspect/commit/e243bf2eda6c4403ac6f1146fddb14d12e9646c1) +- [meta] add support info [`ca20ba3`](https://github.com/inspect-js/object-inspect/commit/ca20ba35713c17068ca912a86c542f5e8acb656c) +- [Fix] ignore `cause` in node v16.9 and v16.10 where it has a bug [`86aa553`](https://github.com/inspect-js/object-inspect/commit/86aa553a4a455562c2c56f1540f0bf857b9d314b) + +## [v1.12.1](https://github.com/inspect-js/object-inspect/compare/v1.12.0...v1.12.1) - 2022-05-21 + +### Commits + +- [Tests] use `mock-property` [`4ec8893`](https://github.com/inspect-js/object-inspect/commit/4ec8893ea9bfd28065ca3638cf6762424bf44352) +- [meta] use `npmignore` to autogenerate an npmignore file [`07f868c`](https://github.com/inspect-js/object-inspect/commit/07f868c10bd25a9d18686528339bb749c211fc9a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`b05244b`](https://github.com/inspect-js/object-inspect/commit/b05244b4f331e00c43b3151bc498041be77ccc91) +- [Dev Deps] update `@ljharb/eslint-config`, `error-cause`, `es-value-fixtures`, `functions-have-names`, `tape` [`d037398`](https://github.com/inspect-js/object-inspect/commit/d037398dcc5d531532e4c19c4a711ed677f579c1) +- [Fix] properly handle callable regexes in older engines [`848fe48`](https://github.com/inspect-js/object-inspect/commit/848fe48bd6dd0064ba781ee6f3c5e54a94144c37) + +## [v1.12.0](https://github.com/inspect-js/object-inspect/compare/v1.11.1...v1.12.0) - 2021-12-18 + +### Commits + +- [New] add `numericSeparator` boolean option [`2d2d537`](https://github.com/inspect-js/object-inspect/commit/2d2d537f5359a4300ce1c10241369f8024f89e11) +- [Robustness] cache more prototype methods [`191533d`](https://github.com/inspect-js/object-inspect/commit/191533da8aec98a05eadd73a5a6e979c9c8653e8) +- [New] ensure an Error’s `cause` is displayed [`53bc2ce`](https://github.com/inspect-js/object-inspect/commit/53bc2cee4e5a9cc4986f3cafa22c0685f340715e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`bc164b6`](https://github.com/inspect-js/object-inspect/commit/bc164b6e2e7d36b263970f16f54de63048b84a36) +- [Robustness] cache `RegExp.prototype.test` [`a314ab8`](https://github.com/inspect-js/object-inspect/commit/a314ab8271b905cbabc594c82914d2485a8daf12) +- [meta] fix auto-changelog settings [`5ed0983`](https://github.com/inspect-js/object-inspect/commit/5ed0983be72f73e32e2559997517a95525c7e20d) + +## [v1.11.1](https://github.com/inspect-js/object-inspect/compare/v1.11.0...v1.11.1) - 2021-12-05 + +### Commits + +- [meta] add `auto-changelog` [`7dbdd22`](https://github.com/inspect-js/object-inspect/commit/7dbdd228401d6025d8b7391476d88aee9ea9bbdf) +- [actions] reuse common workflows [`c8823bc`](https://github.com/inspect-js/object-inspect/commit/c8823bc0a8790729680709d45fb6e652432e91aa) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`7532b12`](https://github.com/inspect-js/object-inspect/commit/7532b120598307497b712890f75af8056f6d37a6) +- [Refactor] use `has-tostringtag` to behave correctly in the presence of symbol shams [`94abb5d`](https://github.com/inspect-js/object-inspect/commit/94abb5d4e745bf33253942dea86b3e538d2ff6c6) +- [actions] update codecov uploader [`5ed5102`](https://github.com/inspect-js/object-inspect/commit/5ed51025267a00e53b1341357315490ac4eb0874) +- [Dev Deps] update `eslint`, `tape` [`37b2ad2`](https://github.com/inspect-js/object-inspect/commit/37b2ad26c08d94bfd01d5d07069a0b28ef4e2ad7) +- [meta] add `sideEffects` flag [`d341f90`](https://github.com/inspect-js/object-inspect/commit/d341f905ef8bffa6a694cda6ddc5ba343532cd4f) + +## [v1.11.0](https://github.com/inspect-js/object-inspect/compare/v1.10.3...v1.11.0) - 2021-07-12 + +### Commits + +- [New] `customInspect`: add `symbol` option, to mimic modern util.inspect behavior [`e973a6e`](https://github.com/inspect-js/object-inspect/commit/e973a6e21f8140c5837cf25e9d89bdde88dc3120) +- [Dev Deps] update `eslint` [`05f1cb3`](https://github.com/inspect-js/object-inspect/commit/05f1cb3cbcfe1f238e8b51cf9bc294305b7ed793) + +## [v1.10.3](https://github.com/inspect-js/object-inspect/compare/v1.10.2...v1.10.3) - 2021-05-07 + +### Commits + +- [Fix] handle core-js Symbol shams [`4acfc2c`](https://github.com/inspect-js/object-inspect/commit/4acfc2c4b503498759120eb517abad6d51c9c5d6) +- [readme] update badges [`95c323a`](https://github.com/inspect-js/object-inspect/commit/95c323ad909d6cbabb95dd6015c190ba6db9c1f2) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud` [`cb38f48`](https://github.com/inspect-js/object-inspect/commit/cb38f485de6ec7a95109b5a9bbd0a1deba2f6611) + +## [v1.10.2](https://github.com/inspect-js/object-inspect/compare/v1.10.1...v1.10.2) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed Symbol [`87f12d6`](https://github.com/inspect-js/object-inspect/commit/87f12d6e69ce530be04659c81a4cd502943acac5) + +## [v1.10.1](https://github.com/inspect-js/object-inspect/compare/v1.10.0...v1.10.1) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed bigint [`d5ca829`](https://github.com/inspect-js/object-inspect/commit/d5ca8298b6d2e5c7b9334a5b21b96ed95d225c91) + +## [v1.10.0](https://github.com/inspect-js/object-inspect/compare/v1.9.0...v1.10.0) - 2021-04-17 + +### Commits + +- [Tests] increase coverage [`d8abb8a`](https://github.com/inspect-js/object-inspect/commit/d8abb8a62c2f084919df994a433b346e0d87a227) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`4bfec2e`](https://github.com/inspect-js/object-inspect/commit/4bfec2e30aaef6ddef6cbb1448306f9f8b9520b7) +- [New] respect `Symbol.toStringTag` on objects [`799b58f`](https://github.com/inspect-js/object-inspect/commit/799b58f536a45e4484633a8e9daeb0330835f175) +- [Fix] do not allow Symbol.toStringTag to masquerade as builtins [`d6c5b37`](https://github.com/inspect-js/object-inspect/commit/d6c5b37d7e94427796b82432fb0c8964f033a6ab) +- [New] add `WeakRef` support [`b6d898e`](https://github.com/inspect-js/object-inspect/commit/b6d898ee21868c780a7ee66b28532b5b34ed7f09) +- [meta] do not publish github action workflow files [`918cdfc`](https://github.com/inspect-js/object-inspect/commit/918cdfc4b6fe83f559ff6ef04fe66201e3ff5cbd) +- [meta] create `FUNDING.yml` [`0bb5fc5`](https://github.com/inspect-js/object-inspect/commit/0bb5fc516dbcd2cd728bd89cee0b580acc5ce301) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`22c8dc0`](https://github.com/inspect-js/object-inspect/commit/22c8dc0cac113d70f4781e49a950070923a671be) +- [meta] use `prepublishOnly` script for npm 7+ [`e52ee09`](https://github.com/inspect-js/object-inspect/commit/e52ee09e8050b8dbac94ef57f786675567728223) +- [Dev Deps] update `eslint` [`7c4e6fd`](https://github.com/inspect-js/object-inspect/commit/7c4e6fdedcd27cc980e13c9ad834d05a96f3d40c) + +## [v1.9.0](https://github.com/inspect-js/object-inspect/compare/v1.8.0...v1.9.0) - 2020-11-30 + +### Commits + +- [Tests] migrate tests to Github Actions [`d262251`](https://github.com/inspect-js/object-inspect/commit/d262251e13e16d3490b5473672f6b6d6ff86675d) +- [New] add enumerable own Symbols to plain object output [`ee60c03`](https://github.com/inspect-js/object-inspect/commit/ee60c033088cff9d33baa71e59a362a541b48284) +- [Tests] add passing tests [`01ac3e4`](https://github.com/inspect-js/object-inspect/commit/01ac3e4b5a30f97875a63dc9b1416b3bd626afc9) +- [actions] add "Require Allow Edits" action [`c2d7746`](https://github.com/inspect-js/object-inspect/commit/c2d774680cde4ca4af332d84d4121b26f798ba9e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `core-js` [`70058de`](https://github.com/inspect-js/object-inspect/commit/70058de1579fc54d1d15ed6c2dbe246637ce70ff) +- [Fix] hex characters in strings should be uppercased, to match node `assert` [`6ab8faa`](https://github.com/inspect-js/object-inspect/commit/6ab8faaa0abc08fe7a8e2afd8b39c6f1f0e00113) +- [Tests] run `nyc` on all tests [`4c47372`](https://github.com/inspect-js/object-inspect/commit/4c473727879ddc8e28b599202551ddaaf07b6210) +- [Tests] node 0.8 has an unpredictable property order; fix `groups` test by removing property [`f192069`](https://github.com/inspect-js/object-inspect/commit/f192069a978a3b60e6f0e0d45ac7df260ab9a778) +- [New] add enumerable properties to Function inspect result, per node’s `assert` [`fd38e1b`](https://github.com/inspect-js/object-inspect/commit/fd38e1bc3e2a1dc82091ce3e021917462eee64fc) +- [Tests] fix tests for node < 10, due to regex match `groups` [`2ac6462`](https://github.com/inspect-js/object-inspect/commit/2ac6462cc4f72eaa0b63a8cfee9aabe3008b2330) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`44b59e2`](https://github.com/inspect-js/object-inspect/commit/44b59e2676a7f825ef530dfd19dafb599e3b9456) +- [Robustness] cache `Symbol.prototype.toString` [`f3c2074`](https://github.com/inspect-js/object-inspect/commit/f3c2074d8f32faf8292587c07c9678ea931703dd) +- [Dev Deps] update `eslint` [`9411294`](https://github.com/inspect-js/object-inspect/commit/94112944b9245e3302e25453277876402d207e7f) +- [meta] `require-allow-edits` no longer requires an explicit github token [`36c0220`](https://github.com/inspect-js/object-inspect/commit/36c02205de3c2b0e84d53777c5c9fd54a36c48ab) +- [actions] update rebase checkout action to v2 [`55a39a6`](https://github.com/inspect-js/object-inspect/commit/55a39a64e944f19c6a7d8efddf3df27700f20d14) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`f59fd3c`](https://github.com/inspect-js/object-inspect/commit/f59fd3cf406c3a7c7ece140904a80bbc6bacfcca) +- [Dev Deps] update `eslint` [`a492bec`](https://github.com/inspect-js/object-inspect/commit/a492becec644b0155c9c4bc1caf6f9fac11fb2c7) + +## [v1.8.0](https://github.com/inspect-js/object-inspect/compare/v1.7.0...v1.8.0) - 2020-06-18 + +### Fixed + +- [New] add `indent` option [`#27`](https://github.com/inspect-js/object-inspect/issues/27) + +### Commits + +- [Tests] add codecov [`4324cbb`](https://github.com/inspect-js/object-inspect/commit/4324cbb1a2bd7710822a4151ff373570db22453e) +- [New] add `maxStringLength` option [`b3995cb`](https://github.com/inspect-js/object-inspect/commit/b3995cb71e15b5ee127a3094c43994df9d973502) +- [New] add `customInspect` option, to disable custom inspect methods [`28b9179`](https://github.com/inspect-js/object-inspect/commit/28b9179ee802bb3b90810100c11637db90c2fb6d) +- [Tests] add Date and RegExp tests [`3b28eca`](https://github.com/inspect-js/object-inspect/commit/3b28eca57b0367aeadffac604ea09e8bdae7d97b) +- [actions] add automatic rebasing / merge commit blocking [`0d9c6c0`](https://github.com/inspect-js/object-inspect/commit/0d9c6c044e83475ff0bfffb9d35b149834c83a2e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape`; add `aud` [`7c204f2`](https://github.com/inspect-js/object-inspect/commit/7c204f22b9e41bc97147f4d32d4cb045b17769a6) +- [readme] fix repo URLs, remove testling [`34ca9a0`](https://github.com/inspect-js/object-inspect/commit/34ca9a0dabfe75bd311f806a326fadad029909a3) +- [Fix] when truncating a deep array, note it as `[Array]` instead of just `[Object]` [`f74c82d`](https://github.com/inspect-js/object-inspect/commit/f74c82dd0b35386445510deb250f34c41be3ec0e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`1a8a5ea`](https://github.com/inspect-js/object-inspect/commit/1a8a5ea069ea2bee89d77caedad83ffa23d35711) +- [Fix] do not be fooled by a function’s own `toString` method [`7cb5c65`](https://github.com/inspect-js/object-inspect/commit/7cb5c657a976f94715c19c10556a30f15bb7d5d7) +- [patch] indicate explicitly that anon functions are anonymous, to match node [`81ebdd4`](https://github.com/inspect-js/object-inspect/commit/81ebdd4215005144074bbdff3f6bafa01407910a) +- [Dev Deps] loosen the `core-js` dep [`e7472e8`](https://github.com/inspect-js/object-inspect/commit/e7472e8e242117670560bd995830c2a4d12080f5) +- [Dev Deps] update `tape` [`699827e`](https://github.com/inspect-js/object-inspect/commit/699827e6b37258b5203c33c78c009bf4b0e6a66d) +- [meta] add `safe-publish-latest` [`c5d2868`](https://github.com/inspect-js/object-inspect/commit/c5d2868d6eb33c472f37a20f89ceef2787046088) +- [Dev Deps] update `@ljharb/eslint-config` [`9199501`](https://github.com/inspect-js/object-inspect/commit/919950195d486114ccebacbdf9d74d7f382693b0) + +## [v1.7.0](https://github.com/inspect-js/object-inspect/compare/v1.6.0...v1.7.0) - 2019-11-10 + +### Commits + +- [Tests] use shared travis-ci configs [`19899ed`](https://github.com/inspect-js/object-inspect/commit/19899edbf31f4f8809acf745ce34ad1ce1bfa63b) +- [Tests] add linting [`a00f057`](https://github.com/inspect-js/object-inspect/commit/a00f057d917f66ea26dd37769c6b810ec4af97e8) +- [Tests] lint last file [`2698047`](https://github.com/inspect-js/object-inspect/commit/2698047b58af1e2e88061598ef37a75f228dddf6) +- [Tests] up to `node` `v12.7`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`589e87a`](https://github.com/inspect-js/object-inspect/commit/589e87a99cadcff4b600e6a303418e9d922836e8) +- [New] add support for `WeakMap` and `WeakSet` [`3ddb3e4`](https://github.com/inspect-js/object-inspect/commit/3ddb3e4e0c8287130c61a12e0ed9c104b1549306) +- [meta] clean up license so github can detect it properly [`27527bb`](https://github.com/inspect-js/object-inspect/commit/27527bb801520c9610c68cc3b55d6f20a2bee56d) +- [Tests] cover `util.inspect.custom` [`36d47b9`](https://github.com/inspect-js/object-inspect/commit/36d47b9c59056a57ef2f1491602c726359561800) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape` [`b614eaa`](https://github.com/inspect-js/object-inspect/commit/b614eaac901da0e5c69151f534671f990a94cace) +- [Tests] fix coverage thresholds [`7b7b176`](https://github.com/inspect-js/object-inspect/commit/7b7b176e15f8bd6e8b2f261ff5a493c2fe78d9c2) +- [Tests] bigint tests now can run on unflagged node [`063af31`](https://github.com/inspect-js/object-inspect/commit/063af31ce9cd13c202e3b67c07ba06dc9b7c0f81) +- [Refactor] add early bailout to `isMap` and `isSet` checks [`fc51047`](https://github.com/inspect-js/object-inspect/commit/fc5104714a3671d37e225813db79470d6335683b) +- [meta] add `funding` field [`7f9953a`](https://github.com/inspect-js/object-inspect/commit/7f9953a113eec7b064a6393cf9f90ba15f1d131b) +- [Tests] Fix invalid strict-mode syntax with hexadecimal [`a8b5425`](https://github.com/inspect-js/object-inspect/commit/a8b542503b4af1599a275209a1a99f5fdedb1ead) +- [Dev Deps] update `@ljharb/eslint-config` [`98df157`](https://github.com/inspect-js/object-inspect/commit/98df1577314d9188a3fc3f17fdcf2fba697ae1bd) +- add copyright to LICENSE [`bb69fd0`](https://github.com/inspect-js/object-inspect/commit/bb69fd017a062d299e44da1f9b2c7dcd67f621e6) +- [Tests] use `npx aud` in `posttest` [`4838353`](https://github.com/inspect-js/object-inspect/commit/4838353593974cf7f905b9ef04c03c094f0cdbe2) +- [Tests] move `0.6` to allowed failures, because it won‘t build on travis [`1bff32a`](https://github.com/inspect-js/object-inspect/commit/1bff32aa52e8aea687f0856b28ba754b3e43ebf7) + +## [v1.6.0](https://github.com/inspect-js/object-inspect/compare/v1.5.0...v1.6.0) - 2018-05-02 + +### Commits + +- [New] add support for boxed BigInt primitives [`356c66a`](https://github.com/inspect-js/object-inspect/commit/356c66a410e7aece7162c8319880a5ef647beaa9) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`c77b65b`](https://github.com/inspect-js/object-inspect/commit/c77b65bba593811b906b9ec57561c5cba92e2db3) +- [New] Add support for upcoming `BigInt` [`1ac548e`](https://github.com/inspect-js/object-inspect/commit/1ac548e4b27e26466c28c9a5e63e5d4e0591c31f) +- [Tests] run bigint tests in CI with --harmony-bigint flag [`d31b738`](https://github.com/inspect-js/object-inspect/commit/d31b73831880254b5c6cf5691cda9a149fbc5f04) +- [Dev Deps] update `core-js`, `tape` [`ff9eff6`](https://github.com/inspect-js/object-inspect/commit/ff9eff67113341ee1aaf80c1c22d683f43bfbccf) +- [Docs] fix example to use `safer-buffer` [`48cae12`](https://github.com/inspect-js/object-inspect/commit/48cae12a73ec6cacc955175bc56bbe6aee6a211f) + +## [v1.5.0](https://github.com/inspect-js/object-inspect/compare/v1.4.1...v1.5.0) - 2017-12-25 + +### Commits + +- [New] add `quoteStyle` option [`f5a72d2`](https://github.com/inspect-js/object-inspect/commit/f5a72d26edb3959b048f74c056ca7100a6b091e4) +- [Tests] add more test coverage [`30ebe4e`](https://github.com/inspect-js/object-inspect/commit/30ebe4e1fa943b99ecbb85be7614256d536e2759) +- [Tests] require 0.6 to pass [`99a008c`](https://github.com/inspect-js/object-inspect/commit/99a008ccace189a60fd7da18bf00e32c9572b980) + +## [v1.4.1](https://github.com/inspect-js/object-inspect/compare/v1.4.0...v1.4.1) - 2017-12-19 + +### Commits + +- [Tests] up to `node` `v9.3`, `v8.9`, `v6.12` [`6674476`](https://github.com/inspect-js/object-inspect/commit/6674476cc56acaac1bde96c84fed5ef631911906) +- [Fix] `inspect(Object(-0))` should be “Object(-0)”, not “Object(0)” [`d0a031f`](https://github.com/inspect-js/object-inspect/commit/d0a031f1cbb3024ee9982bfe364dd18a7e4d1bd3) + +## [v1.4.0](https://github.com/inspect-js/object-inspect/compare/v1.3.0...v1.4.0) - 2017-10-24 + +### Commits + +- [Tests] add `npm run coverage` [`3b48fb2`](https://github.com/inspect-js/object-inspect/commit/3b48fb25db037235eeb808f0b2830aad7aa36f70) +- [Tests] remove commented-out osx builds [`71e24db`](https://github.com/inspect-js/object-inspect/commit/71e24db8ad6ee3b9b381c5300b0475f2ba595a73) +- [New] add support for `util.inspect.custom`, in node only. [`20cca77`](https://github.com/inspect-js/object-inspect/commit/20cca7762d7e17f15b21a90793dff84acce155df) +- [Tests] up to `node` `v8.6`; use `nvm install-latest-npm` to ensure new npm doesn’t break old node [`252952d`](https://github.com/inspect-js/object-inspect/commit/252952d230d8065851dd3d4d5fe8398aae068529) +- [Tests] up to `node` `v8.8` [`4aa868d`](https://github.com/inspect-js/object-inspect/commit/4aa868d3a62914091d489dd6ec6eed194ee67cd3) +- [Dev Deps] update `core-js`, `tape` [`59483d1`](https://github.com/inspect-js/object-inspect/commit/59483d1df418f852f51fa0db7b24aa6b0209a27a) + +## [v1.3.0](https://github.com/inspect-js/object-inspect/compare/v1.2.2...v1.3.0) - 2017-07-31 + +### Fixed + +- [Fix] Map/Set: work around core-js bug < v2.5.0 [`#9`](https://github.com/inspect-js/object-inspect/issues/9) + +### Commits + +- [New] add support for arrays with additional object keys [`0d19937`](https://github.com/inspect-js/object-inspect/commit/0d199374ee37959e51539616666f420ccb29acb9) +- [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`; fix new npm breaking on older nodes [`e24784a`](https://github.com/inspect-js/object-inspect/commit/e24784a90c49117787157a12a63897c49cf89bbb) +- Only apps should have lockfiles [`c6faebc`](https://github.com/inspect-js/object-inspect/commit/c6faebcb2ee486a889a4a1c4d78c0776c7576185) +- [Dev Deps] update `tape` [`7345a0a`](https://github.com/inspect-js/object-inspect/commit/7345a0aeba7e91b888a079c10004d17696a7f586) + +## [v1.2.2](https://github.com/inspect-js/object-inspect/compare/v1.2.1...v1.2.2) - 2017-03-24 + +### Commits + +- [Tests] up to `node` `v7.7`, `v6.10`, `v4.8`; improve test matrix [`a2ddc15`](https://github.com/inspect-js/object-inspect/commit/a2ddc15a1f2c65af18076eea1c0eb9cbceb478a0) +- [Tests] up to `node` `v7.0`, `v6.9`, `v5.12`, `v4.6`, `io.js` `v3.3`; improve test matrix [`a48949f`](https://github.com/inspect-js/object-inspect/commit/a48949f6b574b2d4d2298109d8e8d0eb3e7a83e7) +- [Performance] check for primitive types as early as possible. [`3b8092a`](https://github.com/inspect-js/object-inspect/commit/3b8092a2a4deffd0575f94334f00194e2d48dad3) +- [Refactor] remove unneeded `else`s. [`7255034`](https://github.com/inspect-js/object-inspect/commit/725503402e08de4f96f6bf2d8edef44ac36f26b6) +- [Refactor] avoid recreating `lowbyte` function every time. [`81edd34`](https://github.com/inspect-js/object-inspect/commit/81edd3475bd15bdd18e84de7472033dcf5004aaa) +- [Fix] differentiate -0 from 0 [`521d345`](https://github.com/inspect-js/object-inspect/commit/521d3456b009da7bf1c5785c8a9df5a9f8718264) +- [Refactor] move object key gathering into separate function [`aca6265`](https://github.com/inspect-js/object-inspect/commit/aca626536eaeef697196c6e9db3e90e7e0355b6a) +- [Refactor] consolidate wrapping logic for boxed primitives into a function. [`4e440cd`](https://github.com/inspect-js/object-inspect/commit/4e440cd9065df04802a2a1dead03f48c353ca301) +- [Robustness] use `typeof` instead of comparing to literal `undefined` [`5ca6f60`](https://github.com/inspect-js/object-inspect/commit/5ca6f601937506daff8ed2fcf686363b55807b69) +- [Refactor] consolidate Map/Set notations. [`4e576e5`](https://github.com/inspect-js/object-inspect/commit/4e576e5d7ed2f9ec3fb7f37a0d16732eb10758a9) +- [Tests] ensure that this function remains anonymous, despite ES6 name inference. [`7540ae5`](https://github.com/inspect-js/object-inspect/commit/7540ae591278756db614fa4def55ca413150e1a3) +- [Refactor] explicitly coerce Error objects to strings. [`7f4ca84`](https://github.com/inspect-js/object-inspect/commit/7f4ca8424ee8dc2c0ca5a422d94f7fac40327261) +- [Refactor] split up `var` declarations for debuggability [`6f2c11e`](https://github.com/inspect-js/object-inspect/commit/6f2c11e6a85418586a00292dcec5e97683f89bc3) +- [Robustness] cache `Object.prototype.toString` [`df44a20`](https://github.com/inspect-js/object-inspect/commit/df44a20adfccf31529d60d1df2079bfc3c836e27) +- [Dev Deps] update `tape` [`3ec714e`](https://github.com/inspect-js/object-inspect/commit/3ec714eba57bc3f58a6eb4fca1376f49e70d300a) +- [Dev Deps] update `tape` [`beb72d9`](https://github.com/inspect-js/object-inspect/commit/beb72d969653747d7cde300393c28755375329b0) + +## [v1.2.1](https://github.com/inspect-js/object-inspect/compare/v1.2.0...v1.2.1) - 2016-04-09 + +### Fixed + +- [Fix] fix Boolean `false` object inspection. [`#7`](https://github.com/substack/object-inspect/pull/7) + +## [v1.2.0](https://github.com/inspect-js/object-inspect/compare/v1.1.0...v1.2.0) - 2016-04-09 + +### Fixed + +- [New] add support for inspecting String/Number/Boolean objects. [`#6`](https://github.com/inspect-js/object-inspect/issues/6) + +### Commits + +- [Dev Deps] update `tape` [`742caa2`](https://github.com/inspect-js/object-inspect/commit/742caa262cf7af4c815d4821c8bd0129c1446432) + +## [v1.1.0](https://github.com/inspect-js/object-inspect/compare/1.0.2...v1.1.0) - 2015-12-14 + +### Merged + +- [New] add ES6 Map/Set support. [`#4`](https://github.com/inspect-js/object-inspect/pull/4) + +### Fixed + +- [New] add ES6 Map/Set support. [`#3`](https://github.com/inspect-js/object-inspect/issues/3) + +### Commits + +- Update `travis.yml` to test on bunches of `iojs` and `node` versions. [`4c1fd65`](https://github.com/inspect-js/object-inspect/commit/4c1fd65cc3bd95307e854d114b90478324287fd2) +- [Dev Deps] update `tape` [`88a907e`](https://github.com/inspect-js/object-inspect/commit/88a907e33afbe408e4b5d6e4e42a33143f88848c) + +## [1.0.2](https://github.com/inspect-js/object-inspect/compare/1.0.1...1.0.2) - 2015-08-07 + +### Commits + +- [Fix] Cache `Object.prototype.hasOwnProperty` in case it's deleted later. [`1d0075d`](https://github.com/inspect-js/object-inspect/commit/1d0075d3091dc82246feeb1f9871cb2b8ed227b3) +- [Dev Deps] Update `tape` [`ca8d5d7`](https://github.com/inspect-js/object-inspect/commit/ca8d5d75635ddbf76f944e628267581e04958457) +- gitignore node_modules since this is a reusable modules. [`ed41407`](https://github.com/inspect-js/object-inspect/commit/ed41407811743ca530cdeb28f982beb96026af82) + +## [1.0.1](https://github.com/inspect-js/object-inspect/compare/1.0.0...1.0.1) - 2015-07-19 + +### Commits + +- Make `inspect` work with symbol primitives and objects, including in node 0.11 and 0.12. [`ddf1b94`](https://github.com/inspect-js/object-inspect/commit/ddf1b94475ab951f1e3bccdc0a48e9073cfbfef4) +- bump tape [`103d674`](https://github.com/inspect-js/object-inspect/commit/103d67496b504bdcfdd765d303a773f87ec106e2) +- use newer travis config [`d497276`](https://github.com/inspect-js/object-inspect/commit/d497276c1da14234bb5098a59cf20de75fbc316a) + +## [1.0.0](https://github.com/inspect-js/object-inspect/compare/0.4.0...1.0.0) - 2014-08-05 + +### Commits + +- error inspect works properly [`260a22d`](https://github.com/inspect-js/object-inspect/commit/260a22d134d3a8a482c67d52091c6040c34f4299) +- seen coverage [`57269e8`](https://github.com/inspect-js/object-inspect/commit/57269e8baa992a7439047f47325111fdcbcb8417) +- htmlelement instance coverage [`397ffe1`](https://github.com/inspect-js/object-inspect/commit/397ffe10a1980350868043ef9de65686d438979f) +- more element coverage [`6905cc2`](https://github.com/inspect-js/object-inspect/commit/6905cc2f7df35600177e613b0642b4df5efd3eca) +- failing test for type errors [`385b615`](https://github.com/inspect-js/object-inspect/commit/385b6152e49b51b68449a662f410b084ed7c601a) +- fn name coverage [`edc906d`](https://github.com/inspect-js/object-inspect/commit/edc906d40fca6b9194d304062c037ee8e398c4c2) +- server-side element test [`362d1d3`](https://github.com/inspect-js/object-inspect/commit/362d1d3e86f187651c29feeb8478110afada385b) +- custom inspect fn [`e89b0f6`](https://github.com/inspect-js/object-inspect/commit/e89b0f6fe6d5e03681282af83732a509160435a6) +- fixed browser test [`b530882`](https://github.com/inspect-js/object-inspect/commit/b5308824a1c8471c5617e394766a03a6977102a9) +- depth test, matches node [`1cfd9e0`](https://github.com/inspect-js/object-inspect/commit/1cfd9e0285a4ae1dff44101ad482915d9bf47e48) +- exercise hasOwnProperty path [`8d753fb`](https://github.com/inspect-js/object-inspect/commit/8d753fb362a534fa1106e4d80f2ee9bea06a66d9) +- more cases covered for errors [`c5c46a5`](https://github.com/inspect-js/object-inspect/commit/c5c46a569ec4606583497e8550f0d8c7ad39a4a4) +- \W obj key test case [`b0eceee`](https://github.com/inspect-js/object-inspect/commit/b0eceeea6e0eb94d686c1046e99b9e25e5005f75) +- coverage for explicit depth param [`e12b91c`](https://github.com/inspect-js/object-inspect/commit/e12b91cd59683362f3a0e80f46481a0211e26c15) + +## [0.4.0](https://github.com/inspect-js/object-inspect/compare/0.3.1...0.4.0) - 2014-03-21 + +### Commits + +- passing lowbyte interpolation test [`b847511`](https://github.com/inspect-js/object-inspect/commit/b8475114f5def7e7961c5353d48d3d8d9a520985) +- lowbyte test [`4a2b0e1`](https://github.com/inspect-js/object-inspect/commit/4a2b0e142667fc933f195472759385ac08f3946c) + +## [0.3.1](https://github.com/inspect-js/object-inspect/compare/0.3.0...0.3.1) - 2014-03-04 + +### Commits + +- sort keys [`a07b19c`](https://github.com/inspect-js/object-inspect/commit/a07b19cc3b1521a82d4fafb6368b7a9775428a05) + +## [0.3.0](https://github.com/inspect-js/object-inspect/compare/0.2.0...0.3.0) - 2014-03-04 + +### Commits + +- [] and {} instead of [ ] and { } [`654c44b`](https://github.com/inspect-js/object-inspect/commit/654c44b2865811f3519e57bb8526e0821caf5c6b) + +## [0.2.0](https://github.com/inspect-js/object-inspect/compare/0.1.3...0.2.0) - 2014-03-04 + +### Commits + +- failing holes test [`99cdfad`](https://github.com/inspect-js/object-inspect/commit/99cdfad03c6474740275a75636fe6ca86c77737a) +- regex already work [`e324033`](https://github.com/inspect-js/object-inspect/commit/e324033267025995ec97d32ed0a65737c99477a6) +- failing undef/null test [`1f88a00`](https://github.com/inspect-js/object-inspect/commit/1f88a00265d3209719dda8117b7e6360b4c20943) +- holes in the all example [`7d345f3`](https://github.com/inspect-js/object-inspect/commit/7d345f3676dcbe980cff89a4f6c243269ebbb709) +- check for .inspect(), fixes Buffer use-case [`c3f7546`](https://github.com/inspect-js/object-inspect/commit/c3f75466dbca125347d49847c05262c292f12b79) +- fixes for holes [`ce25f73`](https://github.com/inspect-js/object-inspect/commit/ce25f736683de4b92ff27dc5471218415e2d78d8) +- weird null behavior [`405c1ea`](https://github.com/inspect-js/object-inspect/commit/405c1ea72cd5a8cf3b498c3eaa903d01b9fbcab5) +- tape is actually a devDependency, upgrade [`703b0ce`](https://github.com/inspect-js/object-inspect/commit/703b0ce6c5817b4245a082564bccd877e0bb6990) +- put date in the example [`a342219`](https://github.com/inspect-js/object-inspect/commit/a3422190eeaa013215f46df2d0d37b48595ac058) +- passing the null test [`4ab737e`](https://github.com/inspect-js/object-inspect/commit/4ab737ebf862a75d247ebe51e79307a34d6380d4) + +## [0.1.3](https://github.com/inspect-js/object-inspect/compare/0.1.1...0.1.3) - 2013-07-26 + +### Commits + +- special isElement() check [`882768a`](https://github.com/inspect-js/object-inspect/commit/882768a54035d30747be9de1baf14e5aa0daa128) +- oh right old IEs don't have indexOf either [`36d1275`](https://github.com/inspect-js/object-inspect/commit/36d12756c38b08a74370b0bb696c809e529913a5) + +## [0.1.1](https://github.com/inspect-js/object-inspect/compare/0.1.0...0.1.1) - 2013-07-26 + +### Commits + +- tests! [`4422fd9`](https://github.com/inspect-js/object-inspect/commit/4422fd95532c2745aa6c4f786f35f1090be29998) +- fix for ie<9, doesn't have hasOwnProperty [`6b7d611`](https://github.com/inspect-js/object-inspect/commit/6b7d61183050f6da801ea04473211da226482613) +- fix for all IEs: no f.name [`4e0c2f6`](https://github.com/inspect-js/object-inspect/commit/4e0c2f6dfd01c306d067d7163319acc97c94ee50) +- badges [`5ed0d88`](https://github.com/inspect-js/object-inspect/commit/5ed0d88e4e407f9cb327fa4a146c17921f9680f3) + +## [0.1.0](https://github.com/inspect-js/object-inspect/compare/0.0.0...0.1.0) - 2013-07-26 + +### Commits + +- [Function] for functions [`ad5c485`](https://github.com/inspect-js/object-inspect/commit/ad5c485098fc83352cb540a60b2548ca56820e0b) + +## 0.0.0 - 2013-07-26 + +### Commits + +- working browser example [`34be6b6`](https://github.com/inspect-js/object-inspect/commit/34be6b6548f9ce92bdc3c27572857ba0c4a1218d) +- package.json etc [`cad51f2`](https://github.com/inspect-js/object-inspect/commit/cad51f23fc6bcf1a456ed6abe16088256c2f632f) +- docs complete [`b80cce2`](https://github.com/inspect-js/object-inspect/commit/b80cce2490c4e7183a9ee11ea89071f0abec4446) +- circular example [`4b4a7b9`](https://github.com/inspect-js/object-inspect/commit/4b4a7b92209e4e6b4630976cb6bcd17d14165a59) +- string rep [`7afb479`](https://github.com/inspect-js/object-inspect/commit/7afb479baa798d27f09e0a178b72ea327f60f5c8) diff --git a/node_modules/object-inspect/LICENSE b/node_modules/object-inspect/LICENSE new file mode 100644 index 000000000..ca64cc1e6 --- /dev/null +++ b/node_modules/object-inspect/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 James Halliday + +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/object-inspect/example/all.js b/node_modules/object-inspect/example/all.js new file mode 100644 index 000000000..2f3355c50 --- /dev/null +++ b/node_modules/object-inspect/example/all.js @@ -0,0 +1,23 @@ +'use strict'; + +var inspect = require('../'); +var Buffer = require('safer-buffer').Buffer; + +var holes = ['a', 'b']; +holes[4] = 'e'; +holes[6] = 'g'; + +var obj = { + a: 1, + b: [3, 4, undefined, null], + c: undefined, + d: null, + e: { + regex: /^x/i, + buf: Buffer.from('abc'), + holes: holes + }, + now: new Date() +}; +obj.self = obj; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/circular.js b/node_modules/object-inspect/example/circular.js new file mode 100644 index 000000000..487a7c169 --- /dev/null +++ b/node_modules/object-inspect/example/circular.js @@ -0,0 +1,6 @@ +'use strict'; + +var inspect = require('../'); +var obj = { a: 1, b: [3, 4] }; +obj.c = obj; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/fn.js b/node_modules/object-inspect/example/fn.js new file mode 100644 index 000000000..9b5db8de0 --- /dev/null +++ b/node_modules/object-inspect/example/fn.js @@ -0,0 +1,5 @@ +'use strict'; + +var inspect = require('../'); +var obj = [1, 2, function f(n) { return n + 5; }, 4]; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/inspect.js b/node_modules/object-inspect/example/inspect.js new file mode 100644 index 000000000..e2df7c9f4 --- /dev/null +++ b/node_modules/object-inspect/example/inspect.js @@ -0,0 +1,10 @@ +'use strict'; + +/* eslint-env browser */ +var inspect = require('../'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }])); diff --git a/node_modules/object-inspect/index.js b/node_modules/object-inspect/index.js new file mode 100644 index 000000000..a4b2d4cd8 --- /dev/null +++ b/node_modules/object-inspect/index.js @@ -0,0 +1,544 @@ +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); + +function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} + +var utilInspect = require('./util.inspect'); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + +var quotes = { + __proto__: null, + 'double': '"', + single: "'" +}; +var quoteREs = { + __proto__: null, + 'double': /(["\\])/g, + single: /(['\\])/g +}; + +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has(opts, 'quoteStyle') && !has(quotes, opts.quoteStyle)) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + // note: in IE 8, sometimes `global !== window` but both are the prototypes of each other + /* eslint-env browser */ + if (typeof window !== 'undefined' && obj === window) { + return '{ [object Window] }'; + } + if ( + (typeof globalThis !== 'undefined' && obj === globalThis) + || (typeof global !== 'undefined' && obj === global) + ) { + return '{ [object globalThis] }'; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; + +function wrapQuotes(s, defaultStyle, opts) { + var style = opts.quoteStyle || defaultStyle; + var quoteChar = quotes[style]; + return quoteChar + s + quoteChar; +} + +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} + +function canTrustToString(obj) { + return !toStringTag || !(typeof obj === 'object' && (toStringTag in obj || typeof obj[toStringTag] !== 'undefined')); +} +function isArray(obj) { return toStr(obj) === '[object Array]' && canTrustToString(obj); } +function isDate(obj) { return toStr(obj) === '[object Date]' && canTrustToString(obj); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && canTrustToString(obj); } +function isError(obj) { return toStr(obj) === '[object Error]' && canTrustToString(obj); } +function isString(obj) { return toStr(obj) === '[object String]' && canTrustToString(obj); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && canTrustToString(obj); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && canTrustToString(obj); } + +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} + +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} + +function toStr(obj) { + return objectToString.call(obj); +} + +function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; +} + +function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; +} + +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} + +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} + +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var quoteRE = quoteREs[opts.quoteStyle || 'single']; + quoteRE.lastIndex = 0; + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, quoteRE, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} + +function markBoxed(str) { + return 'Object(' + str + ')'; +} + +function weakCollectionOf(type) { + return type + ' { ? }'; +} + +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} + +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} + +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} + +function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} + +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} diff --git a/node_modules/object-inspect/package-support.json b/node_modules/object-inspect/package-support.json new file mode 100644 index 000000000..5cc12d058 --- /dev/null +++ b/node_modules/object-inspect/package-support.json @@ -0,0 +1,20 @@ +{ + "versions": [ + { + "version": "*", + "target": { + "node": "all" + }, + "response": { + "type": "time-permitting" + }, + "backing": { + "npm-funding": true, + "donations": [ + "https://github.com/ljharb", + "https://tidelift.com/funding/github/npm/object-inspect" + ] + } + } + ] +} diff --git a/node_modules/object-inspect/package.json b/node_modules/object-inspect/package.json new file mode 100644 index 000000000..9fd97ff75 --- /dev/null +++ b/node_modules/object-inspect/package.json @@ -0,0 +1,105 @@ +{ + "name": "object-inspect", + "version": "1.13.4", + "description": "string representations of objects in node and the browser", + "main": "index.js", + "sideEffects": false, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.1", + "@pkgjs/support": "^0.0.6", + "auto-changelog": "^2.5.0", + "core-js": "^2.6.12", + "error-cause": "^1.0.8", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "for-each": "^0.3.4", + "functions-have-names": "^1.2.3", + "glob": "=10.3.7", + "globalthis": "^1.0.4", + "has-symbols": "^1.1.0", + "has-tostringtag": "^1.0.2", + "in-publish": "^2.0.1", + "jackspeak": "=2.1.1", + "make-arrow-function": "^1.2.0", + "mock-property": "^1.1.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "safer-buffer": "^2.1.2", + "semver": "^6.3.1", + "string.prototype.repeat": "^1.0.0", + "tape": "^5.9.0" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "lint": "eslint --ext=js,mjs .", + "postlint": "npx @pkgjs/support validate", + "test": "npm run tests-only && npm run test:corejs", + "tests-only": "nyc tape 'test/*.js'", + "test:corejs": "nyc tape test-core-js.js 'test/*.js'", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": [ + "test/*.js", + "test/browser/*.js" + ], + "browsers": [ + "ie/6..latest", + "chrome/latest", + "firefox/latest", + "safari/latest", + "opera/latest", + "iphone/latest", + "ipad/latest", + "android/latest" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/object-inspect.git" + }, + "homepage": "https://github.com/inspect-js/object-inspect", + "keywords": [ + "inspect", + "util.inspect", + "object", + "stringify", + "pretty" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "browser": { + "./util.inspect.js": false + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "./test-core-js.js" + ] + }, + "support": true, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/object-inspect/readme.markdown b/node_modules/object-inspect/readme.markdown new file mode 100644 index 000000000..f91617df3 --- /dev/null +++ b/node_modules/object-inspect/readme.markdown @@ -0,0 +1,84 @@ +# object-inspect [![Version Badge][npm-version-svg]][package-url] + +string representations of objects in node and the browser + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +# example + +## circular + +``` js +var inspect = require('object-inspect'); +var obj = { a: 1, b: [3,4] }; +obj.c = obj; +console.log(inspect(obj)); +``` + +## dom element + +``` js +var inspect = require('object-inspect'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ])); +``` + +output: + +``` +[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [ ... ] ] ] ] } ] +``` + +# methods + +``` js +var inspect = require('object-inspect') +``` + +## var s = inspect(obj, opts={}) + +Return a string `s` with the string representation of `obj` up to a depth of `opts.depth`. + +Additional options: + - `quoteStyle`: must be "single" or "double", if present. Default `'single'` for strings, `'double'` for HTML elements. + - `maxStringLength`: must be `0`, a positive integer, `Infinity`, or `null`, if present. Default `Infinity`. + - `customInspect`: When `true`, a custom inspect method function will be invoked (either undere the `util.inspect.custom` symbol, or the `inspect` property). When the string `'symbol'`, only the symbol method will be invoked. Default `true`. + - `indent`: must be "\t", `null`, or a positive integer. Default `null`. + - `numericSeparator`: must be a boolean, if present. Default `false`. If `true`, all numbers will be printed with numeric separators (eg, `1234.5678` will be printed as `'1_234.567_8'`) + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install object-inspect +``` + +# license + +MIT + +[package-url]: https://npmjs.org/package/object-inspect +[npm-version-svg]: https://versionbadg.es/inspect-js/object-inspect.svg +[deps-svg]: https://david-dm.org/inspect-js/object-inspect.svg +[deps-url]: https://david-dm.org/inspect-js/object-inspect +[dev-deps-svg]: https://david-dm.org/inspect-js/object-inspect/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/object-inspect#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/object-inspect.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/object-inspect.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/object-inspect.svg +[downloads-url]: https://npm-stat.com/charts.html?package=object-inspect +[codecov-image]: https://codecov.io/gh/inspect-js/object-inspect/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/object-inspect/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/object-inspect +[actions-url]: https://github.com/inspect-js/object-inspect/actions diff --git a/node_modules/object-inspect/test-core-js.js b/node_modules/object-inspect/test-core-js.js new file mode 100644 index 000000000..e53c40022 --- /dev/null +++ b/node_modules/object-inspect/test-core-js.js @@ -0,0 +1,26 @@ +'use strict'; + +require('core-js'); + +var inspect = require('./'); +var test = require('tape'); + +test('Maps', function (t) { + t.equal(inspect(new Map([[1, 2]])), 'Map (1) {1 => 2}'); + t.end(); +}); + +test('WeakMaps', function (t) { + t.equal(inspect(new WeakMap([[{}, 2]])), 'WeakMap { ? }'); + t.end(); +}); + +test('Sets', function (t) { + t.equal(inspect(new Set([[1, 2]])), 'Set (1) {[ 1, 2 ]}'); + t.end(); +}); + +test('WeakSets', function (t) { + t.equal(inspect(new WeakSet([[1, 2]])), 'WeakSet { ? }'); + t.end(); +}); diff --git a/node_modules/object-inspect/test/bigint.js b/node_modules/object-inspect/test/bigint.js new file mode 100644 index 000000000..4ecc31df8 --- /dev/null +++ b/node_modules/object-inspect/test/bigint.js @@ -0,0 +1,58 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('bigint', { skip: typeof BigInt === 'undefined' }, function (t) { + t.test('primitives', function (st) { + st.plan(3); + + st.equal(inspect(BigInt(-256)), '-256n'); + st.equal(inspect(BigInt(0)), '0n'); + st.equal(inspect(BigInt(256)), '256n'); + }); + + t.test('objects', function (st) { + st.plan(3); + + st.equal(inspect(Object(BigInt(-256))), 'Object(-256n)'); + st.equal(inspect(Object(BigInt(0))), 'Object(0n)'); + st.equal(inspect(Object(BigInt(256))), 'Object(256n)'); + }); + + t.test('syntactic primitives', function (st) { + st.plan(3); + + /* eslint-disable no-new-func */ + st.equal(inspect(Function('return -256n')()), '-256n'); + st.equal(inspect(Function('return 0n')()), '0n'); + st.equal(inspect(Function('return 256n')()), '256n'); + }); + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'BigInt'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'BigInt\' }', + 'object lying about being a BigInt inspects as an object' + ); + }); + + t.test('numericSeparator', function (st) { + st.equal(inspect(BigInt(0), { numericSeparator: false }), '0n', '0n, numericSeparator false'); + st.equal(inspect(BigInt(0), { numericSeparator: true }), '0n', '0n, numericSeparator true'); + + st.equal(inspect(BigInt(1234), { numericSeparator: false }), '1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(1234), { numericSeparator: true }), '1_234n', '1234n, numericSeparator true'); + st.equal(inspect(BigInt(-1234), { numericSeparator: false }), '-1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(-1234), { numericSeparator: true }), '-1_234n', '1234n, numericSeparator true'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/browser/dom.js b/node_modules/object-inspect/test/browser/dom.js new file mode 100644 index 000000000..210c0b233 --- /dev/null +++ b/node_modules/object-inspect/test/browser/dom.js @@ -0,0 +1,15 @@ +var inspect = require('../../'); +var test = require('tape'); + +test('dom element', function (t) { + t.plan(1); + + var d = document.createElement('div'); + d.setAttribute('id', 'beep'); + d.innerHTML = 'woooiiiii'; + + t.equal( + inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }]), + '[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [Object] ] ] ] } ]' + ); +}); diff --git a/node_modules/object-inspect/test/circular.js b/node_modules/object-inspect/test/circular.js new file mode 100644 index 000000000..5df4233cb --- /dev/null +++ b/node_modules/object-inspect/test/circular.js @@ -0,0 +1,16 @@ +var inspect = require('../'); +var test = require('tape'); + +test('circular', function (t) { + t.plan(2); + var obj = { a: 1, b: [3, 4] }; + obj.c = obj; + t.equal(inspect(obj), '{ a: 1, b: [ 3, 4 ], c: [Circular] }'); + + var double = {}; + double.a = [double]; + double.b = {}; + double.b.inner = double.b; + double.b.obj = double; + t.equal(inspect(double), '{ a: [ [Circular] ], b: { inner: [Circular], obj: [Circular] } }'); +}); diff --git a/node_modules/object-inspect/test/deep.js b/node_modules/object-inspect/test/deep.js new file mode 100644 index 000000000..99ce32a08 --- /dev/null +++ b/node_modules/object-inspect/test/deep.js @@ -0,0 +1,12 @@ +var inspect = require('../'); +var test = require('tape'); + +test('deep', function (t) { + t.plan(4); + var obj = [[[[[[500]]]]]]; + t.equal(inspect(obj), '[ [ [ [ [ [Array] ] ] ] ] ]'); + t.equal(inspect(obj, { depth: 4 }), '[ [ [ [ [Array] ] ] ] ]'); + t.equal(inspect(obj, { depth: 2 }), '[ [ [Array] ] ]'); + + t.equal(inspect([[[{ a: 1 }]]], { depth: 3 }), '[ [ [ [Object] ] ] ]'); +}); diff --git a/node_modules/object-inspect/test/element.js b/node_modules/object-inspect/test/element.js new file mode 100644 index 000000000..47fa9e240 --- /dev/null +++ b/node_modules/object-inspect/test/element.js @@ -0,0 +1,53 @@ +var inspect = require('../'); +var test = require('tape'); + +test('element', function (t) { + t.plan(3); + var elem = { + nodeName: 'div', + attributes: [{ name: 'class', value: 'row' }], + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + t.deepEqual(inspect(obj, { quoteStyle: 'single' }), "[ 1,
, 3 ]"); + t.deepEqual(inspect(obj, { quoteStyle: 'double' }), '[ 1,
, 3 ]'); +}); + +test('element no attr', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); +}); + +test('element with contents', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [{ nodeName: 'b' }] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
...
, 3 ]'); +}); + +test('element instance', function (t) { + t.plan(1); + var h = global.HTMLElement; + global.HTMLElement = function (name, attr) { + this.nodeName = name; + this.attributes = attr; + }; + global.HTMLElement.prototype.getAttribute = function () {}; + + var elem = new global.HTMLElement('div', []); + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + global.HTMLElement = h; +}); diff --git a/node_modules/object-inspect/test/err.js b/node_modules/object-inspect/test/err.js new file mode 100644 index 000000000..cc1d884ab --- /dev/null +++ b/node_modules/object-inspect/test/err.js @@ -0,0 +1,48 @@ +var test = require('tape'); +var ErrorWithCause = require('error-cause/Error'); + +var inspect = require('../'); + +test('type error', function (t) { + t.plan(1); + var aerr = new TypeError(); + aerr.foo = 555; + aerr.bar = [1, 2, 3]; + + var berr = new TypeError('tuv'); + berr.baz = 555; + + var cerr = new SyntaxError(); + cerr.message = 'whoa'; + cerr['a-b'] = 5; + + var withCause = new ErrorWithCause('foo', { cause: 'bar' }); + var withCausePlus = new ErrorWithCause('foo', { cause: 'bar' }); + withCausePlus.foo = 'bar'; + var withUndefinedCause = new ErrorWithCause('foo', { cause: undefined }); + var withEnumerableCause = new Error('foo'); + withEnumerableCause.cause = 'bar'; + + var obj = [ + new TypeError(), + new TypeError('xxx'), + aerr, + berr, + cerr, + withCause, + withCausePlus, + withUndefinedCause, + withEnumerableCause + ]; + t.equal(inspect(obj), '[ ' + [ + '[TypeError]', + '[TypeError: xxx]', + '{ [TypeError] foo: 555, bar: [ 1, 2, 3 ] }', + '{ [TypeError: tuv] baz: 555 }', + '{ [SyntaxError: whoa] message: \'whoa\', \'a-b\': 5 }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: \'bar\' }', + '{ [Error: foo] ' + ('cause' in Error.prototype ? '' : '[cause]: \'bar\', ') + 'foo: \'bar\' }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: undefined }', + '{ [Error: foo] cause: \'bar\' }' + ].join(', ') + ' ]'); +}); diff --git a/node_modules/object-inspect/test/fakes.js b/node_modules/object-inspect/test/fakes.js new file mode 100644 index 000000000..a65c08c15 --- /dev/null +++ b/node_modules/object-inspect/test/fakes.js @@ -0,0 +1,29 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('for-each'); + +test('fakes', { skip: !hasToStringTag }, function (t) { + forEach([ + 'Array', + 'Boolean', + 'Date', + 'Error', + 'Number', + 'RegExp', + 'String' + ], function (expected) { + var faker = {}; + faker[Symbol.toStringTag] = expected; + + t.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'' + expected + '\' }', + 'faker masquerading as ' + expected + ' is not shown as one' + ); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/fn.js b/node_modules/object-inspect/test/fn.js new file mode 100644 index 000000000..de3ca625e --- /dev/null +++ b/node_modules/object-inspect/test/fn.js @@ -0,0 +1,76 @@ +var inspect = require('../'); +var test = require('tape'); +var arrow = require('make-arrow-function')(); +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); + +test('function', function (t) { + t.plan(1); + var obj = [1, 2, function f(n) { return n; }, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function: f], 4 ]'); +}); + +test('function name', function (t) { + t.plan(1); + var f = (function () { + return function () {}; + }()); + f.toString = function toStr() { return 'function xxx () {}'; }; + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)] { toString: [Function: toStr] }, 4 ]'); +}); + +test('anon function', function (t) { + var f = (function () { + return function () {}; + }()); + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)], 4 ]'); + + t.end(); +}); + +test('arrow function', { skip: !arrow }, function (t) { + t.equal(inspect(arrow), '[Function (anonymous)]'); + + t.end(); +}); + +test('truly nameless function', { skip: !arrow || !functionsHaveConfigurableNames }, function (t) { + function f() {} + Object.defineProperty(f, 'name', { value: false }); + t.equal(f.name, false); + t.equal( + inspect(f), + '[Function: f]', + 'named function with falsy `.name` does not hide its original name' + ); + + function g() {} + Object.defineProperty(g, 'name', { value: true }); + t.equal(g.name, true); + t.equal( + inspect(g), + '[Function: true]', + 'named function with truthy `.name` hides its original name' + ); + + var anon = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon, 'name', { value: null }); + t.equal(anon.name, null); + t.equal( + inspect(anon), + '[Function (anonymous)]', + 'anon function with falsy `.name` does not hide its anonymity' + ); + + var anon2 = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon2, 'name', { value: 1 }); + t.equal(anon2.name, 1); + t.equal( + inspect(anon2), + '[Function: 1]', + 'anon function with truthy `.name` hides its anonymity' + ); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/global.js b/node_modules/object-inspect/test/global.js new file mode 100644 index 000000000..c57216aeb --- /dev/null +++ b/node_modules/object-inspect/test/global.js @@ -0,0 +1,17 @@ +'use strict'; + +var inspect = require('../'); + +var test = require('tape'); +var globalThis = require('globalthis')(); + +test('global object', function (t) { + /* eslint-env browser */ + var expected = typeof window === 'undefined' ? 'globalThis' : 'Window'; + t.equal( + inspect([globalThis]), + '[ { [object ' + expected + '] } ]' + ); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/has.js b/node_modules/object-inspect/test/has.js new file mode 100644 index 000000000..01800dee6 --- /dev/null +++ b/node_modules/object-inspect/test/has.js @@ -0,0 +1,15 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); + +test('when Object#hasOwnProperty is deleted', function (t) { + t.plan(1); + var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays + + t.teardown(mockProperty(Array.prototype, 1, { value: 2 })); // this is needed to account for "in" vs "hasOwnProperty" + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect(arr), '[ 1, , 3 ]'); +}); diff --git a/node_modules/object-inspect/test/holes.js b/node_modules/object-inspect/test/holes.js new file mode 100644 index 000000000..87fc8c84a --- /dev/null +++ b/node_modules/object-inspect/test/holes.js @@ -0,0 +1,15 @@ +var test = require('tape'); +var inspect = require('../'); + +var xs = ['a', 'b']; +xs[5] = 'f'; +xs[7] = 'j'; +xs[8] = 'k'; + +test('holes', function (t) { + t.plan(1); + t.equal( + inspect(xs), + "[ 'a', 'b', , , , 'f', , 'j', 'k' ]" + ); +}); diff --git a/node_modules/object-inspect/test/indent-option.js b/node_modules/object-inspect/test/indent-option.js new file mode 100644 index 000000000..89d8fcedf --- /dev/null +++ b/node_modules/object-inspect/test/indent-option.js @@ -0,0 +1,271 @@ +var test = require('tape'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('bad indent options', function (t) { + forEach([ + undefined, + true, + false, + -1, + 1.2, + Infinity, + -Infinity, + NaN + ], function (indent) { + t['throws']( + function () { inspect('', { indent: indent }); }, + TypeError, + inspect(indent) + ' is invalid' + ); + }); + + t.end(); +}); + +test('simple object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: 2 }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('two deep object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: { c: 3, d: 4 } }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('simple array with all single line elements', function (t) { + t.plan(2); + + var obj = [1, 2, 3, 'asdf\nsdf']; + + var expected = '[ 1, 2, 3, \'asdf\\nsdf\' ]'; + + t.equal(inspect(obj, { indent: 2 }), expected, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expected, 'tabs'); +}); + +test('array with complex elements', function (t) { + t.plan(2); + + var obj = [1, { a: 1, b: { c: 1 } }, 'asdf\nsdf']; + + var expectedSpaces = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('values', function (t) { + t.plan(2); + var obj = [{}, [], { 'a-b': 5 }]; + + var expectedSpaces = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + + var expectedStringSpaces = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabsDoubleQuotes = [ + 'Map (2) {', + ' { a: 1 } => [ "b" ],', + ' 3 => NaN', + '}' + ].join('\n'); + + t.equal( + inspect(map, { indent: 2 }), + expectedStringSpaces, + 'Map keys are not indented (two)' + ); + t.equal( + inspect(map, { indent: '\t' }), + expectedStringTabs, + 'Map keys are not indented (tabs)' + ); + t.equal( + inspect(map, { indent: '\t', quoteStyle: 'double' }), + expectedStringTabsDoubleQuotes, + 'Map keys are not indented (tabs + double quotes)' + ); + + t.equal(inspect(new Map(), { indent: 2 }), 'Map (0) {}', 'empty Map should show as empty (two)'); + t.equal(inspect(new Map(), { indent: '\t' }), 'Map (0) {}', 'empty Map should show as empty (tabs)'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + var expectedNestedSpaces = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + t.equal(inspect(nestedMap, { indent: 2 }), expectedNestedSpaces, 'Map containing a Map should work (two)'); + t.equal(inspect(nestedMap, { indent: '\t' }), expectedNestedTabs, 'Map containing a Map should work (tabs)'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedStringSpaces = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + t.equal(inspect(set, { indent: 2 }), expectedStringSpaces, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (two)'); + t.equal(inspect(set, { indent: '\t' }), expectedStringTabs, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (tabs)'); + + t.equal(inspect(new Set(), { indent: 2 }), 'Set (0) {}', 'empty Set should show as empty (two)'); + t.equal(inspect(new Set(), { indent: '\t' }), 'Set (0) {}', 'empty Set should show as empty (tabs)'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + var expectedNestedSpaces = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + t.equal(inspect(nestedSet, { indent: 2 }), expectedNestedSpaces, 'Set containing a Set should work (two)'); + t.equal(inspect(nestedSet, { indent: '\t' }), expectedNestedTabs, 'Set containing a Set should work (tabs)'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/inspect.js b/node_modules/object-inspect/test/inspect.js new file mode 100644 index 000000000..1abf81b1f --- /dev/null +++ b/node_modules/object-inspect/test/inspect.js @@ -0,0 +1,139 @@ +var test = require('tape'); +var hasSymbols = require('has-symbols/shams')(); +var utilInspect = require('../util.inspect'); +var repeat = require('string.prototype.repeat'); + +var inspect = require('..'); + +test('inspect', function (t) { + t.plan(5); + + var obj = [{ inspect: function xyzInspect() { return '!XYZ¡'; } }, []]; + var stringResult = '[ !XYZ¡, [] ]'; + var falseResult = '[ { inspect: [Function: xyzInspect] }, [] ]'; + + t.equal(inspect(obj), stringResult); + t.equal(inspect(obj, { customInspect: true }), stringResult); + t.equal(inspect(obj, { customInspect: 'symbol' }), falseResult); + t.equal(inspect(obj, { customInspect: false }), falseResult); + t['throws']( + function () { inspect(obj, { customInspect: 'not a boolean or "symbol"' }); }, + TypeError, + '`customInspect` must be a boolean or the string "symbol"' + ); +}); + +test('inspect custom symbol', { skip: !hasSymbols || !utilInspect || !utilInspect.custom }, function (t) { + t.plan(4); + + var obj = { inspect: function stringInspect() { return 'string'; } }; + obj[utilInspect.custom] = function custom() { return 'symbol'; }; + + var symbolResult = '[ symbol, [] ]'; + var stringResult = '[ string, [] ]'; + var falseResult = '[ { inspect: [Function: stringInspect]' + (utilInspect.custom ? ', [' + inspect(utilInspect.custom) + ']: [Function: custom]' : '') + ' }, [] ]'; + + var symbolStringFallback = utilInspect.custom ? symbolResult : stringResult; + var symbolFalseFallback = utilInspect.custom ? symbolResult : falseResult; + + t.equal(inspect([obj, []]), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: true }), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: 'symbol' }), symbolFalseFallback); + t.equal(inspect([obj, []], { customInspect: false }), falseResult); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + t.plan(2); + + var obj = { a: 1 }; + obj[Symbol('test')] = 2; + obj[Symbol.iterator] = 3; + Object.defineProperty(obj, Symbol('non-enum'), { + enumerable: false, + value: 4 + }); + + if (typeof Symbol.iterator === 'symbol') { + t.equal(inspect(obj), '{ a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }', 'object with symbols'); + t.equal(inspect([obj, []]), '[ { a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }, [] ]', 'object with symbols in array'); + } else { + // symbol sham key ordering is unreliable + t.match( + inspect(obj), + /^(?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 })$/, + 'object with symbols (nondeterministic symbol sham key ordering)' + ); + t.match( + inspect([obj, []]), + /^\[ (?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 }), \[\] \]$/, + 'object with symbols in array (nondeterministic symbol sham key ordering)' + ); + } +}); + +test('maxStringLength', function (t) { + t['throws']( + function () { inspect('', { maxStringLength: -1 }); }, + TypeError, + 'maxStringLength must be >= 0, or Infinity, not negative' + ); + + var str = repeat('a', 1e8); + + t.equal( + inspect([str], { maxStringLength: 10 }), + '[ \'aaaaaaaaaa\'... 99999990 more characters ]', + 'maxStringLength option limits output' + ); + + t.equal( + inspect(['f'], { maxStringLength: null }), + '[ \'\'... 1 more character ]', + 'maxStringLength option accepts `null`' + ); + + t.equal( + inspect([str], { maxStringLength: Infinity }), + '[ \'' + str + '\' ]', + 'maxStringLength option accepts ∞' + ); + + t.end(); +}); + +test('inspect options', { skip: !utilInspect.custom }, function (t) { + var obj = {}; + obj[utilInspect.custom] = function () { + return JSON.stringify(arguments); + }; + t.equal( + inspect(obj), + utilInspect(obj, { depth: 5 }), + 'custom symbols will use node\'s inspect' + ); + t.equal( + inspect(obj, { depth: 2 }), + utilInspect(obj, { depth: 2 }), + 'a reduced depth will be passed to node\'s inspect' + ); + t.equal( + inspect({ d1: obj }, { depth: 3 }), + '{ d1: ' + utilInspect(obj, { depth: 2 }) + ' }', + 'deep objects will receive a reduced depth' + ); + t.equal( + inspect({ d1: obj }, { depth: 1 }), + '{ d1: [Object] }', + 'unlike nodejs inspect, customInspect will not be used once the depth is exceeded.' + ); + t.end(); +}); + +test('inspect URL', { skip: typeof URL === 'undefined' }, function (t) { + t.match( + inspect(new URL('https://nodejs.org')), + /nodejs\.org/, // Different environments stringify it differently + 'url can be inspected' + ); + t.end(); +}); diff --git a/node_modules/object-inspect/test/lowbyte.js b/node_modules/object-inspect/test/lowbyte.js new file mode 100644 index 000000000..68a345d85 --- /dev/null +++ b/node_modules/object-inspect/test/lowbyte.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { x: 'a\r\nb', y: '\x05! \x1f \x12' }; + +test('interpolate low bytes', function (t) { + t.plan(1); + t.equal( + inspect(obj), + "{ x: 'a\\r\\nb', y: '\\x05! \\x1F \\x12' }" + ); +}); diff --git a/node_modules/object-inspect/test/number.js b/node_modules/object-inspect/test/number.js new file mode 100644 index 000000000..8f287e8e2 --- /dev/null +++ b/node_modules/object-inspect/test/number.js @@ -0,0 +1,58 @@ +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('negative zero', function (t) { + t.equal(inspect(0), '0', 'inspect(0) === "0"'); + t.equal(inspect(Object(0)), 'Object(0)', 'inspect(Object(0)) === "Object(0)"'); + + t.equal(inspect(-0), '-0', 'inspect(-0) === "-0"'); + t.equal(inspect(Object(-0)), 'Object(-0)', 'inspect(Object(-0)) === "Object(-0)"'); + + t.end(); +}); + +test('numericSeparator', function (t) { + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { inspect(true, { numericSeparator: nonBoolean }); }, + TypeError, + inspect(nonBoolean) + ' is not a boolean' + ); + }); + + t.test('3 digit numbers', function (st) { + var failed = false; + for (var i = -999; i < 1000; i += 1) { + var actual = inspect(i); + var actualSepNo = inspect(i, { numericSeparator: false }); + var actualSepYes = inspect(i, { numericSeparator: true }); + var expected = String(i); + if (actual !== expected || actualSepNo !== expected || actualSepYes !== expected) { + failed = true; + t.equal(actual, expected); + t.equal(actualSepNo, expected); + t.equal(actualSepYes, expected); + } + } + + st.notOk(failed, 'all 3 digit numbers passed'); + + st.end(); + }); + + t.equal(inspect(1e3), '1000', '1000'); + t.equal(inspect(1e3, { numericSeparator: false }), '1000', '1000, numericSeparator false'); + t.equal(inspect(1e3, { numericSeparator: true }), '1_000', '1000, numericSeparator true'); + t.equal(inspect(-1e3), '-1000', '-1000'); + t.equal(inspect(-1e3, { numericSeparator: false }), '-1000', '-1000, numericSeparator false'); + t.equal(inspect(-1e3, { numericSeparator: true }), '-1_000', '-1000, numericSeparator true'); + + t.equal(inspect(1234.5678, { numericSeparator: true }), '1_234.567_8', 'fractional numbers get separators'); + t.equal(inspect(1234.56789, { numericSeparator: true }), '1_234.567_89', 'fractional numbers get separators'); + t.equal(inspect(1234.567891, { numericSeparator: true }), '1_234.567_891', 'fractional numbers get separators'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/quoteStyle.js b/node_modules/object-inspect/test/quoteStyle.js new file mode 100644 index 000000000..da23e630c --- /dev/null +++ b/node_modules/object-inspect/test/quoteStyle.js @@ -0,0 +1,26 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); + +test('quoteStyle option', function (t) { + t['throws'](function () { inspect(null, { quoteStyle: false }); }, 'false is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: true }); }, 'true is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: '' }); }, '"" is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: {} }); }, '{} is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: [] }); }, '[] is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: 42 }); }, '42 is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: NaN }); }, 'NaN is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: function () {} }); }, 'a function is not a valid value'); + + t.equal(inspect('"', { quoteStyle: 'single' }), '\'"\'', 'double quote, quoteStyle: "single"'); + t.equal(inspect('"', { quoteStyle: 'double' }), '"\\""', 'double quote, quoteStyle: "double"'); + + t.equal(inspect('\'', { quoteStyle: 'single' }), '\'\\\'\'', 'single quote, quoteStyle: "single"'); + t.equal(inspect('\'', { quoteStyle: 'double' }), '"\'"', 'single quote, quoteStyle: "double"'); + + t.equal(inspect('`', { quoteStyle: 'single' }), '\'`\'', 'backtick, quoteStyle: "single"'); + t.equal(inspect('`', { quoteStyle: 'double' }), '"`"', 'backtick, quoteStyle: "double"'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/toStringTag.js b/node_modules/object-inspect/test/toStringTag.js new file mode 100644 index 000000000..95f82703d --- /dev/null +++ b/node_modules/object-inspect/test/toStringTag.js @@ -0,0 +1,40 @@ +'use strict'; + +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +var inspect = require('../'); + +test('Symbol.toStringTag', { skip: !hasToStringTag }, function (t) { + t.plan(4); + + var obj = { a: 1 }; + t.equal(inspect(obj), '{ a: 1 }', 'object, no Symbol.toStringTag'); + + obj[Symbol.toStringTag] = 'foo'; + t.equal(inspect(obj), '{ a: 1, [Symbol(Symbol.toStringTag)]: \'foo\' }', 'object with Symbol.toStringTag'); + + t.test('null objects', { skip: 'toString' in { __proto__: null } }, function (st) { + st.plan(2); + + var dict = { __proto__: null, a: 1 }; + st.equal(inspect(dict), '[Object: null prototype] { a: 1 }', 'null object with Symbol.toStringTag'); + + dict[Symbol.toStringTag] = 'Dict'; + st.equal(inspect(dict), '[Dict: null prototype] { a: 1, [Symbol(Symbol.toStringTag)]: \'Dict\' }', 'null object with Symbol.toStringTag'); + }); + + t.test('instances', function (st) { + st.plan(4); + + function C() { + this.a = 1; + } + st.equal(Object.prototype.toString.call(new C()), '[object Object]', 'instance, no toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C { a: 1 }', 'instance, no toStringTag'); + + C.prototype[Symbol.toStringTag] = 'Class!'; + st.equal(Object.prototype.toString.call(new C()), '[object Class!]', 'instance, with toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C [Class!] { a: 1 }', 'instance, with toStringTag'); + }); +}); diff --git a/node_modules/object-inspect/test/undef.js b/node_modules/object-inspect/test/undef.js new file mode 100644 index 000000000..e3f496122 --- /dev/null +++ b/node_modules/object-inspect/test/undef.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { a: 1, b: [3, 4, undefined, null], c: undefined, d: null }; + +test('undef and null', function (t) { + t.plan(1); + t.equal( + inspect(obj), + '{ a: 1, b: [ 3, 4, undefined, null ], c: undefined, d: null }' + ); +}); diff --git a/node_modules/object-inspect/test/values.js b/node_modules/object-inspect/test/values.js new file mode 100644 index 000000000..15986cd0e --- /dev/null +++ b/node_modules/object-inspect/test/values.js @@ -0,0 +1,261 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); +var hasSymbols = require('has-symbols/shams')(); +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('for-each'); +var semver = require('semver'); + +test('values', function (t) { + t.plan(1); + var obj = [{}, [], { 'a-b': 5 }]; + t.equal(inspect(obj), '[ {}, [], { \'a-b\': 5 } ]'); +}); + +test('arrays with properties', function (t) { + t.plan(1); + var arr = [3]; + arr.foo = 'bar'; + var obj = [1, 2, arr]; + obj.baz = 'quux'; + obj.index = -1; + t.equal(inspect(obj), '[ 1, 2, [ 3, foo: \'bar\' ], baz: \'quux\', index: -1 ]'); +}); + +test('has', function (t) { + t.plan(1); + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect({ a: 1, b: 2 }), '{ a: 1, b: 2 }'); +}); + +test('indexOf seen', function (t) { + t.plan(1); + var xs = [1, 2, 3, {}]; + xs.push(xs); + + var seen = []; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[ 1, 2, 3, {}, [Circular] ]' + ); +}); + +test('seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('seen seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [5, xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + var sym = Symbol('foo'); + t.equal(inspect(sym), 'Symbol(foo)', 'Symbol("foo") should be "Symbol(foo)"'); + if (typeof sym === 'symbol') { + // Symbol shams are incapable of differentiating boxed from unboxed symbols + t.equal(inspect(Object(sym)), 'Object(Symbol(foo))', 'Object(Symbol("foo")) should be "Object(Symbol(foo))"'); + } + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'Symbol'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'Symbol\' }', + 'object lying about being a Symbol inspects as an object' + ); + }); + + t.end(); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + var expectedString = 'Map (2) {' + inspect({ a: 1 }) + ' => ' + inspect(['b']) + ', 3 => NaN}'; + t.equal(inspect(map), expectedString, 'new Map([[{ a: 1 }, ["b"]], [3, NaN]]) should show size and contents'); + t.equal(inspect(new Map()), 'Map (0) {}', 'empty Map should show as empty'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + t.equal(inspect(nestedMap), 'Map (1) {[Circular] => ' + expectedString + '}', 'Map containing a Map should work'); + + t.end(); +}); + +test('WeakMap', { skip: typeof WeakMap !== 'function' }, function (t) { + var map = new WeakMap(); + map.set({ a: 1 }, ['b']); + var expectedString = 'WeakMap { ? }'; + t.equal(inspect(map), expectedString, 'new WeakMap([[{ a: 1 }, ["b"]]]) should not show size or contents'); + t.equal(inspect(new WeakMap()), 'WeakMap { ? }', 'empty WeakMap should not show as empty'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedString = 'Set (2) {' + inspect({ a: 1 }) + ', ' + inspect(['b']) + '}'; + t.equal(inspect(set), expectedString, 'new Set([{ a: 1 }, ["b"]]) should show size and contents'); + t.equal(inspect(new Set()), 'Set (0) {}', 'empty Set should show as empty'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + t.equal(inspect(nestedSet), 'Set (2) {' + expectedString + ', [Circular]}', 'Set containing a Set should work'); + + t.end(); +}); + +test('WeakSet', { skip: typeof WeakSet !== 'function' }, function (t) { + var map = new WeakSet(); + map.add({ a: 1 }); + var expectedString = 'WeakSet { ? }'; + t.equal(inspect(map), expectedString, 'new WeakSet([{ a: 1 }]) should not show size or contents'); + t.equal(inspect(new WeakSet()), 'WeakSet { ? }', 'empty WeakSet should not show as empty'); + + t.end(); +}); + +test('WeakRef', { skip: typeof WeakRef !== 'function' }, function (t) { + var ref = new WeakRef({ a: 1 }); + var expectedString = 'WeakRef { ? }'; + t.equal(inspect(ref), expectedString, 'new WeakRef({ a: 1 }) should not show contents'); + + t.end(); +}); + +test('FinalizationRegistry', { skip: typeof FinalizationRegistry !== 'function' }, function (t) { + var registry = new FinalizationRegistry(function () {}); + var expectedString = 'FinalizationRegistry [FinalizationRegistry] {}'; + t.equal(inspect(registry), expectedString, 'new FinalizationRegistry(function () {}) should work normallys'); + + t.end(); +}); + +test('Strings', function (t) { + var str = 'abc'; + + t.equal(inspect(str), "'" + str + "'", 'primitive string shows as such'); + t.equal(inspect(str, { quoteStyle: 'single' }), "'" + str + "'", 'primitive string shows as such, single quoted'); + t.equal(inspect(str, { quoteStyle: 'double' }), '"' + str + '"', 'primitive string shows as such, double quoted'); + t.equal(inspect(Object(str)), 'Object(' + inspect(str) + ')', 'String object shows as such'); + t.equal(inspect(Object(str), { quoteStyle: 'single' }), 'Object(' + inspect(str, { quoteStyle: 'single' }) + ')', 'String object shows as such, single quoted'); + t.equal(inspect(Object(str), { quoteStyle: 'double' }), 'Object(' + inspect(str, { quoteStyle: 'double' }) + ')', 'String object shows as such, double quoted'); + + t.end(); +}); + +test('Numbers', function (t) { + var num = 42; + + t.equal(inspect(num), String(num), 'primitive number shows as such'); + t.equal(inspect(Object(num)), 'Object(' + inspect(num) + ')', 'Number object shows as such'); + + t.end(); +}); + +test('Booleans', function (t) { + t.equal(inspect(true), String(true), 'primitive true shows as such'); + t.equal(inspect(Object(true)), 'Object(' + inspect(true) + ')', 'Boolean object true shows as such'); + + t.equal(inspect(false), String(false), 'primitive false shows as such'); + t.equal(inspect(Object(false)), 'Object(' + inspect(false) + ')', 'Boolean false object shows as such'); + + t.end(); +}); + +test('Date', function (t) { + var now = new Date(); + t.equal(inspect(now), String(now), 'Date shows properly'); + t.equal(inspect(new Date(NaN)), 'Invalid Date', 'Invalid Date shows properly'); + + t.end(); +}); + +test('RegExps', function (t) { + t.equal(inspect(/a/g), '/a/g', 'regex shows properly'); + t.equal(inspect(new RegExp('abc', 'i')), '/abc/i', 'new RegExp shows properly'); + + var match = 'abc abc'.match(/[ab]+/); + delete match.groups; // for node < 10 + t.equal(inspect(match), '[ \'ab\', index: 0, input: \'abc abc\' ]', 'RegExp match object shows properly'); + + t.end(); +}); + +test('Proxies', { skip: typeof Proxy !== 'function' || !hasToStringTag }, function (t) { + var target = { proxy: true }; + var fake = new Proxy(target, { has: function () { return false; } }); + + // needed to work around a weird difference in node v6.0 - v6.4 where non-present properties are not logged + var isNode60 = semver.satisfies(process.version, '6.0 - 6.4'); + + forEach([ + 'Boolean', + 'Number', + 'String', + 'Symbol', + 'Date' + ], function (tag) { + target[Symbol.toStringTag] = tag; + + t.equal( + inspect(fake), + '{ ' + (isNode60 ? '' : 'proxy: true, ') + '[Symbol(Symbol.toStringTag)]: \'' + tag + '\' }', + 'Proxy for + ' + tag + ' shows as the target, which has no slots' + ); + }); + + t.end(); +}); + +test('fakers', { skip: !hasToStringTag }, function (t) { + var target = { proxy: false }; + + forEach([ + 'Boolean', + 'Number', + 'String', + 'Symbol', + 'Date' + ], function (tag) { + target[Symbol.toStringTag] = tag; + + t.equal( + inspect(target), + '{ proxy: false, [Symbol(Symbol.toStringTag)]: \'' + tag + '\' }', + 'Object pretending to be ' + tag + ' does not trick us' + ); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/util.inspect.js b/node_modules/object-inspect/util.inspect.js new file mode 100644 index 000000000..7784fab55 --- /dev/null +++ b/node_modules/object-inspect/util.inspect.js @@ -0,0 +1 @@ +module.exports = require('util').inspect; diff --git a/node_modules/on-finished/HISTORY.md b/node_modules/on-finished/HISTORY.md new file mode 100644 index 000000000..1917595a7 --- /dev/null +++ b/node_modules/on-finished/HISTORY.md @@ -0,0 +1,98 @@ +2.4.1 / 2022-02-22 +================== + + * Fix error on early async hooks implementations + +2.4.0 / 2022-02-21 +================== + + * Prevent loss of async hooks context + +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +2.2.1 / 2015-04-22 +================== + + * Fix `isFinished(req)` when data buffered + +2.2.0 / 2014-12-22 +================== + + * Add message object to callback arguments + +2.1.1 / 2014-10-22 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/node_modules/on-finished/LICENSE b/node_modules/on-finished/LICENSE new file mode 100644 index 000000000..5931fd23e --- /dev/null +++ b/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 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/on-finished/README.md b/node_modules/on-finished/README.md new file mode 100644 index 000000000..8973cded6 --- /dev/null +++ b/node_modules/on-finished/README.md @@ -0,0 +1,162 @@ +# on-finished + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +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 on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to an error, the first argument will contain the error. If the response +has already finished, the listener will be invoked. + +Listening to the end of a response would be used to close things associated +with the response, like open files. + +Listener is invoked as `listener(err, res)`. + + + +```js +onFinished(res, function (err, res) { + // clean up open fds, etc. + // err contains the error if request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to an error, the first argument will contain the error. If the request +has already finished, the listener will be invoked. + +Listening to the end of a request would be used to know when to continue +after reading the data. + +Listener is invoked as `listener(err, req)`. + + + +```js +var data = '' + +req.setEncoding('utf8') +req.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var fs = require('fs') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest (req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function () { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/on-finished/master?label=ci +[ci-url]: https://github.com/jshttp/on-finished/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-finished/master +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[node-image]: https://badgen.net/npm/node/on-finished +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/on-finished +[npm-url]: https://npmjs.org/package/on-finished +[npm-version-image]: https://badgen.net/npm/v/on-finished diff --git a/node_modules/on-finished/index.js b/node_modules/on-finished/index.js new file mode 100644 index 000000000..e68df7bde --- /dev/null +++ b/node_modules/on-finished/index.js @@ -0,0 +1,234 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var asyncHooks = tryRequireAsyncHooks() +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished (msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, wrap(listener)) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished (msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener (msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish (error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket (socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // istanbul ignore next: node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener (msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener (msg) { + function listener (err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +// istanbul ignore next: node.js 0.8 patch +function patchAssignSocket (res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket (socket) { + assignSocket.call(this, socket) + callback(socket) + } +} + +/** + * Try to require async_hooks + * @private + */ + +function tryRequireAsyncHooks () { + try { + return require('async_hooks') + } catch (e) { + return {} + } +} + +/** + * Wrap function with async resource, if possible. + * AsyncResource.bind static method backported. + * @private + */ + +function wrap (fn) { + var res + + // create anonymous resource + if (asyncHooks.AsyncResource) { + res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') + } + + // incompatible node.js + if (!res || !res.runInAsyncScope) { + return fn + } + + // return bound function + return res.runInAsyncScope.bind(res, fn, null) +} diff --git a/node_modules/on-finished/package.json b/node_modules/on-finished/package.json new file mode 100644 index 000000000..644cd814b --- /dev/null +++ b/node_modules/on-finished/package.json @@ -0,0 +1,39 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.4.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/on-finished", + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/once/LICENSE b/node_modules/once/LICENSE new file mode 100644 index 000000000..19129e315 --- /dev/null +++ b/node_modules/once/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/once/README.md b/node_modules/once/README.md new file mode 100644 index 000000000..1f1ffca93 --- /dev/null +++ b/node_modules/once/README.md @@ -0,0 +1,79 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. + +To check whether you function has been called, use `fn.called`. Once the +function is called for the first time the return value of the original +function is saved in `fn.value` and subsequent calls will continue to +return this value. + +```javascript +var once = require('once') + +function load (cb) { + cb = once(cb) + var stream = createStream() + stream.once('data', cb) + stream.once('end', function () { + if (!cb.called) cb(new Error('not found')) + }) +} +``` + +## `once.strict(func)` + +Throw an error if the function is called twice. + +Some functions are expected to be called only once. Using `once` for them would +potentially hide logical errors. + +In the example below, the `greet` function has to call the callback only once: + +```javascript +function greet (name, cb) { + // return is missing from the if statement + // when no name is passed, the callback is called twice + if (!name) cb('Hello anonymous') + cb('Hello ' + name) +} + +function log (msg) { + console.log(msg) +} + +// this will print 'Hello anonymous' but the logical error will be missed +greet(null, once(msg)) + +// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time +greet(null, once.strict(msg)) +``` diff --git a/node_modules/once/once.js b/node_modules/once/once.js new file mode 100644 index 000000000..235406736 --- /dev/null +++ b/node_modules/once/once.js @@ -0,0 +1,42 @@ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} diff --git a/node_modules/once/package.json b/node_modules/once/package.json new file mode 100644 index 000000000..16815b2fa --- /dev/null +++ b/node_modules/once/package.json @@ -0,0 +1,33 @@ +{ + "name": "once", + "version": "1.4.0", + "description": "Run a function exactly one time", + "main": "once.js", + "directories": { + "test": "test" + }, + "dependencies": { + "wrappy": "1" + }, + "devDependencies": { + "tap": "^7.0.1" + }, + "scripts": { + "test": "tap test/*.js" + }, + "files": [ + "once.js" + ], + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once" + }, + "keywords": [ + "once", + "function", + "one", + "single" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC" +} diff --git a/node_modules/parseurl/HISTORY.md b/node_modules/parseurl/HISTORY.md new file mode 100644 index 000000000..8e409541d --- /dev/null +++ b/node_modules/parseurl/HISTORY.md @@ -0,0 +1,58 @@ +1.3.3 / 2019-04-15 +================== + + * Fix Node.js 0.8 return value inconsistencies + +1.3.2 / 2017-09-09 +================== + + * perf: reduce overhead for full URLs + * perf: unroll the "fast-path" `RegExp` + +1.3.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.3.0 / 2014-08-09 +================== + + * Add `parseurl.original` for parsing `req.originalUrl` with fallback + * Return `undefined` if `req.url` is `undefined` + +1.2.0 / 2014-07-21 +================== + + * Cache URLs based on original value + * Remove no-longer-needed URL mis-parse work-around + * Simplify the "fast-path" `RegExp` + +1.1.3 / 2014-07-08 +================== + + * Fix typo + +1.1.2 / 2014-07-08 +================== + + * Seriously fix Node.js 0.8 compatibility + +1.1.1 / 2014-07-08 +================== + + * Fix Node.js 0.8 compatibility + +1.1.0 / 2014-07-08 +================== + + * Incorporate URL href-only parse fast-path + +1.0.1 / 2014-03-08 +================== + + * Add missing `require` + +1.0.0 / 2014-03-08 +================== + + * Genesis from `connect` diff --git a/node_modules/parseurl/LICENSE b/node_modules/parseurl/LICENSE new file mode 100644 index 000000000..27653d3db --- /dev/null +++ b/node_modules/parseurl/LICENSE @@ -0,0 +1,24 @@ + +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2017 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/parseurl/README.md b/node_modules/parseurl/README.md new file mode 100644 index 000000000..443e716b8 --- /dev/null +++ b/node_modules/parseurl/README.md @@ -0,0 +1,133 @@ +# parseurl + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse a URL with memoization. + +## Install + +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 parseurl +``` + +## API + +```js +var parseurl = require('parseurl') +``` + +### parseurl(req) + +Parse the URL of the given request object (looks at the `req.url` property) +and return the result. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.url` does +not change will return a cached parsed object, rather than parsing again. + +### parseurl.original(req) + +Parse the original URL of the given request object and return the result. +This works by trying to parse `req.originalUrl` if it is a string, otherwise +parses `req.url`. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.originalUrl` +does not change will return a cached parsed object, rather than parsing again. + +## Benchmark + +```bash +$ npm run-script bench + +> parseurl@1.3.3 bench nodejs-parseurl +> node benchmark/index.js + + http_parser@2.8.0 + node@10.6.0 + v8@6.7.288.46-node.13 + uv@1.21.0 + zlib@1.2.11 + ares@1.14.0 + modules@64 + nghttp2@1.32.0 + napi@3 + openssl@1.1.0h + icu@61.1 + unicode@10.0 + cldr@33.0 + tz@2018c + +> node benchmark/fullurl.js + + Parsing URL "http://localhost:8888/foo/bar?user=tj&pet=fluffy" + + 4 tests completed. + + fasturl x 2,207,842 ops/sec ±3.76% (184 runs sampled) + nativeurl - legacy x 507,180 ops/sec ±0.82% (191 runs sampled) + nativeurl - whatwg x 290,044 ops/sec ±1.96% (189 runs sampled) + parseurl x 488,907 ops/sec ±2.13% (192 runs sampled) + +> node benchmark/pathquery.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" + + 4 tests completed. + + fasturl x 3,812,564 ops/sec ±3.15% (188 runs sampled) + nativeurl - legacy x 2,651,631 ops/sec ±1.68% (189 runs sampled) + nativeurl - whatwg x 161,837 ops/sec ±2.26% (189 runs sampled) + parseurl x 4,166,338 ops/sec ±2.23% (184 runs sampled) + +> node benchmark/samerequest.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" on same request object + + 4 tests completed. + + fasturl x 3,821,651 ops/sec ±2.42% (185 runs sampled) + nativeurl - legacy x 2,651,162 ops/sec ±1.90% (187 runs sampled) + nativeurl - whatwg x 175,166 ops/sec ±1.44% (188 runs sampled) + parseurl x 14,912,606 ops/sec ±3.59% (183 runs sampled) + +> node benchmark/simplepath.js + + Parsing URL "/foo/bar" + + 4 tests completed. + + fasturl x 12,421,765 ops/sec ±2.04% (191 runs sampled) + nativeurl - legacy x 7,546,036 ops/sec ±1.41% (188 runs sampled) + nativeurl - whatwg x 198,843 ops/sec ±1.83% (189 runs sampled) + parseurl x 24,244,006 ops/sec ±0.51% (194 runs sampled) + +> node benchmark/slash.js + + Parsing URL "/" + + 4 tests completed. + + fasturl x 17,159,456 ops/sec ±3.25% (188 runs sampled) + nativeurl - legacy x 11,635,097 ops/sec ±3.79% (184 runs sampled) + nativeurl - whatwg x 240,693 ops/sec ±0.83% (189 runs sampled) + parseurl x 42,279,067 ops/sec ±0.55% (190 runs sampled) +``` + +## License + + [MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/parseurl/master +[coveralls-url]: https://coveralls.io/r/pillarjs/parseurl?branch=master +[node-image]: https://badgen.net/npm/node/parseurl +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/parseurl +[npm-url]: https://npmjs.org/package/parseurl +[npm-version-image]: https://badgen.net/npm/v/parseurl +[travis-image]: https://badgen.net/travis/pillarjs/parseurl/master +[travis-url]: https://travis-ci.org/pillarjs/parseurl diff --git a/node_modules/parseurl/index.js b/node_modules/parseurl/index.js new file mode 100644 index 000000000..ece722327 --- /dev/null +++ b/node_modules/parseurl/index.js @@ -0,0 +1,158 @@ +/*! + * parseurl + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var url = require('url') +var parse = url.parse +var Url = url.Url + +/** + * Module exports. + * @public + */ + +module.exports = parseurl +module.exports.original = originalurl + +/** + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function parseurl (req) { + var url = req.url + + if (url === undefined) { + // URL is undefined + return undefined + } + + var parsed = req._parsedUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return (req._parsedUrl = parsed) +}; + +/** + * Parse the `req` original url with fallback and memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function originalurl (req) { + var url = req.originalUrl + + if (typeof url !== 'string') { + // Fallback + return parseurl(req) + } + + var parsed = req._parsedOriginalUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return (req._parsedOriginalUrl = parsed) +}; + +/** + * Parse the `str` url with fast-path short-cut. + * + * @param {string} str + * @return {Object} + * @private + */ + +function fastparse (str) { + if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { + return parse(str) + } + + var pathname = str + var query = null + var search = null + + // This takes the regexp from https://github.com/joyent/node/pull/7878 + // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ + // And unrolls it into a for loop + for (var i = 1; i < str.length; i++) { + switch (str.charCodeAt(i)) { + case 0x3f: /* ? */ + if (search === null) { + pathname = str.substring(0, i) + query = str.substring(i + 1) + search = str.substring(i) + } + break + case 0x09: /* \t */ + case 0x0a: /* \n */ + case 0x0c: /* \f */ + case 0x0d: /* \r */ + case 0x20: /* */ + case 0x23: /* # */ + case 0xa0: + case 0xfeff: + return parse(str) + } + } + + var url = Url !== undefined + ? new Url() + : {} + + url.path = str + url.href = str + url.pathname = pathname + + if (search !== null) { + url.query = query + url.search = search + } + + return url +} + +/** + * Determine if parsed is still fresh for url. + * + * @param {string} url + * @param {object} parsedUrl + * @return {boolean} + * @private + */ + +function fresh (url, parsedUrl) { + return typeof parsedUrl === 'object' && + parsedUrl !== null && + (Url === undefined || parsedUrl instanceof Url) && + parsedUrl._raw === url +} diff --git a/node_modules/parseurl/package.json b/node_modules/parseurl/package.json new file mode 100644 index 000000000..6b443ca7a --- /dev/null +++ b/node_modules/parseurl/package.json @@ -0,0 +1,40 @@ +{ + "name": "parseurl", + "description": "parse a url with memoization", + "version": "1.3.3", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "pillarjs/parseurl", + "license": "MIT", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.1", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "fast-url-parser": "1.1.3", + "istanbul": "0.4.5", + "mocha": "6.1.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --check-leaks --bail --reporter spec test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec test/" + } +} diff --git a/node_modules/path-key/index.d.ts b/node_modules/path-key/index.d.ts new file mode 100644 index 000000000..7c575d197 --- /dev/null +++ b/node_modules/path-key/index.d.ts @@ -0,0 +1,40 @@ +/// + +declare namespace pathKey { + interface Options { + /** + Use a custom environment variables object. Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env). + */ + readonly env?: {[key: string]: string | undefined}; + + /** + Get the PATH key for a specific platform. Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform). + */ + readonly platform?: NodeJS.Platform; + } +} + +declare const pathKey: { + /** + Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform. + + @example + ``` + import pathKey = require('path-key'); + + const key = pathKey(); + //=> 'PATH' + + const PATH = process.env[key]; + //=> '/usr/local/bin:/usr/bin:/bin' + ``` + */ + (options?: pathKey.Options): string; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function pathKey(options?: pathKey.Options): string; + // export = pathKey; + default: typeof pathKey; +}; + +export = pathKey; diff --git a/node_modules/path-key/index.js b/node_modules/path-key/index.js new file mode 100644 index 000000000..0cf6415d6 --- /dev/null +++ b/node_modules/path-key/index.js @@ -0,0 +1,16 @@ +'use strict'; + +const pathKey = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +}; + +module.exports = pathKey; +// TODO: Remove this for the next major release +module.exports.default = pathKey; diff --git a/node_modules/path-key/license b/node_modules/path-key/license new file mode 100644 index 000000000..e7af2f771 --- /dev/null +++ b/node_modules/path-key/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/path-key/package.json b/node_modules/path-key/package.json new file mode 100644 index 000000000..c8cbd383a --- /dev/null +++ b/node_modules/path-key/package.json @@ -0,0 +1,39 @@ +{ + "name": "path-key", + "version": "3.1.1", + "description": "Get the PATH environment variable key cross-platform", + "license": "MIT", + "repository": "sindresorhus/path-key", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "path", + "key", + "environment", + "env", + "variable", + "var", + "get", + "cross-platform", + "windows" + ], + "devDependencies": { + "@types/node": "^11.13.0", + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/path-key/readme.md b/node_modules/path-key/readme.md new file mode 100644 index 000000000..a9052d7a6 --- /dev/null +++ b/node_modules/path-key/readme.md @@ -0,0 +1,61 @@ +# path-key [![Build Status](https://travis-ci.org/sindresorhus/path-key.svg?branch=master)](https://travis-ci.org/sindresorhus/path-key) + +> Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform + +It's usually `PATH`, but on Windows it can be any casing like `Path`... + + +## Install + +``` +$ npm install path-key +``` + + +## Usage + +```js +const pathKey = require('path-key'); + +const key = pathKey(); +//=> 'PATH' + +const PATH = process.env[key]; +//=> '/usr/local/bin:/usr/bin:/bin' +``` + + +## API + +### pathKey(options?) + +#### options + +Type: `object` + +##### env + +Type: `object`
+Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env) + +Use a custom environment variables object. + +#### platform + +Type: `string`
+Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform) + +Get the PATH key for a specific platform. + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/path-to-regexp/LICENSE b/node_modules/path-to-regexp/LICENSE new file mode 100644 index 000000000..983fbe8ae --- /dev/null +++ b/node_modules/path-to-regexp/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/path-to-regexp/Readme.md b/node_modules/path-to-regexp/Readme.md new file mode 100644 index 000000000..f5df40a9a --- /dev/null +++ b/node_modules/path-to-regexp/Readme.md @@ -0,0 +1,224 @@ +# Path-to-RegExp + +> Turn a path string such as `/user/:name` into a regular expression. + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][build-image]][build-url] +[![Build coverage][coverage-image]][coverage-url] +[![License][license-image]][license-url] + +## Installation + +``` +npm install path-to-regexp --save +``` + +## Usage + +```js +const { + match, + pathToRegexp, + compile, + parse, + stringify, +} = require("path-to-regexp"); +``` + +### Parameters + +Parameters match arbitrary strings in a path by matching up to the end of the segment, or up to any proceeding tokens. They are defined by prefixing a colon to the parameter name (`:foo`). Parameter names can use any valid JavaScript identifier, or be double quoted to use other characters (`:"param-name"`). + +```js +const fn = match("/:foo/:bar"); + +fn("/test/route"); +//=> { path: '/test/route', params: { foo: 'test', bar: 'route' } } +``` + +### Wildcard + +Wildcard parameters match one or more characters across multiple segments. They are defined the same way as regular parameters, but are prefixed with an asterisk (`*foo`). + +```js +const fn = match("/*splat"); + +fn("/bar/baz"); +//=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] } } +``` + +### Optional + +Braces can be used to define parts of the path that are optional. + +```js +const fn = match("/users{/:id}/delete"); + +fn("/users/delete"); +//=> { path: '/users/delete', params: {} } + +fn("/users/123/delete"); +//=> { path: '/users/123/delete', params: { id: '123' } } +``` + +## Match + +The `match` function returns a function for matching strings against a path: + +- **path** String, `TokenData` object, or array of strings and `TokenData` objects. +- **options** _(optional)_ (Extends [pathToRegexp](#pathToRegexp) options) + - **decode** Function for decoding strings to params, or `false` to disable all processing. (default: `decodeURIComponent`) + +```js +const fn = match("/foo/:bar"); +``` + +**Please note:** `path-to-regexp` is intended for ordered data (e.g. paths, hosts). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc). + +## PathToRegexp + +The `pathToRegexp` function returns the `regexp` for matching strings against paths, and an array of `keys` for understanding the `RegExp#exec` matches. + +- **path** String, `TokenData` object, or array of strings and `TokenData` objects. +- **options** _(optional)_ (See [parse](#parse) for more options) + - **sensitive** Regexp will be case sensitive. (default: `false`) + - **end** Validate the match reaches the end of the string. (default: `true`) + - **delimiter** The default delimiter for segments, e.g. `[^/]` for `:named` parameters. (default: `'/'`) + - **trailing** Allows optional trailing delimiter to match. (default: `true`) + +```js +const { regexp, keys } = pathToRegexp("/foo/:bar"); + +regexp.exec("/foo/123"); //=> ["/foo/123", "123"] +``` + +## Compile ("Reverse" Path-To-RegExp) + +The `compile` function will return a function for transforming parameters into a valid path: + +- **path** A string or `TokenData` object. +- **options** (See [parse](#parse) for more options) + - **delimiter** The default delimiter for segments, e.g. `[^/]` for `:named` parameters. (default: `'/'`) + - **encode** Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`) + +```js +const toPath = compile("/user/:id"); + +toPath({ id: "name" }); //=> "/user/name" +toPath({ id: "café" }); //=> "/user/caf%C3%A9" + +const toPathRepeated = compile("/*segment"); + +toPathRepeated({ segment: ["foo"] }); //=> "/foo" +toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c" + +// When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted. +const toPathRaw = compile("/user/:id", { encode: false }); + +toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F" +``` + +## Stringify + +Transform a `TokenData` object to a Path-to-RegExp string. + +- **data** A `TokenData` object. + +```js +const data = { + tokens: [ + { type: "text", value: "/" }, + { type: "param", name: "foo" }, + ], +}; + +const path = stringify(data); //=> "/:foo" +``` + +## Developers + +- If you are rewriting paths with match and compile, consider using `encode: false` and `decode: false` to keep raw paths passed around. +- To ensure matches work on paths containing characters usually encoded, such as emoji, consider using [encodeurl](https://github.com/pillarjs/encodeurl) for `encodePath`. + +### Parse + +The `parse` function accepts a string and returns `TokenData`, which can be used with `match` and `compile`. + +- **path** A string. +- **options** _(optional)_ + - **encodePath** A function for encoding input strings. (default: `x => x`, recommended: [`encodeurl`](https://github.com/pillarjs/encodeurl)) + +### Tokens + +`TokenData` has two properties: + +- **tokens** A sequence of tokens, currently of types `text`, `parameter`, `wildcard`, or `group`. +- **originalPath** The original path used with `parse`, shown in error messages to assist debugging. + +### Custom path + +In some applications you may not be able to use the `path-to-regexp` syntax, but you still want to use this library for `match` and `compile`. For example: + +```js +import { match } from "path-to-regexp"; + +const tokens = [ + { type: "text", value: "/" }, + { type: "parameter", name: "foo" }, +]; +const originalPath = "/[foo]"; // To help debug error messages. +const path = { tokens, originalPath }; +const fn = match(path); + +fn("/test"); //=> { path: '/test', index: 0, params: { foo: 'test' } } +``` + +## Errors + +An effort has been made to ensure ambiguous paths from previous releases throw an error. This means you might be seeing an error when things worked before. + +### Missing parameter name + +Parameter names must be provided after `:` or `*`, for example `/*path`. They can be valid JavaScript identifiers (e.g. `:myName`) or JSON strings (`:"my-name"`). + +### Unexpected `?` or `+` + +In past releases, `?`, `*`, and `+` were used to denote optional or repeating parameters. As an alternative, try these: + +- For optional (`?`), use braces: `/file{.:ext}`. +- For one or more (`+`), use a wildcard: `/*path`. +- For zero or more (`*`), use both: `/files{/*path}`. + +### Unexpected `(`, `)`, `[`, `]`, etc. + +Previous versions of Path-to-RegExp used these for RegExp features. This version no longer supports them so they've been reserved to avoid ambiguity. To match these characters literally, escape them with a backslash, e.g. `"\\("`. + +### Unterminated quote + +Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character. For example, `:"foo`. + +### Express <= 4.x + +Path-To-RegExp breaks compatibility with Express <= `4.x` in the following ways: + +- The wildcard `*` must have a name and matches the behavior of parameters `:`. +- The optional character `?` is no longer supported, use braces instead: `/:file{.:ext}`. +- Regexp characters are not supported. +- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`). +- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/path-to-regexp +[npm-url]: https://npmjs.org/package/path-to-regexp +[downloads-image]: https://img.shields.io/npm/dm/path-to-regexp +[downloads-url]: https://npmjs.org/package/path-to-regexp +[build-image]: https://img.shields.io/github/actions/workflow/status/pillarjs/path-to-regexp/ci.yml?branch=master +[build-url]: https://github.com/pillarjs/path-to-regexp/actions/workflows/ci.yml?query=branch%3Amaster +[coverage-image]: https://img.shields.io/codecov/c/gh/pillarjs/path-to-regexp +[coverage-url]: https://codecov.io/gh/pillarjs/path-to-regexp +[license-image]: http://img.shields.io/npm/l/path-to-regexp.svg?style=flat +[license-url]: LICENSE.md diff --git a/node_modules/path-to-regexp/dist/index.d.ts b/node_modules/path-to-regexp/dist/index.d.ts new file mode 100644 index 000000000..b59dff0e2 --- /dev/null +++ b/node_modules/path-to-regexp/dist/index.d.ts @@ -0,0 +1,144 @@ +/** + * Encode a string into another string. + */ +export type Encode = (value: string) => string; +/** + * Decode a string into another string. + */ +export type Decode = (value: string) => string; +export interface ParseOptions { + /** + * A function for encoding input strings. + */ + encodePath?: Encode; +} +export interface PathToRegexpOptions { + /** + * Matches the path completely without trailing characters. (default: `true`) + */ + end?: boolean; + /** + * Allows optional trailing delimiter to match. (default: `true`) + */ + trailing?: boolean; + /** + * Match will be case sensitive. (default: `false`) + */ + sensitive?: boolean; + /** + * The default delimiter for segments. (default: `'/'`) + */ + delimiter?: string; +} +export interface MatchOptions extends PathToRegexpOptions { + /** + * Function for decoding strings for params, or `false` to disable entirely. (default: `decodeURIComponent`) + */ + decode?: Decode | false; +} +export interface CompileOptions { + /** + * Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`) + */ + encode?: Encode | false; + /** + * The default delimiter for segments. (default: `'/'`) + */ + delimiter?: string; +} +/** + * Plain text. + */ +export interface Text { + type: "text"; + value: string; +} +/** + * A parameter designed to match arbitrary text within a segment. + */ +export interface Parameter { + type: "param"; + name: string; +} +/** + * A wildcard parameter designed to match multiple segments. + */ +export interface Wildcard { + type: "wildcard"; + name: string; +} +/** + * A set of possible tokens to expand when matching. + */ +export interface Group { + type: "group"; + tokens: Token[]; +} +/** + * A token that corresponds with a regexp capture. + */ +export type Key = Parameter | Wildcard; +/** + * A sequence of `path-to-regexp` keys that match capturing groups. + */ +export type Keys = Array; +/** + * A sequence of path match characters. + */ +export type Token = Text | Parameter | Wildcard | Group; +/** + * Tokenized path instance. + */ +export declare class TokenData { + readonly tokens: Token[]; + readonly originalPath?: string | undefined; + constructor(tokens: Token[], originalPath?: string | undefined); +} +/** + * ParseError is thrown when there is an error processing the path. + */ +export declare class PathError extends TypeError { + readonly originalPath: string | undefined; + constructor(message: string, originalPath: string | undefined); +} +/** + * Parse a string for the raw tokens. + */ +export declare function parse(str: string, options?: ParseOptions): TokenData; +/** + * Compile a string to a template function for the path. + */ +export declare function compile

(path: Path, options?: CompileOptions & ParseOptions): (params?: P) => string; +export type ParamData = Partial>; +export type PathFunction

= (data?: P) => string; +/** + * A match result contains data about the path match. + */ +export interface MatchResult

{ + path: string; + params: P; +} +/** + * A match is either `false` (no match) or a match result. + */ +export type Match

= false | MatchResult

; +/** + * The match function takes a string and returns whether it matched the path. + */ +export type MatchFunction

= (path: string) => Match

; +/** + * Supported path types. + */ +export type Path = string | TokenData; +/** + * Transform a path into a match function. + */ +export declare function match

(path: Path | Path[], options?: MatchOptions & ParseOptions): MatchFunction

; +export declare function pathToRegexp(path: Path | Path[], options?: PathToRegexpOptions & ParseOptions): { + regexp: RegExp; + keys: Keys; +}; +/** + * Stringify token data into a path string. + */ +export declare function stringify(data: TokenData): string; diff --git a/node_modules/path-to-regexp/dist/index.js b/node_modules/path-to-regexp/dist/index.js new file mode 100644 index 000000000..9331ae067 --- /dev/null +++ b/node_modules/path-to-regexp/dist/index.js @@ -0,0 +1,409 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PathError = exports.TokenData = void 0; +exports.parse = parse; +exports.compile = compile; +exports.match = match; +exports.pathToRegexp = pathToRegexp; +exports.stringify = stringify; +const DEFAULT_DELIMITER = "/"; +const NOOP_VALUE = (value) => value; +const ID_START = /^[$_\p{ID_Start}]$/u; +const ID_CONTINUE = /^[$\u200c\u200d\p{ID_Continue}]$/u; +const SIMPLE_TOKENS = { + // Groups. + "{": "{", + "}": "}", + // Reserved. + "(": "(", + ")": ")", + "[": "[", + "]": "]", + "+": "+", + "?": "?", + "!": "!", +}; +/** + * Escape text for stringify to path. + */ +function escapeText(str) { + return str.replace(/[{}()\[\]+?!:*\\]/g, "\\$&"); +} +/** + * Escape a regular expression string. + */ +function escape(str) { + return str.replace(/[.+*?^${}()[\]|/\\]/g, "\\$&"); +} +/** + * Tokenized path instance. + */ +class TokenData { + constructor(tokens, originalPath) { + this.tokens = tokens; + this.originalPath = originalPath; + } +} +exports.TokenData = TokenData; +/** + * ParseError is thrown when there is an error processing the path. + */ +class PathError extends TypeError { + constructor(message, originalPath) { + let text = message; + if (originalPath) + text += `: ${originalPath}`; + text += `; visit https://git.new/pathToRegexpError for info`; + super(text); + this.originalPath = originalPath; + } +} +exports.PathError = PathError; +/** + * Parse a string for the raw tokens. + */ +function parse(str, options = {}) { + const { encodePath = NOOP_VALUE } = options; + const chars = [...str]; + const tokens = []; + let index = 0; + let pos = 0; + function name() { + let value = ""; + if (ID_START.test(chars[index])) { + do { + value += chars[index++]; + } while (ID_CONTINUE.test(chars[index])); + } + else if (chars[index] === '"') { + let quoteStart = index; + while (index++ < chars.length) { + if (chars[index] === '"') { + index++; + quoteStart = 0; + break; + } + // Increment over escape characters. + if (chars[index] === "\\") + index++; + value += chars[index]; + } + if (quoteStart) { + throw new PathError(`Unterminated quote at index ${quoteStart}`, str); + } + } + if (!value) { + throw new PathError(`Missing parameter name at index ${index}`, str); + } + return value; + } + while (index < chars.length) { + const value = chars[index]; + const type = SIMPLE_TOKENS[value]; + if (type) { + tokens.push({ type, index: index++, value }); + } + else if (value === "\\") { + tokens.push({ type: "escape", index: index++, value: chars[index++] }); + } + else if (value === ":") { + tokens.push({ type: "param", index: index++, value: name() }); + } + else if (value === "*") { + tokens.push({ type: "wildcard", index: index++, value: name() }); + } + else { + tokens.push({ type: "char", index: index++, value }); + } + } + tokens.push({ type: "end", index, value: "" }); + function consumeUntil(endType) { + const output = []; + while (true) { + const token = tokens[pos++]; + if (token.type === endType) + break; + if (token.type === "char" || token.type === "escape") { + let path = token.value; + let cur = tokens[pos]; + while (cur.type === "char" || cur.type === "escape") { + path += cur.value; + cur = tokens[++pos]; + } + output.push({ + type: "text", + value: encodePath(path), + }); + continue; + } + if (token.type === "param" || token.type === "wildcard") { + output.push({ + type: token.type, + name: token.value, + }); + continue; + } + if (token.type === "{") { + output.push({ + type: "group", + tokens: consumeUntil("}"), + }); + continue; + } + throw new PathError(`Unexpected ${token.type} at index ${token.index}, expected ${endType}`, str); + } + return output; + } + return new TokenData(consumeUntil("end"), str); +} +/** + * Compile a string to a template function for the path. + */ +function compile(path, options = {}) { + const { encode = encodeURIComponent, delimiter = DEFAULT_DELIMITER } = options; + const data = typeof path === "object" ? path : parse(path, options); + const fn = tokensToFunction(data.tokens, delimiter, encode); + return function path(params = {}) { + const [path, ...missing] = fn(params); + if (missing.length) { + throw new TypeError(`Missing parameters: ${missing.join(", ")}`); + } + return path; + }; +} +function tokensToFunction(tokens, delimiter, encode) { + const encoders = tokens.map((token) => tokenToFunction(token, delimiter, encode)); + return (data) => { + const result = [""]; + for (const encoder of encoders) { + const [value, ...extras] = encoder(data); + result[0] += value; + result.push(...extras); + } + return result; + }; +} +/** + * Convert a single token into a path building function. + */ +function tokenToFunction(token, delimiter, encode) { + if (token.type === "text") + return () => [token.value]; + if (token.type === "group") { + const fn = tokensToFunction(token.tokens, delimiter, encode); + return (data) => { + const [value, ...missing] = fn(data); + if (!missing.length) + return [value]; + return [""]; + }; + } + const encodeValue = encode || NOOP_VALUE; + if (token.type === "wildcard" && encode !== false) { + return (data) => { + const value = data[token.name]; + if (value == null) + return ["", token.name]; + if (!Array.isArray(value) || value.length === 0) { + throw new TypeError(`Expected "${token.name}" to be a non-empty array`); + } + return [ + value + .map((value, index) => { + if (typeof value !== "string") { + throw new TypeError(`Expected "${token.name}/${index}" to be a string`); + } + return encodeValue(value); + }) + .join(delimiter), + ]; + }; + } + return (data) => { + const value = data[token.name]; + if (value == null) + return ["", token.name]; + if (typeof value !== "string") { + throw new TypeError(`Expected "${token.name}" to be a string`); + } + return [encodeValue(value)]; + }; +} +/** + * Transform a path into a match function. + */ +function match(path, options = {}) { + const { decode = decodeURIComponent, delimiter = DEFAULT_DELIMITER } = options; + const { regexp, keys } = pathToRegexp(path, options); + const decoders = keys.map((key) => { + if (decode === false) + return NOOP_VALUE; + if (key.type === "param") + return decode; + return (value) => value.split(delimiter).map(decode); + }); + return function match(input) { + const m = regexp.exec(input); + if (!m) + return false; + const path = m[0]; + const params = Object.create(null); + for (let i = 1; i < m.length; i++) { + if (m[i] === undefined) + continue; + const key = keys[i - 1]; + const decoder = decoders[i - 1]; + params[key.name] = decoder(m[i]); + } + return { path, params }; + }; +} +function pathToRegexp(path, options = {}) { + const { delimiter = DEFAULT_DELIMITER, end = true, sensitive = false, trailing = true, } = options; + const keys = []; + const flags = sensitive ? "" : "i"; + const sources = []; + for (const input of pathsToArray(path, [])) { + const data = typeof input === "object" ? input : parse(input, options); + for (const tokens of flatten(data.tokens, 0, [])) { + sources.push(toRegExpSource(tokens, delimiter, keys, data.originalPath)); + } + } + let pattern = `^(?:${sources.join("|")})`; + if (trailing) + pattern += `(?:${escape(delimiter)}$)?`; + pattern += end ? "$" : `(?=${escape(delimiter)}|$)`; + const regexp = new RegExp(pattern, flags); + return { regexp, keys }; +} +/** + * Convert a path or array of paths into a flat array. + */ +function pathsToArray(paths, init) { + if (Array.isArray(paths)) { + for (const p of paths) + pathsToArray(p, init); + } + else { + init.push(paths); + } + return init; +} +/** + * Generate a flat list of sequence tokens from the given tokens. + */ +function* flatten(tokens, index, init) { + if (index === tokens.length) { + return yield init; + } + const token = tokens[index]; + if (token.type === "group") { + for (const seq of flatten(token.tokens, 0, init.slice())) { + yield* flatten(tokens, index + 1, seq); + } + } + else { + init.push(token); + } + yield* flatten(tokens, index + 1, init); +} +/** + * Transform a flat sequence of tokens into a regular expression. + */ +function toRegExpSource(tokens, delimiter, keys, originalPath) { + let result = ""; + let backtrack = ""; + let isSafeSegmentParam = true; + for (const token of tokens) { + if (token.type === "text") { + result += escape(token.value); + backtrack += token.value; + isSafeSegmentParam || (isSafeSegmentParam = token.value.includes(delimiter)); + continue; + } + if (token.type === "param" || token.type === "wildcard") { + if (!isSafeSegmentParam && !backtrack) { + throw new PathError(`Missing text before "${token.name}" ${token.type}`, originalPath); + } + if (token.type === "param") { + result += `(${negate(delimiter, isSafeSegmentParam ? "" : backtrack)}+)`; + } + else { + result += `([\\s\\S]+)`; + } + keys.push(token); + backtrack = ""; + isSafeSegmentParam = false; + continue; + } + } + return result; +} +/** + * Block backtracking on previous text and ignore delimiter string. + */ +function negate(delimiter, backtrack) { + if (backtrack.length < 2) { + if (delimiter.length < 2) + return `[^${escape(delimiter + backtrack)}]`; + return `(?:(?!${escape(delimiter)})[^${escape(backtrack)}])`; + } + if (delimiter.length < 2) { + return `(?:(?!${escape(backtrack)})[^${escape(delimiter)}])`; + } + return `(?:(?!${escape(backtrack)}|${escape(delimiter)})[\\s\\S])`; +} +/** + * Stringify an array of tokens into a path string. + */ +function stringifyTokens(tokens) { + let value = ""; + let i = 0; + function name(value) { + const isSafe = isNameSafe(value) && isNextNameSafe(tokens[i]); + return isSafe ? value : JSON.stringify(value); + } + while (i < tokens.length) { + const token = tokens[i++]; + if (token.type === "text") { + value += escapeText(token.value); + continue; + } + if (token.type === "group") { + value += `{${stringifyTokens(token.tokens)}}`; + continue; + } + if (token.type === "param") { + value += `:${name(token.name)}`; + continue; + } + if (token.type === "wildcard") { + value += `*${name(token.name)}`; + continue; + } + throw new TypeError(`Unknown token type: ${token.type}`); + } + return value; +} +/** + * Stringify token data into a path string. + */ +function stringify(data) { + return stringifyTokens(data.tokens); +} +/** + * Validate the parameter name contains valid ID characters. + */ +function isNameSafe(name) { + const [first, ...rest] = name; + return ID_START.test(first) && rest.every((char) => ID_CONTINUE.test(char)); +} +/** + * Validate the next token does not interfere with the current param name. + */ +function isNextNameSafe(token) { + if (token && token.type === "text") + return !ID_CONTINUE.test(token.value[0]); + return true; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/path-to-regexp/dist/index.js.map b/node_modules/path-to-regexp/dist/index.js.map new file mode 100644 index 000000000..ec14c730a --- /dev/null +++ b/node_modules/path-to-regexp/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AA4LA,sBA8GC;AAKD,0BAgBC;AAgHD,sBA+BC;AAED,oCA2BC;AAmJD,8BAEC;AAhoBD,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,UAAU,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,KAAK,CAAC;AAC5C,MAAM,QAAQ,GAAG,qBAAqB,CAAC;AACvC,MAAM,WAAW,GAAG,mCAAmC,CAAC;AAkFxD,MAAM,aAAa,GAA8B;IAC/C,UAAU;IACV,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;IACR,YAAY;IACZ,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;IACR,GAAG,EAAE,GAAG;CACT,CAAC;AAEF;;GAEG;AACH,SAAS,UAAU,CAAC,GAAW;IAC7B,OAAO,GAAG,CAAC,OAAO,CAAC,oBAAoB,EAAE,MAAM,CAAC,CAAC;AACnD,CAAC;AAED;;GAEG;AACH,SAAS,MAAM,CAAC,GAAW;IACzB,OAAO,GAAG,CAAC,OAAO,CAAC,sBAAsB,EAAE,MAAM,CAAC,CAAC;AACrD,CAAC;AAiDD;;GAEG;AACH,MAAa,SAAS;IACpB,YACkB,MAAe,EACf,YAAqB;QADrB,WAAM,GAAN,MAAM,CAAS;QACf,iBAAY,GAAZ,YAAY,CAAS;IACpC,CAA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CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;YAChC,SAAS;QACX,CAAC;QAED,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YAC9B,KAAK,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;YAChC,SAAS;QACX,CAAC;QAED,MAAM,IAAI,SAAS,CAAC,uBAAwB,KAAa,CAAC,IAAI,EAAE,CAAC,CAAC;IACpE,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;GAEG;AACH,SAAgB,SAAS,CAAC,IAAe;IACvC,OAAO,eAAe,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACtC,CAAC;AAED;;GAEG;AACH,SAAS,UAAU,CAAC,IAAY;IAC9B,MAAM,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;IAC9B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAC9E,CAAC;AAED;;GAEG;AACH,SAAS,cAAc,CAAC,KAAwB;IAC9C,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7E,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["const DEFAULT_DELIMITER = \"/\";\nconst NOOP_VALUE = (value: string) => value;\nconst ID_START = /^[$_\\p{ID_Start}]$/u;\nconst ID_CONTINUE = /^[$\\u200c\\u200d\\p{ID_Continue}]$/u;\n\n/**\n * Encode a string into another string.\n */\nexport type Encode = (value: string) => string;\n\n/**\n * Decode a string into another string.\n */\nexport type Decode = (value: string) => string;\n\nexport interface ParseOptions {\n /**\n * A function for encoding input strings.\n */\n encodePath?: Encode;\n}\n\nexport interface PathToRegexpOptions {\n /**\n * Matches the path completely without trailing characters. (default: `true`)\n */\n end?: boolean;\n /**\n * Allows optional trailing delimiter to match. (default: `true`)\n */\n trailing?: boolean;\n /**\n * Match will be case sensitive. (default: `false`)\n */\n sensitive?: boolean;\n /**\n * The default delimiter for segments. (default: `'/'`)\n */\n delimiter?: string;\n}\n\nexport interface MatchOptions extends PathToRegexpOptions {\n /**\n * Function for decoding strings for params, or `false` to disable entirely. (default: `decodeURIComponent`)\n */\n decode?: Decode | false;\n}\n\nexport interface CompileOptions {\n /**\n * Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`)\n */\n encode?: Encode | false;\n /**\n * The default delimiter for segments. (default: `'/'`)\n */\n delimiter?: string;\n}\n\ntype TokenType =\n | \"{\"\n | \"}\"\n | \"wildcard\"\n | \"param\"\n | \"char\"\n | \"escape\"\n | \"end\"\n // Reserved for use or ambiguous due to past use.\n | \"(\"\n | \")\"\n | \"[\"\n | \"]\"\n | \"+\"\n | \"?\"\n | \"!\";\n\n/**\n * Tokenizer results.\n */\ninterface LexToken {\n type: TokenType;\n index: number;\n value: string;\n}\n\nconst SIMPLE_TOKENS: Record = {\n // Groups.\n \"{\": \"{\",\n \"}\": \"}\",\n // Reserved.\n \"(\": \"(\",\n \")\": \")\",\n \"[\": \"[\",\n \"]\": \"]\",\n \"+\": \"+\",\n \"?\": \"?\",\n \"!\": \"!\",\n};\n\n/**\n * Escape text for stringify to path.\n */\nfunction escapeText(str: string) {\n return str.replace(/[{}()\\[\\]+?!:*\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Escape a regular expression string.\n */\nfunction escape(str: string) {\n return str.replace(/[.+*?^${}()[\\]|/\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Plain text.\n */\nexport interface Text {\n type: \"text\";\n value: string;\n}\n\n/**\n * A parameter designed to match arbitrary text within a segment.\n */\nexport interface Parameter {\n type: \"param\";\n name: string;\n}\n\n/**\n * A wildcard parameter designed to match multiple segments.\n */\nexport interface Wildcard {\n type: \"wildcard\";\n name: string;\n}\n\n/**\n * A set of possible tokens to expand when matching.\n */\nexport interface Group {\n type: \"group\";\n tokens: Token[];\n}\n\n/**\n * A token that corresponds with a regexp capture.\n */\nexport type Key = Parameter | Wildcard;\n\n/**\n * A sequence of `path-to-regexp` keys that match capturing groups.\n */\nexport type Keys = Array;\n\n/**\n * A sequence of path match characters.\n */\nexport type Token = Text | Parameter | Wildcard | Group;\n\n/**\n * Tokenized path instance.\n */\nexport class TokenData {\n constructor(\n public readonly tokens: Token[],\n public readonly originalPath?: string,\n ) {}\n}\n\n/**\n * ParseError is thrown when there is an error processing the path.\n */\nexport class PathError extends TypeError {\n constructor(\n message: string,\n public readonly originalPath: string | undefined,\n ) {\n let text = message;\n if (originalPath) text += `: ${originalPath}`;\n text += `; visit https://git.new/pathToRegexpError for info`;\n super(text);\n }\n}\n\n/**\n * Parse a string for the raw tokens.\n */\nexport function parse(str: string, options: ParseOptions = {}): TokenData {\n const { encodePath = NOOP_VALUE } = options;\n const chars = [...str];\n const tokens: Array = [];\n let index = 0;\n let pos = 0;\n\n function name() {\n let value = \"\";\n\n if (ID_START.test(chars[index])) {\n do {\n value += chars[index++];\n } while (ID_CONTINUE.test(chars[index]));\n } else if (chars[index] === '\"') {\n let quoteStart = index;\n\n while (index++ < chars.length) {\n if (chars[index] === '\"') {\n index++;\n quoteStart = 0;\n break;\n }\n\n // Increment over escape characters.\n if (chars[index] === \"\\\\\") index++;\n\n value += chars[index];\n }\n\n if (quoteStart) {\n throw new PathError(`Unterminated quote at index ${quoteStart}`, str);\n }\n }\n\n if (!value) {\n throw new PathError(`Missing parameter name at index ${index}`, str);\n }\n\n return value;\n }\n\n while (index < chars.length) {\n const value = chars[index];\n const type = SIMPLE_TOKENS[value];\n\n if (type) {\n tokens.push({ type, index: index++, value });\n } else if (value === \"\\\\\") {\n tokens.push({ type: \"escape\", index: index++, value: chars[index++] });\n } else if (value === \":\") {\n tokens.push({ type: \"param\", index: index++, value: name() });\n } else if (value === \"*\") {\n tokens.push({ type: \"wildcard\", index: index++, value: name() });\n } else {\n tokens.push({ type: \"char\", index: index++, value });\n }\n }\n\n tokens.push({ type: \"end\", index, value: \"\" });\n\n function consumeUntil(endType: TokenType): Token[] {\n const output: Token[] = [];\n\n while (true) {\n const token = tokens[pos++];\n if (token.type === endType) break;\n\n if (token.type === \"char\" || token.type === \"escape\") {\n let path = token.value;\n let cur = tokens[pos];\n\n while (cur.type === \"char\" || cur.type === \"escape\") {\n path += cur.value;\n cur = tokens[++pos];\n }\n\n output.push({\n type: \"text\",\n value: encodePath(path),\n });\n continue;\n }\n\n if (token.type === \"param\" || token.type === \"wildcard\") {\n output.push({\n type: token.type,\n name: token.value,\n });\n continue;\n }\n\n if (token.type === \"{\") {\n output.push({\n type: \"group\",\n tokens: consumeUntil(\"}\"),\n });\n continue;\n }\n\n throw new PathError(\n `Unexpected ${token.type} at index ${token.index}, expected ${endType}`,\n str,\n );\n }\n\n return output;\n }\n\n return new TokenData(consumeUntil(\"end\"), str);\n}\n\n/**\n * Compile a string to a template function for the path.\n */\nexport function compile

(\n path: Path,\n options: CompileOptions & ParseOptions = {},\n) {\n const { encode = encodeURIComponent, delimiter = DEFAULT_DELIMITER } =\n options;\n const data = typeof path === \"object\" ? path : parse(path, options);\n const fn = tokensToFunction(data.tokens, delimiter, encode);\n\n return function path(params: P = {} as P) {\n const [path, ...missing] = fn(params);\n if (missing.length) {\n throw new TypeError(`Missing parameters: ${missing.join(\", \")}`);\n }\n return path;\n };\n}\n\nexport type ParamData = Partial>;\nexport type PathFunction

= (data?: P) => string;\n\nfunction tokensToFunction(\n tokens: Token[],\n delimiter: string,\n encode: Encode | false,\n) {\n const encoders = tokens.map((token) =>\n tokenToFunction(token, delimiter, encode),\n );\n\n return (data: ParamData) => {\n const result: string[] = [\"\"];\n\n for (const encoder of encoders) {\n const [value, ...extras] = encoder(data);\n result[0] += value;\n result.push(...extras);\n }\n\n return result;\n };\n}\n\n/**\n * Convert a single token into a path building function.\n */\nfunction tokenToFunction(\n token: Token,\n delimiter: string,\n encode: Encode | false,\n): (data: ParamData) => string[] {\n if (token.type === \"text\") return () => [token.value];\n\n if (token.type === \"group\") {\n const fn = tokensToFunction(token.tokens, delimiter, encode);\n\n return (data) => {\n const [value, ...missing] = fn(data);\n if (!missing.length) return [value];\n return [\"\"];\n };\n }\n\n const encodeValue = encode || NOOP_VALUE;\n\n if (token.type === \"wildcard\" && encode !== false) {\n return (data) => {\n const value = data[token.name];\n if (value == null) return [\"\", token.name];\n\n if (!Array.isArray(value) || value.length === 0) {\n throw new TypeError(`Expected \"${token.name}\" to be a non-empty array`);\n }\n\n return [\n value\n .map((value, index) => {\n if (typeof value !== \"string\") {\n throw new TypeError(\n `Expected \"${token.name}/${index}\" to be a string`,\n );\n }\n\n return encodeValue(value);\n })\n .join(delimiter),\n ];\n };\n }\n\n return (data) => {\n const value = data[token.name];\n if (value == null) return [\"\", token.name];\n\n if (typeof value !== \"string\") {\n throw new TypeError(`Expected \"${token.name}\" to be a string`);\n }\n\n return [encodeValue(value)];\n };\n}\n\n/**\n * A match result contains data about the path match.\n */\nexport interface MatchResult

{\n path: string;\n params: P;\n}\n\n/**\n * A match is either `false` (no match) or a match result.\n */\nexport type Match

= false | MatchResult

;\n\n/**\n * The match function takes a string and returns whether it matched the path.\n */\nexport type MatchFunction

= (path: string) => Match

;\n\n/**\n * Supported path types.\n */\nexport type Path = string | TokenData;\n\n/**\n * Transform a path into a match function.\n */\nexport function match

(\n path: Path | Path[],\n options: MatchOptions & ParseOptions = {},\n): MatchFunction

{\n const { decode = decodeURIComponent, delimiter = DEFAULT_DELIMITER } =\n options;\n const { regexp, keys } = pathToRegexp(path, options);\n\n const decoders = keys.map((key) => {\n if (decode === false) return NOOP_VALUE;\n if (key.type === \"param\") return decode;\n return (value: string) => value.split(delimiter).map(decode);\n });\n\n return function match(input: string) {\n const m = regexp.exec(input);\n if (!m) return false;\n\n const path = m[0];\n const params = Object.create(null);\n\n for (let i = 1; i < m.length; i++) {\n if (m[i] === undefined) continue;\n\n const key = keys[i - 1];\n const decoder = decoders[i - 1];\n params[key.name] = decoder(m[i]);\n }\n\n return { path, params };\n };\n}\n\nexport function pathToRegexp(\n path: Path | Path[],\n options: PathToRegexpOptions & ParseOptions = {},\n) {\n const {\n delimiter = DEFAULT_DELIMITER,\n end = true,\n sensitive = false,\n trailing = true,\n } = options;\n const keys: Keys = [];\n const flags = sensitive ? \"\" : \"i\";\n const sources: string[] = [];\n\n for (const input of pathsToArray(path, [])) {\n const data = typeof input === \"object\" ? input : parse(input, options);\n for (const tokens of flatten(data.tokens, 0, [])) {\n sources.push(toRegExpSource(tokens, delimiter, keys, data.originalPath));\n }\n }\n\n let pattern = `^(?:${sources.join(\"|\")})`;\n if (trailing) pattern += `(?:${escape(delimiter)}$)?`;\n pattern += end ? \"$\" : `(?=${escape(delimiter)}|$)`;\n\n const regexp = new RegExp(pattern, flags);\n return { regexp, keys };\n}\n\n/**\n * Convert a path or array of paths into a flat array.\n */\nfunction pathsToArray(paths: Path | Path[], init: Path[]): Path[] {\n if (Array.isArray(paths)) {\n for (const p of paths) pathsToArray(p, init);\n } else {\n init.push(paths);\n }\n return init;\n}\n\n/**\n * Flattened token set.\n */\ntype FlatToken = Text | Parameter | Wildcard;\n\n/**\n * Generate a flat list of sequence tokens from the given tokens.\n */\nfunction* flatten(\n tokens: Token[],\n index: number,\n init: FlatToken[],\n): Generator {\n if (index === tokens.length) {\n return yield init;\n }\n\n const token = tokens[index];\n\n if (token.type === \"group\") {\n for (const seq of flatten(token.tokens, 0, init.slice())) {\n yield* flatten(tokens, index + 1, seq);\n }\n } else {\n init.push(token);\n }\n\n yield* flatten(tokens, index + 1, init);\n}\n\n/**\n * Transform a flat sequence of tokens into a regular expression.\n */\nfunction toRegExpSource(\n tokens: FlatToken[],\n delimiter: string,\n keys: Keys,\n originalPath: string | undefined,\n): string {\n let result = \"\";\n let backtrack = \"\";\n let isSafeSegmentParam = true;\n\n for (const token of tokens) {\n if (token.type === \"text\") {\n result += escape(token.value);\n backtrack += token.value;\n isSafeSegmentParam ||= token.value.includes(delimiter);\n continue;\n }\n\n if (token.type === \"param\" || token.type === \"wildcard\") {\n if (!isSafeSegmentParam && !backtrack) {\n throw new PathError(\n `Missing text before \"${token.name}\" ${token.type}`,\n originalPath,\n );\n }\n\n if (token.type === \"param\") {\n result += `(${negate(delimiter, isSafeSegmentParam ? \"\" : backtrack)}+)`;\n } else {\n result += `([\\\\s\\\\S]+)`;\n }\n\n keys.push(token);\n backtrack = \"\";\n isSafeSegmentParam = false;\n continue;\n }\n }\n\n return result;\n}\n\n/**\n * Block backtracking on previous text and ignore delimiter string.\n */\nfunction negate(delimiter: string, backtrack: string): string {\n if (backtrack.length < 2) {\n if (delimiter.length < 2) return `[^${escape(delimiter + backtrack)}]`;\n return `(?:(?!${escape(delimiter)})[^${escape(backtrack)}])`;\n }\n if (delimiter.length < 2) {\n return `(?:(?!${escape(backtrack)})[^${escape(delimiter)}])`;\n }\n return `(?:(?!${escape(backtrack)}|${escape(delimiter)})[\\\\s\\\\S])`;\n}\n\n/**\n * Stringify an array of tokens into a path string.\n */\nfunction stringifyTokens(tokens: Token[]): string {\n let value = \"\";\n let i = 0;\n\n function name(value: string) {\n const isSafe = isNameSafe(value) && isNextNameSafe(tokens[i]);\n return isSafe ? value : JSON.stringify(value);\n }\n\n while (i < tokens.length) {\n const token = tokens[i++];\n\n if (token.type === \"text\") {\n value += escapeText(token.value);\n continue;\n }\n\n if (token.type === \"group\") {\n value += `{${stringifyTokens(token.tokens)}}`;\n continue;\n }\n\n if (token.type === \"param\") {\n value += `:${name(token.name)}`;\n continue;\n }\n\n if (token.type === \"wildcard\") {\n value += `*${name(token.name)}`;\n continue;\n }\n\n throw new TypeError(`Unknown token type: ${(token as any).type}`);\n }\n\n return value;\n}\n\n/**\n * Stringify token data into a path string.\n */\nexport function stringify(data: TokenData): string {\n return stringifyTokens(data.tokens);\n}\n\n/**\n * Validate the parameter name contains valid ID characters.\n */\nfunction isNameSafe(name: string): boolean {\n const [first, ...rest] = name;\n return ID_START.test(first) && rest.every((char) => ID_CONTINUE.test(char));\n}\n\n/**\n * Validate the next token does not interfere with the current param name.\n */\nfunction isNextNameSafe(token: Token | undefined): boolean {\n if (token && token.type === \"text\") return !ID_CONTINUE.test(token.value[0]);\n return true;\n}\n"]} \ No newline at end of file diff --git a/node_modules/path-to-regexp/package.json b/node_modules/path-to-regexp/package.json new file mode 100644 index 000000000..7ae266ef7 --- /dev/null +++ b/node_modules/path-to-regexp/package.json @@ -0,0 +1,64 @@ +{ + "name": "path-to-regexp", + "version": "8.3.0", + "description": "Express style path to RegExp utility", + "keywords": [ + "express", + "regexp", + "route", + "routing" + ], + "repository": { + "type": "git", + "url": "https://github.com/pillarjs/path-to-regexp.git" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "license": "MIT", + "exports": "./dist/index.js", + "main": "dist/index.js", + "typings": "dist/index.d.ts", + "files": [ + "dist/" + ], + "scripts": { + "bench": "vitest bench", + "build": "ts-scripts build", + "format": "ts-scripts format", + "lint": "ts-scripts lint", + "prepare": "ts-scripts install && npm run build", + "size": "size-limit", + "specs": "ts-scripts specs", + "test": "ts-scripts test && npm run size" + }, + "devDependencies": { + "@borderless/ts-scripts": "^0.15.0", + "@size-limit/preset-small-lib": "^11.1.2", + "@types/node": "^22.7.2", + "@types/semver": "^7.3.1", + "@vitest/coverage-v8": "^3.0.5", + "recheck": "^4.4.5", + "size-limit": "^11.1.2", + "typescript": "^5.7.3", + "vitest": "^3.0.5" + }, + "publishConfig": { + "access": "public" + }, + "size-limit": [ + { + "path": "dist/index.js", + "limit": "2 kB" + } + ], + "ts-scripts": { + "dist": [ + "dist" + ], + "project": [ + "tsconfig.build.json" + ] + } +} diff --git a/node_modules/pkce-challenge/CHANGELOG.md b/node_modules/pkce-challenge/CHANGELOG.md new file mode 100644 index 000000000..09e31b818 --- /dev/null +++ b/node_modules/pkce-challenge/CHANGELOG.md @@ -0,0 +1,114 @@ +# Changelog + +## [5.0.1](https://github.com/crouchcd/pkce-challenge/releases/tag/5.0.1) - 2025-11-22 + +## What's Changed +* Use even distribution by @RobinVdBroeck in https://github.com/crouchcd/pkce-challenge/pull/38 + +## New Contributors +* @RobinVdBroeck made their first contribution in https://github.com/crouchcd/pkce-challenge/pull/38 + +**Full Changelog**: https://github.com/crouchcd/pkce-challenge/compare/5.0.0...5.0.1 + +## [5.0.0](https://github.com/crouchcd/pkce-challenge/releases/tag/5.0.0) - 2025-03-30 + +## What's Changed +* fix: add support for commonjs module by @li-yechao in https://github.com/crouchcd/pkce-challenge/pull/32 + +## New Contributors +* @li-yechao made their first contribution in https://github.com/crouchcd/pkce-challenge/pull/32 + +**Full Changelog**: https://github.com/crouchcd/pkce-challenge/compare/4.1.0...5.0.0 + +## [4.1.0](https://github.com/crouchcd/pkce-challenge/releases/tag/4.1.0) - 2024-01-25 + +## What's Changed +* Separate entrypoints for node and browser by @mdarocha in https://github.com/crouchcd/pkce-challenge/pull/25 + +## New Contributors +* @mdarocha made their first contribution in https://github.com/crouchcd/pkce-challenge/pull/25 + +**Full Changelog**: https://github.com/crouchcd/pkce-challenge/compare/4.0.1...4.1.0 + +## [4.0.1](https://github.com/crouchcd/pkce-challenge/releases/tag/4.0.1) - 2023-05-11 + +- chore: update README (dc76443a502c25ce98258cea3f25fd78a22cb2a8) +- chore: specify node engines >= 16.20.0 (5e7fc5edbcd0e19f99fc11a9705e5e708a100be8) + +## [4.0.0](https://github.com/crouchcd/pkce-challenge/releases/tag/4.0.0) - 2023-05-11 + +- BREAKING CHANGE: Use Web Cryptography API (#20), closes #21, #18 + +### Contributors + +- [saschanaz](https://github.com/saschanaz) + +## [3.1.0] - 2023-03-29 + +- chore: Use ES6 imports for crypto-js to reduce bundle size + +### Contributors + +- [gretchenfitze] + +## [3.0.0] - 2022-03-28 + +- feat!: depend on crypto-js for node/browser compatibility. Using Typescript with Parcel. + +```js +// commonjs +const pkceChallenge = require("pkce-challenge").default; + +// es modules +import pkceChallenge from "pkce-challenge"; +``` + +## [2.2.0] - 2021-05-19 + +### Added + +- `generateChallenge` exported from index + +### Contributors + +- [SeyyedKhandon] + +## [2.1.0] - 2019-12-20 + +### Added + +- `verifyChallenge` exported from index + +### Changed + +- code/comment formatting +- refactored `random` function + +## [2.0.0] - 2019-10-18 + +### Added + +- CHANGELOG +- typescript definition +- Cryptographically secured method for generating code verifier +- Method for base64 url encoding + +### Removed + +- `generateVerifier` export from index +- `generateChallenge` export from index +- `base64url` npm dependency +- `randomatic` npm dependency + +### Contributors + +- [lordnox] + +[gretchenfitze]: https://github.com/gretchenfitze +[seyyedkhandon]: https://github.com/SeyyedKhandon +[lordnox]: https://github.com/lordnox +[3.1.0]: https://github.com/crouchcd/pkce-challenge/releases/tag/3.1.0 +[3.0.0]: https://github.com/crouchcd/pkce-challenge/releases/tag/3.0.0 +[2.2.0]: https://github.com/crouchcd/pkce-challenge/releases/tag/2.2.0 +[2.1.0]: https://github.com/crouchcd/pkce-challenge/releases/tag/2.1.0 +[2.0.0]: https://github.com/crouchcd/pkce-challenge/releases/tag/2.0.0 diff --git a/node_modules/pkce-challenge/LICENSE b/node_modules/pkce-challenge/LICENSE new file mode 100644 index 000000000..8b23445f4 --- /dev/null +++ b/node_modules/pkce-challenge/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 + +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/pkce-challenge/README.md b/node_modules/pkce-challenge/README.md new file mode 100644 index 000000000..e2218b629 --- /dev/null +++ b/node_modules/pkce-challenge/README.md @@ -0,0 +1,55 @@ +# pkce-challenge + +Generate or verify a Proof Key for Code Exchange (PKCE) challenge pair. + +Read more about [PKCE](https://www.oauth.com/oauth2-servers/pkce/authorization-request/). + +## Installation + +```bash +npm install pkce-challenge +``` + +## Usage + +Default length for the verifier is 43 + +```js +import pkceChallenge from "pkce-challenge"; + +await pkceChallenge(); +``` + +gives something like: + +```js +{ + code_verifier: 'u1ta-MQ0e7TcpHjgz33M2DcBnOQu~aMGxuiZt0QMD1C', + code_challenge: 'CUZX5qE8Wvye6kS_SasIsa8MMxacJftmWdsIA_iKp3I' +} +``` + +### Specify a verifier length + +```js +const challenge = await pkceChallenge(128); + +challenge.code_verifier.length === 128; // true +``` + +### Challenge verification + +```js +import { verifyChallenge } from "pkce-challenge"; + +(await verifyChallenge(challenge.code_verifier, challenge.code_challenge)) === + true; // true +``` + +### Challenge generation from existing code verifier + +```js +import { generateChallenge } from "pkce-challenge"; + +(await generateChallenge(challenge.code_verifier)) === challenge.code_challenge; // true +``` diff --git a/node_modules/pkce-challenge/dist/index.browser.d.ts b/node_modules/pkce-challenge/dist/index.browser.d.ts new file mode 100644 index 000000000..602e32ee9 --- /dev/null +++ b/node_modules/pkce-challenge/dist/index.browser.d.ts @@ -0,0 +1,19 @@ +/** Generate a PKCE code challenge from a code verifier + * @param code_verifier + * @returns The base64 url encoded code challenge + */ +export declare function generateChallenge(code_verifier: string): Promise; +/** Generate a PKCE challenge pair + * @param length Length of the verifer (between 43-128). Defaults to 43. + * @returns PKCE challenge pair + */ +export default function pkceChallenge(length?: number): Promise<{ + code_verifier: string; + code_challenge: string; +}>; +/** Verify that a code_verifier produces the expected code challenge + * @param code_verifier + * @param expectedChallenge The code challenge to verify + * @returns True if challenges are equal. False otherwise. + */ +export declare function verifyChallenge(code_verifier: string, expectedChallenge: string): Promise; diff --git a/node_modules/pkce-challenge/dist/index.browser.js b/node_modules/pkce-challenge/dist/index.browser.js new file mode 100644 index 000000000..f40d7f7c3 --- /dev/null +++ b/node_modules/pkce-challenge/dist/index.browser.js @@ -0,0 +1,75 @@ +let crypto; +crypto = globalThis.crypto; // web browsers +/** + * Creates an array of length `size` of random bytes + * @param size + * @returns Array of random ints (0 to 255) + */ +async function getRandomValues(size) { + return (await crypto).getRandomValues(new Uint8Array(size)); +} +/** Generate cryptographically strong random string + * @param size The desired length of the string + * @returns The random string + */ +async function random(size) { + const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"; + const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length; + let result = ""; + while (result.length < size) { + const randomBytes = await getRandomValues(size - result.length); + for (const randomByte of randomBytes) { + if (randomByte < evenDistCutoff) { + result += mask[randomByte % mask.length]; + } + } + } + return result; +} +/** Generate a PKCE challenge verifier + * @param length Length of the verifier + * @returns A random verifier `length` characters long + */ +async function generateVerifier(length) { + return await random(length); +} +/** Generate a PKCE code challenge from a code verifier + * @param code_verifier + * @returns The base64 url encoded code challenge + */ +export async function generateChallenge(code_verifier) { + const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier)); + // Generate base64url string + // btoa is deprecated in Node.js but is used here for web browser compatibility + // (which has no good replacement yet, see also https://github.com/whatwg/html/issues/6811) + return btoa(String.fromCharCode(...new Uint8Array(buffer))) + .replace(/\//g, '_') + .replace(/\+/g, '-') + .replace(/=/g, ''); +} +/** Generate a PKCE challenge pair + * @param length Length of the verifer (between 43-128). Defaults to 43. + * @returns PKCE challenge pair + */ +export default async function pkceChallenge(length) { + if (!length) + length = 43; + if (length < 43 || length > 128) { + throw `Expected a length between 43 and 128. Received ${length}.`; + } + const verifier = await generateVerifier(length); + const challenge = await generateChallenge(verifier); + return { + code_verifier: verifier, + code_challenge: challenge, + }; +} +/** Verify that a code_verifier produces the expected code challenge + * @param code_verifier + * @param expectedChallenge The code challenge to verify + * @returns True if challenges are equal. False otherwise. + */ +export async function verifyChallenge(code_verifier, expectedChallenge) { + const actualChallenge = await generateChallenge(code_verifier); + return actualChallenge === expectedChallenge; +} diff --git a/node_modules/pkce-challenge/dist/index.node.cjs b/node_modules/pkce-challenge/dist/index.node.cjs new file mode 100644 index 000000000..774ae407f --- /dev/null +++ b/node_modules/pkce-challenge/dist/index.node.cjs @@ -0,0 +1,83 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.generateChallenge = generateChallenge; +exports.default = pkceChallenge; +exports.verifyChallenge = verifyChallenge; +let crypto; +crypto = + globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL + globalThis.crypto ?? // Node.js >18 + import("node:crypto").then(m => m.webcrypto); // Node.js <18 Non-REPL +/** + * Creates an array of length `size` of random bytes + * @param size + * @returns Array of random ints (0 to 255) + */ +async function getRandomValues(size) { + return (await crypto).getRandomValues(new Uint8Array(size)); +} +/** Generate cryptographically strong random string + * @param size The desired length of the string + * @returns The random string + */ +async function random(size) { + const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"; + const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length; + let result = ""; + while (result.length < size) { + const randomBytes = await getRandomValues(size - result.length); + for (const randomByte of randomBytes) { + if (randomByte < evenDistCutoff) { + result += mask[randomByte % mask.length]; + } + } + } + return result; +} +/** Generate a PKCE challenge verifier + * @param length Length of the verifier + * @returns A random verifier `length` characters long + */ +async function generateVerifier(length) { + return await random(length); +} +/** Generate a PKCE code challenge from a code verifier + * @param code_verifier + * @returns The base64 url encoded code challenge + */ +async function generateChallenge(code_verifier) { + const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier)); + // Generate base64url string + // btoa is deprecated in Node.js but is used here for web browser compatibility + // (which has no good replacement yet, see also https://github.com/whatwg/html/issues/6811) + return btoa(String.fromCharCode(...new Uint8Array(buffer))) + .replace(/\//g, '_') + .replace(/\+/g, '-') + .replace(/=/g, ''); +} +/** Generate a PKCE challenge pair + * @param length Length of the verifer (between 43-128). Defaults to 43. + * @returns PKCE challenge pair + */ +async function pkceChallenge(length) { + if (!length) + length = 43; + if (length < 43 || length > 128) { + throw `Expected a length between 43 and 128. Received ${length}.`; + } + const verifier = await generateVerifier(length); + const challenge = await generateChallenge(verifier); + return { + code_verifier: verifier, + code_challenge: challenge, + }; +} +/** Verify that a code_verifier produces the expected code challenge + * @param code_verifier + * @param expectedChallenge The code challenge to verify + * @returns True if challenges are equal. False otherwise. + */ +async function verifyChallenge(code_verifier, expectedChallenge) { + const actualChallenge = await generateChallenge(code_verifier); + return actualChallenge === expectedChallenge; +} diff --git a/node_modules/pkce-challenge/dist/index.node.d.cts b/node_modules/pkce-challenge/dist/index.node.d.cts new file mode 100644 index 000000000..602e32ee9 --- /dev/null +++ b/node_modules/pkce-challenge/dist/index.node.d.cts @@ -0,0 +1,19 @@ +/** Generate a PKCE code challenge from a code verifier + * @param code_verifier + * @returns The base64 url encoded code challenge + */ +export declare function generateChallenge(code_verifier: string): Promise; +/** Generate a PKCE challenge pair + * @param length Length of the verifer (between 43-128). Defaults to 43. + * @returns PKCE challenge pair + */ +export default function pkceChallenge(length?: number): Promise<{ + code_verifier: string; + code_challenge: string; +}>; +/** Verify that a code_verifier produces the expected code challenge + * @param code_verifier + * @param expectedChallenge The code challenge to verify + * @returns True if challenges are equal. False otherwise. + */ +export declare function verifyChallenge(code_verifier: string, expectedChallenge: string): Promise; diff --git a/node_modules/pkce-challenge/dist/index.node.d.ts b/node_modules/pkce-challenge/dist/index.node.d.ts new file mode 100644 index 000000000..602e32ee9 --- /dev/null +++ b/node_modules/pkce-challenge/dist/index.node.d.ts @@ -0,0 +1,19 @@ +/** Generate a PKCE code challenge from a code verifier + * @param code_verifier + * @returns The base64 url encoded code challenge + */ +export declare function generateChallenge(code_verifier: string): Promise; +/** Generate a PKCE challenge pair + * @param length Length of the verifer (between 43-128). Defaults to 43. + * @returns PKCE challenge pair + */ +export default function pkceChallenge(length?: number): Promise<{ + code_verifier: string; + code_challenge: string; +}>; +/** Verify that a code_verifier produces the expected code challenge + * @param code_verifier + * @param expectedChallenge The code challenge to verify + * @returns True if challenges are equal. False otherwise. + */ +export declare function verifyChallenge(code_verifier: string, expectedChallenge: string): Promise; diff --git a/node_modules/pkce-challenge/dist/index.node.js b/node_modules/pkce-challenge/dist/index.node.js new file mode 100644 index 000000000..56b47dbe8 --- /dev/null +++ b/node_modules/pkce-challenge/dist/index.node.js @@ -0,0 +1,78 @@ +let crypto; +crypto = + globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL + globalThis.crypto ?? // Node.js >18 + import("node:crypto").then(m => m.webcrypto); // Node.js <18 Non-REPL +/** + * Creates an array of length `size` of random bytes + * @param size + * @returns Array of random ints (0 to 255) + */ +async function getRandomValues(size) { + return (await crypto).getRandomValues(new Uint8Array(size)); +} +/** Generate cryptographically strong random string + * @param size The desired length of the string + * @returns The random string + */ +async function random(size) { + const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"; + const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length; + let result = ""; + while (result.length < size) { + const randomBytes = await getRandomValues(size - result.length); + for (const randomByte of randomBytes) { + if (randomByte < evenDistCutoff) { + result += mask[randomByte % mask.length]; + } + } + } + return result; +} +/** Generate a PKCE challenge verifier + * @param length Length of the verifier + * @returns A random verifier `length` characters long + */ +async function generateVerifier(length) { + return await random(length); +} +/** Generate a PKCE code challenge from a code verifier + * @param code_verifier + * @returns The base64 url encoded code challenge + */ +export async function generateChallenge(code_verifier) { + const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier)); + // Generate base64url string + // btoa is deprecated in Node.js but is used here for web browser compatibility + // (which has no good replacement yet, see also https://github.com/whatwg/html/issues/6811) + return btoa(String.fromCharCode(...new Uint8Array(buffer))) + .replace(/\//g, '_') + .replace(/\+/g, '-') + .replace(/=/g, ''); +} +/** Generate a PKCE challenge pair + * @param length Length of the verifer (between 43-128). Defaults to 43. + * @returns PKCE challenge pair + */ +export default async function pkceChallenge(length) { + if (!length) + length = 43; + if (length < 43 || length > 128) { + throw `Expected a length between 43 and 128. Received ${length}.`; + } + const verifier = await generateVerifier(length); + const challenge = await generateChallenge(verifier); + return { + code_verifier: verifier, + code_challenge: challenge, + }; +} +/** Verify that a code_verifier produces the expected code challenge + * @param code_verifier + * @param expectedChallenge The code challenge to verify + * @returns True if challenges are equal. False otherwise. + */ +export async function verifyChallenge(code_verifier, expectedChallenge) { + const actualChallenge = await generateChallenge(code_verifier); + return actualChallenge === expectedChallenge; +} diff --git a/node_modules/pkce-challenge/package.json b/node_modules/pkce-challenge/package.json new file mode 100644 index 000000000..3d2315888 --- /dev/null +++ b/node_modules/pkce-challenge/package.json @@ -0,0 +1,59 @@ +{ + "name": "pkce-challenge", + "version": "5.0.1", + "description": "Generate or verify a Proof Key for Code Exchange (PKCE) challenge pair", + "browser": "dist/index.browser.js", + "type": "module", + "exports": { + ".": { + "types": { + "require": "./dist/index.node.d.cts", + "import": "./dist/index.node.d.ts" + }, + "browser": { + "types": "./dist/index.browser.d.ts", + "default": "./dist/index.browser.js" + }, + "node": { + "import": "./dist/index.node.js", + "require": "./dist/index.node.cjs" + } + } + }, + "files": [ + "dist/", + "CHANGELOG.md" + ], + "scripts": { + "watch": "tsc --watch --declaration", + "preprocess": "env=browser diverge -f src/index.ts src/index.browser.ts && env=node diverge -f src/index.ts src/index.node.ts && env=node diverge -f src/index.ts src/index.node.cts", + "build": "npm run preprocess && tsc --declaration", + "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js", + "test:bundle": "npm run --prefix browser-test build" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crouchcd/pkce-challenge.git" + }, + "keywords": [ + "PKCE", + "oauth2" + ], + "author": "crouchcd", + "license": "MIT", + "bugs": { + "url": "https://github.com/crouchcd/pkce-challenge/issues" + }, + "homepage": "https://github.com/crouchcd/pkce-challenge#readme", + "engines": { + "node": ">=16.20.0" + }, + "devDependencies": { + "@types/jest": "^29.5.0", + "@types/node": "^18.15.11", + "diverge": "^1.0.2", + "esbuild": "^0.25.2", + "jest": "^29.5.0", + "typescript": "^5.0.3" + } +} diff --git a/node_modules/proxy-addr/HISTORY.md b/node_modules/proxy-addr/HISTORY.md new file mode 100644 index 000000000..8480242a0 --- /dev/null +++ b/node_modules/proxy-addr/HISTORY.md @@ -0,0 +1,161 @@ +2.0.7 / 2021-05-31 +================== + + * deps: forwarded@0.2.0 + - Use `req.socket` over deprecated `req.connection` + +2.0.6 / 2020-02-24 +================== + + * deps: ipaddr.js@1.9.1 + +2.0.5 / 2019-04-16 +================== + + * deps: ipaddr.js@1.9.0 + +2.0.4 / 2018-07-26 +================== + + * deps: ipaddr.js@1.8.0 + +2.0.3 / 2018-02-19 +================== + + * deps: ipaddr.js@1.6.0 + +2.0.2 / 2017-09-24 +================== + + * deps: forwarded@~0.1.2 + - perf: improve header parsing + - perf: reduce overhead when no `X-Forwarded-For` header + +2.0.1 / 2017-09-10 +================== + + * deps: forwarded@~0.1.1 + - Fix trimming leading / trailing OWS + - perf: hoist regular expression + * deps: ipaddr.js@1.5.2 + +2.0.0 / 2017-08-08 +================== + + * Drop support for Node.js below 0.10 + +1.1.5 / 2017-07-25 +================== + + * Fix array argument being altered + * deps: ipaddr.js@1.4.0 + +1.1.4 / 2017-03-24 +================== + + * deps: ipaddr.js@1.3.0 + +1.1.3 / 2017-01-14 +================== + + * deps: ipaddr.js@1.2.0 + +1.1.2 / 2016-05-29 +================== + + * deps: ipaddr.js@1.1.1 + - Fix IPv6-mapped IPv4 validation edge cases + +1.1.1 / 2016-05-03 +================== + + * Fix regression matching mixed versions against multiple subnets + +1.1.0 / 2016-05-01 +================== + + * Fix accepting various invalid netmasks + - IPv4 netmasks must be contingous + - IPv6 addresses cannot be used as a netmask + * deps: ipaddr.js@1.1.0 + +1.0.10 / 2015-12-09 +=================== + + * deps: ipaddr.js@1.0.5 + - Fix regression in `isValid` with non-string arguments + +1.0.9 / 2015-12-01 +================== + + * deps: ipaddr.js@1.0.4 + - Fix accepting some invalid IPv6 addresses + - Reject CIDRs with negative or overlong masks + * perf: enable strict mode + +1.0.8 / 2015-05-10 +================== + + * deps: ipaddr.js@1.0.1 + +1.0.7 / 2015-03-16 +================== + + * deps: ipaddr.js@0.1.9 + - Fix OOM on certain inputs to `isValid` + +1.0.6 / 2015-02-01 +================== + + * deps: ipaddr.js@0.1.8 + +1.0.5 / 2015-01-08 +================== + + * deps: ipaddr.js@0.1.6 + +1.0.4 / 2014-11-23 +================== + + * deps: ipaddr.js@0.1.5 + - Fix edge cases with `isValid` + +1.0.3 / 2014-09-21 +================== + + * Use `forwarded` npm module + +1.0.2 / 2014-09-18 +================== + + * Fix a global leak when multiple subnets are trusted + * Support Node.js 0.6 + * deps: ipaddr.js@0.1.3 + +1.0.1 / 2014-06-03 +================== + + * Fix links in npm package + +1.0.0 / 2014-05-08 +================== + + * Add `trust` argument to determine proxy trust on + * Accepts custom function + * Accepts IPv4/IPv6 address(es) + * Accepts subnets + * Accepts pre-defined names + * Add optional `trust` argument to `proxyaddr.all` to + stop at first untrusted + * Add `proxyaddr.compile` to pre-compile `trust` function + to make subsequent calls faster + +0.0.1 / 2014-05-04 +================== + + * Fix bad npm publish + +0.0.0 / 2014-05-04 +================== + + * Initial release diff --git a/node_modules/proxy-addr/LICENSE b/node_modules/proxy-addr/LICENSE new file mode 100644 index 000000000..cab251c2b --- /dev/null +++ b/node_modules/proxy-addr/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 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/proxy-addr/README.md b/node_modules/proxy-addr/README.md new file mode 100644 index 000000000..69c0b63ea --- /dev/null +++ b/node_modules/proxy-addr/README.md @@ -0,0 +1,139 @@ +# proxy-addr + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Determine address of proxied request + +## Install + +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 proxy-addr +``` + +## API + +```js +var proxyaddr = require('proxy-addr') +``` + +### proxyaddr(req, trust) + +Return the address of the request, using the given `trust` parameter. + +The `trust` argument is a function that returns `true` if you trust +the address, `false` if you don't. The closest untrusted address is +returned. + +```js +proxyaddr(req, function (addr) { return addr === '127.0.0.1' }) +proxyaddr(req, function (addr, i) { return i < 1 }) +``` + +The `trust` arugment may also be a single IP address string or an +array of trusted addresses, as plain IP addresses, CIDR-formatted +strings, or IP/netmask strings. + +```js +proxyaddr(req, '127.0.0.1') +proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']) +proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']) +``` + +This module also supports IPv6. Your IPv6 addresses will be normalized +automatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`). + +```js +proxyaddr(req, '::1') +proxyaddr(req, ['::1/128', 'fe80::/10']) +``` + +This module will automatically work with IPv4-mapped IPv6 addresses +as well to support node.js in IPv6-only mode. This means that you do +not have to specify both `::ffff:a00:1` and `10.0.0.1`. + +As a convenience, this module also takes certain pre-defined names +in addition to IP addresses, which expand into IP addresses: + +```js +proxyaddr(req, 'loopback') +proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']) +``` + + * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and + `127.0.0.1`). + * `linklocal`: IPv4 and IPv6 link-local addresses (like + `fe80::1:1:1:1` and `169.254.0.1`). + * `uniquelocal`: IPv4 private addresses and IPv6 unique-local + addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`). + +When `trust` is specified as a function, it will be called for each +address to determine if it is a trusted address. The function is +given two arguments: `addr` and `i`, where `addr` is a string of +the address to check and `i` is a number that represents the distance +from the socket address. + +### proxyaddr.all(req, [trust]) + +Return all the addresses of the request, optionally stopping at the +first untrusted. This array is ordered from closest to furthest +(i.e. `arr[0] === req.connection.remoteAddress`). + +```js +proxyaddr.all(req) +``` + +The optional `trust` argument takes the same arguments as `trust` +does in `proxyaddr(req, trust)`. + +```js +proxyaddr.all(req, 'loopback') +``` + +### proxyaddr.compile(val) + +Compiles argument `val` into a `trust` function. This function takes +the same arguments as `trust` does in `proxyaddr(req, trust)` and +returns a function suitable for `proxyaddr(req, trust)`. + +```js +var trust = proxyaddr.compile('loopback') +var addr = proxyaddr(req, trust) +``` + +This function is meant to be optimized for use against every request. +It is recommend to compile a trust function up-front for the trusted +configuration and pass that to `proxyaddr(req, trust)` for each request. + +## Testing + +```sh +$ npm test +``` + +## Benchmarks + +```sh +$ npm run-script bench +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/proxy-addr/master?label=ci +[ci-url]: https://github.com/jshttp/proxy-addr/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/proxy-addr/master +[coveralls-url]: https://coveralls.io/r/jshttp/proxy-addr?branch=master +[node-image]: https://badgen.net/npm/node/proxy-addr +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/proxy-addr +[npm-url]: https://npmjs.org/package/proxy-addr +[npm-version-image]: https://badgen.net/npm/v/proxy-addr diff --git a/node_modules/proxy-addr/index.js b/node_modules/proxy-addr/index.js new file mode 100644 index 000000000..a909b0506 --- /dev/null +++ b/node_modules/proxy-addr/index.js @@ -0,0 +1,327 @@ +/*! + * proxy-addr + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = proxyaddr +module.exports.all = alladdrs +module.exports.compile = compile + +/** + * Module dependencies. + * @private + */ + +var forwarded = require('forwarded') +var ipaddr = require('ipaddr.js') + +/** + * Variables. + * @private + */ + +var DIGIT_REGEXP = /^[0-9]+$/ +var isip = ipaddr.isValid +var parseip = ipaddr.parse + +/** + * Pre-defined IP ranges. + * @private + */ + +var IP_RANGES = { + linklocal: ['169.254.0.0/16', 'fe80::/10'], + loopback: ['127.0.0.1/8', '::1/128'], + uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'] +} + +/** + * Get all addresses in the request, optionally stopping + * at the first untrusted. + * + * @param {Object} request + * @param {Function|Array|String} [trust] + * @public + */ + +function alladdrs (req, trust) { + // get addresses + var addrs = forwarded(req) + + if (!trust) { + // Return all addresses + return addrs + } + + if (typeof trust !== 'function') { + trust = compile(trust) + } + + for (var i = 0; i < addrs.length - 1; i++) { + if (trust(addrs[i], i)) continue + + addrs.length = i + 1 + } + + return addrs +} + +/** + * Compile argument into trust function. + * + * @param {Array|String} val + * @private + */ + +function compile (val) { + if (!val) { + throw new TypeError('argument is required') + } + + var trust + + if (typeof val === 'string') { + trust = [val] + } else if (Array.isArray(val)) { + trust = val.slice() + } else { + throw new TypeError('unsupported trust argument') + } + + for (var i = 0; i < trust.length; i++) { + val = trust[i] + + if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) { + continue + } + + // Splice in pre-defined range + val = IP_RANGES[val] + trust.splice.apply(trust, [i, 1].concat(val)) + i += val.length - 1 + } + + return compileTrust(compileRangeSubnets(trust)) +} + +/** + * Compile `arr` elements into range subnets. + * + * @param {Array} arr + * @private + */ + +function compileRangeSubnets (arr) { + var rangeSubnets = new Array(arr.length) + + for (var i = 0; i < arr.length; i++) { + rangeSubnets[i] = parseipNotation(arr[i]) + } + + return rangeSubnets +} + +/** + * Compile range subnet array into trust function. + * + * @param {Array} rangeSubnets + * @private + */ + +function compileTrust (rangeSubnets) { + // Return optimized function based on length + var len = rangeSubnets.length + return len === 0 + ? trustNone + : len === 1 + ? trustSingle(rangeSubnets[0]) + : trustMulti(rangeSubnets) +} + +/** + * Parse IP notation string into range subnet. + * + * @param {String} note + * @private + */ + +function parseipNotation (note) { + var pos = note.lastIndexOf('/') + var str = pos !== -1 + ? note.substring(0, pos) + : note + + if (!isip(str)) { + throw new TypeError('invalid IP address: ' + str) + } + + var ip = parseip(str) + + if (pos === -1 && ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) { + // Store as IPv4 + ip = ip.toIPv4Address() + } + + var max = ip.kind() === 'ipv6' + ? 128 + : 32 + + var range = pos !== -1 + ? note.substring(pos + 1, note.length) + : null + + if (range === null) { + range = max + } else if (DIGIT_REGEXP.test(range)) { + range = parseInt(range, 10) + } else if (ip.kind() === 'ipv4' && isip(range)) { + range = parseNetmask(range) + } else { + range = null + } + + if (range <= 0 || range > max) { + throw new TypeError('invalid range on address: ' + note) + } + + return [ip, range] +} + +/** + * Parse netmask string into CIDR range. + * + * @param {String} netmask + * @private + */ + +function parseNetmask (netmask) { + var ip = parseip(netmask) + var kind = ip.kind() + + return kind === 'ipv4' + ? ip.prefixLengthFromSubnetMask() + : null +} + +/** + * Determine address of proxied request. + * + * @param {Object} request + * @param {Function|Array|String} trust + * @public + */ + +function proxyaddr (req, trust) { + if (!req) { + throw new TypeError('req argument is required') + } + + if (!trust) { + throw new TypeError('trust argument is required') + } + + var addrs = alladdrs(req, trust) + var addr = addrs[addrs.length - 1] + + return addr +} + +/** + * Static trust function to trust nothing. + * + * @private + */ + +function trustNone () { + return false +} + +/** + * Compile trust function for multiple subnets. + * + * @param {Array} subnets + * @private + */ + +function trustMulti (subnets) { + return function trust (addr) { + if (!isip(addr)) return false + + var ip = parseip(addr) + var ipconv + var kind = ip.kind() + + for (var i = 0; i < subnets.length; i++) { + var subnet = subnets[i] + var subnetip = subnet[0] + var subnetkind = subnetip.kind() + var subnetrange = subnet[1] + var trusted = ip + + if (kind !== subnetkind) { + if (subnetkind === 'ipv4' && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + continue + } + + if (!ipconv) { + // Convert IP to match subnet IP kind + ipconv = subnetkind === 'ipv4' + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + trusted = ipconv + } + + if (trusted.match(subnetip, subnetrange)) { + return true + } + } + + return false + } +} + +/** + * Compile trust function for single subnet. + * + * @param {Object} subnet + * @private + */ + +function trustSingle (subnet) { + var subnetip = subnet[0] + var subnetkind = subnetip.kind() + var subnetisipv4 = subnetkind === 'ipv4' + var subnetrange = subnet[1] + + return function trust (addr) { + if (!isip(addr)) return false + + var ip = parseip(addr) + var kind = ip.kind() + + if (kind !== subnetkind) { + if (subnetisipv4 && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + return false + } + + // Convert IP to match subnet IP kind + ip = subnetisipv4 + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + return ip.match(subnetip, subnetrange) + } +} diff --git a/node_modules/proxy-addr/package.json b/node_modules/proxy-addr/package.json new file mode 100644 index 000000000..24ba8f7db --- /dev/null +++ b/node_modules/proxy-addr/package.json @@ -0,0 +1,47 @@ +{ + "name": "proxy-addr", + "description": "Determine address of proxied request", + "version": "2.0.7", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "ip", + "proxy", + "x-forwarded-for" + ], + "repository": "jshttp/proxy-addr", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "devDependencies": { + "benchmark": "2.1.4", + "beautify-benchmark": "0.2.4", + "deep-equal": "1.0.1", + "eslint": "7.26.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.23.4", + "eslint-plugin-markdown": "2.2.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.10" + }, + "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" + } +} diff --git a/node_modules/qs/.editorconfig b/node_modules/qs/.editorconfig new file mode 100644 index 000000000..6adecfbf4 --- /dev/null +++ b/node_modules/qs/.editorconfig @@ -0,0 +1,46 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 160 +quote_type = single + +[test/*] +max_line_length = off + +[LICENSE.md] +indent_size = off + +[*.md] +max_line_length = off + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[LICENSE] +indent_size = 2 +max_line_length = off + +[coverage/**/*] +indent_size = off +indent_style = off +indent = off +max_line_length = off + +[.nycrc] +indent_style = tab + +[tea.yaml] +indent_size = 2 diff --git a/node_modules/qs/.github/FUNDING.yml b/node_modules/qs/.github/FUNDING.yml new file mode 100644 index 000000000..0355f4f5f --- /dev/null +++ b/node_modules/qs/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/qs +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/qs/.github/SECURITY.md b/node_modules/qs/.github/SECURITY.md new file mode 100644 index 000000000..b499cb686 --- /dev/null +++ b/node_modules/qs/.github/SECURITY.md @@ -0,0 +1,11 @@ +# Security + +Please file a private vulnerability report via GitHub, email [@ljharb](https://github.com/ljharb), or see https://tidelift.com/security if you have a potential security vulnerability to report. + +## Incident Response Plan + +Please see our [Incident Response Plan](https://github.com/ljharb/.github/blob/main/INCIDENT_RESPONSE_PLAN.md). + +## Threat Model + +Please see [THREAT_MODEL.md](./THREAT_MODEL.md). diff --git a/node_modules/qs/.github/THREAT_MODEL.md b/node_modules/qs/.github/THREAT_MODEL.md new file mode 100644 index 000000000..7e6fef1a5 --- /dev/null +++ b/node_modules/qs/.github/THREAT_MODEL.md @@ -0,0 +1,78 @@ +## Threat Model for qs (querystring parsing library) + +### 1. Library Overview + +- **Library Name:** qs +- **Brief Description:** A JavaScript library for parsing and stringifying URL query strings, supporting nested objects and arrays. It is widely used in Node.js and web applications for processing query parameters[2][6][8]. +- **Key Public APIs/Functions:** `qs.parse()`, `qs.stringify()` + +### 2. Define Scope + +This threat model focuses on the core parsing and stringifying functionality, specifically the handling of nested objects and arrays, option validation, and cycle management in stringification. + +### 3. Conceptual System Diagram + +``` +Caller Application → qs.parse(input, options) → Parsing Engine → Output Object + │ + └→ Options Handling + +Caller Application → qs.stringify(obj, options) → Stringifying Engine → Output String + │ + └→ Options Handling + └→ Cycle Tracking +``` + +**Trust Boundaries:** +- **Input string (parse):** May come from untrusted sources (e.g., user input, network requests) +- **Input object (stringify):** May contain cycles, which can lead to infinite loops during stringification +- **Options:** Provided by the caller +- **Cycle Tracking:** Used only during stringification to detect and handle circular references + +### 4. Identify Assets + +- **Integrity of parsed output:** Prevent malicious manipulation of the output object structure, especially ensuring builtins/globals are not modified as a result of parse[3][4][8]. +- **Confidentiality of processed data:** Avoid leaking sensitive information through errors or output. +- **Availability/performance for host application:** Prevent crashes or resource exhaustion in the consuming application. +- **Security of host application:** Prevent the library from being a vector for attacks (e.g., prototype pollution, DoS). +- **Reputation of library:** Maintain trust by avoiding supply chain attacks and vulnerabilities[1]. + +### 5. Identify Threats + +| Component / API / Interaction | S | T | R | I | D | E | +|---------------------------------------|----|----|----|----|----|----| +| Public API Call (`parse`) | – | ✓ | – | ✓ | ✓ | ✓ | +| Public API Call (`stringify`) | – | ✓ | – | ✓ | ✓ | – | +| Options Handling | ✓ | ✓ | – | ✓ | – | ✓ | +| Dependency Interaction | – | – | – | – | ✓ | – | + +**Key Threats:** +- **Tampering:** Malicious input can, if not prevented, alter parsed output (e.g., prototype pollution via `__proto__`, modification of builtins/globals)[3][4][8]. +- **Information Disclosure:** Error messages may expose internal details or sensitive data. +- **Denial of Service:** Large or malformed input can exhaust memory or CPU. +- **Elevation of Privilege:** Prototype pollution can lead to unintended privilege escalation in the host application[3][4][8]. + +### 6. Mitigation/Countermeasures + +| Threat Identified | Proposed Mitigation | +|---------------------------------------------------|---------------------| +| Tampering (malicious input, prototype pollution) | Strict input validation; keep `allowPrototypes: false` by default; use `plainObjects` for output; ensure builtins/globals are never modified by parse[4][8]. | +| Information Disclosure (error messages) | Generic error messages without stack traces or internal paths. | +| Denial of Service (memory/CPU exhaustion) | Enforce `arrayLimit` and `parameterLimit` with safe defaults; enable `throwOnLimitExceeded`; limit nesting depth[7]. | +| Elevation of Privilege (prototype pollution) | Keep `allowPrototypes: false`; validate options against allowlist; use `plainObjects` to avoid prototype pollution[4][8]. | + +### 7. Risk Ranking + +- **High:** Denial of Service via array parsing or malformed input (historical vulnerability) +- **Medium:** Prototype pollution via options or input (if `allowPrototypes` enabled) +- **Low:** Information disclosure in errors + +### 8. Next Steps & Review + +1. **Audit option validation logic.** +2. **Add depth limiting to nested parsing and stringification.** +3. **Implement fuzz testing for parser and stringifier edge cases.** +4. **Regularly review dependencies for vulnerabilities.** +5. **Keep documentation and threat model up to date.** +6. **Ensure builtins/globals are never modified as a result of parse.** +7. **Support round-trip consistency between parse and stringify as a non-security goal, with the right options[5][9].** diff --git a/node_modules/qs/.nycrc b/node_modules/qs/.nycrc new file mode 100644 index 000000000..1d57cabe1 --- /dev/null +++ b/node_modules/qs/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "dist" + ] +} diff --git a/node_modules/qs/CHANGELOG.md b/node_modules/qs/CHANGELOG.md new file mode 100644 index 000000000..35828d510 --- /dev/null +++ b/node_modules/qs/CHANGELOG.md @@ -0,0 +1,631 @@ +## **6.14.1** +- [Fix] ensure arrayLength applies to `[]` notation as well +- [Fix] `parse`: when a custom decoder returns `null` for a key, ignore that key +- [Refactor] `parse`: extract key segment splitting helper +- [meta] add threat model +- [actions] add workflow permissions +- [Tests] `stringify`: increase coverage +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `npmignore`, `es-value-fixtures`, `for-each`, `object-inspect` + +## **6.14.0** +- [New] `parse`: add `throwOnParameterLimitExceeded` option (#517) +- [Refactor] `parse`: use `utils.combine` more +- [patch] `parse`: add explicit `throwOnLimitExceeded` default +- [actions] use shared action; re-add finishers +- [meta] Fix changelog formatting bug +- [Deps] update `side-channel` +- [Dev Deps] update `es-value-fixtures`, `has-bigints`, `has-proto`, `has-symbols` +- [Tests] increase coverage + +## **6.13.1** +- [Fix] `stringify`: avoid a crash when a `filter` key is `null` +- [Fix] `utils.merge`: functions should not be stringified into keys +- [Fix] `parse`: avoid a crash with interpretNumericEntities: true, comma: true, and iso charset +- [Fix] `stringify`: ensure a non-string `filter` does not crash +- [Refactor] use `__proto__` syntax instead of `Object.create` for null objects +- [Refactor] misc cleanup +- [Tests] `utils.merge`: add some coverage +- [Tests] fix a test case +- [actions] split out node 10-20, and 20+ +- [Dev Deps] update `es-value-fixtures`, `mock-property`, `object-inspect`, `tape` + +## **6.13.0** +- [New] `parse`: add `strictDepth` option (#511) +- [Tests] use `npm audit` instead of `aud` + +## **6.12.3** +- [Fix] `parse`: properly account for `strictNullHandling` when `allowEmptyArrays` +- [meta] fix changelog indentation + +## **6.12.2** +- [Fix] `parse`: parse encoded square brackets (#506) +- [readme] add CII best practices badge + +## **6.12.1** +- [Fix] `parse`: Disable `decodeDotInKeys` by default to restore previous behavior (#501) +- [Performance] `utils`: Optimize performance under large data volumes, reduce memory usage, and speed up processing (#502) +- [Refactor] `utils`: use `+=` +- [Tests] increase coverage + +## **6.12.0** + +- [New] `parse`/`stringify`: add `decodeDotInKeys`/`encodeDotKeys` options (#488) +- [New] `parse`: add `duplicates` option +- [New] `parse`/`stringify`: add `allowEmptyArrays` option to allow [] in object values (#487) +- [Refactor] `parse`/`stringify`: move allowDots config logic to its own variable +- [Refactor] `stringify`: move option-handling code into `normalizeStringifyOptions` +- [readme] update readme, add logos (#484) +- [readme] `stringify`: clarify default `arrayFormat` behavior +- [readme] fix line wrapping +- [readme] remove dead badges +- [Deps] update `side-channel` +- [meta] make the dist build 50% smaller +- [meta] add `sideEffects` flag +- [meta] run build in prepack, not prepublish +- [Tests] `parse`: remove useless tests; add coverage +- [Tests] `stringify`: increase coverage +- [Tests] use `mock-property` +- [Tests] `stringify`: improve coverage +- [Dev Deps] update `@ljharb/eslint-config `, `aud`, `has-override-mistake`, `has-property-descriptors`, `mock-property`, `npmignore`, `object-inspect`, `tape` +- [Dev Deps] pin `glob`, since v10.3.8+ requires a broken `jackspeak` +- [Dev Deps] pin `jackspeak` since 2.1.2+ depends on npm aliases, which kill the install process in npm < 6 + +## **6.11.2** +- [Fix] `parse`: Fix parsing when the global Object prototype is frozen (#473) +- [Tests] add passing test cases with empty keys (#473) + +## **6.11.1** +- [Fix] `stringify`: encode comma values more consistently (#463) +- [readme] add usage of `filter` option for injecting custom serialization, i.e. of custom types (#447) +- [meta] remove extraneous code backticks (#457) +- [meta] fix changelog markdown +- [actions] update checkout action +- [actions] restrict action permissions +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` + +## **6.11.0** +- [New] [Fix] `stringify`: revert 0e903c0; add `commaRoundTrip` option (#442) +- [readme] fix version badge + +## **6.10.5** +- [Fix] `stringify`: with `arrayFormat: comma`, properly include an explicit `[]` on a single-item array (#434) + +## **6.10.4** +- [Fix] `stringify`: with `arrayFormat: comma`, include an explicit `[]` on a single-item array (#441) +- [meta] use `npmignore` to autogenerate an npmignore file +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbol`, `object-inspect`, `tape` + +## **6.10.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [actions] reuse common workflows +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `tape` + +## **6.10.2** +- [Fix] `stringify`: actually fix cyclic references (#426) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [actions] update codecov uploader +- [actions] update workflows +- [Tests] clean up stringify tests slightly +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `safe-publish-latest`, `tape` + +## **6.10.1** +- [Fix] `stringify`: avoid exception on repeated object values (#402) + +## **6.10.0** +- [New] `stringify`: throw on cycles, instead of an infinite loop (#395, #394, #393) +- [New] `parse`: add `allowSparse` option for collapsing arrays with missing indices (#312) +- [meta] fix README.md (#399) +- [meta] only run `npm run dist` in publish, not install +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbols`, `tape` +- [Tests] fix tests on node v0.6 +- [Tests] use `ljharb/actions/node/install` instead of `ljharb/actions/node/run` +- [Tests] Revert "[meta] ignore eclint transitive audit warning" + +## **6.9.7** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [Tests] clean up stringify tests slightly +- [meta] fix README.md (#399) +- Revert "[meta] ignore eclint transitive audit warning" +- [actions] backport actions from main +- [Dev Deps] backport updates from main + +## **6.9.6** +- [Fix] restore `dist` dir; mistakenly removed in d4f6c32 + +## **6.9.5** +- [Fix] `stringify`: do not encode parens for RFC1738 +- [Fix] `stringify`: fix arrayFormat comma with empty array/objects (#350) +- [Refactor] `format`: remove `util.assign` call +- [meta] add "Allow Edits" workflow; update rebase workflow +- [actions] switch Automatic Rebase workflow to `pull_request_target` event +- [Tests] `stringify`: add tests for #378 +- [Tests] migrate tests to Github Actions +- [Tests] run `nyc` on all tests; use `tape` runner +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `mkdirp`, `object-inspect`, `tape`; add `aud` + +## **6.9.4** +- [Fix] `stringify`: when `arrayFormat` is `comma`, respect `serializeDate` (#364) +- [Refactor] `stringify`: reduce branching (part of #350) +- [Refactor] move `maybeMap` to `utils` +- [Dev Deps] update `browserify`, `tape` + +## **6.9.3** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.9.2** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [meta] ignore eclint transitive audit warning +- [meta] fix indentation in package.json +- [meta] add tidelift marketing copy +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `has-symbols`, `tape`, `mkdirp`, `iconv-lite` +- [actions] add automatic rebasing / merge commit blocking + +## **6.9.1** +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [Fix] `parse`: with comma true, do not split non-string values (#334) +- [meta] add `funding` field +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` +- [Tests] use shared travis-ci config + +## **6.9.0** +- [New] `parse`/`stringify`: Pass extra key/value argument to `decoder` (#333) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `evalmd` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] add `posttest` using `npx aud` to run `npm audit` without a lockfile +- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16` +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray + +## **6.8.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Tests] clean up stringify tests slightly +- [Docs] add note and links for coercing primitive values (#408) +- [meta] fix README.md (#399) +- [actions] backport actions from main +- [Dev Deps] backport updates from main +- [Refactor] `stringify`: reduce branching +- [meta] do not publish workflow files + +## **6.8.2** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.8.1** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [fix] `parse`: with comma true, do not split non-string values (#334) +- [meta] add tidelift marketing copy +- [meta] add `funding` field +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `safe-publish-latest`, `evalmd`, `has-symbols`, `iconv-lite`, `mkdirp`, `object-inspect` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] use shared travis-ci configs +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray +- [actions] add automatic rebasing / merge commit blocking + +## **6.8.0** +- [New] add `depth=false` to preserve the original key; [Fix] `depth=0` should preserve the original key (#326) +- [New] [Fix] stringify symbols and bigints +- [Fix] ensure node 0.12 can stringify Symbols +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Refactor] `formats`: tiny bit of cleanup. +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `safe-publish-latest`, `iconv-lite`, `tape` +- [Tests] add tests for `depth=0` and `depth=false` behavior, both current and intuitive/intended (#326) +- [Tests] use `eclint` instead of `editorconfig-tools` +- [docs] readme: add security note +- [meta] add github sponsorship +- [meta] add FUNDING.yml +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause + +## **6.7.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [meta] fix README.md (#399) +- [meta] do not publish workflow files +- [actions] backport actions from main +- [Dev Deps] backport updates from main +- [Tests] use `nyc` for coverage +- [Tests] clean up stringify tests slightly + +## **6.7.2** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.7.1** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [fix] `parse`: with comma true, do not split non-string values (#334) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Refactor] `formats`: tiny bit of cleanup. +- readme: add security note +- [meta] add tidelift marketing copy +- [meta] add `funding` field +- [meta] add FUNDING.yml +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `safe-publish-latest`, `evalmd`, `iconv-lite`, `mkdirp`, `object-inspect`, `browserify` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] use shared travis-ci configs +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray +- [Tests] add tests for `depth=0` and `depth=false` behavior, both current and intuitive/intended +- [Tests] use `eclint` instead of `editorconfig-tools` +- [actions] add automatic rebasing / merge commit blocking + +## **6.7.0** +- [New] `stringify`/`parse`: add `comma` as an `arrayFormat` option (#276, #219) +- [Fix] correctly parse nested arrays (#212) +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source, also with an array source +- [Robustness] `stringify`: cache `Object.prototype.hasOwnProperty` +- [Refactor] `utils`: `isBuffer`: small tweak; add tests +- [Refactor] use cached `Array.isArray` +- [Refactor] `parse`/`stringify`: make a function to normalize the options +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] `stringify`/`utils`: cache `Array.isArray` +- [Tests] always use `String(x)` over `x.toString()` +- [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 +- [Tests] temporarily allow coverage to fail + +## **6.6.1** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] correctly parse nested arrays +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Robustness] `stringify`: cache `Object.prototype.hasOwnProperty` +- [Refactor] `formats`: tiny bit of cleanup. +- [Refactor] `utils`: `isBuffer`: small tweak; add tests +- [Refactor]: `stringify`/`utils`: cache `Array.isArray` +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] use cached `Array.isArray` +- [Refactor] `parse`/`stringify`: make a function to normalize the options +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] do not publish workflow files +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [meta] Fixes typo in CHANGELOG.md +- [actions] backport actions from main +- [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 +- [Tests] always use `String(x)` over `x.toString()` +- [Dev Deps] backport from main + +## **6.6.0** +- [New] Add support for iso-8859-1, utf8 "sentinel" and numeric entities (#268) +- [New] move two-value combine to a `utils` function (#189) +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` (#260) +- [Fix] `stringify`: do not crash in an obscure combo of `interpretNumericEntities`, a bad custom `decoder`, & `iso-8859-1` +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Refactor] `parse`: only need to reassign the var once +- [Refactor] `parse`/`stringify`: clean up `charset` options checking; fix defaults +- [Refactor] add missing defaults +- [Refactor] `parse`: one less `concat` call +- [Refactor] `utils`: `compactQueue`: make it explicitly side-effecting +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`, `iconv-lite`, `safe-publish-latest`, `tape` +- [Tests] up to `node` `v10.10`, `v9.11`, `v8.12`, `v6.14`, `v4.9`; pin included builds to LTS + +## **6.5.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] correctly parse nested arrays +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Refactor] `parse`: only need to reassign the var once +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clean up license text so it’s properly detected as BSD-3-Clause +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] always use `String(x)` over `x.toString()` +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.5.2** +- [Fix] use `safer-buffer` instead of `Buffer` constructor +- [Refactor] utils: `module.exports` one thing, instead of mutating `exports` (#230) +- [Dev Deps] update `browserify`, `eslint`, `iconv-lite`, `safer-buffer`, `tape`, `browserify` + +## **6.5.1** +- [Fix] Fix parsing & compacting very deep objects (#224) +- [Refactor] name utils functions +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` +- [Tests] up to `node` `v8.4`; use `nvm install-latest-npm` so newer npm doesn’t break older node +- [Tests] Use precise dist for Node.js 0.6 runtime (#225) +- [Tests] make 0.6 required, now that it’s passing +- [Tests] on `node` `v8.2`; fix npm on node 0.6 + +## **6.5.0** +- [New] add `utils.assign` +- [New] pass default encoder/decoder to custom encoder/decoder functions (#206) +- [New] `parse`/`stringify`: add `ignoreQueryPrefix`/`addQueryPrefix` options, respectively (#213) +- [Fix] Handle stringifying empty objects with addQueryPrefix (#217) +- [Fix] do not mutate `options` argument (#207) +- [Refactor] `parse`: cache index to reuse in else statement (#182) +- [Docs] add various badges to readme (#208) +- [Dev Deps] update `eslint`, `browserify`, `iconv-lite`, `tape` +- [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`; npm v4.6 breaks on node < v1; npm v5+ breaks on node < v4 +- [Tests] add `editorconfig-tools` + +## **6.4.1** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] use `safer-buffer` instead of `Buffer` constructor +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.4.0** +- [New] `qs.stringify`: add `encodeValuesOnly` option +- [Fix] follow `allowPrototypes` option during merge (#201, #201) +- [Fix] support keys starting with brackets (#202, #200) +- [Fix] chmod a-x +- [Dev Deps] update `eslint` +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds +- [eslint] reduce warnings + +## **6.3.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] use `safer-buffer` instead of `Buffer` constructor +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.3.2** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Dev Deps] update `eslint` +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.3.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties (thanks, @snyk!) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `iconv-lite`, `qs-iconv`, `tape` +- [Tests] on all node minors; improve test matrix +- [Docs] document stringify option `allowDots` (#195) +- [Docs] add empty object and array values example (#195) +- [Docs] Fix minor inconsistency/typo (#192) +- [Docs] document stringify option `sort` (#191) +- [Refactor] `stringify`: throw faster with an invalid encoder +- [Refactor] remove unnecessary escapes (#184) +- Remove contributing.md, since `qs` is no longer part of `hapi` (#183) + +## **6.3.0** +- [New] Add support for RFC 1738 (#174, #173) +- [New] `stringify`: Add `serializeDate` option to customize Date serialization (#159) +- [Fix] ensure `utils.merge` handles merging two arrays +- [Refactor] only constructors should be capitalized +- [Refactor] capitalized var names are for constructors only +- [Refactor] avoid using a sparse array +- [Robustness] `formats`: cache `String#replace` +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`; add `safe-publish-latest` +- [Tests] up to `node` `v6.8`, `v4.6`; improve test matrix +- [Tests] flesh out arrayLimit/arrayFormat tests (#107) +- [Tests] skip Object.create tests when null objects are not available +- [Tests] Turn on eslint for test files (#175) + +## **6.2.4** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] use `safer-buffer` instead of `Buffer` constructor +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.2.3** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.2.2** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## **6.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values +- [Refactor] Be explicit and use `Object.prototype.hasOwnProperty.call` +- [Tests] remove `parallelshell` since it does not reliably report failures +- [Tests] up to `node` `v6.3`, `v5.12` +- [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `qs-iconv` + +## [**6.2.0**](https://github.com/ljharb/qs/issues?milestone=36&state=closed) +- [New] pass Buffers to the encoder/decoder directly (#161) +- [New] add "encoder" and "decoder" options, for custom param encoding/decoding (#160) +- [Fix] fix compacting of nested sparse arrays (#150) + +## **6.1.2** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.1.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## [**6.1.0**](https://github.com/ljharb/qs/issues?milestone=35&state=closed) +- [New] allowDots option for `stringify` (#151) +- [Fix] "sort" option should work at a depth of 3 or more (#151) +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## **6.0.4** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.0.3** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## [**6.0.2**](https://github.com/ljharb/qs/issues?milestone=33&state=closed) +- Revert ES6 requirement and restore support for node down to v0.8. + +## [**6.0.1**](https://github.com/ljharb/qs/issues?milestone=32&state=closed) +- [**#127**](https://github.com/ljharb/qs/pull/127) Fix engines definition in package.json + +## [**6.0.0**](https://github.com/ljharb/qs/issues?milestone=31&state=closed) +- [**#124**](https://github.com/ljharb/qs/issues/124) Use ES6 and drop support for node < v4 + +## **5.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values + +## [**5.2.0**](https://github.com/ljharb/qs/issues?milestone=30&state=closed) +- [**#64**](https://github.com/ljharb/qs/issues/64) Add option to sort object keys in the query string + +## [**5.1.0**](https://github.com/ljharb/qs/issues?milestone=29&state=closed) +- [**#117**](https://github.com/ljharb/qs/issues/117) make URI encoding stringified results optional +- [**#106**](https://github.com/ljharb/qs/issues/106) Add flag `skipNulls` to optionally skip null values in stringify + +## [**5.0.0**](https://github.com/ljharb/qs/issues?milestone=28&state=closed) +- [**#114**](https://github.com/ljharb/qs/issues/114) default allowDots to false +- [**#100**](https://github.com/ljharb/qs/issues/100) include dist to npm + +## [**4.0.0**](https://github.com/ljharb/qs/issues?milestone=26&state=closed) +- [**#98**](https://github.com/ljharb/qs/issues/98) make returning plain objects and allowing prototype overwriting properties optional + +## [**3.1.0**](https://github.com/ljharb/qs/issues?milestone=24&state=closed) +- [**#89**](https://github.com/ljharb/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/ljharb/qs/issues?milestone=23&state=closed) +- [**#80**](https://github.com/ljharb/qs/issues/80) qs.parse silently drops properties +- [**#77**](https://github.com/ljharb/qs/issues/77) Perf boost +- [**#60**](https://github.com/ljharb/qs/issues/60) Add explicit option to disable array parsing +- [**#74**](https://github.com/ljharb/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/ljharb/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/ljharb/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/ljharb/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/ljharb/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/ljharb/qs/issues/85) No equal sign +- [**#84**](https://github.com/ljharb/qs/issues/84) update license attribute + +## [**2.4.1**](https://github.com/ljharb/qs/issues?milestone=20&state=closed) +- [**#73**](https://github.com/ljharb/qs/issues/73) Property 'hasOwnProperty' of object # is not a function + +## [**2.4.0**](https://github.com/ljharb/qs/issues?milestone=19&state=closed) +- [**#70**](https://github.com/ljharb/qs/issues/70) Add arrayFormat option + +## [**2.3.3**](https://github.com/ljharb/qs/issues?milestone=18&state=closed) +- [**#59**](https://github.com/ljharb/qs/issues/59) make sure array indexes are >= 0, closes #57 +- [**#58**](https://github.com/ljharb/qs/issues/58) make qs usable for browser loader + +## [**2.3.2**](https://github.com/ljharb/qs/issues?milestone=17&state=closed) +- [**#55**](https://github.com/ljharb/qs/issues/55) allow merging a string into an object + +## [**2.3.1**](https://github.com/ljharb/qs/issues?milestone=16&state=closed) +- [**#52**](https://github.com/ljharb/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError". + +## [**2.3.0**](https://github.com/ljharb/qs/issues?milestone=15&state=closed) +- [**#50**](https://github.com/ljharb/qs/issues/50) add option to omit array indices, closes #46 + +## [**2.2.5**](https://github.com/ljharb/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/ljharb/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/ljharb/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/ljharb/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/ljharb/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/ljharb/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/ljharb/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/ljharb/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/ljharb/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/ljharb/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/ljharb/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/ljharb/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/ljharb/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/ljharb/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/ljharb/qs/issues/32) account for circular references properly, closes #31 +- [**#31**](https://github.com/ljharb/qs/issues/31) qs.parse stackoverflow on circular objects + +## [**2.2.0**](https://github.com/ljharb/qs/issues?milestone=9&state=closed) +- [**#26**](https://github.com/ljharb/qs/issues/26) Don't use Buffer global if it's not present +- [**#30**](https://github.com/ljharb/qs/issues/30) Bug when merging non-object values into arrays +- [**#29**](https://github.com/ljharb/qs/issues/29) Don't call Utils.clone at the top of Utils.merge +- [**#23**](https://github.com/ljharb/qs/issues/23) Ability to not limit parameters? + +## [**2.1.0**](https://github.com/ljharb/qs/issues?milestone=8&state=closed) +- [**#22**](https://github.com/ljharb/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/ljharb/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/ljharb/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/ljharb/qs/issues/20) Configurable parametersLimit +- [**#21**](https://github.com/ljharb/qs/issues/21) make all limits optional, for #18, for #20 + +## [**1.2.2**](https://github.com/ljharb/qs/issues?milestone=6&state=closed) +- [**#19**](https://github.com/ljharb/qs/issues/19) Don't overwrite null values + +## [**1.2.1**](https://github.com/ljharb/qs/issues?milestone=5&state=closed) +- [**#16**](https://github.com/ljharb/qs/issues/16) ignore non-string delimiters +- [**#15**](https://github.com/ljharb/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/ljharb/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/ljharb/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/ljharb/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/ljharb/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/ljharb/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/ljharb/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/ljharb/qs/issues/6) Minor grammar fix in README + +## [**1.0.2**](https://github.com/ljharb/qs/issues?milestone=2&state=closed) +- [**#5**](https://github.com/ljharb/qs/issues/5) array holes incorrectly copied into object on large index diff --git a/node_modules/qs/LICENSE.md b/node_modules/qs/LICENSE.md new file mode 100644 index 000000000..fecf6b694 --- /dev/null +++ b/node_modules/qs/LICENSE.md @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2014, Nathan LaFreniere and other [contributors](https://github.com/ljharb/qs/graphs/contributors) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/qs/README.md b/node_modules/qs/README.md new file mode 100644 index 000000000..22c411dfe --- /dev/null +++ b/node_modules/qs/README.md @@ -0,0 +1,733 @@ +

+ qs +

+ +# qs [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/9058/badge)](https://bestpractices.coreinfrastructure.org/projects/9058) + +[![npm badge][npm-badge-png]][package-url] + +A querystring parsing and stringifying library with some added security. + +Lead Maintainer: [Jordan Harband](https://github.com/ljharb) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var qs = require('qs'); +var assert = require('assert'); + +var obj = qs.parse('a=c'); +assert.deepEqual(obj, { a: 'c' }); + +var str = qs.stringify(obj); +assert.equal(str, 'a=c'); +``` + +### Parsing Objects + +[](#preventEval) +```javascript +qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +assert.deepEqual(qs.parse('foo[bar]=baz'), { + foo: { + bar: 'baz' + } +}); +``` + +When using the `plainObjects` option the parsed value is returned as a null object, created via `{ __proto__: null }` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true }); +assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } }); +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. +*WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. +Always be careful with this option. + +```javascript +var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }); +assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } }); +``` + +URI encoded strings work too: + +```javascript +assert.deepEqual(qs.parse('a%5Bb%5D=c'), { + a: { b: 'c' } +}); +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), { + foo: { + bar: { + baz: 'foobarbaz' + } + } +}); +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. +This means if you attempt to parse a string like `'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +var expected = { + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +}; +var string = 'a[b][c][d][e][f][g][h][i]=j'; +assert.deepEqual(qs.parse(string), expected); +``` + +This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`: + +```javascript +var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }); +``` + +You can configure **qs** to throw an error when parsing nested input beyond this depth using the `strictDepth` option (defaulted to false): + +```javascript +try { + qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1, strictDepth: true }); +} catch (err) { + assert(err instanceof RangeError); + assert.strictEqual(err.message, 'Input depth exceeded depth option of 1 and strictDepth is true'); +} +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. The strictDepth option adds a layer of protection by throwing an error when the limit is exceeded, allowing you to catch and handle such cases. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +var limited = qs.parse('a=b&c=d', { parameterLimit: 1 }); +assert.deepEqual(limited, { a: 'b' }); +``` + +If you want an error to be thrown whenever the a limit is exceeded (eg, `parameterLimit`, `arrayLimit`), set the `throwOnLimitExceeded` option to `true`. This option will generate a descriptive error if the query string exceeds a configured limit. +```javascript +try { + qs.parse('a=1&b=2&c=3&d=4', { parameterLimit: 3, throwOnLimitExceeded: true }); +} catch (err) { + assert(err instanceof Error); + assert.strictEqual(err.message, 'Parameter limit exceeded. Only 3 parameters allowed.'); +} +``` + +When `throwOnLimitExceeded` is set to `false` (default), **qs** will parse up to the specified `parameterLimit` and ignore the rest without throwing an error. + +To bypass the leading question mark, use `ignoreQueryPrefix`: + +```javascript +var prefixed = qs.parse('?a=b&c=d', { ignoreQueryPrefix: true }); +assert.deepEqual(prefixed, { a: 'b', c: 'd' }); +``` + +An optional delimiter can also be passed: + +```javascript +var delimited = qs.parse('a=b;c=d', { delimiter: ';' }); +assert.deepEqual(delimited, { a: 'b', c: 'd' }); +``` + +Delimiters can be a regular expression too: + +```javascript +var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' }); +``` + +Option `allowDots` can be used to enable dot notation: + +```javascript +var withDots = qs.parse('a.b=c', { allowDots: true }); +assert.deepEqual(withDots, { a: { b: 'c' } }); +``` + +Option `decodeDotInKeys` can be used to decode dots in keys +Note: it implies `allowDots`, so `parse` will error if you set `decodeDotInKeys` to `true`, and `allowDots` to `false`. + +```javascript +var withDots = qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { decodeDotInKeys: true }); +assert.deepEqual(withDots, { 'name.obj': { first: 'John', last: 'Doe' }}); +``` + +Option `allowEmptyArrays` can be used to allowing empty array values in object +```javascript +var withEmptyArrays = qs.parse('foo[]&bar=baz', { allowEmptyArrays: true }); +assert.deepEqual(withEmptyArrays, { foo: [], bar: 'baz' }); +``` + +Option `duplicates` can be used to change the behavior when duplicate keys are encountered +```javascript +assert.deepEqual(qs.parse('foo=bar&foo=baz'), { foo: ['bar', 'baz'] }); +assert.deepEqual(qs.parse('foo=bar&foo=baz', { duplicates: 'combine' }), { foo: ['bar', 'baz'] }); +assert.deepEqual(qs.parse('foo=bar&foo=baz', { duplicates: 'first' }), { foo: 'bar' }); +assert.deepEqual(qs.parse('foo=bar&foo=baz', { duplicates: 'last' }), { foo: 'baz' }); +``` + +If you have to deal with legacy browsers or services, there's also support for decoding percent-encoded octets as iso-8859-1: + +```javascript +var oldCharset = qs.parse('a=%A7', { charset: 'iso-8859-1' }); +assert.deepEqual(oldCharset, { a: '§' }); +``` + +Some services add an initial `utf8=✓` value to forms so that old Internet Explorer versions are more likely to submit the form as utf-8. +Additionally, the server can check the value against wrong encodings of the checkmark character and detect that a query string or `application/x-www-form-urlencoded` body was *not* sent as utf-8, eg. if the form had an `accept-charset` parameter or the containing page had a different character set. + +**qs** supports this mechanism via the `charsetSentinel` option. +If specified, the `utf8` parameter will be omitted from the returned object. +It will be used to switch to `iso-8859-1`/`utf-8` mode depending on how the checkmark is encoded. + +**Important**: When you specify both the `charset` option and the `charsetSentinel` option, the `charset` will be overridden when the request contains a `utf8` parameter from which the actual charset can be deduced. +In that sense the `charset` will behave as the default charset rather than the authoritative charset. + +```javascript +var detectedAsUtf8 = qs.parse('utf8=%E2%9C%93&a=%C3%B8', { + charset: 'iso-8859-1', + charsetSentinel: true +}); +assert.deepEqual(detectedAsUtf8, { a: 'ø' }); + +// Browsers encode the checkmark as ✓ when submitting as iso-8859-1: +var detectedAsIso8859_1 = qs.parse('utf8=%26%2310003%3B&a=%F8', { + charset: 'utf-8', + charsetSentinel: true +}); +assert.deepEqual(detectedAsIso8859_1, { a: 'ø' }); +``` + +If you want to decode the `&#...;` syntax to the actual character, you can specify the `interpretNumericEntities` option as well: + +```javascript +var detectedAsIso8859_1 = qs.parse('a=%26%239786%3B', { + charset: 'iso-8859-1', + interpretNumericEntities: true +}); +assert.deepEqual(detectedAsIso8859_1, { a: '☺' }); +``` + +It also works when the charset has been detected in `charsetSentinel` mode. + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +var withArray = qs.parse('a[]=b&a[]=c'); +assert.deepEqual(withArray, { a: ['b', 'c'] }); +``` + +You may specify an index as well: + +```javascript +var withIndexes = qs.parse('a[1]=c&a[0]=b'); +assert.deepEqual(withIndexes, { a: ['b', 'c'] }); +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number to create an array. +When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving their order: + +```javascript +var noSparse = qs.parse('a[1]=b&a[15]=c'); +assert.deepEqual(noSparse, { a: ['b', 'c'] }); +``` + +You may also use `allowSparse` option to parse sparse arrays: + +```javascript +var sparseArray = qs.parse('a[1]=2&a[3]=5', { allowSparse: true }); +assert.deepEqual(sparseArray, { a: [, '2', , '5'] }); +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +var withEmptyString = qs.parse('a[]=&a[]=b'); +assert.deepEqual(withEmptyString, { a: ['', 'b'] }); + +var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c'); +assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] }); +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. +Any array members with an index of greater than `20` will instead be converted to an object with the index as the key. +This is needed to handle cases when someone sent, for example, `a[999999999]` and it will take significant time to iterate over this huge array. + +```javascript +var withMaxIndex = qs.parse('a[100]=b'); +assert.deepEqual(withMaxIndex, { a: { '100': 'b' } }); +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 }); +assert.deepEqual(withArrayLimit, { a: { '1': 'b' } }); +``` + +If you want to throw an error whenever the array limit is exceeded, set the `throwOnLimitExceeded` option to `true`. This option will generate a descriptive error if the query string exceeds a configured limit. +```javascript +try { + qs.parse('a[1]=b', { arrayLimit: 0, throwOnLimitExceeded: true }); +} catch (err) { + assert(err instanceof Error); + assert.strictEqual(err.message, 'Array limit exceeded. Only 0 elements allowed in an array.'); +} +``` + +When `throwOnLimitExceeded` is set to `false` (default), **qs** will parse up to the specified `arrayLimit` and if the limit is exceeded, the array will instead be converted to an object with the index as the key + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +var noParsingArrays = qs.parse('a[]=b', { parseArrays: false }); +assert.deepEqual(noParsingArrays, { a: { '0': 'b' } }); +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +var mixedNotation = qs.parse('a[0]=b&a[b]=c'); +assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } }); +``` + +You can also create arrays of objects: + +```javascript +var arraysOfObjects = qs.parse('a[][b]=c'); +assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] }); +``` + +Some people use comma to join array, **qs** can parse it: +```javascript +var arraysOfObjects = qs.parse('a=b,c', { comma: true }) +assert.deepEqual(arraysOfObjects, { a: ['b', 'c'] }) +``` +(_this cannot convert nested objects, such as `a={b:1},{c:d}`_) + +### Parsing primitive/scalar values (numbers, booleans, null, etc) + +By default, all values are parsed as strings. +This behavior will not change and is explained in [issue #91](https://github.com/ljharb/qs/issues/91). + +```javascript +var primitiveValues = qs.parse('a=15&b=true&c=null'); +assert.deepEqual(primitiveValues, { a: '15', b: 'true', c: 'null' }); +``` + +If you wish to auto-convert values which look like numbers, booleans, and other values into their primitive counterparts, you can use the [query-types Express JS middleware](https://github.com/xpepermint/query-types) which will auto-convert all request query parameters. + +### Stringifying + +[](#preventEval) +```javascript +qs.stringify(object, [options]); +``` + +When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect: + +```javascript +assert.equal(qs.stringify({ a: 'b' }), 'a=b'); +assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); +``` + +This encoding can be disabled by setting the `encode` option to `false`: + +```javascript +var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false }); +assert.equal(unencoded, 'a[b]=c'); +``` + +Encoding can be disabled for keys by setting the `encodeValuesOnly` option to `true`: +```javascript +var encodedValues = qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true } +); +assert.equal(encodedValues,'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h'); +``` + +This encoding can also be replaced by a custom encoding method set as `encoder` option: + +```javascript +var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) { + // Passed in values `a`, `b`, `c` + return // Return encoded string +}}) +``` + +_(Note: the `encoder` option does not apply if `encode` is `false`)_ + +Analogue to the `encoder` there is a `decoder` option for `parse` to override decoding of properties and values: + +```javascript +var decoded = qs.parse('x=z', { decoder: function (str) { + // Passed in values `x`, `z` + return // Return decoded string +}}) +``` + +You can encode keys and values using different logic by using the type argument provided to the encoder: + +```javascript +var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str, defaultEncoder, charset, type) { + if (type === 'key') { + return // Encoded key + } else if (type === 'value') { + return // Encoded value + } +}}) +``` + +The type argument is also provided to the decoder: + +```javascript +var decoded = qs.parse('x=z', { decoder: function (str, defaultDecoder, charset, type) { + if (type === 'key') { + return // Decoded key + } else if (type === 'value') { + return // Decoded value + } +}}) +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. +Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, they follow the `arrayFormat` option, which defaults to `indices`: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`, or to be more explicit, the `arrayFormat` option to `repeat`: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }); +// 'a=b&a=c&a=d' +``` + +You may use the `arrayFormat` option to specify the format of the output array: + +```javascript +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) +// 'a[0]=b&a[1]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) +// 'a[]=b&a[]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) +// 'a=b&a=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' }) +// 'a=b,c' +``` + +Note: when using `arrayFormat` set to `'comma'`, you can also pass the `commaRoundTrip` option set to `true` or `false`, to append `[]` on single-item arrays, so that they can round trip through a parse. + +When objects are stringified, by default they use bracket notation: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }); +// 'a[b][c]=d&a[b][e]=f' +``` + +You may override this to use dot notation by setting the `allowDots` option to `true`: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true }); +// 'a.b.c=d&a.b.e=f' +``` + +You may encode the dot notation in the keys of object with option `encodeDotInKeys` by setting it to `true`: +Note: it implies `allowDots`, so `stringify` will error if you set `decodeDotInKeys` to `true`, and `allowDots` to `false`. +Caveat: when `encodeValuesOnly` is `true` as well as `encodeDotInKeys`, only dots in keys and nothing else will be encoded. +```javascript +qs.stringify({ "name.obj": { "first": "John", "last": "Doe" } }, { allowDots: true, encodeDotInKeys: true }) +// 'name%252Eobj.first=John&name%252Eobj.last=Doe' +``` + +You may allow empty array values by setting the `allowEmptyArrays` option to `true`: +```javascript +qs.stringify({ foo: [], bar: 'baz' }, { allowEmptyArrays: true }); +// 'foo[]&bar=baz' +``` + +Empty strings and null values will omit the value, but the equals sign (=) remains in place: + +```javascript +assert.equal(qs.stringify({ a: '' }), 'a='); +``` + +Key with no values (such as an empty object or array) will return nothing: + +```javascript +assert.equal(qs.stringify({ a: [] }), ''); +assert.equal(qs.stringify({ a: {} }), ''); +assert.equal(qs.stringify({ a: [{}] }), ''); +assert.equal(qs.stringify({ a: { b: []} }), ''); +assert.equal(qs.stringify({ a: { b: {}} }), ''); +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +assert.equal(qs.stringify({ a: null, b: undefined }), 'a='); +``` + +The query string may optionally be prepended with a question mark: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true }), '?a=b&c=d'); +``` + +The delimiter may be overridden with stringify as well: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); +``` + +If you only want to override the serialization of `Date` objects, you can provide a `serializeDate` option: + +```javascript +var date = new Date(7); +assert.equal(qs.stringify({ a: date }), 'a=1970-01-01T00:00:00.007Z'.replace(/:/g, '%3A')); +assert.equal( + qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); } }), + 'a=7' +); +``` + +You may use the `sort` option to affect the order of parameter keys: + +```javascript +function alphabeticalSort(a, b) { + return a.localeCompare(b); +} +assert.equal(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }), 'a=c&b=f&z=y'); +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. +Otherwise, if you pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }); +// 'a=b&c=d&e[f]=123&e[g][0]=4' +qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }); +// 'a=b&e=f' +qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }); +// 'a[0]=b&a[2]=d' +``` + +You could also use `filter` to inject custom serialization for user defined types. +Consider you're working with some api that expects query strings of the format for ranges: + +``` +https://domain.com/endpoint?range=30...70 +``` + +For which you model as: + +```javascript +class Range { + constructor(from, to) { + this.from = from; + this.to = to; + } +} +``` + +You could _inject_ a custom serializer to handle values of this type: + +```javascript +qs.stringify( + { + range: new Range(30, 70), + }, + { + filter: (prefix, value) => { + if (value instanceof Range) { + return `${value.from}...${value.to}`; + } + // serialize the usual way + return value; + }, + } +); +// range=30...70 +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +var withNull = qs.stringify({ a: null, b: '' }); +assert.equal(withNull, 'a=&b='); +``` + +Parsing does not distinguish between parameters with and without equal signs. +Both are converted to empty strings. + +```javascript +var equalsInsensitive = qs.parse('a&b='); +assert.deepEqual(equalsInsensitive, { a: '', b: '' }); +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +assert.equal(strictNull, 'a&b='); +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true }); +assert.deepEqual(parsedStrictNull, { a: null, b: '' }); +``` + +To completely skip rendering keys with `null` values, use the `skipNulls` flag: + +```javascript +var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true }); +assert.equal(nullsSkipped, 'a=b'); +``` + +If you're communicating with legacy systems, you can switch to `iso-8859-1` using the `charset` option: + +```javascript +var iso = qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }); +assert.equal(iso, '%E6=%E6'); +``` + +Characters that don't exist in `iso-8859-1` will be converted to numeric entities, similar to what browsers do: + +```javascript +var numeric = qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }); +assert.equal(numeric, 'a=%26%239786%3B'); +``` + +You can use the `charsetSentinel` option to announce the character by including an `utf8=✓` parameter with the proper encoding if the checkmark, similar to what Ruby on Rails and others do when submitting forms. + +```javascript +var sentinel = qs.stringify({ a: '☺' }, { charsetSentinel: true }); +assert.equal(sentinel, 'utf8=%E2%9C%93&a=%E2%98%BA'); + +var isoSentinel = qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }); +assert.equal(isoSentinel, 'utf8=%26%2310003%3B&a=%E6'); +``` + +### Dealing with special character sets + +By default the encoding and decoding of characters is done in `utf-8`, and `iso-8859-1` support is also built in via the `charset` parameter. + +If you wish to encode querystrings to a different character set (i.e. +[Shift JIS](https://en.wikipedia.org/wiki/Shift_JIS)) you can use the +[`qs-iconv`](https://github.com/martinheidegger/qs-iconv) library: + +```javascript +var encoder = require('qs-iconv/encoder')('shift_jis'); +var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder }); +assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I'); +``` + +This also works for decoding of query strings: + +```javascript +var decoder = require('qs-iconv/decoder')('shift_jis'); +var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder }); +assert.deepEqual(obj, { a: 'こんにちは!' }); +``` + +### RFC 3986 and RFC 1738 space encoding + +RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible. +In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'. + +``` +assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c'); +``` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +## qs for enterprise + +Available as part of the Tidelift Subscription + +The maintainers of qs and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. +Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. +[Learn more.](https://tidelift.com/subscription/pkg/npm-qs?utm_source=npm-qs&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +[package-url]: https://npmjs.org/package/qs +[npm-version-svg]: https://versionbadg.es/ljharb/qs.svg +[deps-svg]: https://david-dm.org/ljharb/qs.svg +[deps-url]: https://david-dm.org/ljharb/qs +[dev-deps-svg]: https://david-dm.org/ljharb/qs/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/qs#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/qs.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/qs.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/qs.svg +[downloads-url]: https://npm-stat.com/charts.html?package=qs +[codecov-image]: https://codecov.io/gh/ljharb/qs/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/qs/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/qs +[actions-url]: https://github.com/ljharb/qs/actions + +## Acknowledgements + +qs logo by [NUMI](https://github.com/numi-hq/open-design): + +[NUMI Logo](https://numi.tech/?ref=qs) diff --git a/node_modules/qs/dist/qs.js b/node_modules/qs/dist/qs.js new file mode 100644 index 000000000..2cee37040 --- /dev/null +++ b/node_modules/qs/dist/qs.js @@ -0,0 +1,141 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i-1)return e.split(",");if(t.throwOnLimitExceeded&&r>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");return e},isoSentinel="utf8=%26%2310003%3B",charsetSentinel="utf8=%E2%9C%93",parseValues=function parseQueryStringValues(e,t){var r={__proto__:null},i=t.ignoreQueryPrefix?e.replace(/^\?/,""):e;i=i.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var a=t.parameterLimit===1/0?void 0:t.parameterLimit,o=i.split(t.delimiter,t.throwOnLimitExceeded?a+1:a);if(t.throwOnLimitExceeded&&o.length>a)throw new RangeError("Parameter limit exceeded. Only "+a+" parameter"+(1===a?"":"s")+" allowed.");var l,n=-1,s=t.charset;if(t.charsetSentinel)for(l=0;l-1&&(d=isArray(d)?[d]:d),null!==p){var f=has.call(r,p);f&&"combine"===t.duplicates?r[p]=utils.combine(r[p],d,t.arrayLimit,t.plainObjects):f&&"last"!==t.duplicates||(r[p]=d)}}return r},parseObject=function(e,t,r,i){var a=0;if(e.length>0&&"[]"===e[e.length-1]){var o=e.slice(0,-1).join("");a=Array.isArray(t)&&t[o]?t[o].length:0}for(var l=i?t:parseArrayValue(t,r,a),n=e.length-1;n>=0;--n){var s,p=e[n];if("[]"===p&&r.parseArrays)s=utils.isOverflow(l)?l:r.allowEmptyArrays&&(""===l||r.strictNullHandling&&null===l)?[]:utils.combine([],l,r.arrayLimit,r.plainObjects);else{s=r.plainObjects?{__proto__:null}:{};var d="["===p.charAt(0)&&"]"===p.charAt(p.length-1)?p.slice(1,-1):p,c=r.decodeDotInKeys?d.replace(/%2E/g,"."):d,u=parseInt(c,10);r.parseArrays||""!==c?!isNaN(u)&&p!==c&&String(u)===c&&u>=0&&r.parseArrays&&u<=r.arrayLimit?(s=[])[u]=l:"__proto__"!==c&&(s[c]=l):s={0:l}}l=s}return l},splitKeyIntoSegments=function splitKeyIntoSegments(e,t){var r=t.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e;if(t.depth<=0){if(!t.plainObjects&&has.call(Object.prototype,r)&&!t.allowPrototypes)return;return[r]}var i=/(\[[^[\]]*])/g,a=/(\[[^[\]]*])/.exec(r),o=a?r.slice(0,a.index):r,l=[];if(o){if(!t.plainObjects&&has.call(Object.prototype,o)&&!t.allowPrototypes)return;l.push(o)}for(var n=0;null!==(a=i.exec(r))&&n0?g.join(",")||null:void 0}];else if(isArray(f))S=f;else{var N=Object.keys(g);S=u?N.sort(u):N}var T=l?String(r).replace(/\./g,"%2E"):String(r),O=o&&isArray(g)&&1===g.length?T+"[]":T;if(a&&isArray(g)&&0===g.length)return O+"[]";for(var k=0;k0?c+y:""}; + +},{"1":1,"46":46,"5":5}],5:[function(require,module,exports){ +"use strict";var formats=require(1),getSideChannel=require(46),has=Object.prototype.hasOwnProperty,isArray=Array.isArray,overflowChannel=getSideChannel(),markOverflow=function markOverflow(e,r){return overflowChannel.set(e,r),e},isOverflow=function isOverflow(e){return overflowChannel.has(e)},getMaxIndex=function getMaxIndex(e){return overflowChannel.get(e)},setMaxIndex=function setMaxIndex(e,r){overflowChannel.set(e,r)},hexTable=function(){for(var e=[],r=0;r<256;++r)e.push("%"+((r<16?"0":"")+r.toString(16)).toUpperCase());return e}(),compactQueue=function compactQueue(e){for(;e.length>1;){var r=e.pop(),t=r.obj[r.prop];if(isArray(t)){for(var o=[],n=0;n=limit?a.slice(i,i+limit):a,f=[],s=0;s=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||n===formats.RFC1738&&(40===u||41===u)?f[f.length]=l.charAt(s):u<128?f[f.length]=hexTable[u]:u<2048?f[f.length]=hexTable[192|u>>6]+hexTable[128|63&u]:u<55296||u>=57344?f[f.length]=hexTable[224|u>>12]+hexTable[128|u>>6&63]+hexTable[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&l.charCodeAt(s)),f[f.length]=hexTable[240|u>>18]+hexTable[128|u>>12&63]+hexTable[128|u>>6&63]+hexTable[128|63&u])}c+=f.join("")}return c},compact=function compact(e){for(var r=[{obj:{o:e},prop:"o"}],t=[],o=0;ot?markOverflow(arrayToObject(a,{plainObjects:o}),a.length-1):a},maybeMap=function maybeMap(e,r){if(isArray(e)){for(var t=[],o=0;o-1?callBindBasic([t]):t}; + +},{"10":10,"25":25}],25:[function(require,module,exports){ +"use strict";var undefined,$Object=require(22),$Error=require(16),$EvalError=require(15),$RangeError=require(17),$ReferenceError=require(18),$SyntaxError=require(19),$TypeError=require(20),$URIError=require(21),abs=require(34),floor=require(35),max=require(37),min=require(38),pow=require(39),round=require(40),sign=require(41),$Function=Function,getEvalledConstructor=function(r){try{return $Function('"use strict"; return ('+r+").constructor;")()}catch(r){}},$gOPD=require(30),$defineProperty=require(14),throwTypeError=function(){throw new $TypeError},ThrowTypeError=$gOPD?function(){try{return throwTypeError}catch(r){try{return $gOPD(arguments,"callee").get}catch(r){return throwTypeError}}}():throwTypeError,hasSymbols=require(31)(),getProto=require(28),$ObjectGPO=require(26),$ReflectGPO=require(27),$apply=require(8),$call=require(9),needsEval={},TypedArray="undefined"!=typeof Uint8Array&&getProto?getProto(Uint8Array):undefined,INTRINSICS={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols&&getProto?getProto([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":"undefined"==typeof Atomics?undefined:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?undefined:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?undefined:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":$Error,"%eval%":eval,"%EvalError%":$EvalError,"%Float16Array%":"undefined"==typeof Float16Array?undefined:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?undefined:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols&&getProto?getProto(getProto([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&hasSymbols&&getProto?getProto((new Map)[Symbol.iterator]()):undefined,"%Math%":Math,"%Number%":Number,"%Object%":$Object,"%Object.getOwnPropertyDescriptor%":$gOPD,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined:Proxy,"%RangeError%":$RangeError,"%ReferenceError%":$ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&hasSymbols&&getProto?getProto((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols&&getProto?getProto(""[Symbol.iterator]()):undefined,"%Symbol%":hasSymbols?Symbol:undefined,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined:Uint32Array,"%URIError%":$URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined:WeakSet,"%Function.prototype.call%":$call,"%Function.prototype.apply%":$apply,"%Object.defineProperty%":$defineProperty,"%Object.getPrototypeOf%":$ObjectGPO,"%Math.abs%":abs,"%Math.floor%":floor,"%Math.max%":max,"%Math.min%":min,"%Math.pow%":pow,"%Math.round%":round,"%Math.sign%":sign,"%Reflect.getPrototypeOf%":$ReflectGPO};if(getProto)try{null.error}catch(r){var errorProto=getProto(getProto(r));INTRINSICS["%Error.prototype%"]=errorProto}var doEval=function doEval(r){var e;if("%AsyncFunction%"===r)e=getEvalledConstructor("async function () {}");else if("%GeneratorFunction%"===r)e=getEvalledConstructor("function* () {}");else if("%AsyncGeneratorFunction%"===r)e=getEvalledConstructor("async function* () {}");else if("%AsyncGenerator%"===r){var t=doEval("%AsyncGeneratorFunction%");t&&(e=t.prototype)}else if("%AsyncIteratorPrototype%"===r){var o=doEval("%AsyncGenerator%");o&&getProto&&(e=getProto(o.prototype))}return INTRINSICS[r]=e,e},LEGACY_ALIASES={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},bind=require(24),hasOwn=require(33),$concat=bind.call($call,Array.prototype.concat),$spliceApply=bind.call($apply,Array.prototype.splice),$replace=bind.call($call,String.prototype.replace),$strSlice=bind.call($call,String.prototype.slice),$exec=bind.call($call,RegExp.prototype.exec),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g,stringToPath=function stringToPath(r){var e=$strSlice(r,0,1),t=$strSlice(r,-1);if("%"===e&&"%"!==t)throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");if("%"===t&&"%"!==e)throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");var o=[];return $replace(r,rePropName,function(r,e,t,n){o[o.length]=t?$replace(n,reEscapeChar,"$1"):e||r}),o},getBaseIntrinsic=function getBaseIntrinsic(r,e){var t,o=r;if(hasOwn(LEGACY_ALIASES,o)&&(o="%"+(t=LEGACY_ALIASES[o])[0]+"%"),hasOwn(INTRINSICS,o)){var n=INTRINSICS[o];if(n===needsEval&&(n=doEval(o)),void 0===n&&!e)throw new $TypeError("intrinsic "+r+" exists, but is not available. Please file an issue!");return{alias:t,name:o,value:n}}throw new $SyntaxError("intrinsic "+r+" does not exist!")};module.exports=function GetIntrinsic(r,e){if("string"!=typeof r||0===r.length)throw new $TypeError("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof e)throw new $TypeError('"allowMissing" argument must be a boolean');if(null===$exec(/^%?[^%]*%?$/,r))throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var t=stringToPath(r),o=t.length>0?t[0]:"",n=getBaseIntrinsic("%"+o+"%",e),a=n.name,i=n.value,y=!1,p=n.alias;p&&(o=p[0],$spliceApply(t,$concat([0,1],p)));for(var d=1,s=!0;d=t.length){var c=$gOPD(i,f);i=(s=!!c)&&"get"in c&&!("originalValue"in c.get)?c.get:i[f]}else s=hasOwn(i,f),i=i[f];s&&!y&&(INTRINSICS[a]=i)}}return i}; + +},{"14":14,"15":15,"16":16,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"24":24,"26":26,"27":27,"28":28,"30":30,"31":31,"33":33,"34":34,"35":35,"37":37,"38":38,"39":39,"40":40,"41":41,"8":8,"9":9}],13:[function(require,module,exports){ +"use strict";var hasProtoAccessor,callBind=require(10),gOPD=require(30);try{hasProtoAccessor=[].__proto__===Array.prototype}catch(t){if(!t||"object"!=typeof t||!("code"in t)||"ERR_PROTO_ACCESS"!==t.code)throw t}var desc=!!hasProtoAccessor&&gOPD&&gOPD(Object.prototype,"__proto__"),$Object=Object,$getPrototypeOf=$Object.getPrototypeOf;module.exports=desc&&"function"==typeof desc.get?callBind([desc.get]):"function"==typeof $getPrototypeOf&&function getDunder(t){return $getPrototypeOf(null==t?t:$Object(t))}; + +},{"10":10,"30":30}],30:[function(require,module,exports){ +"use strict";var $gOPD=require(29);if($gOPD)try{$gOPD([],"length")}catch(g){$gOPD=null}module.exports=$gOPD; + +},{"29":29}],14:[function(require,module,exports){ +"use strict";var $defineProperty=Object.defineProperty||!1;if($defineProperty)try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=!1}module.exports=$defineProperty; + +},{}],15:[function(require,module,exports){ +"use strict";module.exports=EvalError; + +},{}],16:[function(require,module,exports){ +"use strict";module.exports=Error; + +},{}],17:[function(require,module,exports){ +"use strict";module.exports=RangeError; + +},{}],18:[function(require,module,exports){ +"use strict";module.exports=ReferenceError; + +},{}],19:[function(require,module,exports){ +"use strict";module.exports=SyntaxError; + +},{}],21:[function(require,module,exports){ +"use strict";module.exports=URIError; + +},{}],22:[function(require,module,exports){ +"use strict";module.exports=Object; + +},{}],23:[function(require,module,exports){ +"use strict";var ERROR_MESSAGE="Function.prototype.bind called on incompatible ",toStr=Object.prototype.toString,max=Math.max,funcType="[object Function]",concatty=function concatty(t,n){for(var r=[],o=0;o-1e3&&t<1e3||$test.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof t){var n=t<0?-$floor(-t):$floor(t);if(n!==t){var o=String(n),i=$slice.call(e,o.length+1);return $replace.call(o,r,"$&_")+"."+$replace.call($replace.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return $replace.call(e,r,"$&_")}var utilInspect=require(6),inspectCustom=utilInspect.custom,inspectSymbol=isSymbol(inspectCustom)?inspectCustom:null,quotes={__proto__:null,double:'"',single:"'"},quoteREs={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};function wrapQuotes(t,e,r){var n=r.quoteStyle||e,o=quotes[n];return o+t+o}function quote(t){return $replace.call(String(t),/"/g,""")}function canTrustToString(t){return!toStringTag||!("object"==typeof t&&(toStringTag in t||void 0!==t[toStringTag]))}function isArray(t){return"[object Array]"===toStr(t)&&canTrustToString(t)}function isDate(t){return"[object Date]"===toStr(t)&&canTrustToString(t)}function isRegExp(t){return"[object RegExp]"===toStr(t)&&canTrustToString(t)}function isError(t){return"[object Error]"===toStr(t)&&canTrustToString(t)}function isString(t){return"[object String]"===toStr(t)&&canTrustToString(t)}function isNumber(t){return"[object Number]"===toStr(t)&&canTrustToString(t)}function isBoolean(t){return"[object Boolean]"===toStr(t)&&canTrustToString(t)}function isSymbol(t){if(hasShammedSymbols)return t&&"object"==typeof t&&t instanceof Symbol;if("symbol"==typeof t)return!0;if(!t||"object"!=typeof t||!symToString)return!1;try{return symToString.call(t),!0}catch(t){}return!1}function isBigInt(t){if(!t||"object"!=typeof t||!bigIntValueOf)return!1;try{return bigIntValueOf.call(t),!0}catch(t){}return!1}module.exports=function inspect_(t,e,r,n){var o=e||{};if(has(o,"quoteStyle")&&!has(quotes,o.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(has(o,"maxStringLength")&&("number"==typeof o.maxStringLength?o.maxStringLength<0&&o.maxStringLength!==1/0:null!==o.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var i=!has(o,"customInspect")||o.customInspect;if("boolean"!=typeof i&&"symbol"!==i)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(has(o,"indent")&&null!==o.indent&&"\t"!==o.indent&&!(parseInt(o.indent,10)===o.indent&&o.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(has(o,"numericSeparator")&&"boolean"!=typeof o.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var a=o.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return inspectString(t,o);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var c=String(t);return a?addNumericSeparator(t,c):c}if("bigint"==typeof t){var l=String(t)+"n";return a?addNumericSeparator(t,l):l}var u=void 0===o.depth?5:o.depth;if(void 0===r&&(r=0),r>=u&&u>0&&"object"==typeof t)return isArray(t)?"[Array]":"[Object]";var p=getIndent(o,r);if(void 0===n)n=[];else if(indexOf(n,t)>=0)return"[Circular]";function inspect(t,e,i){if(e&&(n=$arrSlice.call(n)).push(e),i){var a={depth:o.depth};return has(o,"quoteStyle")&&(a.quoteStyle=o.quoteStyle),inspect_(t,a,r+1,n)}return inspect_(t,o,r+1,n)}if("function"==typeof t&&!isRegExp(t)){var s=nameOf(t),f=arrObjKeys(t,inspect);return"[Function"+(s?": "+s:" (anonymous)")+"]"+(f.length>0?" { "+$join.call(f,", ")+" }":"")}if(isSymbol(t)){var y=hasShammedSymbols?$replace.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):symToString.call(t);return"object"!=typeof t||hasShammedSymbols?y:markBoxed(y)}if(isElement(t)){for(var S="<"+$toLowerCase.call(String(t.nodeName)),g=t.attributes||[],m=0;m"}if(isArray(t)){if(0===t.length)return"[]";var b=arrObjKeys(t,inspect);return p&&!singleLineValues(b)?"["+indentedJoin(b,p)+"]":"[ "+$join.call(b,", ")+" ]"}if(isError(t)){var h=arrObjKeys(t,inspect);return"cause"in Error.prototype||!("cause"in t)||isEnumerable.call(t,"cause")?0===h.length?"["+String(t)+"]":"{ ["+String(t)+"] "+$join.call(h,", ")+" }":"{ ["+String(t)+"] "+$join.call($concat.call("[cause]: "+inspect(t.cause),h),", ")+" }"}if("object"==typeof t&&i){if(inspectSymbol&&"function"==typeof t[inspectSymbol]&&utilInspect)return utilInspect(t,{depth:u-r});if("symbol"!==i&&"function"==typeof t.inspect)return t.inspect()}if(isMap(t)){var d=[];return mapForEach&&mapForEach.call(t,function(e,r){d.push(inspect(r,t,!0)+" => "+inspect(e,t))}),collectionOf("Map",mapSize.call(t),d,p)}if(isSet(t)){var O=[];return setForEach&&setForEach.call(t,function(e){O.push(inspect(e,t))}),collectionOf("Set",setSize.call(t),O,p)}if(isWeakMap(t))return weakCollectionOf("WeakMap");if(isWeakSet(t))return weakCollectionOf("WeakSet");if(isWeakRef(t))return weakCollectionOf("WeakRef");if(isNumber(t))return markBoxed(inspect(Number(t)));if(isBigInt(t))return markBoxed(inspect(bigIntValueOf.call(t)));if(isBoolean(t))return markBoxed(booleanValueOf.call(t));if(isString(t))return markBoxed(inspect(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&t===globalThis||"undefined"!=typeof global&&t===global)return"{ [object globalThis] }";if(!isDate(t)&&!isRegExp(t)){var j=arrObjKeys(t,inspect),w=gPO?gPO(t)===Object.prototype:t instanceof Object||t.constructor===Object,$=t instanceof Object?"":"null prototype",v=!w&&toStringTag&&Object(t)===t&&toStringTag in t?$slice.call(toStr(t),8,-1):$?"Object":"",k=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(v||$?"["+$join.call($concat.call([],v||[],$||[]),": ")+"] ":"");return 0===j.length?k+"{}":p?k+"{"+indentedJoin(j,p)+"}":k+"{ "+$join.call(j,", ")+" }"}return String(t)};var hasOwn=Object.prototype.hasOwnProperty||function(t){return t in this};function has(t,e){return hasOwn.call(t,e)}function toStr(t){return objectToString.call(t)}function nameOf(t){if(t.name)return t.name;var e=$match.call(functionToString.call(t),/^function\s*([\w$]+)/);return e?e[1]:null}function indexOf(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;re.maxStringLength){var r=t.length-e.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return inspectString($slice.call(t,0,e.maxStringLength),e)+n}var o=quoteREs[e.quoteStyle||"single"];return o.lastIndex=0,wrapQuotes($replace.call($replace.call(t,o,"\\$1"),/[\x00-\x1f]/g,lowbyte),"single",e)}function lowbyte(t){var e=t.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return r?"\\"+r:"\\x"+(e<16?"0":"")+$toUpperCase.call(e.toString(16))}function markBoxed(t){return"Object("+t+")"}function weakCollectionOf(t){return t+" { ? }"}function collectionOf(t,e,r,n){return t+" ("+e+") {"+(n?indentedJoin(r,n):$join.call(r,", "))+"}"}function singleLineValues(t){for(var e=0;e=0)return!1;return!0}function getIndent(t,e){var r;if("\t"===t.indent)r="\t";else{if(!("number"==typeof t.indent&&t.indent>0))return null;r=$join.call(Array(t.indent+1)," ")}return{base:r,prev:$join.call(Array(e+1),r)}}function indentedJoin(t,e){if(0===t.length)return"";var r="\n"+e.prev+e.base;return r+$join.call(t,","+r)+"\n"+e.prev}function arrObjKeys(t,e){var r=isArray(t),n=[];if(r){n.length=t.length;for(var o=0;o -1) { + return val.split(','); + } + + if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) { + throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); + } + + return val; +}; + +// This is what browsers will submit when the ✓ character occurs in an +// application/x-www-form-urlencoded body and the encoding of the page containing +// the form is iso-8859-1, or when the submitted form has an accept-charset +// attribute of iso-8859-1. Presumably also with other charsets that do not contain +// the ✓ character, such as us-ascii. +var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') + +// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. +var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') + +var parseValues = function parseQueryStringValues(str, options) { + var obj = { __proto__: null }; + + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + cleanStr = cleanStr.replace(/%5B/gi, '[').replace(/%5D/gi, ']'); + + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split( + options.delimiter, + options.throwOnLimitExceeded ? limit + 1 : limit + ); + + if (options.throwOnLimitExceeded && parts.length > limit) { + throw new RangeError('Parameter limit exceeded. Only ' + limit + ' parameter' + (limit === 1 ? '' : 's') + ' allowed.'); + } + + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; + + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf('utf8=') === 0) { + if (parts[i] === charsetSentinel) { + charset = 'utf-8'; + } else if (parts[i] === isoSentinel) { + charset = 'iso-8859-1'; + } + skipIndex = i; + i = parts.length; // The eslint settings do not allow break; + } + } + } + + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key; + var val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, 'key'); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); + + if (key !== null) { + val = utils.maybeMap( + parseArrayValue( + part.slice(pos + 1), + options, + isArray(obj[key]) ? obj[key].length : 0 + ), + function (encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, 'value'); + } + ); + } + } + + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(String(val)); + } + + if (part.indexOf('[]=') > -1) { + val = isArray(val) ? [val] : val; + } + + if (key !== null) { + var existing = has.call(obj, key); + if (existing && options.duplicates === 'combine') { + obj[key] = utils.combine( + obj[key], + val, + options.arrayLimit, + options.plainObjects + ); + } else if (!existing || options.duplicates === 'last') { + obj[key] = val; + } + } + } + + return obj; +}; + +var parseObject = function (chain, val, options, valuesParsed) { + var currentArrayLength = 0; + if (chain.length > 0 && chain[chain.length - 1] === '[]') { + var parentKey = chain.slice(0, -1).join(''); + currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0; + } + + var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength); + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + if (utils.isOverflow(leaf)) { + // leaf is already an overflow object, preserve it + obj = leaf; + } else { + obj = options.allowEmptyArrays && (leaf === '' || (options.strictNullHandling && leaf === null)) + ? [] + : utils.combine( + [], + leaf, + options.arrayLimit, + options.plainObjects + ); + } + } else { + obj = options.plainObjects ? { __proto__: null } : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, '.') : cleanRoot; + var index = parseInt(decodedRoot, 10); + if (!options.parseArrays && decodedRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== decodedRoot + && String(index) === decodedRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else if (decodedRoot !== '__proto__') { + obj[decodedRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var splitKeyIntoSegments = function splitKeyIntoSegments(givenKey, options) { + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + if (options.depth <= 0) { + if (!options.plainObjects && has.call(Object.prototype, key)) { + if (!options.allowPrototypes) { + return; + } + } + + return [key]; + } + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + var segment = brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + var keys = []; + + if (parent) { + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + + var segmentContent = segment[1].slice(1, -1); + if (!options.plainObjects && has.call(Object.prototype, segmentContent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(segment[1]); + } + + if (segment) { + if (options.strictDepth === true) { + throw new RangeError('Input depth exceeded depth option of ' + options.depth + ' and strictDepth is true'); + } + + keys.push('[' + key.slice(segment.index) + ']'); + } + + return keys; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + + var keys = splitKeyIntoSegments(givenKey, options); + + if (!keys) { + return; + } + + return parseObject(keys, val, options, valuesParsed); +}; + +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.decodeDotInKeys !== 'undefined' && typeof opts.decodeDotInKeys !== 'boolean') { + throw new TypeError('`decodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.decoder !== null && typeof opts.decoder !== 'undefined' && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + if (typeof opts.throwOnLimitExceeded !== 'undefined' && typeof opts.throwOnLimitExceeded !== 'boolean') { + throw new TypeError('`throwOnLimitExceeded` option must be a boolean'); + } + + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + var duplicates = typeof opts.duplicates === 'undefined' ? defaults.duplicates : opts.duplicates; + + if (duplicates !== 'combine' && duplicates !== 'first' && duplicates !== 'last') { + throw new TypeError('The duplicates option must be either combine, first, or last'); + } + + var allowDots = typeof opts.allowDots === 'undefined' ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + + return { + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decodeDotInKeys: typeof opts.decodeDotInKeys === 'boolean' ? opts.decodeDotInKeys : defaults.decodeDotInKeys, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, + duplicates: duplicates, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictDepth: typeof opts.strictDepth === 'boolean' ? !!opts.strictDepth : defaults.strictDepth, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, + throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === 'boolean' ? opts.throwOnLimitExceeded : false + }; +}; + +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? { __proto__: null } : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? { __proto__: null } : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); + obj = utils.merge(obj, newObj, options); + } + + if (options.allowSparse === true) { + return obj; + } + + return utils.compact(obj); +}; diff --git a/node_modules/qs/lib/stringify.js b/node_modules/qs/lib/stringify.js new file mode 100644 index 000000000..2666eaf9c --- /dev/null +++ b/node_modules/qs/lib/stringify.js @@ -0,0 +1,356 @@ +'use strict'; + +var getSideChannel = require('side-channel'); +var utils = require('./utils'); +var formats = require('./formats'); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } +}; + +var isArray = Array.isArray; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaultFormat = formats['default']; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: 'indices', + charset: 'utf-8', + charsetSentinel: false, + commaRoundTrip: false, + delimiter: '&', + encode: true, + encodeDotInKeys: false, + encoder: utils.encode, + encodeValuesOnly: false, + filter: void undefined, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var isNonNullishPrimitive = function isNonNullishPrimitive(v) { + return typeof v === 'string' + || typeof v === 'number' + || typeof v === 'boolean' + || typeof v === 'symbol' + || typeof v === 'bigint'; +}; + +var sentinel = {}; + +var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + sideChannel +) { + var obj = object; + + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { + // Where object last appeared in the ref tree + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + findFlag = true; // Break while + } + } + if (typeof tmpSc.get(sentinel) === 'undefined') { + step = 0; + } + } + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = utils.maybeMap(obj, function (value) { + if (value instanceof Date) { + return serializeDate(value); + } + return value; + }); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; + } + + obj = ''; + } + + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + if (encodeValuesOnly && encoder) { + obj = utils.maybeMap(obj, encoder); + } + objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); + + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix; + + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjustedPrefix + '[]'; + } + + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === 'object' && key && typeof key.value !== 'undefined' + ? key.value + : obj[key]; + + if (skipNulls && value === null) { + continue; + } + + var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, '%2E') : String(key); + var keyPrefix = isArray(obj) + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + encodedKey : '[' + encodedKey + ']'); + + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { + throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + var arrayFormat; + if (opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if ('indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = defaults.arrayFormat; + } + + if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + + var allowDots = typeof opts.allowDots === 'undefined' ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat: arrayFormat, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat]; + var commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + var sideChannel = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + var value = obj[key]; + + if (options.skipNulls && value === null) { + continue; + } + pushToArray(keys, stringify( + value, + key, + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; diff --git a/node_modules/qs/lib/utils.js b/node_modules/qs/lib/utils.js new file mode 100644 index 000000000..91f555e48 --- /dev/null +++ b/node_modules/qs/lib/utils.js @@ -0,0 +1,320 @@ +'use strict'; + +var formats = require('./formats'); +var getSideChannel = require('side-channel'); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +// Track objects created from arrayLimit overflow using side-channel +// Stores the current max numeric index for O(1) lookup +var overflowChannel = getSideChannel(); + +var markOverflow = function markOverflow(obj, maxIndex) { + overflowChannel.set(obj, maxIndex); + return obj; +}; + +var isOverflow = function isOverflow(obj) { + return overflowChannel.has(obj); +}; + +var getMaxIndex = function getMaxIndex(obj) { + return overflowChannel.get(obj); +}; + +var setMaxIndex = function setMaxIndex(obj, maxIndex) { + overflowChannel.set(obj, maxIndex); +}; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? { __proto__: null } : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } + + if (typeof source !== 'object' && typeof source !== 'function') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if (isOverflow(target)) { + // Add at next numeric index for overflow objects + var newIndex = getMaxIndex(target) + 1; + target[newIndex] = source; + setMaxIndex(target, newIndex); + } else if ( + (options && (options.plainObjects || options.allowPrototypes)) + || !has.call(Object.prototype, source) + ) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + if (isOverflow(source)) { + // Create new object with target at 0, source values shifted by 1 + var sourceKeys = Object.keys(source); + var result = options && options.plainObjects + ? { __proto__: null, 0: target } + : { 0: target }; + for (var m = 0; m < sourceKeys.length; m++) { + var oldKey = parseInt(sourceKeys[m], 10); + result[oldKey + 1] = source[sourceKeys[m]]; + } + return markOverflow(result, getMaxIndex(source) + 1); + } + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, defaultDecoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var limit = 1024; + +/* eslint operator-linebreak: [2, "before"] */ + +var encode = function encode(str, defaultEncoder, charset, kind, format) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var j = 0; j < string.length; j += limit) { + var segment = string.length >= limit ? string.slice(j, j + limit) : string; + var arr = []; + + for (var i = 0; i < segment.length; ++i) { + var c = segment.charCodeAt(i); + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + arr[arr.length] = segment.charAt(i); + continue; + } + + if (c < 0x80) { + arr[arr.length] = hexTable[c]; + continue; + } + + if (c < 0x800) { + arr[arr.length] = hexTable[0xC0 | (c >> 6)] + + hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + arr[arr.length] = hexTable[0xE0 | (c >> 12)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (segment.charCodeAt(i) & 0x3FF)); + + arr[arr.length] = hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + out += arr.join(''); + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b, arrayLimit, plainObjects) { + // If 'a' is already an overflow object, add to it + if (isOverflow(a)) { + var newIndex = getMaxIndex(a) + 1; + a[newIndex] = b; + setMaxIndex(a, newIndex); + return a; + } + + var result = [].concat(a, b); + if (result.length > arrayLimit) { + return markOverflow(arrayToObject(result, { plainObjects: plainObjects }), result.length - 1); + } + return result; +}; + +var maybeMap = function maybeMap(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isOverflow: isOverflow, + isRegExp: isRegExp, + maybeMap: maybeMap, + merge: merge +}; diff --git a/node_modules/qs/package.json b/node_modules/qs/package.json new file mode 100644 index 000000000..e4875e4a8 --- /dev/null +++ b/node_modules/qs/package.json @@ -0,0 +1,94 @@ +{ + "name": "qs", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/ljharb/qs", + "version": "6.14.1", + "repository": { + "type": "git", + "url": "https://github.com/ljharb/qs.git" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "main": "lib/index.js", + "sideEffects": false, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "keywords": [ + "querystring", + "qs", + "query", + "url", + "parse", + "stringify" + ], + "engines": { + "node": ">=0.6" + }, + "dependencies": { + "side-channel": "^1.1.0" + }, + "devDependencies": { + "@browserify/envify": "^6.0.0", + "@browserify/uglifyify": "^6.0.0", + "@ljharb/eslint-config": "^22.1.3", + "browserify": "^16.5.2", + "bundle-collapser": "^1.4.0", + "common-shakeify": "~1.0.0", + "eclint": "^2.8.1", + "es-value-fixtures": "^1.7.1", + "eslint": "^9.39.2", + "evalmd": "^0.0.19", + "for-each": "^0.3.5", + "glob": "=10.3.7", + "has-bigints": "^1.1.0", + "has-override-mistake": "^1.0.1", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "iconv-lite": "^0.5.1", + "in-publish": "^2.0.1", + "jackspeak": "=2.1.1", + "jiti": "^0.0.0", + "mkdirp": "^0.5.5", + "mock-property": "^1.1.0", + "module-deps": "^6.2.3", + "npmignore": "^0.3.5", + "nyc": "^10.3.2", + "object-inspect": "^1.13.4", + "qs-iconv": "^1.0.4", + "safe-publish-latest": "^2.0.0", + "safer-buffer": "^2.1.2", + "tape": "^5.9.0", + "unassertify": "^3.0.1" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated && npm run dist", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent readme && npm run --silent lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "npx npm@'>=10.2' audit --production", + "readme": "evalmd README.md", + "postlint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "lint": "eslint .", + "dist": "mkdirp dist && browserify --standalone Qs -g unassertify -g @browserify/envify -g [@browserify/uglifyify --mangle.keep_fnames --compress.keep_fnames --format.indent_level=1 --compress.arrows=false --compress.passes=4 --compress.typeofs=false] -p common-shakeify -p bundle-collapser/plugin lib/index.js > dist/qs.js" + }, + "license": "BSD-3-Clause", + "publishConfig": { + "ignore": [ + "!dist/*", + "bower.json", + "component.json", + ".github/workflows", + "logos", + "tea.yaml" + ] + } +} diff --git a/node_modules/qs/test/empty-keys-cases.js b/node_modules/qs/test/empty-keys-cases.js new file mode 100644 index 000000000..2b1190ef5 --- /dev/null +++ b/node_modules/qs/test/empty-keys-cases.js @@ -0,0 +1,267 @@ +'use strict'; + +module.exports = { + emptyTestCases: [ + { + input: '&', + withEmptyKeys: {}, + stringifyOutput: { + brackets: '', + indices: '', + repeat: '' + }, + noEmptyKeys: {} + }, + { + input: '&&', + withEmptyKeys: {}, + stringifyOutput: { + brackets: '', + indices: '', + repeat: '' + }, + noEmptyKeys: {} + }, + { + input: '&=', + withEmptyKeys: { '': '' }, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + }, + noEmptyKeys: {} + }, + { + input: '&=&', + withEmptyKeys: { '': '' }, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + }, + noEmptyKeys: {} + }, + { + input: '&=&=', + withEmptyKeys: { '': ['', ''] }, + stringifyOutput: { + brackets: '[]=&[]=', + indices: '[0]=&[1]=', + repeat: '=&=' + }, + noEmptyKeys: {} + }, + { + input: '&=&=&', + withEmptyKeys: { '': ['', ''] }, + stringifyOutput: { + brackets: '[]=&[]=', + indices: '[0]=&[1]=', + repeat: '=&=' + }, + noEmptyKeys: {} + }, + { + input: '=', + withEmptyKeys: { '': '' }, + noEmptyKeys: {}, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + } + }, + { + input: '=&', + withEmptyKeys: { '': '' }, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + }, + noEmptyKeys: {} + }, + { + input: '=&&&', + withEmptyKeys: { '': '' }, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + }, + noEmptyKeys: {} + }, + { + input: '=&=&=&', + withEmptyKeys: { '': ['', '', ''] }, + stringifyOutput: { + brackets: '[]=&[]=&[]=', + indices: '[0]=&[1]=&[2]=', + repeat: '=&=&=' + }, + noEmptyKeys: {} + }, + { + input: '=&a[]=b&a[1]=c', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: '=a', + withEmptyKeys: { '': 'a' }, + noEmptyKeys: {}, + stringifyOutput: { + brackets: '=a', + indices: '=a', + repeat: '=a' + } + }, + { + input: 'a==a', + withEmptyKeys: { a: '=a' }, + noEmptyKeys: { a: '=a' }, + stringifyOutput: { + brackets: 'a==a', + indices: 'a==a', + repeat: 'a==a' + } + }, + { + input: '=&a[]=b', + withEmptyKeys: { '': '', a: ['b'] }, + stringifyOutput: { + brackets: '=&a[]=b', + indices: '=&a[0]=b', + repeat: '=&a=b' + }, + noEmptyKeys: { a: ['b'] } + }, + { + input: '=&a[]=b&a[]=c&a[2]=d', + withEmptyKeys: { '': '', a: ['b', 'c', 'd'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c&a[]=d', + indices: '=&a[0]=b&a[1]=c&a[2]=d', + repeat: '=&a=b&a=c&a=d' + }, + noEmptyKeys: { a: ['b', 'c', 'd'] } + }, + { + input: '=a&=b', + withEmptyKeys: { '': ['a', 'b'] }, + stringifyOutput: { + brackets: '[]=a&[]=b', + indices: '[0]=a&[1]=b', + repeat: '=a&=b' + }, + noEmptyKeys: {} + }, + { + input: '=a&foo=b', + withEmptyKeys: { '': 'a', foo: 'b' }, + noEmptyKeys: { foo: 'b' }, + stringifyOutput: { + brackets: '=a&foo=b', + indices: '=a&foo=b', + repeat: '=a&foo=b' + } + }, + { + input: 'a[]=b&a=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: 'a[]=b&a=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: 'a[0]=b&a=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: 'a=b&a[]=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: 'a=b&a[0]=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: '[]=a&[]=b& []=1', + withEmptyKeys: { '': ['a', 'b'], ' ': ['1'] }, + stringifyOutput: { + brackets: '[]=a&[]=b& []=1', + indices: '[0]=a&[1]=b& [0]=1', + repeat: '=a&=b& =1' + }, + noEmptyKeys: { 0: 'a', 1: 'b', ' ': ['1'] } + }, + { + input: '[0]=a&[1]=b&a[0]=1&a[1]=2', + withEmptyKeys: { '': ['a', 'b'], a: ['1', '2'] }, + noEmptyKeys: { 0: 'a', 1: 'b', a: ['1', '2'] }, + stringifyOutput: { + brackets: '[]=a&[]=b&a[]=1&a[]=2', + indices: '[0]=a&[1]=b&a[0]=1&a[1]=2', + repeat: '=a&=b&a=1&a=2' + } + }, + { + input: '[deep]=a&[deep]=2', + withEmptyKeys: { '': { deep: ['a', '2'] } + }, + stringifyOutput: { + brackets: '[deep][]=a&[deep][]=2', + indices: '[deep][0]=a&[deep][1]=2', + repeat: '[deep]=a&[deep]=2' + }, + noEmptyKeys: { deep: ['a', '2'] } + }, + { + input: '%5B0%5D=a&%5B1%5D=b', + withEmptyKeys: { '': ['a', 'b'] }, + stringifyOutput: { + brackets: '[]=a&[]=b', + indices: '[0]=a&[1]=b', + repeat: '=a&=b' + }, + noEmptyKeys: { 0: 'a', 1: 'b' } + } + ] +}; diff --git a/node_modules/qs/test/parse.js b/node_modules/qs/test/parse.js new file mode 100644 index 000000000..7b353ffc9 --- /dev/null +++ b/node_modules/qs/test/parse.js @@ -0,0 +1,1396 @@ +'use strict'; + +var test = require('tape'); +var hasPropertyDescriptors = require('has-property-descriptors')(); +var iconv = require('iconv-lite'); +var mockProperty = require('mock-property'); +var hasOverrideMistake = require('has-override-mistake')(); +var SaferBuffer = require('safer-buffer').Buffer; +var v = require('es-value-fixtures'); +var inspect = require('object-inspect'); +var emptyTestCases = require('./empty-keys-cases').emptyTestCases; +var hasProto = require('has-proto')(); + +var qs = require('../'); +var utils = require('../lib/utils'); + +test('parse()', function (t) { + t.test('parses a simple string', function (st) { + st.deepEqual(qs.parse('0=foo'), { 0: 'foo' }); + st.deepEqual(qs.parse('foo=c++'), { foo: 'c ' }); + st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } }); + st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } }); + st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } }); + st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null }); + st.deepEqual(qs.parse('foo'), { foo: '' }); + st.deepEqual(qs.parse('foo='), { foo: '' }); + st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' }); + st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' }); + st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' }); + st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' }); + st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' }); + st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null }); + st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' }); + st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), { + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + st.end(); + }); + + t.test('comma: false', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c'), { a: 'b,c' }); + st.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('comma: true', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c', { comma: true }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { comma: true }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c', { comma: true }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a=c', { comma: true }), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('allows enabling dot notation', function (st) { + st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' }); + st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } }); + + st.end(); + }); + + t.test('decode dot keys correctly', function (st) { + st.deepEqual( + qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: false, decodeDotInKeys: false }), + { 'name%2Eobj.first': 'John', 'name%2Eobj.last': 'Doe' }, + 'with allowDots false and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse('name.obj.first=John&name.obj.last=Doe', { allowDots: true, decodeDotInKeys: false }), + { name: { obj: { first: 'John', last: 'Doe' } } }, + 'with allowDots false and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: true, decodeDotInKeys: false }), + { 'name%2Eobj': { first: 'John', last: 'Doe' } }, + 'with allowDots true and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: true, decodeDotInKeys: true }), + { 'name.obj': { first: 'John', last: 'Doe' } }, + 'with allowDots true and decodeDotInKeys true' + ); + + st.deepEqual( + qs.parse( + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + { allowDots: false, decodeDotInKeys: false } + ), + { 'name%2Eobj%2Esubobject.first%2Egodly%2Ename': 'John', 'name%2Eobj%2Esubobject.last': 'Doe' }, + 'with allowDots false and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse( + 'name.obj.subobject.first.godly.name=John&name.obj.subobject.last=Doe', + { allowDots: true, decodeDotInKeys: false } + ), + { name: { obj: { subobject: { first: { godly: { name: 'John' } }, last: 'Doe' } } } }, + 'with allowDots true and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse( + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + { allowDots: true, decodeDotInKeys: true } + ), + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + 'with allowDots true and decodeDotInKeys true' + ); + st.deepEqual( + qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe'), + { 'name%2Eobj.first': 'John', 'name%2Eobj.last': 'Doe' }, + 'with allowDots and decodeDotInKeys undefined' + ); + + st.end(); + }); + + t.test('decodes dot in key of object, and allow enabling dot notation when decodeDotInKeys is set to true and allowDots is undefined', function (st) { + st.deepEqual( + qs.parse( + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + { decodeDotInKeys: true } + ), + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + 'with allowDots undefined and decodeDotInKeys true' + ); + + st.end(); + }); + + t.test('throws when decodeDotInKeys is not of type boolean', function (st) { + st['throws']( + function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: 'foobar' }); }, + TypeError + ); + + st['throws']( + function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: 0 }); }, + TypeError + ); + st['throws']( + function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: NaN }); }, + TypeError + ); + + st['throws']( + function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: null }); }, + TypeError + ); + + st.end(); + }); + + t.test('allows empty arrays in obj values', function (st) { + st.deepEqual(qs.parse('foo[]&bar=baz', { allowEmptyArrays: true }), { foo: [], bar: 'baz' }); + st.deepEqual(qs.parse('foo[]&bar=baz', { allowEmptyArrays: false }), { foo: [''], bar: 'baz' }); + + st.end(); + }); + + t.test('throws when allowEmptyArrays is not of type boolean', function (st) { + st['throws']( + function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: 'foobar' }); }, + TypeError + ); + + st['throws']( + function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: 0 }); }, + TypeError + ); + st['throws']( + function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: NaN }); }, + TypeError + ); + + st['throws']( + function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: null }); }, + TypeError + ); + + st.end(); + }); + + t.test('allowEmptyArrays + strictNullHandling', function (st) { + st.deepEqual( + qs.parse('testEmptyArray[]', { strictNullHandling: true, allowEmptyArrays: true }), + { testEmptyArray: [] } + ); + + st.end(); + }); + + t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string'); + t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string'); + t.deepEqual( + qs.parse('a[b][c][d][e][f][g][h]=i'), + { a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }, + 'defaults to a depth of 5' + ); + + t.test('only parses one level when depth = 1', function (st) { + st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } }); + st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } }); + st.end(); + }); + + t.test('uses original key when depth = 0', function (st) { + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: 0 }), { 'a[0]': 'b', 'a[1]': 'c' }); + st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: 0 }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' }); + st.end(); + }); + + t.test('uses original key when depth = false', function (st) { + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: false }), { 'a[0]': 'b', 'a[1]': 'c' }); + st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: false }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' }); + st.end(); + }); + + t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array'); + + t.test('parses an explicit array', function (st) { + st.deepEqual(qs.parse('a[]=b'), { a: ['b'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] }); + st.end(); + }); + + t.test('parses a mix of simple and explicit arrays', function (st) { + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a[1]=b&a=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a=b&a[1]=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } }); + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + + st.end(); + }); + + t.test('parses a nested array', function (st) { + st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } }); + st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } }); + st.end(); + }); + + t.test('allows to specify array indices', function (st) { + st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] }); + st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 20 }), { a: ['c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 0 }), { a: { 1: 'c' } }); + st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] }); + st.end(); + }); + + t.test('limits specific array indices to arrayLimit', function (st) { + st.deepEqual(qs.parse('a[20]=a', { arrayLimit: 20 }), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a', { arrayLimit: 20 }), { a: { 21: 'a' } }); + + st.deepEqual(qs.parse('a[20]=a'), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a'), { a: { 21: 'a' } }); + st.end(); + }); + + t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number'); + + t.test('supports encoded = signs', function (st) { + st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' }); + st.end(); + }); + + t.test('is ok with url encoded strings', function (st) { + st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } }); + st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } }); + st.end(); + }); + + t.test('allows brackets in the value', function (st) { + st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' }); + st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' }); + st.end(); + }); + + t.test('allows empty values', function (st) { + st.deepEqual(qs.parse(''), {}); + st.deepEqual(qs.parse(null), {}); + st.deepEqual(qs.parse(undefined), {}); + st.end(); + }); + + t.test('transforms arrays to objects', function (st) { + st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: false }), { a: { 0: 'b', t: 'u' } }); + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: true }), { a: { 0: 'b', t: 'u', hasOwnProperty: 'c' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: false }), { a: { 0: 'b', x: 'y' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: true }), { a: { 0: 'b', hasOwnProperty: 'c', x: 'y' } }); + st.end(); + }); + + t.test('transforms arrays to objects (dot notation)', function (st) { + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] }); + st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + st.end(); + }); + + t.test('correctly prunes undefined values when converting an array to an object', function (st) { + st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { 2: 'b', 99999999: 'c' } }); + st.end(); + }); + + t.test('supports malformed uri characters', function (st) { + st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null }); + st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' }); + st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' }); + st.end(); + }); + + t.test('doesn\'t produce empty keys', function (st) { + st.deepEqual(qs.parse('_r=1&'), { _r: '1' }); + st.end(); + }); + + t.test('cannot access Object prototype', function (st) { + qs.parse('constructor[prototype][bad]=bad'); + qs.parse('bad[constructor][prototype][bad]=bad'); + st.equal(typeof Object.prototype.bad, 'undefined'); + st.end(); + }); + + t.test('parses arrays of objects', function (st) { + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] }); + st.end(); + }); + + t.test('allows for empty strings in arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] }); + + st.deepEqual( + qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 20 + array indices: null then empty string works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }), + { a: { 0: 'b', 1: null, 2: 'c', 3: '' } }, + 'with arrayLimit 0 + array brackets: null then empty string works' + ); + + st.deepEqual( + qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 20 + array indices: empty string then null works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }), + { a: { 0: 'b', 1: '', 2: 'c', 3: null } }, + 'with arrayLimit 0 + array brackets: empty string then null works' + ); + + st.deepEqual( + qs.parse('a[]=&a[]=b&a[]=c'), + { a: ['', 'b', 'c'] }, + 'array brackets: empty strings work' + ); + st.end(); + }); + + t.test('compacts sparse arrays', function (st) { + st.deepEqual(qs.parse('a[10]=1&a[2]=2', { arrayLimit: 20 }), { a: ['2', '1'] }); + st.deepEqual(qs.parse('a[1][b][2][c]=1', { arrayLimit: 20 }), { a: [{ b: [{ c: '1' }] }] }); + st.deepEqual(qs.parse('a[1][2][3][c]=1', { arrayLimit: 20 }), { a: [[[{ c: '1' }]]] }); + st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { arrayLimit: 20 }), { a: [[[{ c: ['1'] }]]] }); + st.end(); + }); + + t.test('parses sparse arrays', function (st) { + /* eslint no-sparse-arrays: 0 */ + st.deepEqual(qs.parse('a[4]=1&a[1]=2', { allowSparse: true }), { a: [, '2', , , '1'] }); + st.deepEqual(qs.parse('a[1][b][2][c]=1', { allowSparse: true }), { a: [, { b: [, , { c: '1' }] }] }); + st.deepEqual(qs.parse('a[1][2][3][c]=1', { allowSparse: true }), { a: [, [, , [, , , { c: '1' }]]] }); + st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { allowSparse: true }), { a: [, [, , [, , , { c: [, '1'] }]]] }); + st.end(); + }); + + t.test('parses semi-parsed strings', function (st) { + st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } }); + st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } }); + st.end(); + }); + + t.test('parses buffers correctly', function (st) { + var b = SaferBuffer.from('test'); + st.deepEqual(qs.parse({ a: b }), { a: b }); + st.end(); + }); + + t.test('parses jquery-param strings', function (st) { + // readable = 'filter[0][]=int1&filter[0][]==&filter[0][]=77&filter[]=and&filter[2][]=int2&filter[2][]==&filter[2][]=8' + var encoded = 'filter%5B0%5D%5B%5D=int1&filter%5B0%5D%5B%5D=%3D&filter%5B0%5D%5B%5D=77&filter%5B%5D=and&filter%5B2%5D%5B%5D=int2&filter%5B2%5D%5B%5D=%3D&filter%5B2%5D%5B%5D=8'; + var expected = { filter: [['int1', '=', '77'], 'and', ['int2', '=', '8']] }; + st.deepEqual(qs.parse(encoded), expected); + st.end(); + }); + + t.test('continues parsing when no parent is found', function (st) { + st.deepEqual(qs.parse('[]=&a=b'), { 0: '', a: 'b' }); + st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { 0: null, a: 'b' }); + st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' }); + st.end(); + }); + + t.test('does not error when parsing a very long array', function (st) { + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str = str + '&' + str; + } + + st.doesNotThrow(function () { + qs.parse(str); + }); + + st.end(); + }); + + t.test('does not throw when a native prototype has an enumerable property', function (st) { + st.intercept(Object.prototype, 'crash', { value: '' }); + st.intercept(Array.prototype, 'crash', { value: '' }); + + st.doesNotThrow(qs.parse.bind(null, 'a=b')); + st.deepEqual(qs.parse('a=b'), { a: 'b' }); + st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c')); + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + + st.end(); + }); + + t.test('parses a string with an alternative string delimiter', function (st) { + st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('parses a string with an alternative RegExp delimiter', function (st) { + st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not use non-splittable objects as delimiters', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding parameter limit', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' }); + st.end(); + }); + + t.test('allows setting the parameter limit to Infinity', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding array limit', function (st) { + st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { 0: 'b' } }); + st.deepEqual(qs.parse('a[0]=b', { arrayLimit: 0 }), { a: ['b'] }); + + st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } }); + st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: 0 }), { a: { '-1': 'b' } }); + + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: -1 }), { a: { 0: 'b', 1: 'c' } }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } }); + + st.end(); + }); + + t.test('allows disabling array parsing', function (st) { + var indices = qs.parse('a[0]=b&a[1]=c', { parseArrays: false }); + st.deepEqual(indices, { a: { 0: 'b', 1: 'c' } }); + st.equal(Array.isArray(indices.a), false, 'parseArrays:false, indices case is not an array'); + + var emptyBrackets = qs.parse('a[]=b', { parseArrays: false }); + st.deepEqual(emptyBrackets, { a: { 0: 'b' } }); + st.equal(Array.isArray(emptyBrackets.a), false, 'parseArrays:false, empty brackets case is not an array'); + + st.end(); + }); + + t.test('allows for query string prefix', function (st) { + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' }); + + st.end(); + }); + + t.test('parses an object', function (st) { + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses string with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo=bar,tee', { comma: true }), { foo: ['bar', 'tee'] }); + st.deepEqual(qs.parse('foo[bar]=coffee,tee', { comma: true }), { foo: { bar: ['coffee', 'tee'] } }); + st.deepEqual(qs.parse('foo=', { comma: true }), { foo: '' }); + st.deepEqual(qs.parse('foo', { comma: true }), { foo: '' }); + st.deepEqual(qs.parse('foo', { comma: true, strictNullHandling: true }), { foo: null }); + + // test cases inversed from from stringify tests + st.deepEqual(qs.parse('a[0]=c'), { a: ['c'] }); + st.deepEqual(qs.parse('a[]=c'), { a: ['c'] }); + st.deepEqual(qs.parse('a[]=c', { comma: true }), { a: ['c'] }); + + st.deepEqual(qs.parse('a[0]=c&a[1]=d'), { a: ['c', 'd'] }); + st.deepEqual(qs.parse('a[]=c&a[]=d'), { a: ['c', 'd'] }); + st.deepEqual(qs.parse('a=c,d', { comma: true }), { a: ['c', 'd'] }); + + st.end(); + }); + + t.test('parses values with comma as array divider', function (st) { + st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: false }), { foo: 'bar,tee' }); + st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: true }), { foo: ['bar', 'tee'] }); + st.end(); + }); + + t.test('use number decoder, parses string that has one number with comma option enabled', function (st) { + var decoder = function (str, defaultDecoder, charset, type) { + if (!isNaN(Number(str))) { + return parseFloat(str); + } + return defaultDecoder(str, defaultDecoder, charset, type); + }; + + st.deepEqual(qs.parse('foo=1', { comma: true, decoder: decoder }), { foo: 1 }); + st.deepEqual(qs.parse('foo=0', { comma: true, decoder: decoder }), { foo: 0 }); + + st.end(); + }); + + t.test('parses brackets holds array of arrays when having two parts of strings with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=4,5,6', { comma: true }), { foo: [['1', '2', '3'], ['4', '5', '6']] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=', { comma: true }), { foo: [['1', '2', '3'], ''] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=,', { comma: true }), { foo: [['1', '2', '3'], ['', '']] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=a', { comma: true }), { foo: [['1', '2', '3'], 'a'] }); + + st.end(); + }); + + t.test('parses url-encoded brackets holds array of arrays when having two parts of strings with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=4,5,6', { comma: true }), { foo: [['1', '2', '3'], ['4', '5', '6']] }); + st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=', { comma: true }), { foo: [['1', '2', '3'], ''] }); + st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=,', { comma: true }), { foo: [['1', '2', '3'], ['', '']] }); + st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=a', { comma: true }), { foo: [['1', '2', '3'], 'a'] }); + + st.end(); + }); + + t.test('parses comma delimited array while having percent-encoded comma treated as normal text', function (st) { + st.deepEqual(qs.parse('foo=a%2Cb', { comma: true }), { foo: 'a,b' }); + st.deepEqual(qs.parse('foo=a%2C%20b,d', { comma: true }), { foo: ['a, b', 'd'] }); + st.deepEqual(qs.parse('foo=a%2C%20b,c%2C%20d', { comma: true }), { foo: ['a, b', 'c, d'] }); + + st.end(); + }); + + t.test('parses an object in dot notation', function (st) { + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input, { allowDots: true }); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses an object and not child values', function (st) { + var input = { + 'user[name]': { 'pop[bob]': { test: 3 } }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': { test: 3 } }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('does not blow up when Buffer global is missing', function (st) { + var restore = mockProperty(global, 'Buffer', { 'delete': true }); + + var result = qs.parse('a=b&c=d'); + + restore(); + + st.deepEqual(result, { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not crash when parsing circular references', function (st) { + var a = {}; + a.b = a; + + var parsed; + + st.doesNotThrow(function () { + parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + st.equal('bar' in parsed.foo, true); + st.equal('baz' in parsed.foo, true); + st.equal(parsed.foo.bar, 'baz'); + st.deepEqual(parsed.foo.baz, a); + st.end(); + }); + + t.test('does not crash when parsing deep objects', function (st) { + var parsed; + var str = 'foo'; + + for (var i = 0; i < 5000; i++) { + str += '[p]'; + } + + str += '=bar'; + + st.doesNotThrow(function () { + parsed = qs.parse(str, { depth: 5000 }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + + var depth = 0; + var ref = parsed.foo; + while ((ref = ref.p)) { + depth += 1; + } + + st.equal(depth, 5000, 'parsed is 5000 properties deep'); + + st.end(); + }); + + t.test('parses null objects correctly', { skip: !hasProto }, function (st) { + var a = { __proto__: null, b: 'c' }; + + st.deepEqual(qs.parse(a), { b: 'c' }); + var result = qs.parse({ a: a }); + st.equal('a' in result, true, 'result has "a" property'); + st.deepEqual(result.a, a); + st.end(); + }); + + t.test('parses dates correctly', function (st) { + var now = new Date(); + st.deepEqual(qs.parse({ a: now }), { a: now }); + st.end(); + }); + + t.test('parses regular expressions correctly', function (st) { + var re = /^test$/; + st.deepEqual(qs.parse({ a: re }), { a: re }); + st.end(); + }); + + t.test('does not allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: false }), {}); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: false }), {}); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: false }), + {}, + 'bare "toString" results in {}' + ); + + st.end(); + }); + + t.test('can allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } }); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' }); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: true }), + { toString: '' }, + 'bare "toString" results in { toString: "" }' + ); + + st.end(); + }); + + t.test('does not crash when the global Object prototype is frozen', { skip: !hasPropertyDescriptors || !hasOverrideMistake }, function (st) { + // We can't actually freeze the global Object prototype as that will interfere with other tests, and once an object is frozen, it + // can't be unfrozen. Instead, we add a new non-writable property to simulate this. + st.teardown(mockProperty(Object.prototype, 'frozenProp', { value: 'foo', nonWritable: true, nonEnumerable: true })); + + st['throws']( + function () { + var obj = {}; + obj.frozenProp = 'bar'; + }, + // node < 6 has a different error message + /^TypeError: Cannot assign to read only property 'frozenProp' of (?:object '#'|#)/, + 'regular assignment of an inherited non-writable property throws' + ); + + var parsed; + st.doesNotThrow( + function () { + parsed = qs.parse('frozenProp', { allowPrototypes: false }); + }, + 'parsing a nonwritable Object.prototype property does not throw' + ); + + st.deepEqual(parsed, {}, 'bare "frozenProp" results in {}'); + + st.end(); + }); + + t.test('params starting with a closing bracket', function (st) { + st.deepEqual(qs.parse(']=toString'), { ']': 'toString' }); + st.deepEqual(qs.parse(']]=toString'), { ']]': 'toString' }); + st.deepEqual(qs.parse(']hello]=toString'), { ']hello]': 'toString' }); + st.end(); + }); + + t.test('params starting with a starting bracket', function (st) { + st.deepEqual(qs.parse('[=toString'), { '[': 'toString' }); + st.deepEqual(qs.parse('[[=toString'), { '[[': 'toString' }); + st.deepEqual(qs.parse('[hello[=toString'), { '[hello[': 'toString' }); + st.end(); + }); + + t.test('add keys to objects', function (st) { + st.deepEqual( + qs.parse('a[b]=c&a=d'), + { a: { b: 'c', d: true } }, + 'can add keys to objects' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString'), + { a: { b: 'c' } }, + 'can not overwrite prototype' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { allowPrototypes: true }), + { a: { b: 'c', toString: true } }, + 'can overwrite prototype with allowPrototypes true' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { plainObjects: true }), + { __proto__: null, a: { __proto__: null, b: 'c', toString: true } }, + 'can overwrite prototype with plainObjects true' + ); + + st.end(); + }); + + t.test('dunder proto is ignored', function (st) { + var payload = 'categories[__proto__]=login&categories[__proto__]&categories[length]=42'; + var result = qs.parse(payload, { allowPrototypes: true }); + + st.deepEqual( + result, + { + categories: { + length: '42' + } + }, + 'silent [[Prototype]] payload' + ); + + var plainResult = qs.parse(payload, { allowPrototypes: true, plainObjects: true }); + + st.deepEqual( + plainResult, + { + __proto__: null, + categories: { + __proto__: null, + length: '42' + } + }, + 'silent [[Prototype]] payload: plain objects' + ); + + var query = qs.parse('categories[__proto__]=cats&categories[__proto__]=dogs&categories[some][json]=toInject', { allowPrototypes: true }); + + st.notOk(Array.isArray(query.categories), 'is not an array'); + st.notOk(query.categories instanceof Array, 'is not instanceof an array'); + st.deepEqual(query.categories, { some: { json: 'toInject' } }); + st.equal(JSON.stringify(query.categories), '{"some":{"json":"toInject"}}', 'stringifies as a non-array'); + + st.deepEqual( + qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true }), + { + foo: { + bar: 'stuffs' + } + }, + 'hidden values' + ); + + st.deepEqual( + qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true, plainObjects: true }), + { + __proto__: null, + foo: { + __proto__: null, + bar: 'stuffs' + } + }, + 'hidden values: plain objects' + ); + + st.end(); + }); + + t.test('can return null objects', { skip: !hasProto }, function (st) { + var expected = { + __proto__: null, + a: { + __proto__: null, + b: 'c', + hasOwnProperty: 'd' + } + }; + st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected); + st.deepEqual(qs.parse(null, { plainObjects: true }), { __proto__: null }); + var expectedArray = { + __proto__: null, + a: { + __proto__: null, + 0: 'b', + c: 'd' + } + }; + st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray); + st.end(); + }); + + t.test('can parse with custom encoding', function (st) { + st.deepEqual(qs.parse('%8c%a7=%91%e5%8d%e3%95%7b', { + decoder: function (str) { + var reg = /%([0-9A-F]{2})/ig; + var result = []; + var parts = reg.exec(str); + while (parts) { + result.push(parseInt(parts[1], 16)); + parts = reg.exec(str); + } + return String(iconv.decode(SaferBuffer.from(result), 'shift_jis')); + } + }), { 県: '大阪府' }); + st.end(); + }); + + t.test('receives the default decoder as a second argument', function (st) { + st.plan(1); + qs.parse('a', { + decoder: function (str, defaultDecoder) { + st.equal(defaultDecoder, utils.decode); + } + }); + st.end(); + }); + + t.test('throws error with wrong decoder', function (st) { + st['throws'](function () { + qs.parse({}, { decoder: 'string' }); + }, new TypeError('Decoder has to be a function.')); + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.parse('a[b]=true', options); + st.deepEqual(options, {}); + st.end(); + }); + + t.test('throws if an invalid charset is specified', function (st) { + st['throws'](function () { + qs.parse('a=b', { charset: 'foobar' }); + }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); + st.end(); + }); + + t.test('parses an iso-8859-1 string if asked to', function (st) { + st.deepEqual(qs.parse('%A2=%BD', { charset: 'iso-8859-1' }), { '¢': '½' }); + st.end(); + }); + + var urlEncodedCheckmarkInUtf8 = '%E2%9C%93'; + var urlEncodedOSlashInUtf8 = '%C3%B8'; + var urlEncodedNumCheckmark = '%26%2310003%3B'; + var urlEncodedNumSmiley = '%26%239786%3B'; + + t.test('prefers an utf-8 charset specified by the utf8 sentinel to a default charset of iso-8859-1', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'iso-8859-1' }), { ø: 'ø' }); + st.end(); + }); + + t.test('prefers an iso-8859-1 charset specified by the utf8 sentinel to a default charset of utf-8', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { 'ø': 'ø' }); + st.end(); + }); + + t.test('does not require the utf8 sentinel to be defined before the parameters whose decoding it affects', function (st) { + st.deepEqual(qs.parse('a=' + urlEncodedOSlashInUtf8 + '&utf8=' + urlEncodedNumCheckmark, { charsetSentinel: true, charset: 'utf-8' }), { a: 'ø' }); + st.end(); + }); + + t.test('ignores an utf8 sentinel with an unknown value', function (st) { + st.deepEqual(qs.parse('utf8=foo&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { ø: 'ø' }); + st.end(); + }); + + t.test('uses the utf8 sentinel to switch to utf-8 when no default charset is given', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { ø: 'ø' }); + st.end(); + }); + + t.test('uses the utf8 sentinel to switch to iso-8859-1 when no default charset is given', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { 'ø': 'ø' }); + st.end(); + }); + + t.test('interprets numeric entities in iso-8859-1 when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1', interpretNumericEntities: true }), { foo: '☺' }); + st.end(); + }); + + t.test('handles a custom decoder returning `null`, in the `iso-8859-1` charset, when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=&bar=' + urlEncodedNumSmiley, { + charset: 'iso-8859-1', + decoder: function (str, defaultDecoder, charset) { + return str ? defaultDecoder(str, defaultDecoder, charset) : null; + }, + interpretNumericEntities: true + }), { foo: null, bar: '☺' }); + st.end(); + }); + + t.test('handles a custom decoder returning `null`, with a string key of `null`', function (st) { + st.deepEqual( + qs.parse('null=1&ToNull=2', { + decoder: function (str, defaultDecoder, charset) { + return str === 'ToNull' ? null : defaultDecoder(str, defaultDecoder, charset); + } + }), + { 'null': '1' }, + '"null" key is not overridden by `null` decoder result' + ); + + st.end(); + }); + + t.test('does not interpret numeric entities in iso-8859-1 when `interpretNumericEntities` is absent', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1' }), { foo: '☺' }); + st.end(); + }); + + t.test('does not interpret numeric entities when the charset is utf-8, even when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'utf-8', interpretNumericEntities: true }), { foo: '☺' }); + st.end(); + }); + + t.test('interpretNumericEntities with comma:true and iso charset does not crash', function (st) { + st.deepEqual( + qs.parse('b&a[]=1,' + urlEncodedNumSmiley, { comma: true, charset: 'iso-8859-1', interpretNumericEntities: true }), + { b: '', a: ['1,☺'] } + ); + + st.end(); + }); + + t.test('does not interpret %uXXXX syntax in iso-8859-1 mode', function (st) { + st.deepEqual(qs.parse('%u263A=%u263A', { charset: 'iso-8859-1' }), { '%u263A': '%u263A' }); + st.end(); + }); + + t.test('allows for decoding keys and values differently', function (st) { + var decoder = function (str, defaultDecoder, charset, type) { + if (type === 'key') { + return defaultDecoder(str, defaultDecoder, charset, type).toLowerCase(); + } + if (type === 'value') { + return defaultDecoder(str, defaultDecoder, charset, type).toUpperCase(); + } + throw 'this should never happen! type: ' + type; + }; + + st.deepEqual(qs.parse('KeY=vAlUe', { decoder: decoder }), { key: 'VALUE' }); + st.end(); + }); + + t.test('parameter limit tests', function (st) { + st.test('does not throw error when within parameter limit', function (sst) { + var result = qs.parse('a=1&b=2&c=3', { parameterLimit: 5, throwOnLimitExceeded: true }); + sst.deepEqual(result, { a: '1', b: '2', c: '3' }, 'parses without errors'); + sst.end(); + }); + + st.test('throws error when throwOnLimitExceeded is present but not boolean', function (sst) { + sst['throws']( + function () { + qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: 3, throwOnLimitExceeded: 'true' }); + }, + new TypeError('`throwOnLimitExceeded` option must be a boolean'), + 'throws error when throwOnLimitExceeded is present and not boolean' + ); + sst.end(); + }); + + st.test('throws error when parameter limit exceeded', function (sst) { + sst['throws']( + function () { + qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: 3, throwOnLimitExceeded: true }); + }, + new RangeError('Parameter limit exceeded. Only 3 parameters allowed.'), + 'throws error when parameter limit is exceeded' + ); + sst.end(); + }); + + st.test('silently truncates when throwOnLimitExceeded is not given', function (sst) { + var result = qs.parse('a=1&b=2&c=3&d=4&e=5', { parameterLimit: 3 }); + sst.deepEqual(result, { a: '1', b: '2', c: '3' }, 'parses and truncates silently'); + sst.end(); + }); + + st.test('silently truncates when parameter limit exceeded without error', function (sst) { + var result = qs.parse('a=1&b=2&c=3&d=4&e=5', { parameterLimit: 3, throwOnLimitExceeded: false }); + sst.deepEqual(result, { a: '1', b: '2', c: '3' }, 'parses and truncates silently'); + sst.end(); + }); + + st.test('allows unlimited parameters when parameterLimit set to Infinity', function (sst) { + var result = qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: Infinity }); + sst.deepEqual(result, { a: '1', b: '2', c: '3', d: '4', e: '5', f: '6' }, 'parses all parameters without truncation'); + sst.end(); + }); + + st.end(); + }); + + t.test('array limit tests', function (st) { + st.test('does not throw error when array is within limit', function (sst) { + var result = qs.parse('a[]=1&a[]=2&a[]=3', { arrayLimit: 5, throwOnLimitExceeded: true }); + sst.deepEqual(result, { a: ['1', '2', '3'] }, 'parses array without errors'); + sst.end(); + }); + + st.test('throws error when throwOnLimitExceeded is present but not boolean for array limit', function (sst) { + sst['throws']( + function () { + qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3, throwOnLimitExceeded: 'true' }); + }, + new TypeError('`throwOnLimitExceeded` option must be a boolean'), + 'throws error when throwOnLimitExceeded is present and not boolean for array limit' + ); + sst.end(); + }); + + st.test('throws error when array limit exceeded', function (sst) { + sst['throws']( + function () { + qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3, throwOnLimitExceeded: true }); + }, + new RangeError('Array limit exceeded. Only 3 elements allowed in an array.'), + 'throws error when array limit is exceeded' + ); + sst.end(); + }); + + st.test('converts array to object if length is greater than limit', function (sst) { + var result = qs.parse('a[1]=1&a[2]=2&a[3]=3&a[4]=4&a[5]=5&a[6]=6', { arrayLimit: 5 }); + + sst.deepEqual(result, { a: { 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6' } }, 'parses into object if array length is greater than limit'); + sst.end(); + }); + + st.end(); + }); + + t.end(); +}); + +test('parses empty keys', function (t) { + emptyTestCases.forEach(function (testCase) { + t.test('skips empty string key with ' + testCase.input, function (st) { + st.deepEqual(qs.parse(testCase.input), testCase.noEmptyKeys); + + st.end(); + }); + }); +}); + +test('`duplicates` option', function (t) { + v.nonStrings.concat('not a valid option').forEach(function (invalidOption) { + if (typeof invalidOption !== 'undefined') { + t['throws']( + function () { qs.parse('', { duplicates: invalidOption }); }, + TypeError, + 'throws on invalid option: ' + inspect(invalidOption) + ); + } + }); + + t.deepEqual( + qs.parse('foo=bar&foo=baz'), + { foo: ['bar', 'baz'] }, + 'duplicates: default, combine' + ); + + t.deepEqual( + qs.parse('foo=bar&foo=baz', { duplicates: 'combine' }), + { foo: ['bar', 'baz'] }, + 'duplicates: combine' + ); + + t.deepEqual( + qs.parse('foo=bar&foo=baz', { duplicates: 'first' }), + { foo: 'bar' }, + 'duplicates: first' + ); + + t.deepEqual( + qs.parse('foo=bar&foo=baz', { duplicates: 'last' }), + { foo: 'baz' }, + 'duplicates: last' + ); + + t.end(); +}); + +test('qs strictDepth option - throw cases', function (t) { + t.test('throws an exception when depth exceeds the limit with strictDepth: true', function (st) { + st['throws']( + function () { + qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1, strictDepth: true }); + }, + RangeError, + 'throws RangeError' + ); + st.end(); + }); + + t.test('throws an exception for multiple nested arrays with strictDepth: true', function (st) { + st['throws']( + function () { + qs.parse('a[0][1][2][3][4]=b', { depth: 3, strictDepth: true }); + }, + RangeError, + 'throws RangeError' + ); + st.end(); + }); + + t.test('throws an exception for nested objects and arrays with strictDepth: true', function (st) { + st['throws']( + function () { + qs.parse('a[b][c][0][d][e]=f', { depth: 3, strictDepth: true }); + }, + RangeError, + 'throws RangeError' + ); + st.end(); + }); + + t.test('throws an exception for different types of values with strictDepth: true', function (st) { + st['throws']( + function () { + qs.parse('a[b][c][d][e]=true&a[b][c][d][f]=42', { depth: 3, strictDepth: true }); + }, + RangeError, + 'throws RangeError' + ); + st.end(); + }); + +}); + +test('qs strictDepth option - non-throw cases', function (t) { + t.test('when depth is 0 and strictDepth true, do not throw', function (st) { + st.doesNotThrow( + function () { + qs.parse('a[b][c][d][e]=true&a[b][c][d][f]=42', { depth: 0, strictDepth: true }); + }, + RangeError, + 'does not throw RangeError' + ); + st.end(); + }); + + t.test('parses successfully when depth is within the limit with strictDepth: true', function (st) { + st.doesNotThrow( + function () { + var result = qs.parse('a[b]=c', { depth: 1, strictDepth: true }); + st.deepEqual(result, { a: { b: 'c' } }, 'parses correctly'); + } + ); + st.end(); + }); + + t.test('does not throw an exception when depth exceeds the limit with strictDepth: false', function (st) { + st.doesNotThrow( + function () { + var result = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); + st.deepEqual(result, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }, 'parses with depth limit'); + } + ); + st.end(); + }); + + t.test('parses successfully when depth is within the limit with strictDepth: false', function (st) { + st.doesNotThrow( + function () { + var result = qs.parse('a[b]=c', { depth: 1 }); + st.deepEqual(result, { a: { b: 'c' } }, 'parses correctly'); + } + ); + st.end(); + }); + + t.test('does not throw when depth is exactly at the limit with strictDepth: true', function (st) { + st.doesNotThrow( + function () { + var result = qs.parse('a[b][c]=d', { depth: 2, strictDepth: true }); + st.deepEqual(result, { a: { b: { c: 'd' } } }, 'parses correctly'); + } + ); + st.end(); + }); +}); + +test('DOS', function (t) { + var arr = []; + for (var i = 0; i < 105; i++) { + arr[arr.length] = 'x'; + } + var attack = 'a[]=' + arr.join('&a[]='); + var result = qs.parse(attack, { arrayLimit: 100 }); + + t.notOk(Array.isArray(result.a), 'arrayLimit is respected: result is an object, not an array'); + t.equal(Object.keys(result.a).length, 105, 'all values are preserved'); + + t.end(); +}); + +test('arrayLimit boundary conditions', function (t) { + t.test('exactly at the limit stays as array', function (st) { + var result = qs.parse('a[]=1&a[]=2&a[]=3', { arrayLimit: 3 }); + st.ok(Array.isArray(result.a), 'result is an array when exactly at limit'); + st.deepEqual(result.a, ['1', '2', '3'], 'all values present'); + st.end(); + }); + + t.test('one over the limit converts to object', function (st) { + var result = qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3 }); + st.notOk(Array.isArray(result.a), 'result is not an array when over limit'); + st.deepEqual(result.a, { 0: '1', 1: '2', 2: '3', 3: '4' }, 'all values preserved as object'); + st.end(); + }); + + t.test('arrayLimit 1 with two values', function (st) { + var result = qs.parse('a[]=1&a[]=2', { arrayLimit: 1 }); + st.notOk(Array.isArray(result.a), 'result is not an array'); + st.deepEqual(result.a, { 0: '1', 1: '2' }, 'both values preserved'); + st.end(); + }); + + t.end(); +}); + +test('mixed array and object notation', function (t) { + t.test('array brackets with object key - under limit', function (st) { + st.deepEqual( + qs.parse('a[]=b&a[c]=d'), + { a: { 0: 'b', c: 'd' } }, + 'mixing [] and [key] converts to object' + ); + st.end(); + }); + + t.test('array index with object key - under limit', function (st) { + st.deepEqual( + qs.parse('a[0]=b&a[c]=d'), + { a: { 0: 'b', c: 'd' } }, + 'mixing [0] and [key] produces object' + ); + st.end(); + }); + + t.test('plain value with array brackets - under limit', function (st) { + st.deepEqual( + qs.parse('a=b&a[]=c', { arrayLimit: 20 }), + { a: ['b', 'c'] }, + 'plain value combined with [] stays as array under limit' + ); + st.end(); + }); + + t.test('array brackets with plain value - under limit', function (st) { + st.deepEqual( + qs.parse('a[]=b&a=c', { arrayLimit: 20 }), + { a: ['b', 'c'] }, + '[] combined with plain value stays as array under limit' + ); + st.end(); + }); + + t.test('plain value with array index - under limit', function (st) { + st.deepEqual( + qs.parse('a=b&a[0]=c', { arrayLimit: 20 }), + { a: ['b', 'c'] }, + 'plain value combined with [0] stays as array under limit' + ); + st.end(); + }); + + t.test('multiple plain values with duplicates combine', function (st) { + st.deepEqual( + qs.parse('a=b&a=c&a=d', { arrayLimit: 20 }), + { a: ['b', 'c', 'd'] }, + 'duplicate plain keys combine into array' + ); + st.end(); + }); + + t.test('multiple plain values exceeding limit', function (st) { + st.deepEqual( + qs.parse('a=b&a=c&a=d', { arrayLimit: 2 }), + { a: { 0: 'b', 1: 'c', 2: 'd' } }, + 'duplicate plain keys convert to object when exceeding limit' + ); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/qs/test/stringify.js b/node_modules/qs/test/stringify.js new file mode 100644 index 000000000..4d776947c --- /dev/null +++ b/node_modules/qs/test/stringify.js @@ -0,0 +1,1310 @@ +'use strict'; + +var test = require('tape'); +var qs = require('../'); +var utils = require('../lib/utils'); +var iconv = require('iconv-lite'); +var SaferBuffer = require('safer-buffer').Buffer; +var hasSymbols = require('has-symbols'); +var mockProperty = require('mock-property'); +var emptyTestCases = require('./empty-keys-cases').emptyTestCases; +var hasProto = require('has-proto')(); +var hasBigInt = require('has-bigints')(); + +test('stringify()', function (t) { + t.test('stringifies a querystring object', function (st) { + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: 1 }), 'a=1'); + st.equal(qs.stringify({ a: 1, b: 2 }), 'a=1&b=2'); + st.equal(qs.stringify({ a: 'A_Z' }), 'a=A_Z'); + st.equal(qs.stringify({ a: '€' }), 'a=%E2%82%AC'); + st.equal(qs.stringify({ a: '' }), 'a=%EE%80%80'); + st.equal(qs.stringify({ a: 'א' }), 'a=%D7%90'); + st.equal(qs.stringify({ a: '𐐷' }), 'a=%F0%90%90%B7'); + st.end(); + }); + + t.test('stringifies falsy values', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(null, { strictNullHandling: true }), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(0), ''); + st.end(); + }); + + t.test('stringifies symbols', { skip: !hasSymbols() }, function (st) { + st.equal(qs.stringify(Symbol.iterator), ''); + st.equal(qs.stringify([Symbol.iterator]), '0=Symbol%28Symbol.iterator%29'); + st.equal(qs.stringify({ a: Symbol.iterator }), 'a=Symbol%28Symbol.iterator%29'); + st.equal( + qs.stringify({ a: [Symbol.iterator] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[]=Symbol%28Symbol.iterator%29' + ); + st.end(); + }); + + t.test('stringifies bigints', { skip: !hasBigInt }, function (st) { + var three = BigInt(3); + var encodeWithN = function (value, defaultEncoder, charset) { + var result = defaultEncoder(value, defaultEncoder, charset); + return typeof value === 'bigint' ? result + 'n' : result; + }; + st.equal(qs.stringify(three), ''); + st.equal(qs.stringify([three]), '0=3'); + st.equal(qs.stringify([three], { encoder: encodeWithN }), '0=3n'); + st.equal(qs.stringify({ a: three }), 'a=3'); + st.equal(qs.stringify({ a: three }, { encoder: encodeWithN }), 'a=3n'); + st.equal( + qs.stringify({ a: [three] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[]=3' + ); + st.equal( + qs.stringify({ a: [three] }, { encodeValuesOnly: true, encoder: encodeWithN, arrayFormat: 'brackets' }), + 'a[]=3n' + ); + st.end(); + }); + + t.test('encodes dot in key of object when encodeDotInKeys and allowDots is provided', function (st) { + st.equal( + qs.stringify( + { 'name.obj': { first: 'John', last: 'Doe' } }, + { allowDots: false, encodeDotInKeys: false } + ), + 'name.obj%5Bfirst%5D=John&name.obj%5Blast%5D=Doe', + 'with allowDots false and encodeDotInKeys false' + ); + st.equal( + qs.stringify( + { 'name.obj': { first: 'John', last: 'Doe' } }, + { allowDots: true, encodeDotInKeys: false } + ), + 'name.obj.first=John&name.obj.last=Doe', + 'with allowDots true and encodeDotInKeys false' + ); + st.equal( + qs.stringify( + { 'name.obj': { first: 'John', last: 'Doe' } }, + { allowDots: false, encodeDotInKeys: true } + ), + 'name%252Eobj%5Bfirst%5D=John&name%252Eobj%5Blast%5D=Doe', + 'with allowDots false and encodeDotInKeys true' + ); + st.equal( + qs.stringify( + { 'name.obj': { first: 'John', last: 'Doe' } }, + { allowDots: true, encodeDotInKeys: true } + ), + 'name%252Eobj.first=John&name%252Eobj.last=Doe', + 'with allowDots true and encodeDotInKeys true' + ); + + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { allowDots: false, encodeDotInKeys: false } + ), + 'name.obj.subobject%5Bfirst.godly.name%5D=John&name.obj.subobject%5Blast%5D=Doe', + 'with allowDots false and encodeDotInKeys false' + ); + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { allowDots: true, encodeDotInKeys: false } + ), + 'name.obj.subobject.first.godly.name=John&name.obj.subobject.last=Doe', + 'with allowDots false and encodeDotInKeys false' + ); + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { allowDots: false, encodeDotInKeys: true } + ), + 'name%252Eobj%252Esubobject%5Bfirst.godly.name%5D=John&name%252Eobj%252Esubobject%5Blast%5D=Doe', + 'with allowDots false and encodeDotInKeys true' + ); + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { allowDots: true, encodeDotInKeys: true } + ), + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + 'with allowDots true and encodeDotInKeys true' + ); + + st.end(); + }); + + t.test('should encode dot in key of object, and automatically set allowDots to `true` when encodeDotInKeys is true and allowDots in undefined', function (st) { + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { encodeDotInKeys: true } + ), + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + 'with allowDots undefined and encodeDotInKeys true' + ); + st.end(); + }); + + t.test('should encode dot in key of object when encodeDotInKeys and allowDots is provided, and nothing else when encodeValuesOnly is provided', function (st) { + st.equal( + qs.stringify({ 'name.obj': { first: 'John', last: 'Doe' } }, { + encodeDotInKeys: true, allowDots: true, encodeValuesOnly: true + }), + 'name%2Eobj.first=John&name%2Eobj.last=Doe' + ); + + st.equal( + qs.stringify({ 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, { allowDots: true, encodeDotInKeys: true, encodeValuesOnly: true }), + 'name%2Eobj%2Esubobject.first%2Egodly%2Ename=John&name%2Eobj%2Esubobject.last=Doe' + ); + + st.end(); + }); + + t.test('throws when `commaRoundTrip` is not a boolean', function (st) { + st['throws']( + function () { qs.stringify({}, { commaRoundTrip: 'not a boolean' }); }, + TypeError, + 'throws when `commaRoundTrip` is not a boolean' + ); + + st.end(); + }); + + t.test('throws when `encodeDotInKeys` is not a boolean', function (st) { + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { encodeDotInKeys: 'foobar' }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { encodeDotInKeys: 0 }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { encodeDotInKeys: NaN }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { encodeDotInKeys: null }); }, + TypeError + ); + + st.end(); + }); + + t.test('adds query prefix', function (st) { + st.equal(qs.stringify({ a: 'b' }, { addQueryPrefix: true }), '?a=b'); + st.end(); + }); + + t.test('with query prefix, outputs blank string given an empty object', function (st) { + st.equal(qs.stringify({}, { addQueryPrefix: true }), ''); + st.end(); + }); + + t.test('stringifies nested falsy values', function (st) { + st.equal(qs.stringify({ a: { b: { c: null } } }), 'a%5Bb%5D%5Bc%5D='); + st.equal(qs.stringify({ a: { b: { c: null } } }, { strictNullHandling: true }), 'a%5Bb%5D%5Bc%5D'); + st.equal(qs.stringify({ a: { b: { c: false } } }), 'a%5Bb%5D%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies a nested object', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + st.end(); + }); + + t.test('`allowDots` option: stringifies a nested object with dots notation', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }, { allowDots: true }), 'a.b=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }, { allowDots: true }), 'a.b.c.d=e'); + st.end(); + }); + + t.test('stringifies an array value', function (st) { + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'indices' }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'brackets' }), + 'a%5B%5D=b&a%5B%5D=c&a%5B%5D=d', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma' }), + 'a=b%2Cc%2Cd', + 'comma => comma' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma', commaRoundTrip: true }), + 'a=b%2Cc%2Cd', + 'comma round trip => comma' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'default => indices' + ); + st.end(); + }); + + t.test('`skipNulls` option', function (st) { + st.equal( + qs.stringify({ a: 'b', c: null }, { skipNulls: true }), + 'a=b', + 'omits nulls when asked' + ); + + st.equal( + qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true }), + 'a%5Bb%5D=c', + 'omits nested nulls when asked' + ); + + st.end(); + }); + + t.test('omits array indices when asked', function (st) { + st.equal(qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }), 'a=b&a=c&a=d'); + + st.end(); + }); + + t.test('omits object key/value pair when value is empty array', function (st) { + st.equal(qs.stringify({ a: [], b: 'zz' }), 'b=zz'); + + st.end(); + }); + + t.test('should not omit object key/value pair when value is empty array and when asked', function (st) { + st.equal(qs.stringify({ a: [], b: 'zz' }), 'b=zz'); + st.equal(qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: false }), 'b=zz'); + st.equal(qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: true }), 'a[]&b=zz'); + + st.end(); + }); + + t.test('should throw when allowEmptyArrays is not of type boolean', function (st) { + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: 'foobar' }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: 0 }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: NaN }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: null }); }, + TypeError + ); + + st.end(); + }); + + t.test('allowEmptyArrays + strictNullHandling', function (st) { + st.equal( + qs.stringify( + { testEmptyArray: [] }, + { strictNullHandling: true, allowEmptyArrays: true } + ), + 'testEmptyArray[]' + ); + + st.end(); + }); + + t.test('stringifies an array value with one item vs multiple items', function (st) { + st.test('non-array item', function (s2t) { + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true }), 'a=c'); + + s2t.end(); + }); + + st.test('array with a single item', function (s2t) { + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a[]=c'); // so it parses back as an array + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true }), 'a[0]=c'); + + s2t.end(); + }); + + st.test('array with multiple items', function (s2t) { + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c&a[1]=d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c&a[]=d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c,d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a=c,d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true }), 'a[0]=c&a[1]=d'); + + s2t.end(); + }); + + st.test('array with multiple items with a comma inside', function (s2t) { + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c%2Cd,e'); + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { arrayFormat: 'comma' }), 'a=c%2Cd%2Ce'); + + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a=c%2Cd,e'); + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { arrayFormat: 'comma', commaRoundTrip: true }), 'a=c%2Cd%2Ce'); + + s2t.end(); + }); + + st.end(); + }); + + t.test('stringifies a nested array value', function (st) { + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[b][0]=c&a[b][1]=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[b][]=c&a[b][]=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a[b]=c,d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true }), 'a[b][0]=c&a[b][1]=d'); + st.end(); + }); + + t.test('stringifies comma and empty array values', function (st) { + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'indices' }), 'a[0]=,&a[1]=&a[2]=c,d%'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'brackets' }), 'a[]=,&a[]=&a[]=c,d%'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'comma' }), 'a=,,,c,d%'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'repeat' }), 'a=,&a=&a=c,d%'); + + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=%2C&a[1]=&a[2]=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=%2C&a[]=&a[]=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=%2C,,c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a=%2C&a=&a=c%2Cd%25'); + + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }), 'a%5B0%5D=%2C&a%5B1%5D=&a%5B2%5D=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'brackets' }), 'a%5B%5D=%2C&a%5B%5D=&a%5B%5D=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }), 'a=%2C%2C%2Cc%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }), 'a=%2C&a=&a=c%2Cd%25'); + + st.end(); + }); + + t.test('stringifies comma and empty non-array values', function (st) { + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'indices' }), 'a=,&b=&c=c,d%'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'brackets' }), 'a=,&b=&c=c,d%'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'comma' }), 'a=,&b=&c=c,d%'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'repeat' }), 'a=,&b=&c=c,d%'); + + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a=%2C&b=&c=c%2Cd%25'); + + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'brackets' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }), 'a=%2C&b=&c=c%2Cd%25'); + + st.end(); + }); + + t.test('stringifies a nested array value with dots notation', function (st) { + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'indices' } + ), + 'a.b[0]=c&a.b[1]=d', + 'indices: stringifies with dots + indices' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'brackets' } + ), + 'a.b[]=c&a.b[]=d', + 'brackets: stringifies with dots + brackets' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'comma' } + ), + 'a.b=c,d', + 'comma: stringifies with dots + comma' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true } + ), + 'a.b[0]=c&a.b[1]=d', + 'default: stringifies with dots + indices' + ); + st.end(); + }); + + t.test('stringifies an object inside an array', function (st) { + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'indices', encodeValuesOnly: true }), + 'a[0][b]=c', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'repeat', encodeValuesOnly: true }), + 'a[b]=c', + 'repeat => repeat' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'brackets', encodeValuesOnly: true }), + 'a[][b]=c', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { encodeValuesOnly: true }), + 'a[0][b]=c', + 'default => indices' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'indices', encodeValuesOnly: true }), + 'a[0][b][c][0]=1', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'repeat', encodeValuesOnly: true }), + 'a[b][c]=1', + 'repeat => repeat' + ); + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'brackets', encodeValuesOnly: true }), + 'a[][b][c][]=1', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { encodeValuesOnly: true }), + 'a[0][b][c][0]=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an array with mixed objects and primitives', function (st) { + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[][b]=1&a[]=2&a[]=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), + '???', + 'brackets => brackets', + { skip: 'TODO: figure out what this should do' } + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an object inside an array with dots notation', function (st) { + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b=c', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b=c', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false } + ), + 'a[0].b=c', + 'default => indices' + ); + + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b.c[0]=1', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b.c[]=1', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false } + ), + 'a[0].b.c[0]=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('does not omit object keys when indices = false', function (st) { + st.equal(qs.stringify({ a: [{ b: 'c' }] }, { indices: false }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when indices=true', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { indices: true }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when no arrayFormat is specified', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when arrayFormat=indices', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses repeat notation for arrays when arrayFormat=repeat', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }), 'a=b&a=c'); + st.end(); + }); + + t.test('uses brackets notation for arrays when arrayFormat=brackets', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c'); + st.end(); + }); + + t.test('stringifies a complicated object', function (st) { + st.equal(qs.stringify({ a: { b: 'c', d: 'e' } }), 'a%5Bb%5D=c&a%5Bd%5D=e'); + st.end(); + }); + + t.test('stringifies an empty value', function (st) { + st.equal(qs.stringify({ a: '' }), 'a='); + st.equal(qs.stringify({ a: null }, { strictNullHandling: true }), 'a'); + + st.equal(qs.stringify({ a: '', b: '' }), 'a=&b='); + st.equal(qs.stringify({ a: null, b: '' }, { strictNullHandling: true }), 'a&b='); + + st.equal(qs.stringify({ a: { b: '' } }), 'a%5Bb%5D='); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: true }), 'a%5Bb%5D'); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: false }), 'a%5Bb%5D='); + + st.end(); + }); + + t.test('stringifies an empty array in different arrayFormat', function (st) { + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false }), 'b[0]=&c=c'); + // arrayFormat default + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices' }), 'b[0]=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets' }), 'b[]=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat' }), 'b=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma' }), 'b=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', commaRoundTrip: true }), 'b[]=&c=c'); + // with strictNullHandling + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', strictNullHandling: true }), 'b[0]&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', strictNullHandling: true }), 'b[]&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', strictNullHandling: true }), 'b&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true }), 'b&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true, commaRoundTrip: true }), 'b[]&c=c'); + // with skipNulls + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', skipNulls: true }), 'c=c'); + + st.end(); + }); + + t.test('stringifies a null object', { skip: !hasProto }, function (st) { + st.equal(qs.stringify({ __proto__: null, a: 'b' }), 'a=b'); + st.end(); + }); + + t.test('returns an empty string for invalid input', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(''), ''); + st.end(); + }); + + t.test('stringifies an object with a null object as a child', { skip: !hasProto }, function (st) { + st.equal(qs.stringify({ a: { __proto__: null, b: 'c' } }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('drops keys with a value of undefined', function (st) { + st.equal(qs.stringify({ a: undefined }), ''); + + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true }), 'a%5Bc%5D'); + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false }), 'a%5Bc%5D='); + st.equal(qs.stringify({ a: { b: undefined, c: '' } }), 'a%5Bc%5D='); + st.end(); + }); + + t.test('url encodes values', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.end(); + }); + + t.test('stringifies a date', function (st) { + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + st.equal(qs.stringify({ a: now }), str); + st.end(); + }); + + t.test('stringifies the weird object from qs', function (st) { + st.equal(qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' }), 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + st.end(); + }); + + t.test('skips properties that are part of the object prototype', function (st) { + st.intercept(Object.prototype, 'crash', { value: 'test' }); + + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + + st.end(); + }); + + t.test('stringifies boolean values', function (st) { + st.equal(qs.stringify({ a: true }), 'a=true'); + st.equal(qs.stringify({ a: { b: true } }), 'a%5Bb%5D=true'); + st.equal(qs.stringify({ b: false }), 'b=false'); + st.equal(qs.stringify({ b: { c: false } }), 'b%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies buffer values', function (st) { + st.equal(qs.stringify({ a: SaferBuffer.from('test') }), 'a=test'); + st.equal(qs.stringify({ a: { b: SaferBuffer.from('test') } }), 'a%5Bb%5D=test'); + st.end(); + }); + + t.test('stringifies an object using an alternative delimiter', function (st) { + st.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); + st.end(); + }); + + t.test('does not blow up when Buffer global is missing', function (st) { + var restore = mockProperty(global, 'Buffer', { 'delete': true }); + + var result = qs.stringify({ a: 'b', c: 'd' }); + + restore(); + + st.equal(result, 'a=b&c=d'); + st.end(); + }); + + t.test('does not crash when parsing circular references', function (st) { + var a = {}; + a.b = a; + + st['throws']( + function () { qs.stringify({ 'foo[bar]': 'baz', 'foo[baz]': a }); }, + /RangeError: Cyclic object value/, + 'cyclic values throw' + ); + + var circular = { + a: 'value' + }; + circular.a = circular; + st['throws']( + function () { qs.stringify(circular); }, + /RangeError: Cyclic object value/, + 'cyclic values throw' + ); + + var arr = ['a']; + st.doesNotThrow( + function () { qs.stringify({ x: arr, y: arr }); }, + 'non-cyclic values do not throw' + ); + + st.end(); + }); + + t.test('non-circular duplicated references can still work', function (st) { + var hourOfDay = { + 'function': 'hour_of_day' + }; + + var p1 = { + 'function': 'gte', + arguments: [hourOfDay, 0] + }; + var p2 = { + 'function': 'lte', + arguments: [hourOfDay, 23] + }; + + st.equal( + qs.stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true, arrayFormat: 'indices' }), + 'filters[$and][0][function]=gte&filters[$and][0][arguments][0][function]=hour_of_day&filters[$and][0][arguments][1]=0&filters[$and][1][function]=lte&filters[$and][1][arguments][0][function]=hour_of_day&filters[$and][1][arguments][1]=23' + ); + st.equal( + qs.stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'filters[$and][][function]=gte&filters[$and][][arguments][][function]=hour_of_day&filters[$and][][arguments][]=0&filters[$and][][function]=lte&filters[$and][][arguments][][function]=hour_of_day&filters[$and][][arguments][]=23' + ); + st.equal( + qs.stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), + 'filters[$and][function]=gte&filters[$and][arguments][function]=hour_of_day&filters[$and][arguments]=0&filters[$and][function]=lte&filters[$and][arguments][function]=hour_of_day&filters[$and][arguments]=23' + ); + + st.end(); + }); + + t.test('selects properties when filter=array', function (st) { + st.equal(qs.stringify({ a: 'b' }, { filter: ['a'] }), 'a=b'); + st.equal(qs.stringify({ a: 1 }, { filter: [] }), ''); + + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'indices' } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'brackets' } + ), + 'a%5Bb%5D%5B%5D=1&a%5Bb%5D%5B%5D=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2] } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('supports custom representations when filter=function', function (st) { + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + calls += 1; + if (calls === 1) { + st.equal(prefix, '', 'prefix is empty'); + st.equal(value, obj); + } else if (prefix === 'c') { + return void 0; + } else if (value instanceof Date) { + st.equal(prefix, 'e[f]'); + return value.getTime(); + } + return value; + }; + + st.equal(qs.stringify(obj, { filter: filterFunc }), 'a=b&e%5Bf%5D=1257894000000'); + st.equal(calls, 5); + st.end(); + }); + + t.test('can disable uri encoding', function (st) { + st.equal(qs.stringify({ a: 'b' }, { encode: false }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }, { encode: false }), 'a[b]=c'); + st.equal(qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false }), 'a=b&c'); + st.end(); + }); + + t.test('can sort the keys', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal(qs.stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort }), 'a=c&b=f&z=y'); + st.equal(qs.stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort }), 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a'); + st.end(); + }); + + t.test('can sort the keys at depth 3 or more too', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: sort, encode: false } + ), + 'a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb' + ); + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: null, encode: false } + ), + 'a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b' + ); + st.end(); + }); + + t.test('can stringify with custom encoding', function (st) { + st.equal(qs.stringify({ 県: '大阪府', '': '' }, { + encoder: function (str) { + if (str.length === 0) { + return ''; + } + var buf = iconv.encode(str, 'shiftjis'); + var result = []; + for (var i = 0; i < buf.length; ++i) { + result.push(buf.readUInt8(i).toString(16)); + } + return '%' + result.join('%'); + } + }), '%8c%a7=%91%e5%8d%e3%95%7b&='); + st.end(); + }); + + t.test('receives the default encoder as a second argument', function (st) { + st.plan(8); + + qs.stringify({ a: 1, b: new Date(), c: true, d: [1] }, { + encoder: function (str) { + st.match(typeof str, /^(?:string|number|boolean)$/); + return ''; + } + }); + + st.end(); + }); + + t.test('receives the default encoder as a second argument', function (st) { + st.plan(2); + + qs.stringify({ a: 1 }, { + encoder: function (str, defaultEncoder) { + st.equal(defaultEncoder, utils.encode); + } + }); + + st.end(); + }); + + t.test('throws error with wrong encoder', function (st) { + st['throws'](function () { + qs.stringify({}, { encoder: 'string' }); + }, new TypeError('Encoder has to be a function.')); + st.end(); + }); + + t.test('can use custom encoder for a buffer object', { skip: typeof Buffer === 'undefined' }, function (st) { + st.equal(qs.stringify({ a: SaferBuffer.from([1]) }, { + encoder: function (buffer) { + if (typeof buffer === 'string') { + return buffer; + } + return String.fromCharCode(buffer.readUInt8(0) + 97); + } + }), 'a=b'); + + st.equal(qs.stringify({ a: SaferBuffer.from('a b') }, { + encoder: function (buffer) { + return buffer; + } + }), 'a=a b'); + st.end(); + }); + + t.test('serializeDate option', function (st) { + var date = new Date(); + st.equal( + qs.stringify({ a: date }), + 'a=' + date.toISOString().replace(/:/g, '%3A'), + 'default is toISOString' + ); + + var mutatedDate = new Date(); + mutatedDate.toISOString = function () { + throw new SyntaxError(); + }; + st['throws'](function () { + mutatedDate.toISOString(); + }, SyntaxError); + st.equal( + qs.stringify({ a: mutatedDate }), + 'a=' + Date.prototype.toISOString.call(mutatedDate).replace(/:/g, '%3A'), + 'toISOString works even when method is not locally present' + ); + + var specificDate = new Date(6); + st.equal( + qs.stringify( + { a: specificDate }, + { serializeDate: function (d) { return d.getTime() * 7; } } + ), + 'a=42', + 'custom serializeDate function called' + ); + + st.equal( + qs.stringify( + { a: [date] }, + { + serializeDate: function (d) { return d.getTime(); }, + arrayFormat: 'comma' + } + ), + 'a=' + date.getTime(), + 'works with arrayFormat comma' + ); + st.equal( + qs.stringify( + { a: [date] }, + { + serializeDate: function (d) { return d.getTime(); }, + arrayFormat: 'comma', + commaRoundTrip: true + } + ), + 'a%5B%5D=' + date.getTime(), + 'works with arrayFormat comma' + ); + + st.end(); + }); + + t.test('RFC 1738 serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC1738 }), 'a=b+c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC1738 }), 'a+b=c+d'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }, { format: qs.formats.RFC1738 }), 'a+b=a+b'); + + st.equal(qs.stringify({ 'foo(ref)': 'bar' }, { format: qs.formats.RFC1738 }), 'foo(ref)=bar'); + + st.end(); + }); + + t.test('RFC 3986 spaces serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC3986 }), 'a=b%20c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC3986 }), 'a%20b=c%20d'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }, { format: qs.formats.RFC3986 }), 'a%20b=a%20b'); + + st.end(); + }); + + t.test('Backward compatibility to RFC 3986', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }), 'a%20b=a%20b'); + + st.end(); + }); + + t.test('Edge cases and unknown formats', function (st) { + ['UFO1234', false, 1234, null, {}, []].forEach(function (format) { + st['throws']( + function () { + qs.stringify({ a: 'b c' }, { format: format }); + }, + new TypeError('Unknown format option provided.') + ); + }); + st.end(); + }); + + t.test('encodeValuesOnly', function (st) { + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true, arrayFormat: 'indices' } + ), + 'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h', + 'encodeValuesOnly + indices' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true, arrayFormat: 'brackets' } + ), + 'a=b&c[]=d&c[]=e%3Df&f[][]=g&f[][]=h', + 'encodeValuesOnly + brackets' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true, arrayFormat: 'repeat' } + ), + 'a=b&c=d&c=e%3Df&f=g&f=h', + 'encodeValuesOnly + repeat' + ); + + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, + { arrayFormat: 'indices' } + ), + 'a=b&c%5B0%5D=d&c%5B1%5D=e&f%5B0%5D%5B0%5D=g&f%5B1%5D%5B0%5D=h', + 'no encodeValuesOnly + indices' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, + { arrayFormat: 'brackets' } + ), + 'a=b&c%5B%5D=d&c%5B%5D=e&f%5B%5D%5B%5D=g&f%5B%5D%5B%5D=h', + 'no encodeValuesOnly + brackets' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, + { arrayFormat: 'repeat' } + ), + 'a=b&c=d&c=e&f=g&f=h', + 'no encodeValuesOnly + repeat' + ); + + st.end(); + }); + + t.test('encodeValuesOnly - strictNullHandling', function (st) { + st.equal( + qs.stringify( + { a: { b: null } }, + { encodeValuesOnly: true, strictNullHandling: true } + ), + 'a[b]' + ); + st.end(); + }); + + t.test('throws if an invalid charset is specified', function (st) { + st['throws'](function () { + qs.stringify({ a: 'b' }, { charset: 'foobar' }); + }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); + st.end(); + }); + + t.test('respects a charset of iso-8859-1', function (st) { + st.equal(qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }), '%E6=%E6'); + st.end(); + }); + + t.test('encodes unrepresentable chars as numeric entities in iso-8859-1 mode', function (st) { + st.equal(qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }), 'a=%26%239786%3B'); + st.end(); + }); + + t.test('respects an explicit charset of utf-8 (the default)', function (st) { + st.equal(qs.stringify({ a: 'æ' }, { charset: 'utf-8' }), 'a=%C3%A6'); + st.end(); + }); + + t.test('`charsetSentinel` option', function (st) { + st.equal( + qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'utf-8' }), + 'utf8=%E2%9C%93&a=%C3%A6', + 'adds the right sentinel when instructed to and the charset is utf-8' + ); + + st.equal( + qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }), + 'utf8=%26%2310003%3B&a=%E6', + 'adds the right sentinel when instructed to and the charset is iso-8859-1' + ); + + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.stringify({}, options); + st.deepEqual(options, {}); + st.end(); + }); + + t.test('strictNullHandling works with custom filter', function (st) { + var filter = function (prefix, value) { + return value; + }; + + var options = { strictNullHandling: true, filter: filter }; + st.equal(qs.stringify({ key: null }, options), 'key'); + st.end(); + }); + + t.test('strictNullHandling works with null serializeDate', function (st) { + var serializeDate = function () { + return null; + }; + var options = { strictNullHandling: true, serializeDate: serializeDate }; + var date = new Date(); + st.equal(qs.stringify({ key: date }, options), 'key'); + st.end(); + }); + + t.test('allows for encoding keys and values differently', function (st) { + var encoder = function (str, defaultEncoder, charset, type) { + if (type === 'key') { + return defaultEncoder(str, defaultEncoder, charset, type).toLowerCase(); + } + if (type === 'value') { + return defaultEncoder(str, defaultEncoder, charset, type).toUpperCase(); + } + throw 'this should never happen! type: ' + type; + }; + + st.deepEqual(qs.stringify({ KeY: 'vAlUe' }, { encoder: encoder }), 'key=VALUE'); + st.end(); + }); + + t.test('objects inside arrays', function (st) { + var obj = { a: { b: { c: 'd', e: 'f' } } }; + var withArray = { a: { b: [{ c: 'd', e: 'f' }] } }; + + st.equal(qs.stringify(obj, { encode: false }), 'a[b][c]=d&a[b][e]=f', 'no array, no arrayFormat'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'brackets' }), 'a[b][c]=d&a[b][e]=f', 'no array, bracket'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'indices' }), 'a[b][c]=d&a[b][e]=f', 'no array, indices'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'repeat' }), 'a[b][c]=d&a[b][e]=f', 'no array, repeat'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'comma' }), 'a[b][c]=d&a[b][e]=f', 'no array, comma'); + + st.equal(qs.stringify(withArray, { encode: false }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, no arrayFormat'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'brackets' }), 'a[b][][c]=d&a[b][][e]=f', 'array, bracket'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'indices' }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, indices'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'repeat' }), 'a[b][c]=d&a[b][e]=f', 'array, repeat'); + st.equal( + qs.stringify(withArray, { encode: false, arrayFormat: 'comma' }), + '???', + 'array, comma', + { skip: 'TODO: figure out what this should do' } + ); + + st.end(); + }); + + t.test('stringifies sparse arrays', function (st) { + /* eslint no-sparse-arrays: 0 */ + st.equal(qs.stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[1]=2&a[4]=1'); + st.equal(qs.stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=2&a[]=1'); + st.equal(qs.stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a=2&a=1'); + + st.equal(qs.stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[1][b][2][c]=1'); + st.equal(qs.stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[][b][][c]=1'); + st.equal(qs.stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a[b][c]=1'); + + st.equal(qs.stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[1][2][3][c]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[][][][c]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a[c]=1'); + + st.equal(qs.stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[1][2][3][c][1]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[][][][c][]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a[c]=1'); + + st.end(); + }); + + t.test('encodes a very long string', function (st) { + var chars = []; + var expected = []; + for (var i = 0; i < 5e3; i++) { + chars.push(' ' + i); + + expected.push('%20' + i); + } + + var obj = { + foo: chars.join('') + }; + + st.equal( + qs.stringify(obj, { arrayFormat: 'brackets', charset: 'utf-8' }), + 'foo=' + expected.join('') + ); + + st.end(); + }); + + t.end(); +}); + +test('stringifies empty keys', function (t) { + emptyTestCases.forEach(function (testCase) { + t.test('stringifies an object with empty string key with ' + testCase.input, function (st) { + st.deepEqual( + qs.stringify(testCase.withEmptyKeys, { encode: false, arrayFormat: 'indices' }), + testCase.stringifyOutput.indices, + 'test case: ' + testCase.input + ', indices' + ); + st.deepEqual( + qs.stringify(testCase.withEmptyKeys, { encode: false, arrayFormat: 'brackets' }), + testCase.stringifyOutput.brackets, + 'test case: ' + testCase.input + ', brackets' + ); + st.deepEqual( + qs.stringify(testCase.withEmptyKeys, { encode: false, arrayFormat: 'repeat' }), + testCase.stringifyOutput.repeat, + 'test case: ' + testCase.input + ', repeat' + ); + + st.end(); + }); + }); + + t.test('edge case with object/arrays', function (st) { + st.deepEqual(qs.stringify({ '': { '': [2, 3] } }, { encode: false }), '[][0]=2&[][1]=3'); + st.deepEqual(qs.stringify({ '': { '': [2, 3], a: 2 } }, { encode: false }), '[][0]=2&[][1]=3&[a]=2'); + st.deepEqual(qs.stringify({ '': { '': [2, 3] } }, { encode: false, arrayFormat: 'indices' }), '[][0]=2&[][1]=3'); + st.deepEqual(qs.stringify({ '': { '': [2, 3], a: 2 } }, { encode: false, arrayFormat: 'indices' }), '[][0]=2&[][1]=3&[a]=2'); + + st.end(); + }); + + t.test('stringifies non-string keys', function (st) { + var S = Object('abc'); + S.toString = function () { + return 'd'; + }; + var actual = qs.stringify({ a: 'b', 'false': {}, 1e+22: 'c', d: 'e' }, { + filter: ['a', false, null, 10000000000000000000000, S], + allowDots: true, + encodeDotInKeys: true + }); + + st.equal(actual, 'a=b&1e%2B22=c&d=e', 'stringifies correctly'); + + st.end(); + }); +}); diff --git a/node_modules/qs/test/utils.js b/node_modules/qs/test/utils.js new file mode 100644 index 000000000..defb7f26e --- /dev/null +++ b/node_modules/qs/test/utils.js @@ -0,0 +1,381 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var SaferBuffer = require('safer-buffer').Buffer; +var forEach = require('for-each'); +var v = require('es-value-fixtures'); + +var utils = require('../lib/utils'); + +test('merge()', function (t) { + t.deepEqual(utils.merge(null, true), [null, true], 'merges true into null'); + + t.deepEqual(utils.merge(null, [42]), [null, 42], 'merges null into an array'); + + t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key'); + + var oneMerged = utils.merge({ foo: 'bar' }, { foo: { first: '123' } }); + t.deepEqual(oneMerged, { foo: ['bar', { first: '123' }] }, 'merges a standalone and an object into an array'); + + var twoMerged = utils.merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } }); + t.deepEqual(twoMerged, { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, 'merges a standalone and two objects into an array'); + + var sandwiched = utils.merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' }); + t.deepEqual(sandwiched, { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, 'merges an object sandwiched by two standalones into an array'); + + var nestedArrays = utils.merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] }); + t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] }); + + var noOptionsNonObjectSource = utils.merge({ foo: 'baz' }, 'bar'); + t.deepEqual(noOptionsNonObjectSource, { foo: 'baz', bar: true }); + + var func = function f() {}; + t.deepEqual( + utils.merge(func, { foo: 'bar' }), + [func, { foo: 'bar' }], + 'functions can not be merged into' + ); + + func.bar = 'baz'; + t.deepEqual( + utils.merge({ foo: 'bar' }, func), + { foo: 'bar', bar: 'baz' }, + 'functions can be merge sources' + ); + + t.test( + 'avoids invoking array setters unnecessarily', + { skip: typeof Object.defineProperty !== 'function' }, + function (st) { + var setCount = 0; + var getCount = 0; + var observed = []; + Object.defineProperty(observed, 0, { + get: function () { + getCount += 1; + return { bar: 'baz' }; + }, + set: function () { setCount += 1; } + }); + utils.merge(observed, [null]); + st.equal(setCount, 0); + st.equal(getCount, 1); + observed[0] = observed[0]; // eslint-disable-line no-self-assign + st.equal(setCount, 1); + st.equal(getCount, 2); + st.end(); + } + ); + + t.test('with overflow objects (from arrayLimit)', function (st) { + st.test('merges primitive into overflow object at next index', function (s2t) { + // Create an overflow object via combine + var overflow = utils.combine(['a'], 'b', 1, false); + s2t.ok(utils.isOverflow(overflow), 'overflow object is marked'); + var merged = utils.merge(overflow, 'c'); + s2t.deepEqual(merged, { 0: 'a', 1: 'b', 2: 'c' }, 'adds primitive at next numeric index'); + s2t.end(); + }); + + st.test('merges primitive into regular object with numeric keys normally', function (s2t) { + var obj = { 0: 'a', 1: 'b' }; + s2t.notOk(utils.isOverflow(obj), 'plain object is not marked as overflow'); + var merged = utils.merge(obj, 'c'); + s2t.deepEqual(merged, { 0: 'a', 1: 'b', c: true }, 'adds primitive as key (not at next index)'); + s2t.end(); + }); + + st.test('merges primitive into object with non-numeric keys normally', function (s2t) { + var obj = { foo: 'bar' }; + var merged = utils.merge(obj, 'baz'); + s2t.deepEqual(merged, { foo: 'bar', baz: true }, 'adds primitive as key with value true'); + s2t.end(); + }); + + st.test('merges overflow object into primitive', function (s2t) { + // Create an overflow object via combine + var overflow = utils.combine([], 'b', 0, false); + s2t.ok(utils.isOverflow(overflow), 'overflow object is marked'); + var merged = utils.merge('a', overflow); + s2t.ok(utils.isOverflow(merged), 'result is also marked as overflow'); + s2t.deepEqual(merged, { 0: 'a', 1: 'b' }, 'creates object with primitive at 0, source values shifted'); + s2t.end(); + }); + + st.test('merges overflow object with multiple values into primitive', function (s2t) { + // Create an overflow object via combine + var overflow = utils.combine(['b'], 'c', 1, false); + s2t.ok(utils.isOverflow(overflow), 'overflow object is marked'); + var merged = utils.merge('a', overflow); + s2t.deepEqual(merged, { 0: 'a', 1: 'b', 2: 'c' }, 'shifts all source indices by 1'); + s2t.end(); + }); + + st.test('merges regular object into primitive as array', function (s2t) { + var obj = { foo: 'bar' }; + var merged = utils.merge('a', obj); + s2t.deepEqual(merged, ['a', { foo: 'bar' }], 'creates array with primitive and object'); + s2t.end(); + }); + + st.end(); + }); + + t.end(); +}); + +test('assign()', function (t) { + var target = { a: 1, b: 2 }; + var source = { b: 3, c: 4 }; + var result = utils.assign(target, source); + + t.equal(result, target, 'returns the target'); + t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged'); + t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched'); + + t.end(); +}); + +test('combine()', function (t) { + t.test('both arrays', function (st) { + var a = [1]; + var b = [2]; + var combined = utils.combine(a, b); + + st.deepEqual(a, [1], 'a is not mutated'); + st.deepEqual(b, [2], 'b is not mutated'); + st.notEqual(a, combined, 'a !== combined'); + st.notEqual(b, combined, 'b !== combined'); + st.deepEqual(combined, [1, 2], 'combined is a + b'); + + st.end(); + }); + + t.test('one array, one non-array', function (st) { + var aN = 1; + var a = [aN]; + var bN = 2; + var b = [bN]; + + var combinedAnB = utils.combine(aN, b); + st.deepEqual(b, [bN], 'b is not mutated'); + st.notEqual(aN, combinedAnB, 'aN + b !== aN'); + st.notEqual(a, combinedAnB, 'aN + b !== a'); + st.notEqual(bN, combinedAnB, 'aN + b !== bN'); + st.notEqual(b, combinedAnB, 'aN + b !== b'); + st.deepEqual([1, 2], combinedAnB, 'first argument is array-wrapped when not an array'); + + var combinedABn = utils.combine(a, bN); + st.deepEqual(a, [aN], 'a is not mutated'); + st.notEqual(aN, combinedABn, 'a + bN !== aN'); + st.notEqual(a, combinedABn, 'a + bN !== a'); + st.notEqual(bN, combinedABn, 'a + bN !== bN'); + st.notEqual(b, combinedABn, 'a + bN !== b'); + st.deepEqual([1, 2], combinedABn, 'second argument is array-wrapped when not an array'); + + st.end(); + }); + + t.test('neither is an array', function (st) { + var combined = utils.combine(1, 2); + st.notEqual(1, combined, '1 + 2 !== 1'); + st.notEqual(2, combined, '1 + 2 !== 2'); + st.deepEqual([1, 2], combined, 'both arguments are array-wrapped when not an array'); + + st.end(); + }); + + t.test('with arrayLimit', function (st) { + st.test('under the limit', function (s2t) { + var combined = utils.combine(['a', 'b'], 'c', 10, false); + s2t.deepEqual(combined, ['a', 'b', 'c'], 'returns array when under limit'); + s2t.ok(Array.isArray(combined), 'result is an array'); + s2t.end(); + }); + + st.test('exactly at the limit stays as array', function (s2t) { + var combined = utils.combine(['a', 'b'], 'c', 3, false); + s2t.deepEqual(combined, ['a', 'b', 'c'], 'stays as array when exactly at limit'); + s2t.ok(Array.isArray(combined), 'result is an array'); + s2t.end(); + }); + + st.test('over the limit', function (s2t) { + var combined = utils.combine(['a', 'b', 'c'], 'd', 3, false); + s2t.deepEqual(combined, { 0: 'a', 1: 'b', 2: 'c', 3: 'd' }, 'converts to object when over limit'); + s2t.notOk(Array.isArray(combined), 'result is not an array'); + s2t.end(); + }); + + st.test('with arrayLimit 0', function (s2t) { + var combined = utils.combine([], 'a', 0, false); + s2t.deepEqual(combined, { 0: 'a' }, 'converts single element to object with arrayLimit 0'); + s2t.notOk(Array.isArray(combined), 'result is not an array'); + s2t.end(); + }); + + st.test('with plainObjects option', function (s2t) { + var combined = utils.combine(['a'], 'b', 1, true); + var expected = { __proto__: null, 0: 'a', 1: 'b' }; + s2t.deepEqual(combined, expected, 'converts to object with null prototype'); + s2t.equal(Object.getPrototypeOf(combined), null, 'result has null prototype when plainObjects is true'); + s2t.end(); + }); + + st.end(); + }); + + t.test('with existing overflow object', function (st) { + st.test('adds to existing overflow object at next index', function (s2t) { + // Create overflow object first via combine + var overflow = utils.combine(['a'], 'b', 1, false); + s2t.ok(utils.isOverflow(overflow), 'initial object is marked as overflow'); + + var combined = utils.combine(overflow, 'c', 10, false); + s2t.equal(combined, overflow, 'returns the same object (mutated)'); + s2t.deepEqual(combined, { 0: 'a', 1: 'b', 2: 'c' }, 'adds value at next numeric index'); + s2t.end(); + }); + + st.test('does not treat plain object with numeric keys as overflow', function (s2t) { + var plainObj = { 0: 'a', 1: 'b' }; + s2t.notOk(utils.isOverflow(plainObj), 'plain object is not marked as overflow'); + + // combine treats this as a regular value, not an overflow object to append to + var combined = utils.combine(plainObj, 'c', 10, false); + s2t.deepEqual(combined, [{ 0: 'a', 1: 'b' }, 'c'], 'concatenates as regular values'); + s2t.end(); + }); + + st.end(); + }); + + t.end(); +}); + +test('decode', function (t) { + t.equal( + utils.decode('a+b'), + 'a b', + 'decodes + to space' + ); + + t.equal( + utils.decode('name%2Eobj'), + 'name.obj', + 'decodes a string' + ); + t.equal( + utils.decode('name%2Eobj%2Efoo', null, 'iso-8859-1'), + 'name.obj.foo', + 'decodes a string in iso-8859-1' + ); + + t.end(); +}); + +test('encode', function (t) { + forEach(v.nullPrimitives, function (nullish) { + t['throws']( + function () { utils.encode(nullish); }, + TypeError, + inspect(nullish) + ' is not a string' + ); + }); + + t.equal(utils.encode(''), '', 'empty string returns itself'); + t.deepEqual(utils.encode([]), [], 'empty array returns itself'); + t.deepEqual(utils.encode({ length: 0 }), { length: 0 }, 'empty arraylike returns itself'); + + t.test('symbols', { skip: !v.hasSymbols }, function (st) { + st.equal(utils.encode(Symbol('x')), 'Symbol%28x%29', 'symbol is encoded'); + + st.end(); + }); + + t.equal( + utils.encode('(abc)'), + '%28abc%29', + 'encodes parentheses' + ); + t.equal( + utils.encode({ toString: function () { return '(abc)'; } }), + '%28abc%29', + 'toStrings and encodes parentheses' + ); + + t.equal( + utils.encode('abc 123 💩', null, 'iso-8859-1'), + 'abc%20123%20%26%2355357%3B%26%2356489%3B', + 'encodes in iso-8859-1' + ); + + var longString = ''; + var expectedString = ''; + for (var i = 0; i < 1500; i++) { + longString += ' '; + expectedString += '%20'; + } + + t.equal( + utils.encode(longString), + expectedString, + 'encodes a long string' + ); + + t.equal( + utils.encode('\x28\x29'), + '%28%29', + 'encodes parens normally' + ); + t.equal( + utils.encode('\x28\x29', null, null, null, 'RFC1738'), + '()', + 'does not encode parens in RFC1738' + ); + + // todo RFC1738 format + + t.equal( + utils.encode('Āက豈'), + '%C4%80%E1%80%80%EF%A4%80', + 'encodes multibyte chars' + ); + + t.equal( + utils.encode('\uD83D \uDCA9'), + '%F0%9F%90%A0%F0%BA%90%80', + 'encodes lone surrogates' + ); + + t.end(); +}); + +test('isBuffer()', function (t) { + forEach([null, undefined, true, false, '', 'abc', 42, 0, NaN, {}, [], function () {}, /a/g], function (x) { + t.equal(utils.isBuffer(x), false, inspect(x) + ' is not a buffer'); + }); + + var fakeBuffer = { constructor: Buffer }; + t.equal(utils.isBuffer(fakeBuffer), false, 'fake buffer is not a buffer'); + + var saferBuffer = SaferBuffer.from('abc'); + t.equal(utils.isBuffer(saferBuffer), true, 'SaferBuffer instance is a buffer'); + + var buffer = Buffer.from && Buffer.alloc ? Buffer.from('abc') : new Buffer('abc'); + t.equal(utils.isBuffer(buffer), true, 'real Buffer instance is a buffer'); + t.end(); +}); + +test('isRegExp()', function (t) { + t.equal(utils.isRegExp(/a/g), true, 'RegExp is a RegExp'); + t.equal(utils.isRegExp(new RegExp('a', 'g')), true, 'new RegExp is a RegExp'); + t.equal(utils.isRegExp(new Date()), false, 'Date is not a RegExp'); + + forEach(v.primitives, function (primitive) { + t.equal(utils.isRegExp(primitive), false, inspect(primitive) + ' is not a RegExp'); + }); + + t.end(); +}); diff --git a/node_modules/range-parser/HISTORY.md b/node_modules/range-parser/HISTORY.md new file mode 100644 index 000000000..70a973d80 --- /dev/null +++ b/node_modules/range-parser/HISTORY.md @@ -0,0 +1,56 @@ +1.2.1 / 2019-05-10 +================== + + * Improve error when `str` is not a string + +1.2.0 / 2016-06-01 +================== + + * Add `combine` option to combine overlapping ranges + +1.1.0 / 2016-05-13 +================== + + * Fix incorrectly returning -1 when there is at least one valid range + * perf: remove internal function + +1.0.3 / 2015-10-29 +================== + + * perf: enable strict mode + +1.0.2 / 2014-09-08 +================== + + * Support Node.js 0.6 + +1.0.1 / 2014-09-07 +================== + + * Move repository to jshttp + +1.0.0 / 2013-12-11 +================== + + * Add repository to package.json + * Add MIT license + +0.0.4 / 2012-06-17 +================== + + * Change ret -1 for unsatisfiable and -2 when invalid + +0.0.3 / 2012-06-17 +================== + + * Fix last-byte-pos default to len - 1 + +0.0.2 / 2012-06-14 +================== + + * Add `.type` + +0.0.1 / 2012-06-11 +================== + + * Initial release diff --git a/node_modules/range-parser/LICENSE b/node_modules/range-parser/LICENSE new file mode 100644 index 000000000..359995436 --- /dev/null +++ b/node_modules/range-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015-2016 Douglas Christopher Wilson + +```js +var parseRange = require('range-parser') +``` + +### parseRange(size, header, options) + +Parse the given `header` string where `size` is the maximum size of the resource. +An array of ranges will be returned or negative numbers indicating an error parsing. + + * `-2` signals a malformed header string + * `-1` signals an unsatisfiable range + + + +```js +// parse header from request +var range = parseRange(size, req.headers.range) + +// the type of the range +if (range.type === 'bytes') { + // the ranges + range.forEach(function (r) { + // do something with r.start and r.end + }) +} +``` + +#### Options + +These properties are accepted in the options object. + +##### combine + +Specifies if overlapping & adjacent ranges should be combined, defaults to `false`. +When `true`, ranges will be combined and returned as if they were specified that +way in the header. + + + +```js +parseRange(100, 'bytes=50-55,0-10,5-10,56-60', { combine: true }) +// => [ +// { start: 0, end: 10 }, +// { start: 50, end: 60 } +// ] +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/range-parser/master +[coveralls-url]: https://coveralls.io/r/jshttp/range-parser?branch=master +[node-image]: https://badgen.net/npm/node/range-parser +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/range-parser +[npm-url]: https://npmjs.org/package/range-parser +[npm-version-image]: https://badgen.net/npm/v/range-parser +[travis-image]: https://badgen.net/travis/jshttp/range-parser/master +[travis-url]: https://travis-ci.org/jshttp/range-parser diff --git a/node_modules/range-parser/index.js b/node_modules/range-parser/index.js new file mode 100644 index 000000000..b7dc5c0f1 --- /dev/null +++ b/node_modules/range-parser/index.js @@ -0,0 +1,162 @@ +/*! + * range-parser + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = rangeParser + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @param {Object} [options] + * @return {Array} + * @public + */ + +function rangeParser (size, str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string') + } + + var index = str.indexOf('=') + + if (index === -1) { + return -2 + } + + // split the range string + var arr = str.slice(index + 1).split(',') + var ranges = [] + + // add ranges type + ranges.type = str.slice(0, index) + + // parse all ranges + for (var i = 0; i < arr.length; i++) { + var range = arr[i].split('-') + var start = parseInt(range[0], 10) + var end = parseInt(range[1], 10) + + // -nnn + if (isNaN(start)) { + start = size - end + end = size - 1 + // nnn- + } else if (isNaN(end)) { + end = size - 1 + } + + // limit last-byte-pos to current length + if (end > size - 1) { + end = size - 1 + } + + // invalid or unsatisifiable + if (isNaN(start) || isNaN(end) || start > end || start < 0) { + continue + } + + // add range + ranges.push({ + start: start, + end: end + }) + } + + if (ranges.length < 1) { + // unsatisifiable + return -1 + } + + return options && options.combine + ? combineRanges(ranges) + : ranges +} + +/** + * Combine overlapping & adjacent ranges. + * @private + */ + +function combineRanges (ranges) { + var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart) + + for (var j = 0, i = 1; i < ordered.length; i++) { + var range = ordered[i] + var current = ordered[j] + + if (range.start > current.end + 1) { + // next range + ordered[++j] = range + } else if (range.end > current.end) { + // extend range + current.end = range.end + current.index = Math.min(current.index, range.index) + } + } + + // trim ordered array + ordered.length = j + 1 + + // generate combined range + var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex) + + // copy ranges type + combined.type = ranges.type + + return combined +} + +/** + * Map function to add index value to ranges. + * @private + */ + +function mapWithIndex (range, index) { + return { + start: range.start, + end: range.end, + index: index + } +} + +/** + * Map function to remove index value from ranges. + * @private + */ + +function mapWithoutIndex (range) { + return { + start: range.start, + end: range.end + } +} + +/** + * Sort function to sort ranges by index. + * @private + */ + +function sortByRangeIndex (a, b) { + return a.index - b.index +} + +/** + * Sort function to sort ranges by start position. + * @private + */ + +function sortByRangeStart (a, b) { + return a.start - b.start +} diff --git a/node_modules/range-parser/package.json b/node_modules/range-parser/package.json new file mode 100644 index 000000000..abea6d852 --- /dev/null +++ b/node_modules/range-parser/package.json @@ -0,0 +1,44 @@ +{ + "name": "range-parser", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "description": "Range header field string parser", + "version": "1.2.1", + "contributors": [ + "Douglas Christopher Wilson ", + "James Wyatt Cready ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "range", + "parser", + "http" + ], + "repository": "jshttp/range-parser", + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "mocha": "6.1.4", + "nyc": "14.1.1" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test" + } +} diff --git a/node_modules/raw-body/LICENSE b/node_modules/raw-body/LICENSE new file mode 100644 index 000000000..1029a7a7c --- /dev/null +++ b/node_modules/raw-body/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2013-2014 Jonathan Ong +Copyright (c) 2014-2022 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/raw-body/README.md b/node_modules/raw-body/README.md new file mode 100644 index 000000000..d9b36d611 --- /dev/null +++ b/node_modules/raw-body/README.md @@ -0,0 +1,223 @@ +# raw-body + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-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] + +Gets the entire buffer of a stream either as a `Buffer` or a string. +Validates the stream's length against an expected length and maximum limit. +Ideal for parsing request bodies. + +## Install + +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 raw-body +``` + +### TypeScript + +This module includes a [TypeScript](https://www.typescriptlang.org/) +declaration file to enable auto complete in compatible editors and type +information for TypeScript projects. This module depends on the Node.js +types, so install `@types/node`: + +```sh +$ npm install @types/node +``` + +## API + +```js +var getRawBody = require('raw-body') +``` + +### getRawBody(stream, [options], [callback]) + +**Returns a promise if no callback specified and global `Promise` exists.** + +Options: + +- `length` - The length of the stream. + If the contents of the stream do not add up to this length, + an `400` error code is returned. +- `limit` - The byte limit of the body. + This is the number of bytes or any string format supported by + [bytes](https://www.npmjs.com/package/bytes), + for example `1000`, `'500kb'` or `'3mb'`. + If the body ends up being larger than this limit, + a `413` error code is returned. +- `encoding` - The encoding to use to decode the body into a string. + By default, a `Buffer` instance will be returned when no encoding is specified. + Most likely, you want `utf-8`, so setting `encoding` to `true` will decode as `utf-8`. + You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme). + +You can also pass a string in place of options to just specify the encoding. + +If an error occurs, the stream will be paused, everything unpiped, +and you are responsible for correctly disposing the stream. +For HTTP requests, you may need to finish consuming the stream if +you want to keep the socket open for future requests. For streams +that use file descriptors, you should `stream.destroy()` or +`stream.close()` to prevent leaks. + +## Errors + +This module creates errors depending on the error condition during reading. +The error may be an error from the underlying Node.js implementation, but is +otherwise an error created by this module, which has the following attributes: + + * `limit` - the limit in bytes + * `length` and `expected` - the expected length of the stream + * `received` - the received bytes + * `encoding` - the invalid encoding + * `status` and `statusCode` - the corresponding status code for the error + * `type` - the error type + +### Types + +The errors from this module have a `type` property which allows for the programmatic +determination of the type of error returned. + +#### encoding.unsupported + +This error will occur when the `encoding` option is specified, but the value does +not map to an encoding supported by the [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme) +module. + +#### entity.too.large + +This error will occur when the `limit` option is specified, but the stream has +an entity that is larger. + +#### request.aborted + +This error will occur when the request stream is aborted by the client before +reading the body has finished. + +#### request.size.invalid + +This error will occur when the `length` option is specified, but the stream has +emitted more bytes. + +#### stream.encoding.set + +This error will occur when the given stream has an encoding set on it, making it +a decoded stream. The stream should not have an encoding set and is expected to +emit `Buffer` objects. + +#### stream.not.readable + +This error will occur when the given stream is not readable. + +## Examples + +### Simple Express example + +```js +var contentType = require('content-type') +var express = require('express') +var getRawBody = require('raw-body') + +var app = express() + +app.use(function (req, res, next) { + getRawBody(req, { + length: req.headers['content-length'], + limit: '1mb', + encoding: contentType.parse(req).parameters.charset + }, function (err, string) { + if (err) return next(err) + req.text = string + next() + }) +}) + +// now access req.text +``` + +### Simple Koa example + +```js +var contentType = require('content-type') +var getRawBody = require('raw-body') +var koa = require('koa') + +var app = koa() + +app.use(function * (next) { + this.text = yield getRawBody(this.req, { + length: this.req.headers['content-length'], + limit: '1mb', + encoding: contentType.parse(this.req).parameters.charset + }) + yield next +}) + +// now access this.text +``` + +### Using as a promise + +To use this library as a promise, simply omit the `callback` and a promise is +returned, provided that a global `Promise` is defined. + +```js +var getRawBody = require('raw-body') +var http = require('http') + +var server = http.createServer(function (req, res) { + getRawBody(req) + .then(function (buf) { + res.statusCode = 200 + res.end(buf.length + ' bytes submitted') + }) + .catch(function (err) { + res.statusCode = 500 + res.end(err.message) + }) +}) + +server.listen(3000) +``` + +### Using with TypeScript + +```ts +import * as getRawBody from 'raw-body'; +import * as http from 'http'; + +const server = http.createServer((req, res) => { + getRawBody(req) + .then((buf) => { + res.statusCode = 200; + res.end(buf.length + ' bytes submitted'); + }) + .catch((err) => { + res.statusCode = err.statusCode; + res.end(err.message); + }); +}); + +server.listen(3000); +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/raw-body.svg +[npm-url]: https://npmjs.org/package/raw-body +[node-version-image]: https://img.shields.io/node/v/raw-body.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/raw-body/master.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/raw-body?branch=master +[downloads-image]: https://img.shields.io/npm/dm/raw-body.svg +[downloads-url]: https://npmjs.org/package/raw-body +[github-actions-ci-image]: https://img.shields.io/github/actions/workflow/status/stream-utils/raw-body/ci.yml?branch=master&label=ci +[github-actions-ci-url]: https://github.com/jshttp/stream-utils/raw-body?query=workflow%3Aci diff --git a/node_modules/raw-body/index.d.ts b/node_modules/raw-body/index.d.ts new file mode 100644 index 000000000..b5046118c --- /dev/null +++ b/node_modules/raw-body/index.d.ts @@ -0,0 +1,85 @@ +declare namespace getRawBody { + export type Encoding = string | true; + + export interface Options { + /** + * The expected length of the stream. + */ + length?: number | string | null; + /** + * The byte limit of the body. This is the number of bytes or any string + * format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. + */ + limit?: number | string | null; + /** + * The encoding to use to decode the body into a string. By default, a + * `Buffer` instance will be returned when no encoding is specified. Most + * likely, you want `utf-8`, so setting encoding to `true` will decode as + * `utf-8`. You can use any type of encoding supported by `iconv-lite`. + */ + encoding?: Encoding | null; + } + + export interface RawBodyError extends Error { + /** + * The limit in bytes. + */ + limit?: number; + /** + * The expected length of the stream. + */ + length?: number; + expected?: number; + /** + * The received bytes. + */ + received?: number; + /** + * The encoding. + */ + encoding?: string; + /** + * The corresponding status code for the error. + */ + status: number; + statusCode: number; + /** + * The error type. + */ + type: string; + } +} + +/** + * Gets the entire buffer of a stream either as a `Buffer` or a string. + * Validates the stream's length against an expected length and maximum + * limit. Ideal for parsing request bodies. + */ +declare function getRawBody( + stream: NodeJS.ReadableStream, + callback: (err: getRawBody.RawBodyError, body: Buffer) => void +): void; + +declare function getRawBody( + stream: NodeJS.ReadableStream, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding, + callback: (err: getRawBody.RawBodyError, body: string) => void +): void; + +declare function getRawBody( + stream: NodeJS.ReadableStream, + options: getRawBody.Options, + callback: (err: getRawBody.RawBodyError, body: Buffer) => void +): void; + +declare function getRawBody( + stream: NodeJS.ReadableStream, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding +): Promise; + +declare function getRawBody( + stream: NodeJS.ReadableStream, + options?: getRawBody.Options +): Promise; + +export = getRawBody; diff --git a/node_modules/raw-body/index.js b/node_modules/raw-body/index.js new file mode 100644 index 000000000..9cdcd1221 --- /dev/null +++ b/node_modules/raw-body/index.js @@ -0,0 +1,336 @@ +/*! + * raw-body + * Copyright(c) 2013-2014 Jonathan Ong + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var asyncHooks = tryRequireAsyncHooks() +var bytes = require('bytes') +var createError = require('http-errors') +var iconv = require('iconv-lite') +var unpipe = require('unpipe') + +/** + * Module exports. + * @public + */ + +module.exports = getRawBody + +/** + * Module variables. + * @private + */ + +var ICONV_ENCODING_MESSAGE_REGEXP = /^Encoding not recognized: / + +/** + * Get the decoder for a given encoding. + * + * @param {string} encoding + * @private + */ + +function getDecoder (encoding) { + if (!encoding) return null + + try { + return iconv.getDecoder(encoding) + } catch (e) { + // error getting decoder + if (!ICONV_ENCODING_MESSAGE_REGEXP.test(e.message)) throw e + + // the encoding was not found + throw createError(415, 'specified encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } +} + +/** + * Get the raw body of a stream (typically HTTP). + * + * @param {object} stream + * @param {object|string|function} [options] + * @param {function} [callback] + * @public + */ + +function getRawBody (stream, options, callback) { + var done = callback + var opts = options || {} + + // light validation + if (stream === undefined) { + throw new TypeError('argument stream is required') + } else if (typeof stream !== 'object' || stream === null || typeof stream.on !== 'function') { + throw new TypeError('argument stream must be a stream') + } + + if (options === true || typeof options === 'string') { + // short cut for encoding + opts = { + encoding: options + } + } + + if (typeof options === 'function') { + done = options + opts = {} + } + + // validate callback is a function, if provided + if (done !== undefined && typeof done !== 'function') { + throw new TypeError('argument callback must be a function') + } + + // require the callback without promises + if (!done && !global.Promise) { + throw new TypeError('argument callback is required') + } + + // get encoding + var encoding = opts.encoding !== true + ? opts.encoding + : 'utf-8' + + // convert the limit to an integer + var limit = bytes.parse(opts.limit) + + // convert the expected length to an integer + var length = opts.length != null && !isNaN(opts.length) + ? parseInt(opts.length, 10) + : null + + if (done) { + // classic callback style + return readStream(stream, encoding, length, limit, wrap(done)) + } + + return new Promise(function executor (resolve, reject) { + readStream(stream, encoding, length, limit, function onRead (err, buf) { + if (err) return reject(err) + resolve(buf) + }) + }) +} + +/** + * Halt a stream. + * + * @param {Object} stream + * @private + */ + +function halt (stream) { + // unpipe everything from the stream + unpipe(stream) + + // pause stream + if (typeof stream.pause === 'function') { + stream.pause() + } +} + +/** + * Read the data from the stream. + * + * @param {object} stream + * @param {string} encoding + * @param {number} length + * @param {number} limit + * @param {function} callback + * @public + */ + +function readStream (stream, encoding, length, limit, callback) { + var complete = false + var sync = true + + // check the length and limit options. + // note: we intentionally leave the stream paused, + // so users should handle the stream themselves. + if (limit !== null && length !== null && length > limit) { + return done(createError(413, 'request entity too large', { + expected: length, + length: length, + limit: limit, + type: 'entity.too.large' + })) + } + + // streams1: assert request encoding is buffer. + // streams2+: assert the stream encoding is buffer. + // stream._decoder: streams1 + // state.encoding: streams2 + // state.decoder: streams2, specifically < 0.10.6 + var state = stream._readableState + if (stream._decoder || (state && (state.encoding || state.decoder))) { + // developer error + return done(createError(500, 'stream encoding should not be set', { + type: 'stream.encoding.set' + })) + } + + if (typeof stream.readable !== 'undefined' && !stream.readable) { + return done(createError(500, 'stream is not readable', { + type: 'stream.not.readable' + })) + } + + var received = 0 + var decoder + + try { + decoder = getDecoder(encoding) + } catch (err) { + return done(err) + } + + var buffer = decoder + ? '' + : [] + + // attach listeners + stream.on('aborted', onAborted) + stream.on('close', cleanup) + stream.on('data', onData) + stream.on('end', onEnd) + stream.on('error', onEnd) + + // mark sync section complete + sync = false + + function done () { + var args = new Array(arguments.length) + + // copy arguments + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + // mark complete + complete = true + + if (sync) { + process.nextTick(invokeCallback) + } else { + invokeCallback() + } + + function invokeCallback () { + cleanup() + + if (args[0]) { + // halt the stream on error + halt(stream) + } + + callback.apply(null, args) + } + } + + function onAborted () { + if (complete) return + + done(createError(400, 'request aborted', { + code: 'ECONNABORTED', + expected: length, + length: length, + received: received, + type: 'request.aborted' + })) + } + + function onData (chunk) { + if (complete) return + + received += chunk.length + + if (limit !== null && received > limit) { + done(createError(413, 'request entity too large', { + limit: limit, + received: received, + type: 'entity.too.large' + })) + } else if (decoder) { + buffer += decoder.write(chunk) + } else { + buffer.push(chunk) + } + } + + function onEnd (err) { + if (complete) return + if (err) return done(err) + + if (length !== null && received !== length) { + done(createError(400, 'request size did not match content length', { + expected: length, + length: length, + received: received, + type: 'request.size.invalid' + })) + } else { + var string = decoder + ? buffer + (decoder.end() || '') + : Buffer.concat(buffer) + done(null, string) + } + } + + function cleanup () { + buffer = null + + stream.removeListener('aborted', onAborted) + stream.removeListener('data', onData) + stream.removeListener('end', onEnd) + stream.removeListener('error', onEnd) + stream.removeListener('close', cleanup) + } +} + +/** + * Try to require async_hooks + * @private + */ + +function tryRequireAsyncHooks () { + try { + return require('async_hooks') + } catch (e) { + return {} + } +} + +/** + * Wrap function with async resource, if possible. + * AsyncResource.bind static method backported. + * @private + */ + +function wrap (fn) { + var res + + // create anonymous resource + if (asyncHooks.AsyncResource) { + res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') + } + + // incompatible node.js + if (!res || !res.runInAsyncScope) { + return fn + } + + // return bound function + return res.runInAsyncScope.bind(res, fn, null) +} diff --git a/node_modules/raw-body/package.json b/node_modules/raw-body/package.json new file mode 100644 index 000000000..eab819f21 --- /dev/null +++ b/node_modules/raw-body/package.json @@ -0,0 +1,46 @@ +{ + "name": "raw-body", + "description": "Get and validate the raw body of a readable stream.", + "version": "3.0.2", + "author": "Jonathan Ong (http://jongleberry.com)", + "contributors": [ + "Douglas Christopher Wilson ", + "Raynos " + ], + "license": "MIT", + "repository": "stream-utils/raw-body", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "devDependencies": { + "@stylistic/eslint-plugin": "^5.1.0", + "@stylistic/eslint-plugin-js": "^4.1.0", + "bluebird": "3.7.2", + "eslint": "^9.0.0", + "mocha": "10.7.0", + "neostandard": "^0.12.0", + "nyc": "17.0.0", + "readable-stream": "2.3.7", + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.10" + }, + "files": [ + "LICENSE", + "README.md", + "index.d.ts", + "index.js" + ], + "scripts": { + "lint": "eslint", + "lint:fix": "eslint --fix", + "test": "mocha --trace-deprecation --reporter spec --check-leaks test/", + "test:ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test:cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/require-from-string/index.js b/node_modules/require-from-string/index.js new file mode 100644 index 000000000..cb5595fde --- /dev/null +++ b/node_modules/require-from-string/index.js @@ -0,0 +1,34 @@ +'use strict'; + +var Module = require('module'); +var path = require('path'); + +module.exports = function requireFromString(code, filename, opts) { + if (typeof filename === 'object') { + opts = filename; + filename = undefined; + } + + opts = opts || {}; + filename = filename || ''; + + opts.appendPaths = opts.appendPaths || []; + opts.prependPaths = opts.prependPaths || []; + + if (typeof code !== 'string') { + throw new Error('code must be a string, not ' + typeof code); + } + + var paths = Module._nodeModulePaths(path.dirname(filename)); + + var parent = module.parent; + var m = new Module(filename, parent); + m.filename = filename; + m.paths = [].concat(opts.prependPaths).concat(paths).concat(opts.appendPaths); + m._compile(code, filename); + + var exports = m.exports; + parent && parent.children && parent.children.splice(parent.children.indexOf(m), 1); + + return exports; +}; diff --git a/node_modules/require-from-string/license b/node_modules/require-from-string/license new file mode 100644 index 000000000..1aeb74fd2 --- /dev/null +++ b/node_modules/require-from-string/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Vsevolod Strukchinsky (github.com/floatdrop) + +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/require-from-string/package.json b/node_modules/require-from-string/package.json new file mode 100644 index 000000000..800d46efc --- /dev/null +++ b/node_modules/require-from-string/package.json @@ -0,0 +1,28 @@ +{ + "name": "require-from-string", + "version": "2.0.2", + "description": "Require module from string", + "license": "MIT", + "repository": "floatdrop/require-from-string", + "author": { + "name": "Vsevolod Strukchinsky", + "email": "floatdrop@gmail.com", + "url": "github.com/floatdrop" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "files": [ + "index.js" + ], + "keywords": [ + "" + ], + "dependencies": {}, + "devDependencies": { + "mocha": "*" + } +} diff --git a/node_modules/require-from-string/readme.md b/node_modules/require-from-string/readme.md new file mode 100644 index 000000000..88b3236f8 --- /dev/null +++ b/node_modules/require-from-string/readme.md @@ -0,0 +1,56 @@ +# require-from-string [![Build Status](https://travis-ci.org/floatdrop/require-from-string.svg?branch=master)](https://travis-ci.org/floatdrop/require-from-string) + +Load module from string in Node. + +## Install + +``` +$ npm install --save require-from-string +``` + + +## Usage + +```js +var requireFromString = require('require-from-string'); + +requireFromString('module.exports = 1'); +//=> 1 +``` + + +## API + +### requireFromString(code, [filename], [options]) + +#### code + +*Required* +Type: `string` + +Module code. + +#### filename +Type: `string` +Default: `''` + +Optional filename. + + +#### options +Type: `object` + +##### appendPaths +Type: `Array` + +List of `paths`, that will be appended to module `paths`. Useful, when you want +to be able require modules from these paths. + +##### prependPaths +Type: `Array` + +Same as `appendPaths`, but paths will be prepended. + +## License + +MIT © [Vsevolod Strukchinsky](http://github.com/floatdrop) diff --git a/node_modules/router/HISTORY.md b/node_modules/router/HISTORY.md new file mode 100644 index 000000000..b292257a4 --- /dev/null +++ b/node_modules/router/HISTORY.md @@ -0,0 +1,228 @@ +2.2.0 / 2025-03-26 +================== + +* Remove `setImmediate` support check +* Restore `debug` dependency + +2.1.0 / 2025-02-10 +================== + +* Updated `engines` field to Node@18 or higher +* Remove `Object.setPrototypeOf` polyfill +* Use `Array.flat` instead of `array-flatten` package +* Replace `methods` dependency with standard library +* deps: parseurl@^1.3.3 +* deps: is-promise@^4.0.0 +* Replace `utils-merge` dependency with `Object.assign` +* deps: Remove unused dep `after` + +2.0.0 / 2024-09-09 +================== + +* Drop support for node <18 +* deps: path-to-regexp@^8.0.0 + - Drop support for partial capture group `router.route('/user(s?)/:user/:op')` but still have optional non-capture `/user{s}/:user/:op` + - `:name?` becomes `{:name}` + - `:name*` becomes `*name`. + - The splat change also changes splat from strings to an array of strings + - Optional splats become `{*name}` + - `:name+` becomes `*name` and thus equivalent to `*name` so I dropped those tests + - Strings as regular expressions are fully removed, need to be converted to native regular expressions + +2.0.0-beta.2 / 2024-03-20 +========================= + +This incorporates all changes after 1.3.5 up to 1.3.8. + + * Add support for returned, rejected Promises to `router.param` + +2.0.0-beta.1 / 2020-03-29 +========================= + +This incorporates all changes after 1.3.3 up to 1.3.5. + + * Internalize private `router.process_params` method + * Remove `debug` dependency + * deps: array-flatten@3.0.0 + * deps: parseurl@~1.3.3 + * deps: path-to-regexp@3.2.0 + - Add new `?`, `*`, and `+` parameter modifiers. + - Matching group expressions are only RegExp syntax. + `(*)` is no longer valid and must be written as `(.*)`, for example. + - Named matching groups no longer available by position in `req.params`. + `/:foo(.*)` only captures as `req.params.foo` and not available as + `req.params[0]`. + - Regular expressions can only be used in a matching group. + `/\\d+` is no longer valid and must be written as `/(\\d+)`. + - Matching groups are now literal regular expressions. + `:foo` named captures can no longer be included inside a capture group. + - Special `*` path segment behavior removed. + `/foo/*/bar` will match a literal `*` as the middle segment. + * deps: setprototypeof@1.2.0 + +2.0.0-alpha.1 / 2018-07-27 +========================== + + * Add basic support for returned, rejected Promises + - Rejected Promises from middleware functions `next(error)` + * Drop support for Node.js below 0.10 + * deps: debug@3.1.0 + - Add `DEBUG_HIDE_DATE` environment variable + - Change timer to per-namespace instead of global + - Change non-TTY date format + - Remove `DEBUG_FD` environment variable support + - Support 256 namespace colors + +1.3.8 / 2023-02-24 +================== + + * Fix routing requests without method + +1.3.7 / 2022-04-28 +================== + + * Fix hanging on large stack of sync routes + +1.3.6 / 2021-11-15 +================== + + * Fix handling very large stacks of sync middleware + * deps: safe-buffer@5.2.1 + +1.3.5 / 2020-03-24 +================== + + * Fix incorrect middleware execution with unanchored `RegExp`s + * perf: use plain object for internal method map + +1.3.4 / 2020-01-24 +================== + + * deps: array-flatten@3.0.0 + * deps: parseurl@~1.3.3 + * deps: setprototypeof@1.2.0 + +1.3.3 / 2018-07-06 +================== + + * Fix JSDoc for `Router` constructor + +1.3.2 / 2017-09-24 +================== + + * deps: debug@2.6.9 + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: setprototypeof@1.1.0 + * deps: utils-merge@1.0.1 + +1.3.1 / 2017-05-19 +================== + + * deps: debug@2.6.8 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + +1.3.0 / 2017-02-25 +================== + + * Add `next("router")` to exit from router + * Fix case where `router.use` skipped requests routes did not + * Use `%o` in path debug to tell types apart + * deps: setprototypeof@1.0.3 + * perf: add fast match path for `*` route + +1.2.0 / 2017-02-17 +================== + + * Skip routing when `req.url` is not set + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + +1.1.5 / 2017-01-28 +================== + + * deps: array-flatten@2.1.1 + * deps: setprototypeof@1.0.2 + - Fix using fallback even when native method exists + +1.1.4 / 2016-01-21 +================== + + * deps: array-flatten@2.0.0 + * deps: methods@~1.1.2 + - perf: enable strict mode + * deps: parseurl@~1.3.1 + - perf: enable strict mode + +1.1.3 / 2015-08-02 +================== + + * Fix infinite loop condition using `mergeParams: true` + * Fix inner numeric indices incorrectly altering parent `req.params` + * deps: array-flatten@1.1.1 + - perf: enable strict mode + * deps: path-to-regexp@0.1.7 + - Fix regression with escaped round brackets and matching groups + +1.1.2 / 2015-07-06 +================== + + * Fix hiding platform issues with `decodeURIComponent` + - Only `URIError`s are a 400 + * Fix using `*` before params in routes + * Fix using capture groups before params in routes + * deps: path-to-regexp@0.1.6 + * perf: enable strict mode + * perf: remove argument reassignments in routing + * perf: skip attempting to decode zero length string + * perf: use plain for loops + +1.1.1 / 2015-05-25 +================== + + * Fix issue where `next('route')` in `router.param` would incorrectly skip values + * deps: array-flatten@1.1.0 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + +1.1.0 / 2015-04-22 +================== + + * Use `setprototypeof` instead of `__proto__` + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +1.0.0 / 2015-01-13 +================== + + * Fix crash from error within `OPTIONS` response handler + * deps: array-flatten@1.0.2 + - Remove redundant code path + +1.0.0-beta.3 / 2015-01-11 +========================= + + * Fix duplicate methods appearing in OPTIONS responses + * Fix OPTIONS responses to include the HEAD method properly + * Remove support for leading colon in `router.param(name, fn)` + * Use `array-flatten` for flattening arrays + * deps: debug@~2.1.1 + * deps: methods@~1.1.1 + +1.0.0-beta.2 / 2014-11-19 +========================= + + * Match routes iteratively to prevent stack overflows + +1.0.0-beta.1 / 2014-11-16 +========================= + + * Initial release ported from Express 4.x + - Altered to work without Express diff --git a/node_modules/router/LICENSE b/node_modules/router/LICENSE new file mode 100644 index 000000000..237e1b67d --- /dev/null +++ b/node_modules/router/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Roman Shtylman +Copyright (c) 2014-2022 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/router/README.md b/node_modules/router/README.md new file mode 100644 index 000000000..218fd5720 --- /dev/null +++ b/node_modules/router/README.md @@ -0,0 +1,416 @@ +# router + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Simple middleware-style router + +## 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): + +```bash +$ npm install router +``` + +## API + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var Router = require('router') + +var router = Router() +router.get('/', function (req, res) { + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end('Hello World!') +}) + +var server = http.createServer(function (req, res) { + router(req, res, finalhandler(req, res)) +}) + +server.listen(3000) +``` + +This module is currently an extracted version from the Express project, +but with the main change being it can be used with a plain `http.createServer` +object or other web frameworks by removing Express-specific API calls. + +## Router(options) + +Options + +- `strict` - When `false` trailing slashes are optional (default: `false`) +- `caseSensitive` - When `true` the routing will be case sensitive. (default: `false`) +- `mergeParams` - When `true` any `req.params` passed to the router will be + merged into the router's `req.params`. (default: `false`) ([example](#example-using-mergeparams)) + +Returns a function with the signature `router(req, res, callback)` where +`callback([err])` must be provided to handle errors and fall-through from +not handling requests. + +### router.use([path], ...middleware) + +Use the given [middleware function](#middleware) for all http methods on the +given `path`, defaulting to the root path. + +`router` does not automatically see `use` as a handler. As such, it will not +consider it one for handling `OPTIONS` requests. + +* Note: If a `path` is specified, that `path` is stripped from the start of + `req.url`. + + + +```js +router.use(function (req, res, next) { + // do your things + + // continue to the next middleware + // the request will stall if this is not called + next() + + // note: you should NOT call `next` if you have begun writing to the response +}) +``` + +[Middleware](#middleware) can themselves use `next('router')` at any time to +exit the current router instance completely, invoking the top-level callback. + +### router\[method](path, ...[middleware], handler) + +The [http methods](https://github.com/jshttp/methods/blob/master/index.js) provide +the routing functionality in `router`. + +Method middleware and handlers follow usual [middleware](#middleware) behavior, +except they will only be called when the method and path match the request. + + + +```js +// handle a `GET` request +router.get('/', function (req, res) { + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end('Hello World!') +}) +``` + +[Middleware](#middleware) given before the handler have one additional trick, +they may invoke `next('route')`. Calling `next('route')` bypasses the remaining +middleware and the handler mounted for this route, passing the request to the +next route suitable for handling this request. + +Route handlers and middleware can themselves use `next('router')` at any time +to exit the current router instance completely, invoking the top-level callback. + +### router.param(name, param_middleware) + +Maps the specified path parameter `name` to a specialized param-capturing middleware. + +This function positions the middleware in the same stack as `.use`. + +The function can optionally return a `Promise` object. If a `Promise` object +is returned from the function, the router will attach an `onRejected` callback +using `.then`. If the promise is rejected, `next` will be called with the +rejected value, or an error if the value is falsy. + +Parameter mapping is used to provide pre-conditions to routes +which use normalized placeholders. For example a _:user_id_ parameter +could automatically load a user's information from the database without +any additional code: + + + +```js +router.param('user_id', function (req, res, next, id) { + User.find(id, function (err, user) { + if (err) { + return next(err) + } else if (!user) { + return next(new Error('failed to load user')) + } + req.user = user + + // continue processing the request + next() + }) +}) +``` + +### router.route(path) + +Creates an instance of a single `Route` for the given `path`. +(See `Router.Route` below) + +Routes can be used to handle http `methods` with their own, optional middleware. + +Using `router.route(path)` is a recommended approach to avoiding duplicate +route naming and thus typo errors. + + + +```js +var api = router.route('/api/') +``` + +## Router.Route(path) + +Represents a single route as an instance that can be used to handle http +`methods` with it's own, optional middleware. + +### route\[method](handler) + +These are functions which you can directly call on a route to register a new +`handler` for the `method` on the route. + + + +```js +// handle a `GET` request +var status = router.route('/status') + +status.get(function (req, res) { + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end('All Systems Green!') +}) +``` + +### route.all(handler) + +Adds a handler for all HTTP methods to this route. + +The handler can behave like middleware and call `next` to continue processing +rather than responding. + + + +```js +router.route('/') + .all(function (req, res, next) { + next() + }) + .all(checkSomething) + .get(function (req, res) { + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end('Hello World!') + }) +``` + +## Middleware + +Middleware (and method handlers) are functions that follow specific function +parameters and have defined behavior when used with `router`. The most common +format is with three parameters - "req", "res" and "next". + +- `req` - This is a [HTTP incoming message](https://nodejs.org/api/http.html#http_http_incomingmessage) instance. +- `res` - This is a [HTTP server response](https://nodejs.org/api/http.html#http_class_http_serverresponse) instance. +- `next` - Calling this function that tells `router` to proceed to the next matching middleware or method handler. It accepts an error as the first argument. + +The function can optionally return a `Promise` object. If a `Promise` object +is returned from the function, the router will attach an `onRejected` callback +using `.then`. If the promise is rejected, `next` will be called with the +rejected value, or an error if the value is falsy. + +Middleware and method handlers can also be defined with four arguments. When +the function has four parameters defined, the first argument is an error and +subsequent arguments remain, becoming - "err", "req", "res", "next". These +functions are "error handling middleware", and can be used for handling +errors that occurred in previous handlers (E.g. from calling `next(err)`). +This is most used when you want to define arbitrary rendering of errors. + + + +```js +router.get('/error_route', function (req, res, next) { + return next(new Error('Bad Request')) +}) + +router.use(function (err, req, res, next) { + res.end(err.message) //= > "Bad Request" +}) +``` + +Error handling middleware will **only** be invoked when an error was given. As +long as the error is in the pipeline, normal middleware and handlers will be +bypassed - only error handling middleware will be invoked with an error. + +## Examples + +```js +// import our modules +var http = require('http') +var Router = require('router') +var finalhandler = require('finalhandler') +var compression = require('compression') +var bodyParser = require('body-parser') + +// store our message to display +var message = 'Hello World!' + +// initialize the router & server and add a final callback. +var router = Router() +var server = http.createServer(function onRequest (req, res) { + router(req, res, finalhandler(req, res)) +}) + +// use some middleware and compress all outgoing responses +router.use(compression()) + +// handle `GET` requests to `/message` +router.get('/message', function (req, res) { + res.statusCode = 200 + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end(message + '\n') +}) + +// create and mount a new router for our API +var api = Router() +router.use('/api/', api) + +// add a body parsing middleware to our API +api.use(bodyParser.json()) + +// handle `PATCH` requests to `/api/set-message` +api.patch('/set-message', function (req, res) { + if (req.body.value) { + message = req.body.value + + res.statusCode = 200 + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end(message + '\n') + } else { + res.statusCode = 400 + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end('Invalid API Syntax\n') + } +}) + +// make our http server listen to connections +server.listen(8080) +``` + +You can get the message by running this command in your terminal, + or navigating to `127.0.0.1:8080` in a web browser. +```bash +curl http://127.0.0.1:8080 +``` + +You can set the message by sending it a `PATCH` request via this command: +```bash +curl http://127.0.0.1:8080/api/set-message -X PATCH -H "Content-Type: application/json" -d '{"value":"Cats!"}' +``` + +### Example using mergeParams + +```js +var http = require('http') +var Router = require('router') +var finalhandler = require('finalhandler') + +// this example is about the mergeParams option +var opts = { mergeParams: true } + +// make a router with out special options +var router = Router(opts) +var server = http.createServer(function onRequest (req, res) { + // set something to be passed into the router + req.params = { type: 'kitten' } + + router(req, res, finalhandler(req, res)) +}) + +router.get('/', function (req, res) { + res.statusCode = 200 + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + + // with respond with the the params that were passed in + res.end(req.params.type + '\n') +}) + +// make another router with our options +var handler = Router(opts) + +// mount our new router to a route that accepts a param +router.use('/:path', handler) + +handler.get('/', function (req, res) { + res.statusCode = 200 + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + + // will respond with the param of the router's parent route + res.end(req.params.path + '\n') +}) + +// make our http server listen to connections +server.listen(8080) +``` + +Now you can get the type, or what path you are requesting: +```bash +curl http://127.0.0.1:8080 +> kitten +curl http://127.0.0.1:8080/such_path +> such_path +``` + +### Example of advanced `.route()` usage + +This example shows how to implement routes where there is a custom +handler to execute when the path matched, but no methods matched. +Without any special handling, this would be treated as just a +generic non-match by `router` (which typically results in a 404), +but with a custom handler, a `405 Method Not Allowed` can be sent. + +```js +var http = require('http') +var finalhandler = require('finalhandler') +var Router = require('router') + +// create the router and server +var router = new Router() +var server = http.createServer(function onRequest (req, res) { + router(req, res, finalhandler(req, res)) +}) + +// register a route and add all methods +router.route('/pet/:id') + .get(function (req, res) { + // this is GET /pet/:id + res.setHeader('Content-Type', 'application/json') + res.end(JSON.stringify({ name: 'tobi' })) + }) + .delete(function (req, res) { + // this is DELETE /pet/:id + res.end() + }) + .all(function (req, res) { + // this is called for all other methods not + // defined above for /pet/:id + res.statusCode = 405 + res.end() + }) + +// make our http server listen to connections +server.listen(8080) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/pillarjs/router/master?label=ci +[ci-url]: https://github.com/pillarjs/router/actions/workflows/ci.yml +[npm-image]: https://img.shields.io/npm/v/router.svg +[npm-url]: https://npmjs.org/package/router +[node-version-image]: https://img.shields.io/node/v/router.svg +[node-version-url]: http://nodejs.org/download/ +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/router/master.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/router?branch=master +[downloads-image]: https://img.shields.io/npm/dm/router.svg +[downloads-url]: https://npmjs.org/package/router diff --git a/node_modules/router/index.js b/node_modules/router/index.js new file mode 100644 index 000000000..4358aebdd --- /dev/null +++ b/node_modules/router/index.js @@ -0,0 +1,748 @@ +/*! + * router + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +const isPromise = require('is-promise') +const Layer = require('./lib/layer') +const { METHODS } = require('node:http') +const parseUrl = require('parseurl') +const Route = require('./lib/route') +const debug = require('debug')('router') +const deprecate = require('depd')('router') + +/** + * Module variables. + * @private + */ + +const slice = Array.prototype.slice +const flatten = Array.prototype.flat +const methods = METHODS.map((method) => method.toLowerCase()) + +/** + * Expose `Router`. + */ + +module.exports = Router + +/** + * Expose `Route`. + */ + +module.exports.Route = Route + +/** + * Initialize a new `Router` with the given `options`. + * + * @param {object} [options] + * @return {Router} which is a callable function + * @public + */ + +function Router (options) { + if (!(this instanceof Router)) { + return new Router(options) + } + + const opts = options || {} + + function router (req, res, next) { + router.handle(req, res, next) + } + + // inherit from the correct prototype + Object.setPrototypeOf(router, this) + + router.caseSensitive = opts.caseSensitive + router.mergeParams = opts.mergeParams + router.params = {} + router.strict = opts.strict + router.stack = [] + + return router +} + +/** + * Router prototype inherits from a Function. + */ + +/* istanbul ignore next */ +Router.prototype = function () {} + +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code. + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * router.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err) + * } else if (!user) { + * return next(new Error('failed to load user')) + * } + * req.user = user + * next() + * }) + * }) + * + * @param {string} name + * @param {function} fn + * @public + */ + +Router.prototype.param = function param (name, fn) { + if (!name) { + throw new TypeError('argument name is required') + } + + if (typeof name !== 'string') { + throw new TypeError('argument name must be a string') + } + + if (!fn) { + throw new TypeError('argument fn is required') + } + + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + let params = this.params[name] + + if (!params) { + params = this.params[name] = [] + } + + params.push(fn) + + return this +} + +/** + * Dispatch a req, res into the router. + * + * @private + */ + +Router.prototype.handle = function handle (req, res, callback) { + if (!callback) { + throw new TypeError('argument callback is required') + } + + debug('dispatching %s %s', req.method, req.url) + + let idx = 0 + let methods + const protohost = getProtohost(req.url) || '' + let removed = '' + const self = this + let slashAdded = false + let sync = 0 + const paramcalled = {} + + // middleware and routes + const stack = this.stack + + // manage inter-router variables + const parentParams = req.params + const parentUrl = req.baseUrl || '' + let done = restore(callback, req, 'baseUrl', 'next', 'params') + + // setup next layer + req.next = next + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + methods = [] + done = wrap(done, generateOptionsResponder(res, methods)) + } + + // setup basic req values + req.baseUrl = parentUrl + req.originalUrl = req.originalUrl || req.url + + next() + + function next (err) { + let layerError = err === 'route' + ? null + : err + + // remove added slash + if (slashAdded) { + req.url = req.url.slice(1) + slashAdded = false + } + + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl + req.url = protohost + removed + req.url.slice(protohost.length) + removed = '' + } + + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return + } + + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError) + return + } + + // max sync stack + if (++sync > 100) { + return setImmediate(next, err) + } + + // get pathname of request + const path = getPathname(req) + + if (path == null) { + return done(layerError) + } + + // find next matching layer + let layer + let match + let route + + while (match !== true && idx < stack.length) { + layer = stack[idx++] + match = matchLayer(layer, path) + route = layer.route + + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match + } + + if (match !== true) { + continue + } + + if (!route) { + // process non-route handlers normally + continue + } + + if (layerError) { + // routes do not match with a pending error + match = false + continue + } + + const method = req.method + const hasMethod = route._handlesMethod(method) + + // build up automatic options response + if (!hasMethod && method === 'OPTIONS' && methods) { + methods.push.apply(methods, route._methods()) + } + + // don't even bother matching route + if (!hasMethod && method !== 'HEAD') { + match = false + } + } + + // no match + if (match !== true) { + return done(layerError) + } + + // store route for dispatch on change + if (route) { + req.route = route + } + + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params + const layerPath = layer.path + + // this should be done for the layer + processParams(self.params, layer, paramcalled, req, res, function (err) { + if (err) { + next(layerError || err) + } else if (route) { + layer.handleRequest(req, res, next) + } else { + trimPrefix(layer, layerError, layerPath, path) + } + + sync = 0 + }) + } + + function trimPrefix (layer, layerError, layerPath, path) { + if (layerPath.length !== 0) { + // Validate path is a prefix match + if (layerPath !== path.substring(0, layerPath.length)) { + next(layerError) + return + } + + // Validate path breaks on a path separator + const c = path[layerPath.length] + if (c && c !== '/') { + next(layerError) + return + } + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + debug('trim prefix (%s) from url %s', layerPath, req.url) + removed = layerPath + req.url = protohost + req.url.slice(protohost.length + removed.length) + + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url + slashAdded = true + } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed) + } + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl) + + if (layerError) { + layer.handleError(layerError, req, res, next) + } else { + layer.handleRequest(req, res, next) + } + } +} + +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public + */ + +Router.prototype.use = function use (handler) { + let offset = 0 + let path = '/' + + // default path to '/' + // disambiguate router.use([handler]) + if (typeof handler !== 'function') { + let arg = handler + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0] + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1 + path = handler + } + } + + const callbacks = flatten.call(slice.call(arguments, offset), Infinity) + + if (callbacks.length === 0) { + throw new TypeError('argument handler is required') + } + + for (let i = 0; i < callbacks.length; i++) { + const fn = callbacks[i] + + if (typeof fn !== 'function') { + throw new TypeError('argument handler must be a function') + } + + // add the middleware + debug('use %o %s', path, fn.name || '') + + const layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn) + + layer.route = undefined + + this.stack.push(layer) + } + + return this +} + +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {string} path + * @return {Route} + * @public + */ + +Router.prototype.route = function route (path) { + const route = new Route(path) + + const layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, handle) + + function handle (req, res, next) { + route.dispatch(req, res, next) + } + + layer.route = route + + this.stack.push(layer) + return route +} + +// create Router#VERB functions +methods.concat('all').forEach(function (method) { + Router.prototype[method] = function (path) { + const route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)) + return this + } +}) + +/** + * Generate a callback that will make an OPTIONS response. + * + * @param {OutgoingMessage} res + * @param {array} methods + * @private + */ + +function generateOptionsResponder (res, methods) { + return function onDone (fn, err) { + if (err || methods.length === 0) { + return fn(err) + } + + trySendOptionsResponse(res, methods, fn) + } +} + +/** + * Get pathname of request. + * + * @param {IncomingMessage} req + * @private + */ + +function getPathname (req) { + try { + return parseUrl(req).pathname + } catch (err) { + return undefined + } +} + +/** + * Get get protocol + host for a URL. + * + * @param {string} url + * @private + */ + +function getProtohost (url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } + + const searchIndex = url.indexOf('?') + const pathLength = searchIndex !== -1 + ? searchIndex + : url.length + const fqdnIndex = url.substring(0, pathLength).indexOf('://') + + return fqdnIndex !== -1 + ? url.substring(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined +} + +/** + * Match path to a layer. + * + * @param {Layer} layer + * @param {string} path + * @private + */ + +function matchLayer (layer, path) { + try { + return layer.match(path) + } catch (err) { + return err + } +} + +/** + * Merge params with parent params + * + * @private + */ + +function mergeParams (params, parent) { + if (typeof parent !== 'object' || !parent) { + return params + } + + // make copy of parent for base + const obj = Object.assign({}, parent) + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return Object.assign(obj, params) + } + + let i = 0 + let o = 0 + + // determine numeric gap in params + while (i in params) { + i++ + } + + // determine numeric gap in parent + while (o in parent) { + o++ + } + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i] + + // create holes for the merge when necessary + if (i < o) { + delete params[i] + } + } + + return Object.assign(obj, params) +} + +/** + * Process any parameters for the layer. + * + * @private + */ + +function processParams (params, layer, called, req, res, done) { + // captured parameters from the layer, keys and values + const keys = layer.keys + + // fast track + if (!keys || keys.length === 0) { + return done() + } + + let i = 0 + let paramIndex = 0 + let key + let paramVal + let paramCallbacks + let paramCalled + + // process params in order + // param callbacks can be async + function param (err) { + if (err) { + return done(err) + } + + if (i >= keys.length) { + return done() + } + + paramIndex = 0 + key = keys[i++] + paramVal = req.params[key] + paramCallbacks = params[key] + paramCalled = called[key] + + if (paramVal === undefined || !paramCallbacks) { + return param() + } + + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal || + (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[key] = paramCalled.value + + // next param + return param(paramCalled.error) + } + + called[key] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + } + + paramCallback() + } + + // single param callbacks + function paramCallback (err) { + const fn = paramCallbacks[paramIndex++] + + // store updated value + paramCalled.value = req.params[key] + + if (err) { + // store error + paramCalled.error = err + param(err) + return + } + + if (!fn) return param() + + try { + const ret = fn(req, res, paramCallback, paramVal, key) + if (isPromise(ret)) { + if (!(ret instanceof Promise)) { + deprecate('parameters that are Promise-like are deprecated, use a native Promise instead') + } + + ret.then(null, function (error) { + paramCallback(error || new Error('Rejected promise')) + }) + } + } catch (e) { + paramCallback(e) + } + } + + param() +} + +/** + * Restore obj props after function + * + * @private + */ + +function restore (fn, obj) { + const props = new Array(arguments.length - 2) + const vals = new Array(arguments.length - 2) + + for (let i = 0; i < props.length; i++) { + props[i] = arguments[i + 2] + vals[i] = obj[props[i]] + } + + return function () { + // restore vals + for (let i = 0; i < props.length; i++) { + obj[props[i]] = vals[i] + } + + return fn.apply(this, arguments) + } +} + +/** + * Send an OPTIONS response. + * + * @private + */ + +function sendOptionsResponse (res, methods) { + const options = Object.create(null) + + // build unique method map + for (let i = 0; i < methods.length; i++) { + options[methods[i]] = true + } + + // construct the allow list + const allow = Object.keys(options).sort().join(', ') + + // send response + res.setHeader('Allow', allow) + res.setHeader('Content-Length', Buffer.byteLength(allow)) + res.setHeader('Content-Type', 'text/plain') + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(allow) +} + +/** + * Try to send an OPTIONS response. + * + * @private + */ + +function trySendOptionsResponse (res, methods, next) { + try { + sendOptionsResponse(res, methods) + } catch (err) { + next(err) + } +} + +/** + * Wrap a function + * + * @private + */ + +function wrap (old, fn) { + return function proxy () { + const args = new Array(arguments.length + 1) + + args[0] = old + for (let i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i] + } + + fn.apply(this, args) + } +} diff --git a/node_modules/router/lib/layer.js b/node_modules/router/lib/layer.js new file mode 100644 index 000000000..6a4408ff3 --- /dev/null +++ b/node_modules/router/lib/layer.js @@ -0,0 +1,247 @@ +/*! + * router + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +const isPromise = require('is-promise') +const pathRegexp = require('path-to-regexp') +const debug = require('debug')('router:layer') +const deprecate = require('depd')('router') + +/** + * Module variables. + * @private + */ + +const TRAILING_SLASH_REGEXP = /\/+$/ +const MATCHING_GROUP_REGEXP = /\((?:\?<(.*?)>)?(?!\?)/g + +/** + * Expose `Layer`. + */ + +module.exports = Layer + +function Layer (path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn) + } + + debug('new %o', path) + const opts = options || {} + + this.handle = fn + this.keys = [] + this.name = fn.name || '' + this.params = undefined + this.path = undefined + this.slash = path === '/' && opts.end === false + + function matcher (_path) { + if (_path instanceof RegExp) { + const keys = [] + let name = 0 + let m + // eslint-disable-next-line no-cond-assign + while (m = MATCHING_GROUP_REGEXP.exec(_path.source)) { + keys.push({ + name: m[1] || name++, + offset: m.index + }) + } + + return function regexpMatcher (p) { + const match = _path.exec(p) + if (!match) { + return false + } + + const params = {} + for (let i = 1; i < match.length; i++) { + const key = keys[i - 1] + const prop = key.name + const val = decodeParam(match[i]) + + if (val !== undefined) { + params[prop] = val + } + } + + return { + params, + path: match[0] + } + } + } + + return pathRegexp.match((opts.strict ? _path : loosen(_path)), { + sensitive: opts.sensitive, + end: opts.end, + trailing: !opts.strict, + decode: decodeParam + }) + } + this.matchers = Array.isArray(path) ? path.map(matcher) : [matcher(path)] +} + +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handleError = function handleError (error, req, res, next) { + const fn = this.handle + + if (fn.length !== 4) { + // not a standard error handler + return next(error) + } + + try { + // invoke function + const ret = fn(error, req, res, next) + + // wait for returned promise + if (isPromise(ret)) { + if (!(ret instanceof Promise)) { + deprecate('handlers that are Promise-like are deprecated, use a native Promise instead') + } + + ret.then(null, function (error) { + next(error || new Error('Rejected promise')) + }) + } + } catch (err) { + next(err) + } +} + +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handleRequest = function handleRequest (req, res, next) { + const fn = this.handle + + if (fn.length > 3) { + // not a standard request handler + return next() + } + + try { + // invoke function + const ret = fn(req, res, next) + + // wait for returned promise + if (isPromise(ret)) { + if (!(ret instanceof Promise)) { + deprecate('handlers that are Promise-like are deprecated, use a native Promise instead') + } + + ret.then(null, function (error) { + next(error || new Error('Rejected promise')) + }) + } + } catch (err) { + next(err) + } +} + +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function match (path) { + let match + + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.slash) { + this.params = {} + this.path = '' + return true + } + + let i = 0 + while (!match && i < this.matchers.length) { + // match the path + match = this.matchers[i](path) + i++ + } + } + + if (!match) { + this.params = undefined + this.path = undefined + return false + } + + // store values + this.params = match.params + this.path = match.path + this.keys = Object.keys(match.params) + + return true +} + +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ + +function decodeParam (val) { + if (typeof val !== 'string' || val.length === 0) { + return val + } + + try { + return decodeURIComponent(val) + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\'' + err.status = 400 + } + + throw err + } +} + +/** + * Loosens the given path for path-to-regexp matching. + */ +function loosen (path) { + if (path instanceof RegExp || path === '/') { + return path + } + + return Array.isArray(path) + ? path.map(function (p) { return loosen(p) }) + : String(path).replace(TRAILING_SLASH_REGEXP, '') +} diff --git a/node_modules/router/lib/route.js b/node_modules/router/lib/route.js new file mode 100644 index 000000000..1887d7898 --- /dev/null +++ b/node_modules/router/lib/route.js @@ -0,0 +1,242 @@ +/*! + * router + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +const debug = require('debug')('router:route') +const Layer = require('./layer') +const { METHODS } = require('node:http') + +/** + * Module variables. + * @private + */ + +const slice = Array.prototype.slice +const flatten = Array.prototype.flat +const methods = METHODS.map((method) => method.toLowerCase()) + +/** + * Expose `Route`. + */ + +module.exports = Route + +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @api private + */ + +function Route (path) { + debug('new %o', path) + this.path = path + this.stack = [] + + // route handlers for various http methods + this.methods = Object.create(null) +} + +/** + * @private + */ + +Route.prototype._handlesMethod = function _handlesMethod (method) { + if (this.methods._all) { + return true + } + + // normalize name + let name = typeof method === 'string' + ? method.toLowerCase() + : method + + if (name === 'head' && !this.methods.head) { + name = 'get' + } + + return Boolean(this.methods[name]) +} + +/** + * @return {array} supported HTTP methods + * @private + */ + +Route.prototype._methods = function _methods () { + const methods = Object.keys(this.methods) + + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head') + } + + for (let i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase() + } + + return methods +} + +/** + * dispatch req, res into this route + * + * @private + */ + +Route.prototype.dispatch = function dispatch (req, res, done) { + let idx = 0 + const stack = this.stack + let sync = 0 + + if (stack.length === 0) { + return done() + } + + let method = typeof req.method === 'string' + ? req.method.toLowerCase() + : req.method + + if (method === 'head' && !this.methods.head) { + method = 'get' + } + + req.route = this + + next() + + function next (err) { + // signal to exit route + if (err && err === 'route') { + return done() + } + + // signal to exit router + if (err && err === 'router') { + return done(err) + } + + // no more matching layers + if (idx >= stack.length) { + return done(err) + } + + // max sync stack + if (++sync > 100) { + return setImmediate(next, err) + } + + let layer + let match + + // find next matching layer + while (match !== true && idx < stack.length) { + layer = stack[idx++] + match = !layer.method || layer.method === method + } + + // no match + if (match !== true) { + return done(err) + } + + if (err) { + layer.handleError(err, req, res, next) + } else { + layer.handleRequest(req, res, next) + } + + sync = 0 + } +} + +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next() + * } + * + * function validate_user(req, res, next){ + * next() + * } + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world') + * }) + * + * @param {array|function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function all (handler) { + const callbacks = flatten.call(slice.call(arguments), Infinity) + + if (callbacks.length === 0) { + throw new TypeError('argument handler is required') + } + + for (let i = 0; i < callbacks.length; i++) { + const fn = callbacks[i] + + if (typeof fn !== 'function') { + throw new TypeError('argument handler must be a function') + } + + const layer = Layer('/', {}, fn) + layer.method = undefined + + this.methods._all = true + this.stack.push(layer) + } + + return this +} + +methods.forEach(function (method) { + Route.prototype[method] = function (handler) { + const callbacks = flatten.call(slice.call(arguments), Infinity) + + if (callbacks.length === 0) { + throw new TypeError('argument handler is required') + } + + for (let i = 0; i < callbacks.length; i++) { + const fn = callbacks[i] + + if (typeof fn !== 'function') { + throw new TypeError('argument handler must be a function') + } + + debug('%s %s', method, this.path) + + const layer = Layer('/', {}, fn) + layer.method = method + + this.methods[method] = true + this.stack.push(layer) + } + + return this + } +}) diff --git a/node_modules/router/package.json b/node_modules/router/package.json new file mode 100644 index 000000000..123eca28e --- /dev/null +++ b/node_modules/router/package.json @@ -0,0 +1,44 @@ +{ + "name": "router", + "description": "Simple middleware-style router", + "version": "2.2.0", + "author": "Douglas Christopher Wilson ", + "contributors": [ + "Blake Embrey " + ], + "license": "MIT", + "repository": "pillarjs/router", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "devDependencies": { + "finalhandler": "^2.1.0", + "mocha": "10.2.0", + "nyc": "15.1.0", + "run-series": "^1.1.9", + "standard": "^17.1.0", + "supertest": "6.3.3" + }, + "files": [ + "lib/", + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 18" + }, + "scripts": { + "lint": "standard", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test:debug": "mocha --reporter spec --bail --check-leaks test/ --inspect --inspect-brk", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/safer-buffer/LICENSE b/node_modules/safer-buffer/LICENSE new file mode 100644 index 000000000..4fe9e6f10 --- /dev/null +++ b/node_modules/safer-buffer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Nikita Skovoroda + +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/safer-buffer/Porting-Buffer.md b/node_modules/safer-buffer/Porting-Buffer.md new file mode 100644 index 000000000..68d86bab0 --- /dev/null +++ b/node_modules/safer-buffer/Porting-Buffer.md @@ -0,0 +1,268 @@ +# Porting to the Buffer.from/Buffer.alloc API + + +## Overview + +- [Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x.](#variant-1) (*recommended*) +- [Variant 2: Use a polyfill](#variant-2) +- [Variant 3: manual detection, with safeguards](#variant-3) + +### Finding problematic bits of code using grep + +Just run `grep -nrE '[^a-zA-Z](Slow)?Buffer\s*\(' --exclude-dir node_modules`. + +It will find all the potentially unsafe places in your own code (with some considerably unlikely +exceptions). + +### Finding problematic bits of code using Node.js 8 + +If you’re using Node.js ≥ 8.0.0 (which is recommended), Node.js exposes multiple options that help with finding the relevant pieces of code: + +- `--trace-warnings` will make Node.js show a stack trace for this warning and other warnings that are printed by Node.js. +- `--trace-deprecation` does the same thing, but only for deprecation warnings. +- `--pending-deprecation` will show more types of deprecation warnings. In particular, it will show the `Buffer()` deprecation warning, even on Node.js 8. + +You can set these flags using an environment variable: + +```console +$ export NODE_OPTIONS='--trace-warnings --pending-deprecation' +$ cat example.js +'use strict'; +const foo = new Buffer('foo'); +$ node example.js +(node:7147) [DEP0005] DeprecationWarning: The Buffer() and new Buffer() constructors are not recommended for use due to security and usability concerns. Please use the new Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() construction methods instead. + at showFlaggedDeprecation (buffer.js:127:13) + at new Buffer (buffer.js:148:3) + at Object. (/path/to/example.js:2:13) + [... more stack trace lines ...] +``` + +### Finding problematic bits of code using linters + +Eslint rules [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +also find calls to deprecated `Buffer()` API. Those rules are included in some pre-sets. + +There is a drawback, though, that it doesn't always +[work correctly](https://github.com/chalker/safer-buffer#why-not-safe-buffer) when `Buffer` is +overriden e.g. with a polyfill, so recommended is a combination of this and some other method +described above. + + +## Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x. + +This is the recommended solution nowadays that would imply only minimal overhead. + +The Node.js 5.x release line has been unsupported since July 2016, and the Node.js 4.x release line reaches its End of Life in April 2018 (→ [Schedule](https://github.com/nodejs/Release#release-schedule)). This means that these versions of Node.js will *not* receive any updates, even in case of security issues, so using these release lines should be avoided, if at all possible. + +What you would do in this case is to convert all `new Buffer()` or `Buffer()` calls to use `Buffer.alloc()` or `Buffer.from()`, in the following way: + +- For `new Buffer(number)`, replace it with `Buffer.alloc(number)`. +- For `new Buffer(string)` (or `new Buffer(string, encoding)`), replace it with `Buffer.from(string)` (or `Buffer.from(string, encoding)`). +- For all other combinations of arguments (these are much rarer), also replace `new Buffer(...arguments)` with `Buffer.from(...arguments)`. + +Note that `Buffer.alloc()` is also _faster_ on the current Node.js versions than +`new Buffer(size).fill(0)`, which is what you would otherwise need to ensure zero-filling. + +Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +is recommended to avoid accidential unsafe Buffer API usage. + +There is also a [JSCodeshift codemod](https://github.com/joyeecheung/node-dep-codemod#dep005) +for automatically migrating Buffer constructors to `Buffer.alloc()` or `Buffer.from()`. +Note that it currently only works with cases where the arguments are literals or where the +constructor is invoked with two arguments. + +_If you currently support those older Node.js versions and dropping them would be a semver-major change +for you, or if you support older branches of your packages, consider using [Variant 2](#variant-2) +or [Variant 3](#variant-3) on older branches, so people using those older branches will also receive +the fix. That way, you will eradicate potential issues caused by unguarded Buffer API usage and +your users will not observe a runtime deprecation warning when running your code on Node.js 10._ + + +## Variant 2: Use a polyfill + +Utilize [safer-buffer](https://www.npmjs.com/package/safer-buffer) as a polyfill to support older +Node.js versions. + +You would take exacly the same steps as in [Variant 1](#variant-1), but with a polyfill +`const Buffer = require('safer-buffer').Buffer` in all files where you use the new `Buffer` api. + +Make sure that you do not use old `new Buffer` API — in any files where the line above is added, +using old `new Buffer()` API will _throw_. It will be easy to notice that in CI, though. + +Alternatively, you could use [buffer-from](https://www.npmjs.com/package/buffer-from) and/or +[buffer-alloc](https://www.npmjs.com/package/buffer-alloc) [ponyfills](https://ponyfill.com/) — +those are great, the only downsides being 4 deps in the tree and slightly more code changes to +migrate off them (as you would be using e.g. `Buffer.from` under a different name). If you need only +`Buffer.from` polyfilled — `buffer-from` alone which comes with no extra dependencies. + +_Alternatively, you could use [safe-buffer](https://www.npmjs.com/package/safe-buffer) — it also +provides a polyfill, but takes a different approach which has +[it's drawbacks](https://github.com/chalker/safer-buffer#why-not-safe-buffer). It will allow you +to also use the older `new Buffer()` API in your code, though — but that's arguably a benefit, as +it is problematic, can cause issues in your code, and will start emitting runtime deprecation +warnings starting with Node.js 10._ + +Note that in either case, it is important that you also remove all calls to the old Buffer +API manually — just throwing in `safe-buffer` doesn't fix the problem by itself, it just provides +a polyfill for the new API. I have seen people doing that mistake. + +Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +is recommended. + +_Don't forget to drop the polyfill usage once you drop support for Node.js < 4.5.0._ + + +## Variant 3 — manual detection, with safeguards + +This is useful if you create Buffer instances in only a few places (e.g. one), or you have your own +wrapper around them. + +### Buffer(0) + +This special case for creating empty buffers can be safely replaced with `Buffer.concat([])`, which +returns the same result all the way down to Node.js 0.8.x. + +### Buffer(notNumber) + +Before: + +```js +var buf = new Buffer(notNumber, encoding); +``` + +After: + +```js +var buf; +if (Buffer.from && Buffer.from !== Uint8Array.from) { + buf = Buffer.from(notNumber, encoding); +} else { + if (typeof notNumber === 'number') + throw new Error('The "size" argument must be of type number.'); + buf = new Buffer(notNumber, encoding); +} +``` + +`encoding` is optional. + +Note that the `typeof notNumber` before `new Buffer` is required (for cases when `notNumber` argument is not +hard-coded) and _is not caused by the deprecation of Buffer constructor_ — it's exactly _why_ the +Buffer constructor is deprecated. Ecosystem packages lacking this type-check caused numereous +security issues — situations when unsanitized user input could end up in the `Buffer(arg)` create +problems ranging from DoS to leaking sensitive information to the attacker from the process memory. + +When `notNumber` argument is hardcoded (e.g. literal `"abc"` or `[0,1,2]`), the `typeof` check can +be omitted. + +Also note that using TypeScript does not fix this problem for you — when libs written in +`TypeScript` are used from JS, or when user input ends up there — it behaves exactly as pure JS, as +all type checks are translation-time only and are not present in the actual JS code which TS +compiles to. + +### Buffer(number) + +For Node.js 0.10.x (and below) support: + +```js +var buf; +if (Buffer.alloc) { + buf = Buffer.alloc(number); +} else { + buf = new Buffer(number); + buf.fill(0); +} +``` + +Otherwise (Node.js ≥ 0.12.x): + +```js +const buf = Buffer.alloc ? Buffer.alloc(number) : new Buffer(number).fill(0); +``` + +## Regarding Buffer.allocUnsafe + +Be extra cautious when using `Buffer.allocUnsafe`: + * Don't use it if you don't have a good reason to + * e.g. you probably won't ever see a performance difference for small buffers, in fact, those + might be even faster with `Buffer.alloc()`, + * if your code is not in the hot code path — you also probably won't notice a difference, + * keep in mind that zero-filling minimizes the potential risks. + * If you use it, make sure that you never return the buffer in a partially-filled state, + * if you are writing to it sequentially — always truncate it to the actuall written length + +Errors in handling buffers allocated with `Buffer.allocUnsafe` could result in various issues, +ranged from undefined behaviour of your code to sensitive data (user input, passwords, certs) +leaking to the remote attacker. + +_Note that the same applies to `new Buffer` usage without zero-filling, depending on the Node.js +version (and lacking type checks also adds DoS to the list of potential problems)._ + + +## FAQ + + +### What is wrong with the `Buffer` constructor? + +The `Buffer` constructor could be used to create a buffer in many different ways: + +- `new Buffer(42)` creates a `Buffer` of 42 bytes. Before Node.js 8, this buffer contained + *arbitrary memory* for performance reasons, which could include anything ranging from + program source code to passwords and encryption keys. +- `new Buffer('abc')` creates a `Buffer` that contains the UTF-8-encoded version of + the string `'abc'`. A second argument could specify another encoding: For example, + `new Buffer(string, 'base64')` could be used to convert a Base64 string into the original + sequence of bytes that it represents. +- There are several other combinations of arguments. + +This meant that, in code like `var buffer = new Buffer(foo);`, *it is not possible to tell +what exactly the contents of the generated buffer are* without knowing the type of `foo`. + +Sometimes, the value of `foo` comes from an external source. For example, this function +could be exposed as a service on a web server, converting a UTF-8 string into its Base64 form: + +``` +function stringToBase64(req, res) { + // The request body should have the format of `{ string: 'foobar' }` + const rawBytes = new Buffer(req.body.string) + const encoded = rawBytes.toString('base64') + res.end({ encoded: encoded }) +} +``` + +Note that this code does *not* validate the type of `req.body.string`: + +- `req.body.string` is expected to be a string. If this is the case, all goes well. +- `req.body.string` is controlled by the client that sends the request. +- If `req.body.string` is the *number* `50`, the `rawBytes` would be 50 bytes: + - Before Node.js 8, the content would be uninitialized + - After Node.js 8, the content would be `50` bytes with the value `0` + +Because of the missing type check, an attacker could intentionally send a number +as part of the request. Using this, they can either: + +- Read uninitialized memory. This **will** leak passwords, encryption keys and other + kinds of sensitive information. (Information leak) +- Force the program to allocate a large amount of memory. For example, when specifying + `500000000` as the input value, each request will allocate 500MB of memory. + This can be used to either exhaust the memory available of a program completely + and make it crash, or slow it down significantly. (Denial of Service) + +Both of these scenarios are considered serious security issues in a real-world +web server context. + +when using `Buffer.from(req.body.string)` instead, passing a number will always +throw an exception instead, giving a controlled behaviour that can always be +handled by the program. + + +### The `Buffer()` constructor has been deprecated for a while. Is this really an issue? + +Surveys of code in the `npm` ecosystem have shown that the `Buffer()` constructor is still +widely used. This includes new code, and overall usage of such code has actually been +*increasing*. diff --git a/node_modules/safer-buffer/Readme.md b/node_modules/safer-buffer/Readme.md new file mode 100644 index 000000000..14b082290 --- /dev/null +++ b/node_modules/safer-buffer/Readme.md @@ -0,0 +1,156 @@ +# safer-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![javascript style guide][standard-image]][standard-url] [![Security Responsible Disclosure][secuirty-image]][secuirty-url] + +[travis-image]: https://travis-ci.org/ChALkeR/safer-buffer.svg?branch=master +[travis-url]: https://travis-ci.org/ChALkeR/safer-buffer +[npm-image]: https://img.shields.io/npm/v/safer-buffer.svg +[npm-url]: https://npmjs.org/package/safer-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com +[secuirty-image]: https://img.shields.io/badge/Security-Responsible%20Disclosure-green.svg +[secuirty-url]: https://github.com/nodejs/security-wg/blob/master/processes/responsible_disclosure_template.md + +Modern Buffer API polyfill without footguns, working on Node.js from 0.8 to current. + +## How to use? + +First, port all `Buffer()` and `new Buffer()` calls to `Buffer.alloc()` and `Buffer.from()` API. + +Then, to achieve compatibility with outdated Node.js versions (`<4.5.0` and 5.x `<5.9.0`), use +`const Buffer = require('safer-buffer').Buffer` in all files where you make calls to the new +Buffer API. _Use `var` instead of `const` if you need that for your Node.js version range support._ + +Also, see the +[porting Buffer](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) guide. + +## Do I need it? + +Hopefully, not — dropping support for outdated Node.js versions should be fine nowdays, and that +is the recommended path forward. You _do_ need to port to the `Buffer.alloc()` and `Buffer.from()` +though. + +See the [porting guide](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) +for a better description. + +## Why not [safe-buffer](https://npmjs.com/safe-buffer)? + +_In short: while `safe-buffer` serves as a polyfill for the new API, it allows old API usage and +itself contains footguns._ + +`safe-buffer` could be used safely to get the new API while still keeping support for older +Node.js versions (like this module), but while analyzing ecosystem usage of the old Buffer API +I found out that `safe-buffer` is itself causing problems in some cases. + +For example, consider the following snippet: + +```console +$ cat example.unsafe.js +console.log(Buffer(20)) +$ ./node-v6.13.0-linux-x64/bin/node example.unsafe.js + +$ standard example.unsafe.js +standard: Use JavaScript Standard Style (https://standardjs.com) + /home/chalker/repo/safer-buffer/example.unsafe.js:2:13: 'Buffer()' was deprecated since v6. Use 'Buffer.alloc()' or 'Buffer.from()' (use 'https://www.npmjs.com/package/safe-buffer' for '<4.5.0') instead. +``` + +This is allocates and writes to console an uninitialized chunk of memory. +[standard](https://www.npmjs.com/package/standard) linter (among others) catch that and warn people +to avoid using unsafe API. + +Let's now throw in `safe-buffer`! + +```console +$ cat example.safe-buffer.js +const Buffer = require('safe-buffer').Buffer +console.log(Buffer(20)) +$ standard example.safe-buffer.js +$ ./node-v6.13.0-linux-x64/bin/node example.safe-buffer.js + +``` + +See the problem? Adding in `safe-buffer` _magically removes the lint warning_, but the behavior +remains identiсal to what we had before, and when launched on Node.js 6.x LTS — this dumps out +chunks of uninitialized memory. +_And this code will still emit runtime warnings on Node.js 10.x and above._ + +That was done by design. I first considered changing `safe-buffer`, prohibiting old API usage or +emitting warnings on it, but that significantly diverges from `safe-buffer` design. After some +discussion, it was decided to move my approach into a separate package, and _this is that separate +package_. + +This footgun is not imaginary — I observed top-downloaded packages doing that kind of thing, +«fixing» the lint warning by blindly including `safe-buffer` without any actual changes. + +Also in some cases, even if the API _was_ migrated to use of safe Buffer API — a random pull request +can bring unsafe Buffer API usage back to the codebase by adding new calls — and that could go +unnoticed even if you have a linter prohibiting that (becase of the reason stated above), and even +pass CI. _I also observed that being done in popular packages._ + +Some examples: + * [webdriverio](https://github.com/webdriverio/webdriverio/commit/05cbd3167c12e4930f09ef7cf93b127ba4effae4#diff-124380949022817b90b622871837d56cR31) + (a module with 548 759 downloads/month), + * [websocket-stream](https://github.com/maxogden/websocket-stream/commit/c9312bd24d08271687d76da0fe3c83493871cf61) + (218 288 d/m, fix in [maxogden/websocket-stream#142](https://github.com/maxogden/websocket-stream/pull/142)), + * [node-serialport](https://github.com/node-serialport/node-serialport/commit/e8d9d2b16c664224920ce1c895199b1ce2def48c) + (113 138 d/m, fix in [node-serialport/node-serialport#1510](https://github.com/node-serialport/node-serialport/pull/1510)), + * [karma](https://github.com/karma-runner/karma/commit/3d94b8cf18c695104ca195334dc75ff054c74eec) + (3 973 193 d/m, fix in [karma-runner/karma#2947](https://github.com/karma-runner/karma/pull/2947)), + * [spdy-transport](https://github.com/spdy-http2/spdy-transport/commit/5375ac33f4a62a4f65bcfc2827447d42a5dbe8b1) + (5 970 727 d/m, fix in [spdy-http2/spdy-transport#53](https://github.com/spdy-http2/spdy-transport/pull/53)). + * And there are a lot more over the ecosystem. + +I filed a PR at +[mysticatea/eslint-plugin-node#110](https://github.com/mysticatea/eslint-plugin-node/pull/110) to +partially fix that (for cases when that lint rule is used), but it is a semver-major change for +linter rules and presets, so it would take significant time for that to reach actual setups. +_It also hasn't been released yet (2018-03-20)._ + +Also, `safer-buffer` discourages the usage of `.allocUnsafe()`, which is often done by a mistake. +It still supports it with an explicit concern barier, by placing it under +`require('safer-buffer/dangereous')`. + +## But isn't throwing bad? + +Not really. It's an error that could be noticed and fixed early, instead of causing havoc later like +unguarded `new Buffer()` calls that end up receiving user input can do. + +This package affects only the files where `var Buffer = require('safer-buffer').Buffer` was done, so +it is really simple to keep track of things and make sure that you don't mix old API usage with that. +Also, CI should hint anything that you might have missed. + +New commits, if tested, won't land new usage of unsafe Buffer API this way. +_Node.js 10.x also deals with that by printing a runtime depecation warning._ + +### Would it affect third-party modules? + +No, unless you explicitly do an awful thing like monkey-patching or overriding the built-in `Buffer`. +Don't do that. + +### But I don't want throwing… + +That is also fine! + +Also, it could be better in some cases when you don't comprehensive enough test coverage. + +In that case — just don't override `Buffer` and use +`var SaferBuffer = require('safer-buffer').Buffer` instead. + +That way, everything using `Buffer` natively would still work, but there would be two drawbacks: + +* `Buffer.from`/`Buffer.alloc` won't be polyfilled — use `SaferBuffer.from` and + `SaferBuffer.alloc` instead. +* You are still open to accidentally using the insecure deprecated API — use a linter to catch that. + +Note that using a linter to catch accidential `Buffer` constructor usage in this case is strongly +recommended. `Buffer` is not overriden in this usecase, so linters won't get confused. + +## «Without footguns»? + +Well, it is still possible to do _some_ things with `Buffer` API, e.g. accessing `.buffer` property +on older versions and duping things from there. You shouldn't do that in your code, probabably. + +The intention is to remove the most significant footguns that affect lots of packages in the +ecosystem, and to do it in the proper way. + +Also, this package doesn't protect against security issues affecting some Node.js versions, so for +usage in your own production code, it is still recommended to update to a Node.js version +[supported by upstream](https://github.com/nodejs/release#release-schedule). diff --git a/node_modules/safer-buffer/dangerous.js b/node_modules/safer-buffer/dangerous.js new file mode 100644 index 000000000..ca41fdc54 --- /dev/null +++ b/node_modules/safer-buffer/dangerous.js @@ -0,0 +1,58 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var buffer = require('buffer') +var Buffer = buffer.Buffer +var safer = require('./safer.js') +var Safer = safer.Buffer + +var dangerous = {} + +var key + +for (key in safer) { + if (!safer.hasOwnProperty(key)) continue + dangerous[key] = safer[key] +} + +var Dangereous = dangerous.Buffer = {} + +// Copy Safer API +for (key in Safer) { + if (!Safer.hasOwnProperty(key)) continue + Dangereous[key] = Safer[key] +} + +// Copy those missing unsafe methods, if they are present +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (Dangereous.hasOwnProperty(key)) continue + Dangereous[key] = Buffer[key] +} + +if (!Dangereous.allocUnsafe) { + Dangereous.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + return Buffer(size) + } +} + +if (!Dangereous.allocUnsafeSlow) { + Dangereous.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + return buffer.SlowBuffer(size) + } +} + +module.exports = dangerous diff --git a/node_modules/safer-buffer/package.json b/node_modules/safer-buffer/package.json new file mode 100644 index 000000000..d452b04ae --- /dev/null +++ b/node_modules/safer-buffer/package.json @@ -0,0 +1,34 @@ +{ + "name": "safer-buffer", + "version": "2.1.2", + "description": "Modern Buffer API polyfill without footguns", + "main": "safer.js", + "scripts": { + "browserify-test": "browserify --external tape tests.js > browserify-tests.js && tape browserify-tests.js", + "test": "standard && tape tests.js" + }, + "author": { + "name": "Nikita Skovoroda", + "email": "chalkerx@gmail.com", + "url": "https://github.com/ChALkeR" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/ChALkeR/safer-buffer.git" + }, + "bugs": { + "url": "https://github.com/ChALkeR/safer-buffer/issues" + }, + "devDependencies": { + "standard": "^11.0.1", + "tape": "^4.9.0" + }, + "files": [ + "Porting-Buffer.md", + "Readme.md", + "tests.js", + "dangerous.js", + "safer.js" + ] +} diff --git a/node_modules/safer-buffer/safer.js b/node_modules/safer-buffer/safer.js new file mode 100644 index 000000000..37c7e1aa6 --- /dev/null +++ b/node_modules/safer-buffer/safer.js @@ -0,0 +1,77 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var buffer = require('buffer') +var Buffer = buffer.Buffer + +var safer = {} + +var key + +for (key in buffer) { + if (!buffer.hasOwnProperty(key)) continue + if (key === 'SlowBuffer' || key === 'Buffer') continue + safer[key] = buffer[key] +} + +var Safer = safer.Buffer = {} +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue + Safer[key] = Buffer[key] +} + +safer.Buffer.prototype = Buffer.prototype + +if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) + } + if (value && typeof value.length === 'undefined') { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) + } + return Buffer(value, encodingOrOffset, length) + } +} + +if (!Safer.alloc) { + Safer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + var buf = Buffer(size) + if (!fill || fill.length === 0) { + buf.fill(0) + } else if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + return buf + } +} + +if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding('buffer').kStringMaxLength + } catch (e) { + // we can't determine kStringMaxLength in environments where process.binding + // is unsupported, so let's not set it + } +} + +if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + } + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength + } +} + +module.exports = safer diff --git a/node_modules/safer-buffer/tests.js b/node_modules/safer-buffer/tests.js new file mode 100644 index 000000000..7ed2777c9 --- /dev/null +++ b/node_modules/safer-buffer/tests.js @@ -0,0 +1,406 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var test = require('tape') + +var buffer = require('buffer') + +var index = require('./') +var safer = require('./safer') +var dangerous = require('./dangerous') + +/* Inheritance tests */ + +test('Default is Safer', function (t) { + t.equal(index, safer) + t.notEqual(safer, dangerous) + t.notEqual(index, dangerous) + t.end() +}) + +test('Is not a function', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(typeof impl, 'object') + t.equal(typeof impl.Buffer, 'object') + }); + [buffer].forEach(function (impl) { + t.equal(typeof impl, 'object') + t.equal(typeof impl.Buffer, 'function') + }) + t.end() +}) + +test('Constructor throws', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.throws(function () { impl.Buffer() }) + t.throws(function () { impl.Buffer(0) }) + t.throws(function () { impl.Buffer('a') }) + t.throws(function () { impl.Buffer('a', 'utf-8') }) + t.throws(function () { return new impl.Buffer() }) + t.throws(function () { return new impl.Buffer(0) }) + t.throws(function () { return new impl.Buffer('a') }) + t.throws(function () { return new impl.Buffer('a', 'utf-8') }) + }) + t.end() +}) + +test('Safe methods exist', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(typeof impl.Buffer.alloc, 'function', 'alloc') + t.equal(typeof impl.Buffer.from, 'function', 'from') + }) + t.end() +}) + +test('Unsafe methods exist only in Dangerous', function (t) { + [index, safer].forEach(function (impl) { + t.equal(typeof impl.Buffer.allocUnsafe, 'undefined') + t.equal(typeof impl.Buffer.allocUnsafeSlow, 'undefined') + }); + [dangerous].forEach(function (impl) { + t.equal(typeof impl.Buffer.allocUnsafe, 'function') + t.equal(typeof impl.Buffer.allocUnsafeSlow, 'function') + }) + t.end() +}) + +test('Generic methods/properties are defined and equal', function (t) { + ['poolSize', 'isBuffer', 'concat', 'byteLength'].forEach(function (method) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], buffer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Built-in buffer static methods/properties are inherited', function (t) { + Object.keys(buffer).forEach(function (method) { + if (method === 'SlowBuffer' || method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], buffer[method], method) + t.notEqual(typeof impl[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Built-in Buffer static methods/properties are inherited', function (t) { + Object.keys(buffer.Buffer).forEach(function (method) { + if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], buffer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('.prototype property of Buffer is inherited', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.prototype, buffer.Buffer.prototype, 'prototype') + t.notEqual(typeof impl.Buffer.prototype, 'undefined', 'prototype') + }) + t.end() +}) + +test('All Safer methods are present in Dangerous', function (t) { + Object.keys(safer).forEach(function (method) { + if (method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], safer[method], method) + if (method !== 'kStringMaxLength') { + t.notEqual(typeof impl[method], 'undefined', method) + } + }) + }) + Object.keys(safer.Buffer).forEach(function (method) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], safer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Safe methods from Dangerous methods are present in Safer', function (t) { + Object.keys(dangerous).forEach(function (method) { + if (method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], dangerous[method], method) + if (method !== 'kStringMaxLength') { + t.notEqual(typeof impl[method], 'undefined', method) + } + }) + }) + Object.keys(dangerous.Buffer).forEach(function (method) { + if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], dangerous.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +/* Behaviour tests */ + +test('Methods return Buffers', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 10))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 'a'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10, 'x'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(9, 'ab'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(''))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string', 'utf-8'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([0, 42, 3]))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(new Uint8Array([0, 42, 3])))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([]))) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](0))) + t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](10))) + }) + t.end() +}) + +test('Constructor is buffer.Buffer', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.alloc(0).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(0, 10).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(0, 'a').constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(10).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(10, 'x').constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(9, 'ab').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('string').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('string', 'utf-8').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').constructor, buffer.Buffer) + t.equal(impl.Buffer.from([0, 42, 3]).constructor, buffer.Buffer) + t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).constructor, buffer.Buffer) + t.equal(impl.Buffer.from([]).constructor, buffer.Buffer) + }); + [0, 10, 100].forEach(function (arg) { + t.equal(dangerous.Buffer.allocUnsafe(arg).constructor, buffer.Buffer) + t.equal(dangerous.Buffer.allocUnsafeSlow(arg).constructor, buffer.SlowBuffer(0).constructor) + }) + t.end() +}) + +test('Invalid calls throw', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.throws(function () { impl.Buffer.from(0) }) + t.throws(function () { impl.Buffer.from(10) }) + t.throws(function () { impl.Buffer.from(10, 'utf-8') }) + t.throws(function () { impl.Buffer.from('string', 'invalid encoding') }) + t.throws(function () { impl.Buffer.from(-10) }) + t.throws(function () { impl.Buffer.from(1e90) }) + t.throws(function () { impl.Buffer.from(Infinity) }) + t.throws(function () { impl.Buffer.from(-Infinity) }) + t.throws(function () { impl.Buffer.from(NaN) }) + t.throws(function () { impl.Buffer.from(null) }) + t.throws(function () { impl.Buffer.from(undefined) }) + t.throws(function () { impl.Buffer.from() }) + t.throws(function () { impl.Buffer.from({}) }) + t.throws(function () { impl.Buffer.alloc('') }) + t.throws(function () { impl.Buffer.alloc('string') }) + t.throws(function () { impl.Buffer.alloc('string', 'utf-8') }) + t.throws(function () { impl.Buffer.alloc('b25ldHdvdGhyZWU=', 'base64') }) + t.throws(function () { impl.Buffer.alloc(-10) }) + t.throws(function () { impl.Buffer.alloc(1e90) }) + t.throws(function () { impl.Buffer.alloc(2 * (1 << 30)) }) + t.throws(function () { impl.Buffer.alloc(Infinity) }) + t.throws(function () { impl.Buffer.alloc(-Infinity) }) + t.throws(function () { impl.Buffer.alloc(null) }) + t.throws(function () { impl.Buffer.alloc(undefined) }) + t.throws(function () { impl.Buffer.alloc() }) + t.throws(function () { impl.Buffer.alloc([]) }) + t.throws(function () { impl.Buffer.alloc([0, 42, 3]) }) + t.throws(function () { impl.Buffer.alloc({}) }) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.throws(function () { dangerous.Buffer[method]('') }) + t.throws(function () { dangerous.Buffer[method]('string') }) + t.throws(function () { dangerous.Buffer[method]('string', 'utf-8') }) + t.throws(function () { dangerous.Buffer[method](2 * (1 << 30)) }) + t.throws(function () { dangerous.Buffer[method](Infinity) }) + if (dangerous.Buffer[method] === buffer.Buffer.allocUnsafe) { + t.skip('Skipping, older impl of allocUnsafe coerced negative sizes to 0') + } else { + t.throws(function () { dangerous.Buffer[method](-10) }) + t.throws(function () { dangerous.Buffer[method](-1e90) }) + t.throws(function () { dangerous.Buffer[method](-Infinity) }) + } + t.throws(function () { dangerous.Buffer[method](null) }) + t.throws(function () { dangerous.Buffer[method](undefined) }) + t.throws(function () { dangerous.Buffer[method]() }) + t.throws(function () { dangerous.Buffer[method]([]) }) + t.throws(function () { dangerous.Buffer[method]([0, 42, 3]) }) + t.throws(function () { dangerous.Buffer[method]({}) }) + }) + t.end() +}) + +test('Buffers have appropriate lengths', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.alloc(0).length, 0) + t.equal(impl.Buffer.alloc(10).length, 10) + t.equal(impl.Buffer.from('').length, 0) + t.equal(impl.Buffer.from('string').length, 6) + t.equal(impl.Buffer.from('string', 'utf-8').length, 6) + t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').length, 11) + t.equal(impl.Buffer.from([0, 42, 3]).length, 3) + t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).length, 3) + t.equal(impl.Buffer.from([]).length, 0) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.equal(dangerous.Buffer[method](0).length, 0) + t.equal(dangerous.Buffer[method](10).length, 10) + }) + t.end() +}) + +test('Buffers have appropriate lengths (2)', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true; + [ safer.Buffer.alloc, + dangerous.Buffer.allocUnsafe, + dangerous.Buffer.allocUnsafeSlow + ].forEach(function (method) { + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 1e5) + var buf = method(length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + } + }) + t.ok(ok) + t.end() +}) + +test('.alloc(size) is zero-filled and has correct length', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var buf = index.Buffer.alloc(length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + var j + for (j = 0; j < length; j++) { + if (buf[j] !== 0) ok = false + } + buf.fill(1) + for (j = 0; j < length; j++) { + if (buf[j] !== 1) ok = false + } + } + t.ok(ok) + t.end() +}) + +test('.allocUnsafe / .allocUnsafeSlow are fillable and have correct lengths', function (t) { + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var buf = dangerous.Buffer[method](length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + buf.fill(0, 0, length) + var j + for (j = 0; j < length; j++) { + if (buf[j] !== 0) ok = false + } + buf.fill(1, 0, length) + for (j = 0; j < length; j++) { + if (buf[j] !== 1) ok = false + } + } + t.ok(ok, method) + }) + t.end() +}) + +test('.alloc(size, fill) is `fill`-filled', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var fill = Math.round(Math.random() * 255) + var buf = index.Buffer.alloc(length, fill) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + for (var j = 0; j < length; j++) { + if (buf[j] !== fill) ok = false + } + } + t.ok(ok) + t.end() +}) + +test('.alloc(size, fill) is `fill`-filled', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var fill = Math.round(Math.random() * 255) + var buf = index.Buffer.alloc(length, fill) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + for (var j = 0; j < length; j++) { + if (buf[j] !== fill) ok = false + } + } + t.ok(ok) + t.deepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 97)) + t.notDeepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 98)) + + var tmp = new buffer.Buffer(2) + tmp.fill('ok') + if (tmp[1] === tmp[0]) { + // Outdated Node.js + t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('ooooo')) + } else { + t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('okoko')) + } + t.notDeepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('kokok')) + + t.end() +}) + +test('safer.Buffer.from returns results same as Buffer constructor', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.deepEqual(impl.Buffer.from(''), new buffer.Buffer('')) + t.deepEqual(impl.Buffer.from('string'), new buffer.Buffer('string')) + t.deepEqual(impl.Buffer.from('string', 'utf-8'), new buffer.Buffer('string', 'utf-8')) + t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), new buffer.Buffer('b25ldHdvdGhyZWU=', 'base64')) + t.deepEqual(impl.Buffer.from([0, 42, 3]), new buffer.Buffer([0, 42, 3])) + t.deepEqual(impl.Buffer.from(new Uint8Array([0, 42, 3])), new buffer.Buffer(new Uint8Array([0, 42, 3]))) + t.deepEqual(impl.Buffer.from([]), new buffer.Buffer([])) + }) + t.end() +}) + +test('safer.Buffer.from returns consistent results', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.deepEqual(impl.Buffer.from(''), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from([]), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from(new Uint8Array([])), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from('string', 'utf-8'), impl.Buffer.from('string')) + t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from([115, 116, 114, 105, 110, 103])) + t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from(impl.Buffer.from('string'))) + t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), impl.Buffer.from('onetwothree')) + t.notDeepEqual(impl.Buffer.from('b25ldHdvdGhyZWU='), impl.Buffer.from('onetwothree')) + }) + t.end() +}) diff --git a/node_modules/send/LICENSE b/node_modules/send/LICENSE new file mode 100644 index 000000000..b6ea1c1fd --- /dev/null +++ b/node_modules/send/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2014-2022 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/send/README.md b/node_modules/send/README.md new file mode 100644 index 000000000..350fccd5a --- /dev/null +++ b/node_modules/send/README.md @@ -0,0 +1,317 @@ +# send + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![CI][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Send is a library for streaming files from the file system as a http response +supporting partial responses (Ranges), conditional-GET negotiation (If-Match, +If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage, +and granular events which may be leveraged to take appropriate actions in your +application or framework. + +Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static). + +## 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): + +```bash +$ npm install send +``` + +## API + +```js +var send = require('send') +``` + +### send(req, path, [options]) + +Create a new `SendStream` for the given path to send to a `res`. The `req` is +the Node.js HTTP request and the `path` is a urlencoded path to send (urlencoded, +not the actual file-system path). + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### dotfiles + +Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path actually exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Send a 403 for any request for a dotfile. + - `'ignore'` Pretend like the dotfile does not exist and 404. + +The default value is _similar_ to `'ignore'`, with the exception that +this default will not ignore the files within a directory that begins +with a dot, for backward-compatibility. + +##### end + +Byte offset at which the stream ends, defaults to the length of the file +minus 1. The end is inclusive in the stream, meaning `end: 3` will include +the 4th byte in the stream. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +If a given file doesn't exist, try appending one of the given extensions, +in the given order. By default, this is disabled (set to `false`). An +example value that will serve extension-less HTML files: `['html', 'htm']`. +This is skipped if the requested file already has an extension. + +##### immutable + +Enable or disable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default send supports "index.html" files, to disable this +set `false` or to supply a new index pass a string or an array +in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for http caching, defaults to 0. +This can also be a string accepted by the +[ms](https://www.npmjs.org/package/ms#readme) module. + +##### root + +Serve files relative to `path`. + +##### start + +Byte offset at which the stream starts, defaults to 0. The start is inclusive, +meaning `start: 2` will include the 3rd byte in the stream. + +#### Events + +The `SendStream` is an event emitter and will emit the following events: + + - `error` an error occurred `(err)` + - `directory` a directory was requested `(res, path)` + - `file` a file was requested `(path, stat)` + - `headers` the headers are about to be set on a file `(res, path, stat)` + - `stream` file streaming has started `(stream)` + - `end` streaming has completed + +#### .pipe + +The `pipe` method is used to pipe the response into the Node.js HTTP response +object, typically `send(req, path, options).pipe(res)`. + +## Error-handling + +By default when no `error` listeners are present an automatic response will be +made, otherwise you have full control over the response, aka you may show a 5xx +page etc. + +## Caching + +It does _not_ perform internal caching, you should use a reverse proxy cache +such as Varnish for this, or those fancy things called CDNs. If your +application is small enough that it would benefit from single-node memory +caching, it's small enough that it does not need caching at all ;). + +## Debugging + +To enable `debug()` instrumentation output export __DEBUG__: + +``` +$ DEBUG=send node app +``` + +## Running tests + +``` +$ npm install +$ npm test +``` + +## Examples + +### Serve a specific file + +This simple example will send a specific file to all requests. + +```js +var http = require('http') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, '/path/to/index.html') + .pipe(res) +}) + +server.listen(3000) +``` + +### Serve all files from a directory + +This simple example will just serve up all the files in a +given directory as the top-level. For example, a request +`GET /foo.txt` will send back `/www/public/foo.txt`. + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .pipe(res) +}) + +server.listen(3000) +``` + +### Custom file types + +```js +var extname = require('path').extname +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .on('headers', function (res, path) { + switch (extname(path)) { + case '.x-mt': + case '.x-mtt': + // custom type for these extensions + res.setHeader('Content-Type', 'application/x-my-type') + break + } + }) + .pipe(res) +}) + +server.listen(3000) +``` + +### Custom directory index view + +This is an example of serving up a structure of directories with a +custom function to render a listing of a directory. + +```js +var http = require('http') +var fs = require('fs') +var parseUrl = require('parseurl') +var send = require('send') + +// Transfer arbitrary files from within /www/example.com/public/* +// with a custom handler for directory listing +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { index: false, root: '/www/public' }) + .once('directory', directory) + .pipe(res) +}) + +server.listen(3000) + +// Custom directory handler +function directory (res, path) { + var stream = this + + // redirect to trailing slash for consistent url + if (!stream.hasTrailingSlash()) { + return stream.redirect(path) + } + + // get directory list + fs.readdir(path, function onReaddir (err, list) { + if (err) return stream.error(err) + + // render an index for the directory + res.setHeader('Content-Type', 'text/plain; charset=UTF-8') + res.end(list.join('\n') + '\n') + }) +} +``` + +### Serving from a root directory with custom error-handling + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + // your custom error-handling logic: + function error (err) { + res.statusCode = err.status || 500 + res.end(err.message) + } + + // your custom headers + function headers (res, path, stat) { + // serve all files for download + res.setHeader('Content-Disposition', 'attachment') + } + + // your custom directory handling logic: + function redirect () { + res.statusCode = 301 + res.setHeader('Location', req.url + '/') + res.end('Redirecting to ' + req.url + '/') + } + + // transfer arbitrary files from within + // /www/example.com/public/* + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .on('error', error) + .on('directory', redirect) + .on('headers', headers) + .pipe(res) +}) + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/send/master +[coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/pillarjs/send/master?label=linux +[github-actions-ci-url]: https://github.com/pillarjs/send/actions/workflows/ci.yml +[node-image]: https://badgen.net/npm/node/send +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/send +[npm-url]: https://npmjs.org/package/send +[npm-version-image]: https://badgen.net/npm/v/send diff --git a/node_modules/send/index.js b/node_modules/send/index.js new file mode 100644 index 000000000..1655053d1 --- /dev/null +++ b/node_modules/send/index.js @@ -0,0 +1,997 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('send') +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var etag = require('etag') +var fresh = require('fresh') +var fs = require('fs') +var mime = require('mime-types') +var ms = require('ms') +var onFinished = require('on-finished') +var parseRange = require('range-parser') +var path = require('path') +var statuses = require('statuses') +var Stream = require('stream') +var util = require('util') + +/** + * Path function references. + * @private + */ + +var extname = path.extname +var join = path.join +var normalize = path.normalize +var resolve = path.resolve +var sep = path.sep + +/** + * Regular expression for identifying a bytes Range header. + * @private + */ + +var BYTES_RANGE_REGEXP = /^ *bytes=/ + +/** + * Maximum value allowed for the max age. + * @private + */ + +var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year + +/** + * Regular expression to match a path with a directory up component. + * @private + */ + +var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = send + +/** + * Return a `SendStream` for `req` and `path`. + * + * @param {object} req + * @param {string} path + * @param {object} [options] + * @return {SendStream} + * @public + */ + +function send (req, path, options) { + return new SendStream(req, path, options) +} + +/** + * Initialize a `SendStream` with the given `path`. + * + * @param {Request} req + * @param {String} path + * @param {object} [options] + * @private + */ + +function SendStream (req, path, options) { + Stream.call(this) + + var opts = options || {} + + this.options = opts + this.path = path + this.req = req + + this._acceptRanges = opts.acceptRanges !== undefined + ? Boolean(opts.acceptRanges) + : true + + this._cacheControl = opts.cacheControl !== undefined + ? Boolean(opts.cacheControl) + : true + + this._etag = opts.etag !== undefined + ? Boolean(opts.etag) + : true + + this._dotfiles = opts.dotfiles !== undefined + ? opts.dotfiles + : 'ignore' + + if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } + + this._extensions = opts.extensions !== undefined + ? normalizeList(opts.extensions, 'extensions option') + : [] + + this._immutable = opts.immutable !== undefined + ? Boolean(opts.immutable) + : false + + this._index = opts.index !== undefined + ? normalizeList(opts.index, 'index option') + : ['index.html'] + + this._lastModified = opts.lastModified !== undefined + ? Boolean(opts.lastModified) + : true + + this._maxage = opts.maxAge || opts.maxage + this._maxage = typeof this._maxage === 'string' + ? ms(this._maxage) + : Number(this._maxage) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) + : 0 + + this._root = opts.root + ? resolve(opts.root) + : null +} + +/** + * Inherits from `Stream`. + */ + +util.inherits(SendStream, Stream) + +/** + * Emit error with `status`. + * + * @param {number} status + * @param {Error} [err] + * @private + */ + +SendStream.prototype.error = function error (status, err) { + // emit if listeners instead of responding + if (hasListeners(this, 'error')) { + return this.emit('error', createHttpError(status, err)) + } + + var res = this.res + var msg = statuses.message[status] || String(status) + var doc = createHtmlDocument('Error', escapeHtml(msg)) + + // clear existing headers + clearHeaders(res) + + // add error headers + if (err && err.headers) { + setHeaders(res, err.headers) + } + + // send basic response + res.statusCode = status + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(doc) +} + +/** + * Check if the pathname ends with "/". + * + * @return {boolean} + * @private + */ + +SendStream.prototype.hasTrailingSlash = function hasTrailingSlash () { + return this.path[this.path.length - 1] === '/' +} + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isConditionalGET = function isConditionalGET () { + return this.req.headers['if-match'] || + this.req.headers['if-unmodified-since'] || + this.req.headers['if-none-match'] || + this.req.headers['if-modified-since'] +} + +/** + * Check if the request preconditions failed. + * + * @return {boolean} + * @private + */ + +SendStream.prototype.isPreconditionFailure = function isPreconditionFailure () { + var req = this.req + var res = this.res + + // if-match + var match = req.headers['if-match'] + if (match) { + var etag = res.getHeader('ETag') + return !etag || (match !== '*' && parseTokenList(match).every(function (match) { + return match !== etag && match !== 'W/' + etag && 'W/' + match !== etag + })) + } + + // if-unmodified-since + var unmodifiedSince = parseHttpDate(req.headers['if-unmodified-since']) + if (!isNaN(unmodifiedSince)) { + var lastModified = parseHttpDate(res.getHeader('Last-Modified')) + return isNaN(lastModified) || lastModified > unmodifiedSince + } + + return false +} + +/** + * Strip various content header fields for a change in entity. + * + * @private + */ + +SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields () { + var res = this.res + + res.removeHeader('Content-Encoding') + res.removeHeader('Content-Language') + res.removeHeader('Content-Length') + res.removeHeader('Content-Range') + res.removeHeader('Content-Type') +} + +/** + * Respond with 304 not modified. + * + * @api private + */ + +SendStream.prototype.notModified = function notModified () { + var res = this.res + debug('not modified') + this.removeContentHeaderFields() + res.statusCode = 304 + res.end() +} + +/** + * Raise error that headers already sent. + * + * @api private + */ + +SendStream.prototype.headersAlreadySent = function headersAlreadySent () { + var err = new Error('Can\'t set headers after they are sent.') + debug('headers already sent') + this.error(500, err) +} + +/** + * Check if the request is cacheable, aka + * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isCachable = function isCachable () { + var statusCode = this.res.statusCode + return (statusCode >= 200 && statusCode < 300) || + statusCode === 304 +} + +/** + * Handle stat() error. + * + * @param {Error} error + * @private + */ + +SendStream.prototype.onStatError = function onStatError (error) { + switch (error.code) { + case 'ENAMETOOLONG': + case 'ENOENT': + case 'ENOTDIR': + this.error(404, error) + break + default: + this.error(500, error) + break + } +} + +/** + * Check if the cache is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isFresh = function isFresh () { + return fresh(this.req.headers, { + etag: this.res.getHeader('ETag'), + 'last-modified': this.res.getHeader('Last-Modified') + }) +} + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isRangeFresh = function isRangeFresh () { + var ifRange = this.req.headers['if-range'] + + if (!ifRange) { + return true + } + + // if-range as etag + if (ifRange.indexOf('"') !== -1) { + var etag = this.res.getHeader('ETag') + return Boolean(etag && ifRange.indexOf(etag) !== -1) + } + + // if-range as modified date + var lastModified = this.res.getHeader('Last-Modified') + return parseHttpDate(lastModified) <= parseHttpDate(ifRange) +} + +/** + * Redirect to path. + * + * @param {string} path + * @private + */ + +SendStream.prototype.redirect = function redirect (path) { + var res = this.res + + if (hasListeners(this, 'directory')) { + this.emit('directory', res, path) + return + } + + if (this.hasTrailingSlash()) { + this.error(403) + return + } + + var loc = encodeUrl(collapseLeadingSlashes(this.path + '/')) + var doc = createHtmlDocument('Redirecting', 'Redirecting to ' + escapeHtml(loc)) + + // redirect + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(doc) +} + +/** + * Pipe to `res. + * + * @param {Stream} res + * @return {Stream} res + * @api public + */ + +SendStream.prototype.pipe = function pipe (res) { + // root path + var root = this._root + + // references + this.res = res + + // decode the path + var path = decode(this.path) + if (path === -1) { + this.error(400) + return res + } + + // null byte(s) + if (~path.indexOf('\0')) { + this.error(400) + return res + } + + var parts + if (root !== null) { + // normalize + if (path) { + path = normalize('.' + sep + path) + } + + // malicious path + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + this.error(403) + return res + } + + // explode path parts + parts = path.split(sep) + + // join / normalize from optional root dir + path = normalize(join(root, path)) + } else { + // ".." is malicious without "root" + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + this.error(403) + return res + } + + // explode path parts + parts = normalize(path).split(sep) + + // resolve the path + path = resolve(path) + } + + // dotfile handling + if (containsDotFile(parts)) { + debug('%s dotfile "%s"', this._dotfiles, path) + switch (this._dotfiles) { + case 'allow': + break + case 'deny': + this.error(403) + return res + case 'ignore': + default: + this.error(404) + return res + } + } + + // index file support + if (this._index.length && this.hasTrailingSlash()) { + this.sendIndex(path) + return res + } + + this.sendFile(path) + return res +} + +/** + * Transfer `path`. + * + * @param {String} path + * @api public + */ + +SendStream.prototype.send = function send (path, stat) { + var len = stat.size + var options = this.options + var opts = {} + var res = this.res + var req = this.req + var ranges = req.headers.range + var offset = options.start || 0 + + if (res.headersSent) { + // impossible to send now + this.headersAlreadySent() + return + } + + debug('pipe "%s"', path) + + // set header fields + this.setHeader(path, stat) + + // set content-type + this.type(path) + + // conditional GET support + if (this.isConditionalGET()) { + if (this.isPreconditionFailure()) { + this.error(412) + return + } + + if (this.isCachable() && this.isFresh()) { + this.notModified() + return + } + } + + // adjust len to start/end options + len = Math.max(0, len - offset) + if (options.end !== undefined) { + var bytes = options.end - offset + 1 + if (len > bytes) len = bytes + } + + // Range support + if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) { + // parse + ranges = parseRange(len, ranges, { + combine: true + }) + + // If-Range support + if (!this.isRangeFresh()) { + debug('range stale') + ranges = -2 + } + + // unsatisfiable + if (ranges === -1) { + debug('range unsatisfiable') + + // Content-Range + res.setHeader('Content-Range', contentRange('bytes', len)) + + // 416 Requested Range Not Satisfiable + return this.error(416, { + headers: { 'Content-Range': res.getHeader('Content-Range') } + }) + } + + // valid (syntactically invalid/multiple ranges are treated as a regular response) + if (ranges !== -2 && ranges.length === 1) { + debug('range %j', ranges) + + // Content-Range + res.statusCode = 206 + res.setHeader('Content-Range', contentRange('bytes', len, ranges[0])) + + // adjust for requested range + offset += ranges[0].start + len = ranges[0].end - ranges[0].start + 1 + } + } + + // clone options + for (var prop in options) { + opts[prop] = options[prop] + } + + // set read options + opts.start = offset + opts.end = Math.max(offset, offset + len - 1) + + // content-length + res.setHeader('Content-Length', len) + + // HEAD support + if (req.method === 'HEAD') { + res.end() + return + } + + this.stream(path, opts) +} + +/** + * Transfer file for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendFile = function sendFile (path) { + var i = 0 + var self = this + + debug('stat "%s"', path) + fs.stat(path, function onstat (err, stat) { + var pathEndsWithSep = path[path.length - 1] === sep + if (err && err.code === 'ENOENT' && !extname(path) && !pathEndsWithSep) { + // not found, check extensions + return next(err) + } + if (err) return self.onStatError(err) + if (stat.isDirectory()) return self.redirect(path) + if (pathEndsWithSep) return self.error(404) + self.emit('file', path, stat) + self.send(path, stat) + }) + + function next (err) { + if (self._extensions.length <= i) { + return err + ? self.onStatError(err) + : self.error(404) + } + + var p = path + '.' + self._extensions[i++] + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } +} + +/** + * Transfer index for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendIndex = function sendIndex (path) { + var i = -1 + var self = this + + function next (err) { + if (++i >= self._index.length) { + if (err) return self.onStatError(err) + return self.error(404) + } + + var p = join(path, self._index[i]) + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } + + next() +} + +/** + * Stream `path` to the response. + * + * @param {String} path + * @param {Object} options + * @api private + */ + +SendStream.prototype.stream = function stream (path, options) { + var self = this + var res = this.res + + // pipe + var stream = fs.createReadStream(path, options) + this.emit('stream', stream) + stream.pipe(res) + + // cleanup + function cleanup () { + stream.destroy() + } + + // response finished, cleanup + onFinished(res, cleanup) + + // error handling + stream.on('error', function onerror (err) { + // clean up stream early + cleanup() + + // error + self.onStatError(err) + }) + + // end + stream.on('end', function onend () { + self.emit('end') + }) +} + +/** + * Set content-type based on `path` + * if it hasn't been explicitly set. + * + * @param {String} path + * @api private + */ + +SendStream.prototype.type = function type (path) { + var res = this.res + + if (res.getHeader('Content-Type')) return + + var ext = extname(path) + var type = mime.contentType(ext) || 'application/octet-stream' + + debug('content-type %s', type) + res.setHeader('Content-Type', type) +} + +/** + * Set response header fields, most + * fields may be pre-defined. + * + * @param {String} path + * @param {Object} stat + * @api private + */ + +SendStream.prototype.setHeader = function setHeader (path, stat) { + var res = this.res + + this.emit('headers', res, path, stat) + + if (this._acceptRanges && !res.getHeader('Accept-Ranges')) { + debug('accept ranges') + res.setHeader('Accept-Ranges', 'bytes') + } + + if (this._cacheControl && !res.getHeader('Cache-Control')) { + var cacheControl = 'public, max-age=' + Math.floor(this._maxage / 1000) + + if (this._immutable) { + cacheControl += ', immutable' + } + + debug('cache-control %s', cacheControl) + res.setHeader('Cache-Control', cacheControl) + } + + if (this._lastModified && !res.getHeader('Last-Modified')) { + var modified = stat.mtime.toUTCString() + debug('modified %s', modified) + res.setHeader('Last-Modified', modified) + } + + if (this._etag && !res.getHeader('ETag')) { + var val = etag(stat) + debug('etag %s', val) + res.setHeader('ETag', val) + } +} + +/** + * Clear all headers from a response. + * + * @param {object} res + * @private + */ + +function clearHeaders (res) { + for (const header of res.getHeaderNames()) { + res.removeHeader(header) + } +} + +/** + * Collapse all leading slashes into a single slash + * + * @param {string} str + * @private + */ +function collapseLeadingSlashes (str) { + for (var i = 0; i < str.length; i++) { + if (str[i] !== '/') { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Determine if path parts contain a dotfile. + * + * @api private + */ + +function containsDotFile (parts) { + for (var i = 0; i < parts.length; i++) { + var part = parts[i] + if (part.length > 1 && part[0] === '.') { + return true + } + } + + return false +} + +/** + * Create a Content-Range header. + * + * @param {string} type + * @param {number} size + * @param {array} [range] + */ + +function contentRange (type, size, range) { + return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size +} + +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ + +function createHtmlDocument (title, body) { + return '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Create a HttpError object from simple arguments. + * + * @param {number} status + * @param {Error|object} err + * @private + */ + +function createHttpError (status, err) { + if (!err) { + return createError(status) + } + + return err instanceof Error + ? createError(status, err, { expose: false }) + : createError(status, err) +} + +/** + * decodeURIComponent. + * + * Allows V8 to only deoptimize this fn instead of all + * of send(). + * + * @param {String} path + * @api private + */ + +function decode (path) { + try { + return decodeURIComponent(path) + } catch (err) { + return -1 + } +} + +/** + * Determine if emitter has listeners of a given type. + * + * The way to do this check is done three different ways in Node.js >= 0.10 + * so this consolidates them into a minimal set using instance methods. + * + * @param {EventEmitter} emitter + * @param {string} type + * @returns {boolean} + * @private + */ + +function hasListeners (emitter, type) { + var count = typeof emitter.listenerCount !== 'function' + ? emitter.listeners(type).length + : emitter.listenerCount(type) + + return count > 0 +} + +/** + * Normalize the index option into an array. + * + * @param {boolean|string|array} val + * @param {string} name + * @private + */ + +function normalizeList (val, name) { + var list = [].concat(val || []) + + for (var i = 0; i < list.length; i++) { + if (typeof list[i] !== 'string') { + throw new TypeError(name + ' must be array of strings or false') + } + } + + return list +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + if (start !== end) { + list.push(str.substring(start, end)) + } + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + if (start !== end) { + list.push(str.substring(start, end)) + } + + return list +} + +/** + * Set an object of headers on a response. + * + * @param {object} res + * @param {object} headers + * @private + */ + +function setHeaders (res, headers) { + var keys = Object.keys(headers) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} diff --git a/node_modules/send/package.json b/node_modules/send/package.json new file mode 100644 index 000000000..e9d3cc293 --- /dev/null +++ b/node_modules/send/package.json @@ -0,0 +1,63 @@ +{ + "name": "send", + "description": "Better streaming static file server with Range and conditional-GET support", + "version": "1.2.1", + "author": "TJ Holowaychuk ", + "contributors": [ + "Douglas Christopher Wilson ", + "James Wyatt Cready ", + "Jesús Leganés Combarro " + ], + "license": "MIT", + "repository": "pillarjs/send", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "keywords": [ + "static", + "file", + "server" + ], + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "devDependencies": { + "after": "^0.8.2", + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.32.0", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "^10.7.0", + "nyc": "^17.0.0", + "supertest": "6.3.4" + }, + "files": [ + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 18" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --check-leaks --reporter spec", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/serve-static/LICENSE b/node_modules/serve-static/LICENSE new file mode 100644 index 000000000..cbe62e8e7 --- /dev/null +++ b/node_modules/serve-static/LICENSE @@ -0,0 +1,25 @@ +(The MIT License) + +Copyright (c) 2010 Sencha Inc. +Copyright (c) 2011 LearnBoost +Copyright (c) 2011 TJ Holowaychuk +Copyright (c) 2014-2016 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/serve-static/README.md b/node_modules/serve-static/README.md new file mode 100644 index 000000000..3ff1f1fa3 --- /dev/null +++ b/node_modules/serve-static/README.md @@ -0,0 +1,253 @@ +# serve-static + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![CI][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +## Install + +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 serve-static +``` + +## API + +```js +const serveStatic = require('serve-static') +``` + +### serveStatic(root, options) + +Create a new middleware function to serve files from within a given root +directory. The file to serve will be determined by combining `req.url` +with the provided root directory. When a file is not found, instead of +sending a 404 response, this module will instead call `next()` to move on +to the next middleware, allowing for stacking and fall-backs. + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### dotfiles + +Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path actually exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Deny a request for a dotfile and 403/`next()`. + - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. + +The default value is `'ignore'`. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +Set file extension fallbacks. When set, if a file is not found, the given +extensions will be added to the file name and search for. The first that +exists will be served. Example: `['html', 'htm']`. + +The default value is `false`. + +##### fallthrough + +Set the middleware to have client errors fall-through as just unhandled +requests, otherwise forward a client error. The difference is that client +errors like a bad request or a request to a non-existent file will cause +this middleware to simply `next()` to your next middleware when this value +is `true`. When this value is `false`, these errors (even 404s), will invoke +`next(err)`. + +Typically `true` is desired such that multiple physical directories can be +mapped to the same web address or for routes to fill in non-existent files. + +The value `false` can be used if this middleware is mounted at a path that +is designed to be strictly a single file system directory, which allows for +short-circuiting 404s for less overhead. This middleware will also reply to +all methods. + +The default value is `true`. + +##### immutable + +Enable or disable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default this module will send "index.html" files in response to a request +on a directory. To disable this set `false` or to supply a new index pass a +string or an array in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for http caching, defaults to 0. This +can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) +module. + +##### redirect + +Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. + +##### setHeaders + +Function to set custom headers on response. Alterations to the headers need to +occur synchronously. The function is called as `fn(res, path, stat)`, where +the arguments are: + + - `res` the response object + - `path` the file path that is being sent + - `stat` the stat object of the file that is being sent + +## Examples + +### Serve files with vanilla node.js http server + +```js +const finalhandler = require('finalhandler') +const http = require('http') +const serveStatic = require('serve-static') + +// Serve up public/ftp folder +const serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] }) + +// Create server +const server = http.createServer((req, res) => { + serve(req, res, finalhandler(req, res)) +}) + +// Listen +server.listen(3000) +``` + +### Serve all files as downloads + +```js +const contentDisposition = require('content-disposition') +const finalhandler = require('finalhandler') +const http = require('http') +const serveStatic = require('serve-static') + +// Serve up public/ftp folder +const serve = serveStatic('public/ftp', { + index: false, + setHeaders: setHeaders +}) + +// Set header to force download +function setHeaders (res, path) { + res.setHeader('Content-Disposition', contentDisposition(path)) +} + +// Create server +const server = http.createServer((req, res) => { + serve(req, res, finalhandler(req, res)) +}) + +// Listen +server.listen(3000) +``` + +### Serving using express + +#### Simple + +This is a simple example of using Express. + +```js +const express = require('express') +const serveStatic = require('serve-static') + +const app = express() + +app.use(serveStatic('public/ftp', { index: ['default.html', 'default.htm'] })) +app.listen(3000) +``` + +#### Multiple roots + +This example shows a simple way to search through multiple directories. +Files are searched for in `public-optimized/` first, then `public/` second +as a fallback. + +```js +const express = require('express') +const path = require('path') +const serveStatic = require('serve-static') + +const app = express() + +app.use(serveStatic(path.join(__dirname, 'public-optimized'))) +app.use(serveStatic(path.join(__dirname, 'public'))) +app.listen(3000) +``` + +#### Different settings for paths + +This example shows how to set a different max age depending on the served +file. In this example, HTML files are not cached, while everything else +is for 1 day. + +```js +const express = require('express') +const path = require('path') +const serveStatic = require('serve-static') + +const app = express() + +app.use(serveStatic(path.join(__dirname, 'public'), { + maxAge: '1d', + setHeaders: setCustomCacheControl +})) + +app.listen(3000) + +function setCustomCacheControl (res, file) { + if (path.extname(file) === '.html') { + // Custom Cache-Control for HTML files + res.setHeader('Cache-Control', 'public, max-age=0') + } +} +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/serve-static/master +[coveralls-url]: https://coveralls.io/r/expressjs/serve-static?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/expressjs/serve-static/master?label=linux +[github-actions-ci-url]: https://github.com/expressjs/serve-static/actions/workflows/ci.yml +[node-image]: https://badgen.net/npm/node/serve-static +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/serve-static +[npm-url]: https://npmjs.org/package/serve-static +[npm-version-image]: https://badgen.net/npm/v/serve-static diff --git a/node_modules/serve-static/index.js b/node_modules/serve-static/index.js new file mode 100644 index 000000000..1bee46378 --- /dev/null +++ b/node_modules/serve-static/index.js @@ -0,0 +1,208 @@ +/*! + * serve-static + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var parseUrl = require('parseurl') +var resolve = require('path').resolve +var send = require('send') +var url = require('url') + +/** + * Module exports. + * @public + */ + +module.exports = serveStatic + +/** + * @param {string} root + * @param {object} [options] + * @return {function} + * @public + */ + +function serveStatic (root, options) { + if (!root) { + throw new TypeError('root path required') + } + + if (typeof root !== 'string') { + throw new TypeError('root path must be a string') + } + + // copy options object + var opts = Object.create(options || null) + + // fall-though + var fallthrough = opts.fallthrough !== false + + // default redirect + var redirect = opts.redirect !== false + + // headers listener + var setHeaders = opts.setHeaders + + if (setHeaders && typeof setHeaders !== 'function') { + throw new TypeError('option setHeaders must be function') + } + + // setup options for send + opts.maxage = opts.maxage || opts.maxAge || 0 + opts.root = resolve(root) + + // construct directory listener + var onDirectory = redirect + ? createRedirectDirectoryListener() + : createNotFoundDirectoryListener() + + return function serveStatic (req, res, next) { + if (req.method !== 'GET' && req.method !== 'HEAD') { + if (fallthrough) { + return next() + } + + // method not allowed + res.statusCode = 405 + res.setHeader('Allow', 'GET, HEAD') + res.setHeader('Content-Length', '0') + res.end() + return + } + + var forwardError = !fallthrough + var originalUrl = parseUrl.original(req) + var path = parseUrl(req).pathname + + // make sure redirect occurs at mount + if (path === '/' && originalUrl.pathname.substr(-1) !== '/') { + path = '' + } + + // create send stream + var stream = send(req, path, opts) + + // add directory handler + stream.on('directory', onDirectory) + + // add headers listener + if (setHeaders) { + stream.on('headers', setHeaders) + } + + // add file listener for fallthrough + if (fallthrough) { + stream.on('file', function onFile () { + // once file is determined, always forward error + forwardError = true + }) + } + + // forward errors + stream.on('error', function error (err) { + if (forwardError || !(err.statusCode < 500)) { + next(err) + return + } + + next() + }) + + // pipe + stream.pipe(res) + } +} + +/** + * Collapse all leading slashes into a single slash + * @private + */ +function collapseLeadingSlashes (str) { + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) !== 0x2f /* / */) { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ + +function createHtmlDocument (title, body) { + return '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Create a directory listener that just 404s. + * @private + */ + +function createNotFoundDirectoryListener () { + return function notFound () { + this.error(404) + } +} + +/** + * Create a directory listener that performs a redirect. + * @private + */ + +function createRedirectDirectoryListener () { + return function redirect (res) { + if (this.hasTrailingSlash()) { + this.error(404) + return + } + + // get original URL + var originalUrl = parseUrl.original(this.req) + + // append trailing slash + originalUrl.path = null + originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') + + // reformat the URL + var loc = encodeUrl(url.format(originalUrl)) + var doc = createHtmlDocument('Redirecting', 'Redirecting to ' + escapeHtml(loc)) + + // send redirect response + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(doc) + } +} diff --git a/node_modules/serve-static/package.json b/node_modules/serve-static/package.json new file mode 100644 index 000000000..5fb5b0234 --- /dev/null +++ b/node_modules/serve-static/package.json @@ -0,0 +1,44 @@ +{ + "name": "serve-static", + "description": "Serve static files", + "version": "2.2.1", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "expressjs/serve-static", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.32.0", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "^10.7.0", + "nyc": "^17.0.0", + "supertest": "^6.3.4" + }, + "files": [ + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 18" + }, + "scripts": { + "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", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/setprototypeof/LICENSE b/node_modules/setprototypeof/LICENSE new file mode 100644 index 000000000..61afa2f18 --- /dev/null +++ b/node_modules/setprototypeof/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015, Wes Todd + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/setprototypeof/README.md b/node_modules/setprototypeof/README.md new file mode 100644 index 000000000..791eeff0c --- /dev/null +++ b/node_modules/setprototypeof/README.md @@ -0,0 +1,31 @@ +# Polyfill for `Object.setPrototypeOf` + +[![NPM Version](https://img.shields.io/npm/v/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) +[![NPM Downloads](https://img.shields.io/npm/dm/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/standard/standard) + +A simple cross platform implementation to set the prototype of an instianted object. Supports all modern browsers and at least back to IE8. + +## Usage: + +``` +$ npm install --save setprototypeof +``` + +```javascript +var setPrototypeOf = require('setprototypeof') + +var obj = {} +setPrototypeOf(obj, { + foo: function () { + return 'bar' + } +}) +obj.foo() // bar +``` + +TypeScript is also supported: + +```typescript +import setPrototypeOf from 'setprototypeof' +``` diff --git a/node_modules/setprototypeof/index.d.ts b/node_modules/setprototypeof/index.d.ts new file mode 100644 index 000000000..f108ecd0a --- /dev/null +++ b/node_modules/setprototypeof/index.d.ts @@ -0,0 +1,2 @@ +declare function setPrototypeOf(o: any, proto: object | null): any; +export = setPrototypeOf; diff --git a/node_modules/setprototypeof/index.js b/node_modules/setprototypeof/index.js new file mode 100644 index 000000000..c5270551e --- /dev/null +++ b/node_modules/setprototypeof/index.js @@ -0,0 +1,17 @@ +'use strict' +/* eslint no-proto: 0 */ +module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties) + +function setProtoOf (obj, proto) { + obj.__proto__ = proto + return obj +} + +function mixinProperties (obj, proto) { + for (var prop in proto) { + if (!Object.prototype.hasOwnProperty.call(obj, prop)) { + obj[prop] = proto[prop] + } + } + return obj +} diff --git a/node_modules/setprototypeof/package.json b/node_modules/setprototypeof/package.json new file mode 100644 index 000000000..f20915bea --- /dev/null +++ b/node_modules/setprototypeof/package.json @@ -0,0 +1,38 @@ +{ + "name": "setprototypeof", + "version": "1.2.0", + "description": "A small polyfill for Object.setprototypeof", + "main": "index.js", + "typings": "index.d.ts", + "scripts": { + "test": "standard && mocha", + "testallversions": "npm run node010 && npm run node4 && npm run node6 && npm run node9 && npm run node11", + "testversion": "docker run -it --rm -v $(PWD):/usr/src/app -w /usr/src/app node:${NODE_VER} npm install mocha@${MOCHA_VER:-latest} && npm t", + "node010": "NODE_VER=0.10 MOCHA_VER=3 npm run testversion", + "node4": "NODE_VER=4 npm run testversion", + "node6": "NODE_VER=6 npm run testversion", + "node9": "NODE_VER=9 npm run testversion", + "node11": "NODE_VER=11 npm run testversion", + "prepublishOnly": "npm t", + "postpublish": "git push origin && git push origin --tags" + }, + "repository": { + "type": "git", + "url": "https://github.com/wesleytodd/setprototypeof.git" + }, + "keywords": [ + "polyfill", + "object", + "setprototypeof" + ], + "author": "Wes Todd", + "license": "ISC", + "bugs": { + "url": "https://github.com/wesleytodd/setprototypeof/issues" + }, + "homepage": "https://github.com/wesleytodd/setprototypeof", + "devDependencies": { + "mocha": "^6.1.4", + "standard": "^13.0.2" + } +} diff --git a/node_modules/setprototypeof/test/index.js b/node_modules/setprototypeof/test/index.js new file mode 100644 index 000000000..afeb4ddb2 --- /dev/null +++ b/node_modules/setprototypeof/test/index.js @@ -0,0 +1,24 @@ +'use strict' +/* eslint-env mocha */ +/* eslint no-proto: 0 */ +var assert = require('assert') +var setPrototypeOf = require('..') + +describe('setProtoOf(obj, proto)', function () { + it('should merge objects', function () { + var obj = { a: 1, b: 2 } + var proto = { b: 3, c: 4 } + var mergeObj = setPrototypeOf(obj, proto) + + if (Object.getPrototypeOf) { + assert.strictEqual(Object.getPrototypeOf(obj), proto) + } else if ({ __proto__: [] } instanceof Array) { + assert.strictEqual(obj.__proto__, proto) + } else { + assert.strictEqual(obj.a, 1) + assert.strictEqual(obj.b, 2) + assert.strictEqual(obj.c, 4) + } + assert.strictEqual(mergeObj, obj) + }) +}) diff --git a/node_modules/shebang-command/index.js b/node_modules/shebang-command/index.js new file mode 100644 index 000000000..f35db3085 --- /dev/null +++ b/node_modules/shebang-command/index.js @@ -0,0 +1,19 @@ +'use strict'; +const shebangRegex = require('shebang-regex'); + +module.exports = (string = '') => { + const match = string.match(shebangRegex); + + if (!match) { + return null; + } + + const [path, argument] = match[0].replace(/#! ?/, '').split(' '); + const binary = path.split('/').pop(); + + if (binary === 'env') { + return argument; + } + + return argument ? `${binary} ${argument}` : binary; +}; diff --git a/node_modules/shebang-command/license b/node_modules/shebang-command/license new file mode 100644 index 000000000..db6bc32cc --- /dev/null +++ b/node_modules/shebang-command/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Kevin Mårtensson (github.com/kevva) + +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/shebang-command/package.json b/node_modules/shebang-command/package.json new file mode 100644 index 000000000..18e3c0463 --- /dev/null +++ b/node_modules/shebang-command/package.json @@ -0,0 +1,34 @@ +{ + "name": "shebang-command", + "version": "2.0.0", + "description": "Get the command from a shebang", + "license": "MIT", + "repository": "kevva/shebang-command", + "author": { + "name": "Kevin Mårtensson", + "email": "kevinmartensson@gmail.com", + "url": "github.com/kevva" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "cmd", + "command", + "parse", + "shebang" + ], + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "devDependencies": { + "ava": "^2.3.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/shebang-command/readme.md b/node_modules/shebang-command/readme.md new file mode 100644 index 000000000..84feb442d --- /dev/null +++ b/node_modules/shebang-command/readme.md @@ -0,0 +1,34 @@ +# shebang-command [![Build Status](https://travis-ci.org/kevva/shebang-command.svg?branch=master)](https://travis-ci.org/kevva/shebang-command) + +> Get the command from a shebang + + +## Install + +``` +$ npm install shebang-command +``` + + +## Usage + +```js +const shebangCommand = require('shebang-command'); + +shebangCommand('#!/usr/bin/env node'); +//=> 'node' + +shebangCommand('#!/bin/bash'); +//=> 'bash' +``` + + +## API + +### shebangCommand(string) + +#### string + +Type: `string` + +String containing a shebang. diff --git a/node_modules/shebang-regex/index.d.ts b/node_modules/shebang-regex/index.d.ts new file mode 100644 index 000000000..61d034b31 --- /dev/null +++ b/node_modules/shebang-regex/index.d.ts @@ -0,0 +1,22 @@ +/** +Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line. + +@example +``` +import shebangRegex = require('shebang-regex'); + +const string = '#!/usr/bin/env node\nconsole.log("unicorns");'; + +shebangRegex.test(string); +//=> true + +shebangRegex.exec(string)[0]; +//=> '#!/usr/bin/env node' + +shebangRegex.exec(string)[1]; +//=> '/usr/bin/env node' +``` +*/ +declare const shebangRegex: RegExp; + +export = shebangRegex; diff --git a/node_modules/shebang-regex/index.js b/node_modules/shebang-regex/index.js new file mode 100644 index 000000000..63fc4a0b6 --- /dev/null +++ b/node_modules/shebang-regex/index.js @@ -0,0 +1,2 @@ +'use strict'; +module.exports = /^#!(.*)/; diff --git a/node_modules/shebang-regex/license b/node_modules/shebang-regex/license new file mode 100644 index 000000000..e7af2f771 --- /dev/null +++ b/node_modules/shebang-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/shebang-regex/package.json b/node_modules/shebang-regex/package.json new file mode 100644 index 000000000..00ab30fee --- /dev/null +++ b/node_modules/shebang-regex/package.json @@ -0,0 +1,35 @@ +{ + "name": "shebang-regex", + "version": "3.0.0", + "description": "Regular expression for matching a shebang line", + "license": "MIT", + "repository": "sindresorhus/shebang-regex", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "regex", + "regexp", + "shebang", + "match", + "test", + "line" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/shebang-regex/readme.md b/node_modules/shebang-regex/readme.md new file mode 100644 index 000000000..5ecf863aa --- /dev/null +++ b/node_modules/shebang-regex/readme.md @@ -0,0 +1,33 @@ +# shebang-regex [![Build Status](https://travis-ci.org/sindresorhus/shebang-regex.svg?branch=master)](https://travis-ci.org/sindresorhus/shebang-regex) + +> Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line + + +## Install + +``` +$ npm install shebang-regex +``` + + +## Usage + +```js +const shebangRegex = require('shebang-regex'); + +const string = '#!/usr/bin/env node\nconsole.log("unicorns");'; + +shebangRegex.test(string); +//=> true + +shebangRegex.exec(string)[0]; +//=> '#!/usr/bin/env node' + +shebangRegex.exec(string)[1]; +//=> '/usr/bin/env node' +``` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/side-channel-list/.editorconfig b/node_modules/side-channel-list/.editorconfig new file mode 100644 index 000000000..72e0ebaa7 --- /dev/null +++ b/node_modules/side-channel-list/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel-list/.eslintrc b/node_modules/side-channel-list/.eslintrc new file mode 100644 index 000000000..93978e7d5 --- /dev/null +++ b/node_modules/side-channel-list/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel-list/.github/FUNDING.yml b/node_modules/side-channel-list/.github/FUNDING.yml new file mode 100644 index 000000000..eaff73503 --- /dev/null +++ b/node_modules/side-channel-list/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel-list +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel-list/.nycrc b/node_modules/side-channel-list/.nycrc new file mode 100644 index 000000000..1826526e0 --- /dev/null +++ b/node_modules/side-channel-list/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel-list/CHANGELOG.md b/node_modules/side-channel-list/CHANGELOG.md new file mode 100644 index 000000000..2ec51b769 --- /dev/null +++ b/node_modules/side-channel-list/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## v1.0.0 - 2024-12-10 + +### Commits + +- Initial implementation, tests, readme, types [`5d6baee`](https://github.com/ljharb/side-channel-list/commit/5d6baee5c9054a1238007f5a1dfc109a7a816251) +- Initial commit [`3ae784c`](https://github.com/ljharb/side-channel-list/commit/3ae784c63a47895fbaeed2a91ab54a8029a7a100) +- npm init [`07055a4`](https://github.com/ljharb/side-channel-list/commit/07055a4d139895565b199dba5fe2479c1a1b9e28) +- Only apps should have lockfiles [`9573058`](https://github.com/ljharb/side-channel-list/commit/9573058a47494e2d68f8c6c77b5d7fbe441949c1) diff --git a/node_modules/side-channel-list/LICENSE b/node_modules/side-channel-list/LICENSE new file mode 100644 index 000000000..f82f38963 --- /dev/null +++ b/node_modules/side-channel-list/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +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/side-channel-list/README.md b/node_modules/side-channel-list/README.md new file mode 100644 index 000000000..d9c7a1373 --- /dev/null +++ b/node_modules/side-channel-list/README.md @@ -0,0 +1,62 @@ +# side-channel-list [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel, using a linked list. + +Warning: this implementation will leak memory until you `delete` the `key`. +Use [`side-channel`](https://npmjs.com/side-channel) for the best available strategy. + +## Getting started + +```sh +npm install --save side-channel-list +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannelList = require('side-channel-list'); + +const channel = getSideChannelList(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel-list +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel-list.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel-list.svg +[deps-url]: https://david-dm.org/ljharb/side-channel-list +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel-list/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel-list#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel-list.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel-list.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel-list.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel-list +[codecov-image]: https://codecov.io/gh/ljharb/side-channel-list/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel-list/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel-list +[actions-url]: https://github.com/ljharb/side-channel-list/actions diff --git a/node_modules/side-channel-list/index.d.ts b/node_modules/side-channel-list/index.d.ts new file mode 100644 index 000000000..c9cabc843 --- /dev/null +++ b/node_modules/side-channel-list/index.d.ts @@ -0,0 +1,13 @@ +declare namespace getSideChannelList { + type Channel = { + assert: (key: K) => void; + has: (key: K) => boolean; + get: (key: K) => V | undefined; + set: (key: K, value: V) => void; + delete: (key: K) => boolean; + }; +} + +declare function getSideChannelList(): getSideChannelList.Channel; + +export = getSideChannelList; diff --git a/node_modules/side-channel-list/index.js b/node_modules/side-channel-list/index.js new file mode 100644 index 000000000..8d6f98ca1 --- /dev/null +++ b/node_modules/side-channel-list/index.js @@ -0,0 +1,113 @@ +'use strict'; + +var inspect = require('object-inspect'); + +var $TypeError = require('es-errors/type'); + +/* +* This function traverses the list returning the node corresponding to the given key. +* +* That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. +* By doing so, all the recently used nodes can be accessed relatively quickly. +*/ +/** @type {import('./list.d.ts').listGetNode} */ +// eslint-disable-next-line consistent-return +var listGetNode = function (list, key, isDelete) { + /** @type {typeof list | NonNullable<(typeof list)['next']>} */ + var prev = list; + /** @type {(typeof list)['next']} */ + var curr; + // eslint-disable-next-line eqeqeq + for (; (curr = prev.next) != null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + if (!isDelete) { + // eslint-disable-next-line no-extra-parens + curr.next = /** @type {NonNullable} */ (list.next); + list.next = curr; // eslint-disable-line no-param-reassign + } + return curr; + } + } +}; + +/** @type {import('./list.d.ts').listGet} */ +var listGet = function (objects, key) { + if (!objects) { + return void undefined; + } + var node = listGetNode(objects, key); + return node && node.value; +}; +/** @type {import('./list.d.ts').listSet} */ +var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = /** @type {import('./list.d.ts').ListNode} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens + key: key, + next: objects.next, + value: value + }); + } +}; +/** @type {import('./list.d.ts').listHas} */ +var listHas = function (objects, key) { + if (!objects) { + return false; + } + return !!listGetNode(objects, key); +}; +/** @type {import('./list.d.ts').listDelete} */ +// eslint-disable-next-line consistent-return +var listDelete = function (objects, key) { + if (objects) { + return listGetNode(objects, key, true); + } +}; + +/** @type {import('.')} */ +module.exports = function getSideChannelList() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {import('./list.d.ts').RootNode | undefined} */ var $o; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + var root = $o && $o.next; + var deletedNode = listDelete($o, key); + if (deletedNode && root && root === deletedNode) { + $o = void undefined; + } + return !!deletedNode; + }, + get: function (key) { + return listGet($o, key); + }, + has: function (key) { + return listHas($o, key); + }, + set: function (key, value) { + if (!$o) { + // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head + $o = { + next: void undefined + }; + } + // eslint-disable-next-line no-extra-parens + listSet(/** @type {NonNullable} */ ($o), key, value); + } + }; + // @ts-expect-error TODO: figure out why this is erroring + return channel; +}; diff --git a/node_modules/side-channel-list/list.d.ts b/node_modules/side-channel-list/list.d.ts new file mode 100644 index 000000000..2c759e253 --- /dev/null +++ b/node_modules/side-channel-list/list.d.ts @@ -0,0 +1,14 @@ +type ListNode = { + key: K; + next: undefined | ListNode; + value: T; +}; +type RootNode = { + next: undefined | ListNode; +}; + +export function listGetNode(list: RootNode, key: ListNode['key'], isDelete?: boolean): ListNode | undefined; +export function listGet(objects: undefined | RootNode, key: ListNode['key']): T | undefined; +export function listSet(objects: RootNode, key: ListNode['key'], value: T): void; +export function listHas(objects: undefined | RootNode, key: ListNode['key']): boolean; +export function listDelete(objects: undefined | RootNode, key: ListNode['key']): ListNode | undefined; diff --git a/node_modules/side-channel-list/package.json b/node_modules/side-channel-list/package.json new file mode 100644 index 000000000..ba0f5c581 --- /dev/null +++ b/node_modules/side-channel-list/package.json @@ -0,0 +1,77 @@ +{ + "name": "side-channel-list", + "version": "1.0.0", + "description": "Store information about any JS value in a side channel, using a linked list", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "evalmd README.md && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel-list.git" + }, + "keywords": [], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel-list/issues" + }, + "homepage": "https://github.com/ljharb/side-channel-list#readme", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel-list/test/index.js b/node_modules/side-channel-list/test/index.js new file mode 100644 index 000000000..3ad436879 --- /dev/null +++ b/node_modules/side-channel-list/test/index.js @@ -0,0 +1,104 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannelList = require('../'); + +test('getSideChannelList', function (t) { + t.test('export', function (st) { + st.equal(typeof getSideChannelList, 'function', 'is a function'); + + st.equal(getSideChannelList.length, 0, 'takes no arguments'); + + var channel = getSideChannelList(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannelList(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannelList(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannelList(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannelList(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannelList(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/side-channel-list/tsconfig.json b/node_modules/side-channel-list/tsconfig.json new file mode 100644 index 000000000..d9a6668c3 --- /dev/null +++ b/node_modules/side-channel-list/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/side-channel-map/.editorconfig b/node_modules/side-channel-map/.editorconfig new file mode 100644 index 000000000..72e0ebaa7 --- /dev/null +++ b/node_modules/side-channel-map/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel-map/.eslintrc b/node_modules/side-channel-map/.eslintrc new file mode 100644 index 000000000..93978e7d5 --- /dev/null +++ b/node_modules/side-channel-map/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel-map/.github/FUNDING.yml b/node_modules/side-channel-map/.github/FUNDING.yml new file mode 100644 index 000000000..f2891bd62 --- /dev/null +++ b/node_modules/side-channel-map/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel-map +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel-map/.nycrc b/node_modules/side-channel-map/.nycrc new file mode 100644 index 000000000..1826526e0 --- /dev/null +++ b/node_modules/side-channel-map/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel-map/CHANGELOG.md b/node_modules/side-channel-map/CHANGELOG.md new file mode 100644 index 000000000..b6ccea906 --- /dev/null +++ b/node_modules/side-channel-map/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/side-channel-map/compare/v1.0.0...v1.0.1) - 2024-12-10 + +### Commits + +- [Deps] update `call-bound` [`6d05aaa`](https://github.com/ljharb/side-channel-map/commit/6d05aaa4ce5f2be4e7825df433d650696f0ba40f) +- [types] fix generics ordering [`11c0184`](https://github.com/ljharb/side-channel-map/commit/11c0184132ac11fdc16857e12682e148e5e9ee74) + +## v1.0.0 - 2024-12-10 + +### Commits + +- Initial implementation, tests, readme, types [`ad877b4`](https://github.com/ljharb/side-channel-map/commit/ad877b42926d46d63fff76a2bd01d2b4a01959a9) +- Initial commit [`28f8879`](https://github.com/ljharb/side-channel-map/commit/28f8879c512abe8fcf9b6a4dc7754a0287e5eba4) +- npm init [`2c9604e`](https://github.com/ljharb/side-channel-map/commit/2c9604e5aa40223e425ea7cea78f8a07697504bd) +- Only apps should have lockfiles [`5e7ba9c`](https://github.com/ljharb/side-channel-map/commit/5e7ba9cffe3ef42095815adc8ac1255b49bbadf5) diff --git a/node_modules/side-channel-map/LICENSE b/node_modules/side-channel-map/LICENSE new file mode 100644 index 000000000..f82f38963 --- /dev/null +++ b/node_modules/side-channel-map/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +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/side-channel-map/README.md b/node_modules/side-channel-map/README.md new file mode 100644 index 000000000..8fa6f77f0 --- /dev/null +++ b/node_modules/side-channel-map/README.md @@ -0,0 +1,62 @@ +# side-channel-map [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel, using a Map. + +Warning: if the `key` is an object, this implementation will leak memory until you `delete` it. +Use [`side-channel`](https://npmjs.com/side-channel) for the best available strategy. + +## Getting started + +```sh +npm install --save side-channel-map +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannelMap = require('side-channel-map'); + +const channel = getSideChannelMap(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel-map +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel-map.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel-map.svg +[deps-url]: https://david-dm.org/ljharb/side-channel-map +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel-map/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel-map#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel-map.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel-map.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel-map.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel-map +[codecov-image]: https://codecov.io/gh/ljharb/side-channel-map/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel-map/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel-map +[actions-url]: https://github.com/ljharb/side-channel-map/actions diff --git a/node_modules/side-channel-map/index.d.ts b/node_modules/side-channel-map/index.d.ts new file mode 100644 index 000000000..de33e899e --- /dev/null +++ b/node_modules/side-channel-map/index.d.ts @@ -0,0 +1,15 @@ +declare namespace getSideChannelMap { + type Channel = { + assert: (key: K) => void; + has: (key: K) => boolean; + get: (key: K) => V | undefined; + set: (key: K, value: V) => void; + delete: (key: K) => boolean; + }; +} + +declare function getSideChannelMap(): getSideChannelMap.Channel; + +declare const x: false | typeof getSideChannelMap; + +export = x; diff --git a/node_modules/side-channel-map/index.js b/node_modules/side-channel-map/index.js new file mode 100644 index 000000000..e111100bf --- /dev/null +++ b/node_modules/side-channel-map/index.js @@ -0,0 +1,68 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bound'); +var inspect = require('object-inspect'); + +var $TypeError = require('es-errors/type'); +var $Map = GetIntrinsic('%Map%', true); + +/** @type {(thisArg: Map, key: K) => V} */ +var $mapGet = callBound('Map.prototype.get', true); +/** @type {(thisArg: Map, key: K, value: V) => void} */ +var $mapSet = callBound('Map.prototype.set', true); +/** @type {(thisArg: Map, key: K) => boolean} */ +var $mapHas = callBound('Map.prototype.has', true); +/** @type {(thisArg: Map, key: K) => boolean} */ +var $mapDelete = callBound('Map.prototype.delete', true); +/** @type {(thisArg: Map) => number} */ +var $mapSize = callBound('Map.prototype.size', true); + +/** @type {import('.')} */ +module.exports = !!$Map && /** @type {Exclude} */ function getSideChannelMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {Map | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($m) { + var result = $mapDelete($m, key); + if ($mapSize($m) === 0) { + $m = void undefined; + } + return result; + } + return false; + }, + get: function (key) { // eslint-disable-line consistent-return + if ($m) { + return $mapGet($m, key); + } + }, + has: function (key) { + if ($m) { + return $mapHas($m, key); + } + return false; + }, + set: function (key, value) { + if (!$m) { + // @ts-expect-error TS can't handle narrowing a variable inside a closure + $m = new $Map(); + } + $mapSet($m, key, value); + } + }; + + // @ts-expect-error TODO: figure out why TS is erroring here + return channel; +}; diff --git a/node_modules/side-channel-map/package.json b/node_modules/side-channel-map/package.json new file mode 100644 index 000000000..18e808059 --- /dev/null +++ b/node_modules/side-channel-map/package.json @@ -0,0 +1,80 @@ +{ + "name": "side-channel-map", + "version": "1.0.1", + "description": "Store information about any JS value in a side channel, using a Map", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "evalmd README.md && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel-map.git" + }, + "keywords": [], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel-map/issues" + }, + "homepage": "https://github.com/ljharb/side-channel-map#readme", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/get-intrinsic": "^1.2.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel-map/test/index.js b/node_modules/side-channel-map/test/index.js new file mode 100644 index 000000000..17433239e --- /dev/null +++ b/node_modules/side-channel-map/test/index.js @@ -0,0 +1,114 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannelMap = require('../'); + +test('getSideChannelMap', { skip: typeof Map !== 'function' }, function (t) { + var getSideChannel = getSideChannelMap || function () { + throw new EvalError('should never happen'); + }; + + t.test('export', function (st) { + st.equal(typeof getSideChannel, 'function', 'is a function'); + + st.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannel(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannel(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); + +test('getSideChannelMap, no Maps', { skip: typeof Map === 'function' }, function (t) { + t.equal(getSideChannelMap, false, 'is false'); + + t.end(); +}); diff --git a/node_modules/side-channel-map/tsconfig.json b/node_modules/side-channel-map/tsconfig.json new file mode 100644 index 000000000..d9a6668c3 --- /dev/null +++ b/node_modules/side-channel-map/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/side-channel-weakmap/.editorconfig b/node_modules/side-channel-weakmap/.editorconfig new file mode 100644 index 000000000..72e0ebaa7 --- /dev/null +++ b/node_modules/side-channel-weakmap/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel-weakmap/.eslintrc b/node_modules/side-channel-weakmap/.eslintrc new file mode 100644 index 000000000..9b13ad8ba --- /dev/null +++ b/node_modules/side-channel-weakmap/.eslintrc @@ -0,0 +1,12 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel-weakmap/.github/FUNDING.yml b/node_modules/side-channel-weakmap/.github/FUNDING.yml new file mode 100644 index 000000000..2ae71cdb9 --- /dev/null +++ b/node_modules/side-channel-weakmap/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel-weakmap +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel-weakmap/.nycrc b/node_modules/side-channel-weakmap/.nycrc new file mode 100644 index 000000000..1826526e0 --- /dev/null +++ b/node_modules/side-channel-weakmap/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel-weakmap/CHANGELOG.md b/node_modules/side-channel-weakmap/CHANGELOG.md new file mode 100644 index 000000000..aba7ab041 --- /dev/null +++ b/node_modules/side-channel-weakmap/CHANGELOG.md @@ -0,0 +1,28 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/ljharb/side-channel-weakmap/compare/v1.0.1...v1.0.2) - 2024-12-10 + +### Commits + +- [types] fix generics ordering [`1b62e94`](https://github.com/ljharb/side-channel-weakmap/commit/1b62e94a2ad6ed30b640ba73c4a2535836c67289) + +## [v1.0.1](https://github.com/ljharb/side-channel-weakmap/compare/v1.0.0...v1.0.1) - 2024-12-10 + +### Commits + +- [types] fix generics ordering [`08a4a5d`](https://github.com/ljharb/side-channel-weakmap/commit/08a4a5dbffedc3ebc79f1aaaf5a3dd6d2196dc1b) +- [Deps] update `side-channel-map` [`b53fe44`](https://github.com/ljharb/side-channel-weakmap/commit/b53fe447dfdd3a9aebedfd015b384eac17fce916) + +## v1.0.0 - 2024-12-10 + +### Commits + +- Initial implementation, tests, readme, types [`53c0fa4`](https://github.com/ljharb/side-channel-weakmap/commit/53c0fa4788435a006f58b9d7b43cb65989ecee49) +- Initial commit [`a157947`](https://github.com/ljharb/side-channel-weakmap/commit/a157947f26fcaf2c4a941d3a044e76bf67343532) +- npm init [`54dfc55`](https://github.com/ljharb/side-channel-weakmap/commit/54dfc55bafb16265910d5aad4e743c43aee5bbbb) +- Only apps should have lockfiles [`0ddd6c7`](https://github.com/ljharb/side-channel-weakmap/commit/0ddd6c7b07fe8ee04d67b2e9f7255af7ce62c07d) diff --git a/node_modules/side-channel-weakmap/LICENSE b/node_modules/side-channel-weakmap/LICENSE new file mode 100644 index 000000000..3900dd7e2 --- /dev/null +++ b/node_modules/side-channel-weakmap/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +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/side-channel-weakmap/README.md b/node_modules/side-channel-weakmap/README.md new file mode 100644 index 000000000..856ee3643 --- /dev/null +++ b/node_modules/side-channel-weakmap/README.md @@ -0,0 +1,62 @@ +# side-channel-weakmap [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel. Uses WeakMap if available. + +Warning: this implementation will leak memory until you `delete` the `key`. +Use [`side-channel`](https://npmjs.com/side-channel) for the best available strategy. + +## Getting started + +```sh +npm install --save side-channel-weakmap +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannelList = require('side-channel-weakmap'); + +const channel = getSideChannelList(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel-weakmap +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel-weakmap.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel-weakmap.svg +[deps-url]: https://david-dm.org/ljharb/side-channel-weakmap +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel-weakmap/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel-weakmap#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel-weakmap.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel-weakmap.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel-weakmap.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel-weakmap +[codecov-image]: https://codecov.io/gh/ljharb/side-channel-weakmap/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel-weakmap/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel-weakmap +[actions-url]: https://github.com/ljharb/side-channel-weakmap/actions diff --git a/node_modules/side-channel-weakmap/index.d.ts b/node_modules/side-channel-weakmap/index.d.ts new file mode 100644 index 000000000..ce1bc2a4a --- /dev/null +++ b/node_modules/side-channel-weakmap/index.d.ts @@ -0,0 +1,15 @@ +declare namespace getSideChannelWeakMap { + type Channel = { + assert: (key: K) => void; + has: (key: K) => boolean; + get: (key: K) => V | undefined; + set: (key: K, value: V) => void; + delete: (key: K) => boolean; + } +} + +declare function getSideChannelWeakMap(): getSideChannelWeakMap.Channel; + +declare const x: false | typeof getSideChannelWeakMap; + +export = x; diff --git a/node_modules/side-channel-weakmap/index.js b/node_modules/side-channel-weakmap/index.js new file mode 100644 index 000000000..e5b8183d9 --- /dev/null +++ b/node_modules/side-channel-weakmap/index.js @@ -0,0 +1,84 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bound'); +var inspect = require('object-inspect'); +var getSideChannelMap = require('side-channel-map'); + +var $TypeError = require('es-errors/type'); +var $WeakMap = GetIntrinsic('%WeakMap%', true); + +/** @type {(thisArg: WeakMap, key: K) => V} */ +var $weakMapGet = callBound('WeakMap.prototype.get', true); +/** @type {(thisArg: WeakMap, key: K, value: V) => void} */ +var $weakMapSet = callBound('WeakMap.prototype.set', true); +/** @type {(thisArg: WeakMap, key: K) => boolean} */ +var $weakMapHas = callBound('WeakMap.prototype.has', true); +/** @type {(thisArg: WeakMap, key: K) => boolean} */ +var $weakMapDelete = callBound('WeakMap.prototype.delete', true); + +/** @type {import('.')} */ +module.exports = $WeakMap + ? /** @type {Exclude} */ function getSideChannelWeakMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {WeakMap | undefined} */ var $wm; + /** @type {Channel | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapDelete($wm, key); + } + } else if (getSideChannelMap) { + if ($m) { + return $m['delete'](key); + } + } + return false; + }, + get: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } + return $m && $m.get(key); + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } + return !!$m && $m.has(key); + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if (getSideChannelMap) { + if (!$m) { + $m = getSideChannelMap(); + } + // eslint-disable-next-line no-extra-parens + /** @type {NonNullable} */ ($m).set(key, value); + } + } + }; + + // @ts-expect-error TODO: figure out why this is erroring + return channel; + } + : getSideChannelMap; diff --git a/node_modules/side-channel-weakmap/package.json b/node_modules/side-channel-weakmap/package.json new file mode 100644 index 000000000..9ef658333 --- /dev/null +++ b/node_modules/side-channel-weakmap/package.json @@ -0,0 +1,87 @@ +{ + "name": "side-channel-weakmap", + "version": "1.0.2", + "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel-weakmap.git" + }, + "keywords": [ + "weakmap", + "map", + "side", + "channel", + "metadata" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel-weakmap/issues" + }, + "homepage": "https://github.com/ljharb/side-channel-weakmap#readme", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/call-bind": "^1.0.5", + "@types/get-intrinsic": "^1.2.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel-weakmap/test/index.js b/node_modules/side-channel-weakmap/test/index.js new file mode 100644 index 000000000..a01248b57 --- /dev/null +++ b/node_modules/side-channel-weakmap/test/index.js @@ -0,0 +1,114 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannelWeakMap = require('../'); + +test('getSideChannelMap', { skip: typeof WeakMap !== 'function' && typeof Map !== 'function' }, function (t) { + var getSideChannel = getSideChannelWeakMap || function () { + throw new EvalError('should never happen'); + }; + + t.test('export', function (st) { + st.equal(typeof getSideChannel, 'function', 'is a function'); + + st.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannel(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannel(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); + +test('getSideChannelMap, no WeakMaps and/or Maps', { skip: typeof WeakMap === 'function' || typeof Map === 'function' }, function (t) { + t.equal(getSideChannelWeakMap, false, 'is false'); + + t.end(); +}); diff --git a/node_modules/side-channel-weakmap/tsconfig.json b/node_modules/side-channel-weakmap/tsconfig.json new file mode 100644 index 000000000..d9a6668c3 --- /dev/null +++ b/node_modules/side-channel-weakmap/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/side-channel/.editorconfig b/node_modules/side-channel/.editorconfig new file mode 100644 index 000000000..72e0ebaa7 --- /dev/null +++ b/node_modules/side-channel/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel/.eslintrc b/node_modules/side-channel/.eslintrc new file mode 100644 index 000000000..9b13ad8ba --- /dev/null +++ b/node_modules/side-channel/.eslintrc @@ -0,0 +1,12 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel/.github/FUNDING.yml b/node_modules/side-channel/.github/FUNDING.yml new file mode 100644 index 000000000..2a94840c6 --- /dev/null +++ b/node_modules/side-channel/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel/.nycrc b/node_modules/side-channel/.nycrc new file mode 100644 index 000000000..1826526e0 --- /dev/null +++ b/node_modules/side-channel/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel/CHANGELOG.md b/node_modules/side-channel/CHANGELOG.md new file mode 100644 index 000000000..58e378c72 --- /dev/null +++ b/node_modules/side-channel/CHANGELOG.md @@ -0,0 +1,110 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.0](https://github.com/ljharb/side-channel/compare/v1.0.6...v1.1.0) - 2024-12-11 + +### Commits + +- [Refactor] extract implementations to `side-channel-weakmap`, `side-channel-map`, `side-channel-list` [`ada5955`](https://github.com/ljharb/side-channel/commit/ada595549a5c4c6c853756d598846b180941c6da) +- [New] add `channel.delete` [`c01d2d3`](https://github.com/ljharb/side-channel/commit/c01d2d3fd51dbb1ce6da72ad7916e61bd6172aad) +- [types] improve types [`0c54356`](https://github.com/ljharb/side-channel/commit/0c5435651417df41b8cc1a5f7cdce8bffae68cde) +- [readme] add content [`be24868`](https://github.com/ljharb/side-channel/commit/be248682ac294b0e22c883092c45985aa91c490a) +- [actions] split out node 10-20, and 20+ [`c4488e2`](https://github.com/ljharb/side-channel/commit/c4488e241ef3d49a19fe266ac830a2e644305911) +- [types] use shared tsconfig [`0e0d57c`](https://github.com/ljharb/side-channel/commit/0e0d57c2ff17c7b45c6cbd43ebcf553edc9e3adc) +- [Dev Deps] update `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/get-intrinsic`, `@types/object-inspect`, `@types/tape`, `auto-changelog`, `tape` [`fb4f622`](https://github.com/ljharb/side-channel/commit/fb4f622e64a99a1e40b6e5cd7691674a9dc429e4) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`b78336b`](https://github.com/ljharb/side-channel/commit/b78336b886172d1b457d414ac9e28de8c5fecc78) +- [Tests] replace `aud` with `npm audit` [`ee3ab46`](https://github.com/ljharb/side-channel/commit/ee3ab4690d954311c35115651bcfd45edd205aa1) +- [Dev Deps] add missing peer dep [`c03e21a`](https://github.com/ljharb/side-channel/commit/c03e21a7def3b67cdc15ae22316884fefcb2f6a8) + +## [v1.0.6](https://github.com/ljharb/side-channel/compare/v1.0.5...v1.0.6) - 2024-02-29 + +### Commits + +- add types [`9beef66`](https://github.com/ljharb/side-channel/commit/9beef6643e6d717ea57bedabf86448123a7dd9e9) +- [meta] simplify `exports` [`4334cf9`](https://github.com/ljharb/side-channel/commit/4334cf9df654151504c383b62a2f9ebdc8d9d5ac) +- [Deps] update `call-bind` [`d6043c4`](https://github.com/ljharb/side-channel/commit/d6043c4d8f4d7be9037dd0f0419c7a2e0e39ec6a) +- [Dev Deps] update `tape` [`6aca376`](https://github.com/ljharb/side-channel/commit/6aca3761868dc8cd5ff7fd9799bf6b95e09a6eb0) + +## [v1.0.5](https://github.com/ljharb/side-channel/compare/v1.0.4...v1.0.5) - 2024-02-06 + +### Commits + +- [actions] reuse common workflows [`3d2e1ff`](https://github.com/ljharb/side-channel/commit/3d2e1ffd16dd6eaaf3e40ff57951f840d2d63c04) +- [meta] use `npmignore` to autogenerate an npmignore file [`04296ea`](https://github.com/ljharb/side-channel/commit/04296ea17d1544b0a5d20fd5bfb31aa4f6513eb9) +- [meta] add `.editorconfig`; add `eclint` [`130f0a6`](https://github.com/ljharb/side-channel/commit/130f0a6adbc04d385c7456a601d38344dce3d6a9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `safe-publish-latest`, `tape` [`d480c2f`](https://github.com/ljharb/side-channel/commit/d480c2fbe757489ae9b4275491ffbcc3ac4725e9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`ecbe70e`](https://github.com/ljharb/side-channel/commit/ecbe70e53a418234081a77971fec1fdfae20c841) +- [actions] update rebase action [`75240b9`](https://github.com/ljharb/side-channel/commit/75240b9963b816e8846400d2287cb68f88c7fba7) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`ae8d281`](https://github.com/ljharb/side-channel/commit/ae8d281572430099109870fd9430d2ca3f320b8d) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`7125b88`](https://github.com/ljharb/side-channel/commit/7125b885fd0eacad4fee9b073b72d14065ece278) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`82577c9`](https://github.com/ljharb/side-channel/commit/82577c9796304519139a570f82a317211b5f3b86) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`550aadf`](https://github.com/ljharb/side-channel/commit/550aadf20475a6081fd70304cc54f77259a5c8a8) +- [Tests] increase coverage [`5130877`](https://github.com/ljharb/side-channel/commit/5130877a7b27c862e64e6d1c12a178b28808859d) +- [Deps] update `get-intrinsic`, `object-inspect` [`ba0194c`](https://github.com/ljharb/side-channel/commit/ba0194c505b1a8a0427be14cadd5b8a46d4d01b8) +- [meta] add missing `engines.node` [`985fd24`](https://github.com/ljharb/side-channel/commit/985fd249663cb06617a693a94fe08cad12f5cb70) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`40227a8`](https://github.com/ljharb/side-channel/commit/40227a87b01709ad2c0eebf87eb4223a800099b9) +- [Deps] update `get-intrinsic` [`a989b40`](https://github.com/ljharb/side-channel/commit/a989b4024958737ae7be9fbffdeff2078f33a0fd) +- [Deps] update `object-inspect` [`aec42d2`](https://github.com/ljharb/side-channel/commit/aec42d2ec541a31aaa02475692c87d489237d9a3) + +## [v1.0.4](https://github.com/ljharb/side-channel/compare/v1.0.3...v1.0.4) - 2020-12-29 + +### Commits + +- [Tests] migrate tests to Github Actions [`10909cb`](https://github.com/ljharb/side-channel/commit/10909cbf8ce9c0bf96f604cf13d7ffd5a22c2d40) +- [Refactor] Use a linked list rather than an array, and move accessed nodes to the beginning [`195613f`](https://github.com/ljharb/side-channel/commit/195613f28b5c1e6072ef0b61b5beebaf2b6a304e) +- [meta] do not publish github action workflow files [`290ec29`](https://github.com/ljharb/side-channel/commit/290ec29cd21a60585145b4a7237ec55228c52c27) +- [Tests] run `nyc` on all tests; use `tape` runner [`ea6d030`](https://github.com/ljharb/side-channel/commit/ea6d030ff3fe6be2eca39e859d644c51ecd88869) +- [actions] add "Allow Edits" workflow [`d464d8f`](https://github.com/ljharb/side-channel/commit/d464d8fe52b5eddf1504a0ed97f0941a90f32c15) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`02daca8`](https://github.com/ljharb/side-channel/commit/02daca87c6809821c97be468d1afa2f5ef447383) +- [Refactor] use `call-bind` and `get-intrinsic` instead of `es-abstract` [`e09d481`](https://github.com/ljharb/side-channel/commit/e09d481528452ebafa5cdeae1af665c35aa2deee) +- [Deps] update `object.assign` [`ee83aa8`](https://github.com/ljharb/side-channel/commit/ee83aa81df313b5e46319a63adb05cf0c179079a) +- [actions] update rebase action to use checkout v2 [`7726b0b`](https://github.com/ljharb/side-channel/commit/7726b0b058b632fccea709f58960871defaaa9d7) + +## [v1.0.3](https://github.com/ljharb/side-channel/compare/v1.0.2...v1.0.3) - 2020-08-23 + +### Commits + +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`1f10561`](https://github.com/ljharb/side-channel/commit/1f105611ef3acf32dec8032ae5c0baa5e56bb868) +- [Deps] update `es-abstract`, `object-inspect` [`bc20159`](https://github.com/ljharb/side-channel/commit/bc201597949a505e37cef9eaf24c7010831e6f03) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`b9b2b22`](https://github.com/ljharb/side-channel/commit/b9b2b225f9e0ea72a6ec2b89348f0bd690bc9ed1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`7055ab4`](https://github.com/ljharb/side-channel/commit/7055ab4de0860606efd2003674a74f1fe6ebc07e) +- [Dev Deps] update `auto-changelog`; add `aud` [`d278c37`](https://github.com/ljharb/side-channel/commit/d278c37d08227be4f84aa769fcd919e73feeba40) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`3bcf982`](https://github.com/ljharb/side-channel/commit/3bcf982faa122745b39c33ce83d32fdf003741c6) +- [Tests] only audit prod deps [`18d01c4`](https://github.com/ljharb/side-channel/commit/18d01c4015b82a3d75044c4d5ba7917b2eac01ec) +- [Deps] update `es-abstract` [`6ab096d`](https://github.com/ljharb/side-channel/commit/6ab096d9de2b482cf5e0717e34e212f5b2b9bc9a) +- [Dev Deps] update `tape` [`9dc174c`](https://github.com/ljharb/side-channel/commit/9dc174cc651dfd300b4b72da936a0a7eda5f9452) +- [Deps] update `es-abstract` [`431d0f0`](https://github.com/ljharb/side-channel/commit/431d0f0ff11fbd2ae6f3115582a356d3a1cfce82) +- [Deps] update `es-abstract` [`49869fd`](https://github.com/ljharb/side-channel/commit/49869fd323bf4453f0ba515c0fb265cf5ab7b932) +- [meta] Add package.json to package's exports [`77d9cdc`](https://github.com/ljharb/side-channel/commit/77d9cdceb2a9e47700074f2ae0c0a202e7dac0d4) + +## [v1.0.2](https://github.com/ljharb/side-channel/compare/v1.0.1...v1.0.2) - 2019-12-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`4a526df`](https://github.com/ljharb/side-channel/commit/4a526df44e4701566ed001ec78546193f818b082) +- [Deps] update `es-abstract` [`d4f6e62`](https://github.com/ljharb/side-channel/commit/d4f6e629b6fb93a07415db7f30d3c90fd7f264fe) + +## [v1.0.1](https://github.com/ljharb/side-channel/compare/v1.0.0...v1.0.1) - 2019-12-01 + +### Commits + +- [Fix] add missing "exports" [`d212907`](https://github.com/ljharb/side-channel/commit/d2129073abf0701a5343bf28aa2145617604dc2e) + +## v1.0.0 - 2019-12-01 + +### Commits + +- Initial implementation [`dbebd3a`](https://github.com/ljharb/side-channel/commit/dbebd3a4b5ed64242f9a6810efe7c4214cd8cde4) +- Initial tests [`73bdefe`](https://github.com/ljharb/side-channel/commit/73bdefe568c9076cf8c0b8719bc2141aec0e19b8) +- Initial commit [`43c03e1`](https://github.com/ljharb/side-channel/commit/43c03e1c2849ec50a87b7a5cd76238a62b0b8770) +- npm init [`5c090a7`](https://github.com/ljharb/side-channel/commit/5c090a765d66a5527d9889b89aeff78dee91348c) +- [meta] add `auto-changelog` [`a5c4e56`](https://github.com/ljharb/side-channel/commit/a5c4e5675ec02d5eb4d84b4243aeea2a1d38fbec) +- [actions] add automatic rebasing / merge commit blocking [`bab1683`](https://github.com/ljharb/side-channel/commit/bab1683d8f9754b086e94397699fdc645e0d7077) +- [meta] add `funding` field; create FUNDING.yml [`63d7aea`](https://github.com/ljharb/side-channel/commit/63d7aeaf34f5650650ae97ca4b9fae685bd0937c) +- [Tests] add `npm run lint` [`46a5a81`](https://github.com/ljharb/side-channel/commit/46a5a81705cd2664f83df232c01dbbf2ee952885) +- Only apps should have lockfiles [`8b16b03`](https://github.com/ljharb/side-channel/commit/8b16b0305f00895d90c4e2e5773c854cfea0e448) +- [meta] add `safe-publish-latest` [`2f098ef`](https://github.com/ljharb/side-channel/commit/2f098ef092a39399cfe548b19a1fc03c2fd2f490) diff --git a/node_modules/side-channel/LICENSE b/node_modules/side-channel/LICENSE new file mode 100644 index 000000000..3900dd7e2 --- /dev/null +++ b/node_modules/side-channel/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +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/side-channel/README.md b/node_modules/side-channel/README.md new file mode 100644 index 000000000..cc7e10358 --- /dev/null +++ b/node_modules/side-channel/README.md @@ -0,0 +1,61 @@ +# side-channel [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel. Uses WeakMap if available. + +Warning: in an environment that lacks `WeakMap`, this implementation will leak memory until you `delete` the `key`. + +## Getting started + +```sh +npm install --save side-channel +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannel = require('side-channel'); + +const channel = getSideChannel(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel.svg +[deps-url]: https://david-dm.org/ljharb/side-channel +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel +[codecov-image]: https://codecov.io/gh/ljharb/side-channel/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel +[actions-url]: https://github.com/ljharb/side-channel/actions diff --git a/node_modules/side-channel/index.d.ts b/node_modules/side-channel/index.d.ts new file mode 100644 index 000000000..18c63171c --- /dev/null +++ b/node_modules/side-channel/index.d.ts @@ -0,0 +1,14 @@ +import getSideChannelList from 'side-channel-list'; +import getSideChannelMap from 'side-channel-map'; +import getSideChannelWeakMap from 'side-channel-weakmap'; + +declare namespace getSideChannel { + type Channel = + | getSideChannelList.Channel + | ReturnType, false>> + | ReturnType, false>>; +} + +declare function getSideChannel(): getSideChannel.Channel; + +export = getSideChannel; diff --git a/node_modules/side-channel/index.js b/node_modules/side-channel/index.js new file mode 100644 index 000000000..a8a9b0559 --- /dev/null +++ b/node_modules/side-channel/index.js @@ -0,0 +1,43 @@ +'use strict'; + +var $TypeError = require('es-errors/type'); +var inspect = require('object-inspect'); +var getSideChannelList = require('side-channel-list'); +var getSideChannelMap = require('side-channel-map'); +var getSideChannelWeakMap = require('side-channel-weakmap'); + +var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList; + +/** @type {import('.')} */ +module.exports = function getSideChannel() { + /** @typedef {ReturnType} Channel */ + + /** @type {Channel | undefined} */ var $channelData; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + return !!$channelData && $channelData['delete'](key); + }, + get: function (key) { + return $channelData && $channelData.get(key); + }, + has: function (key) { + return !!$channelData && $channelData.has(key); + }, + set: function (key, value) { + if (!$channelData) { + $channelData = makeChannel(); + } + + $channelData.set(key, value); + } + }; + // @ts-expect-error TODO: figure out why this is erroring + return channel; +}; diff --git a/node_modules/side-channel/package.json b/node_modules/side-channel/package.json new file mode 100644 index 000000000..30fa42cd8 --- /dev/null +++ b/node_modules/side-channel/package.json @@ -0,0 +1,85 @@ +{ + "name": "side-channel", + "version": "1.1.0", + "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel.git" + }, + "keywords": [ + "weakmap", + "map", + "side", + "channel", + "metadata" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel/issues" + }, + "homepage": "https://github.com/ljharb/side-channel#readme", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel/test/index.js b/node_modules/side-channel/test/index.js new file mode 100644 index 000000000..bd1e7c2a2 --- /dev/null +++ b/node_modules/side-channel/test/index.js @@ -0,0 +1,104 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannel = require('../'); + +test('getSideChannel', function (t) { + t.test('export', function (st) { + st.equal(typeof getSideChannel, 'function', 'is a function'); + + st.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannel(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannel(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/side-channel/tsconfig.json b/node_modules/side-channel/tsconfig.json new file mode 100644 index 000000000..d9a6668c3 --- /dev/null +++ b/node_modules/side-channel/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/statuses/HISTORY.md b/node_modules/statuses/HISTORY.md new file mode 100644 index 000000000..dc549b821 --- /dev/null +++ b/node_modules/statuses/HISTORY.md @@ -0,0 +1,87 @@ +2.0.2 / 2025-06-06 +================== + + * Migrate to `String.prototype.slice()` + +2.0.1 / 2021-01-03 +================== + + * Fix returning values from `Object.prototype` + +2.0.0 / 2020-04-19 +================== + + * Drop support for Node.js 0.6 + * Fix messaging casing of `418 I'm a Teapot` + * Remove code 306 + * Remove `status[code]` exports; use `status.message[code]` + * Remove `status[msg]` exports; use `status.code[msg]` + * Rename `425 Unordered Collection` to standard `425 Too Early` + * Rename `STATUS_CODES` export to `message` + * Return status message for `statuses(code)` when given code + +1.5.0 / 2018-03-27 +================== + + * Add `103 Early Hints` + +1.4.0 / 2017-10-20 +================== + + * Add `STATUS_CODES` export + +1.3.1 / 2016-11-11 +================== + + * Fix return type in JSDoc + +1.3.0 / 2016-05-17 +================== + + * Add `421 Misdirected Request` + * perf: enable strict mode + +1.2.1 / 2015-02-01 +================== + + * Fix message for status 451 + - `451 Unavailable For Legal Reasons` + +1.2.0 / 2014-09-28 +================== + + * Add `208 Already Repored` + * Add `226 IM Used` + * Add `306 (Unused)` + * Add `415 Unable For Legal Reasons` + * Add `508 Loop Detected` + +1.1.1 / 2014-09-24 +================== + + * Add missing 308 to `codes.json` + +1.1.0 / 2014-09-21 +================== + + * Add `codes.json` for universal support + +1.0.4 / 2014-08-20 +================== + + * Package cleanup + +1.0.3 / 2014-06-08 +================== + + * Add 308 to `.redirect` category + +1.0.2 / 2014-03-13 +================== + + * Add `.retry` category + +1.0.1 / 2014-03-12 +================== + + * Initial release diff --git a/node_modules/statuses/LICENSE b/node_modules/statuses/LICENSE new file mode 100644 index 000000000..28a316182 --- /dev/null +++ b/node_modules/statuses/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2016 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/statuses/README.md b/node_modules/statuses/README.md new file mode 100644 index 000000000..89d542f6a --- /dev/null +++ b/node_modules/statuses/README.md @@ -0,0 +1,139 @@ +# statuses + +[![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][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] + +HTTP status utility for node. + +This module provides a list of status codes and messages sourced from +a few different projects: + + * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) + * The [Node.js project](https://nodejs.org/) + * The [NGINX project](https://www.nginx.com/) + * The [Apache HTTP Server project](https://httpd.apache.org/) + +## 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 statuses +``` + +## API + + + +```js +var status = require('statuses') +``` + +### status(code) + +Returns the status message string for a known HTTP status code. The code +may be a number or a string. An error is thrown for an unknown status code. + + + +```js +status(403) // => 'Forbidden' +status('403') // => 'Forbidden' +status(306) // throws +``` + +### status(msg) + +Returns the numeric status code for a known HTTP status message. The message +is case-insensitive. An error is thrown for an unknown status message. + + + +```js +status('forbidden') // => 403 +status('Forbidden') // => 403 +status('foo') // throws +``` + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### status.code[msg] + +Returns the numeric status code for a known status message (in lower-case), +otherwise `undefined`. + + + +```js +status['not found'] // => 404 +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + + + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.message[code] + +Returns the string message for a known numeric status code, otherwise +`undefined`. This object is the same format as the +[Node.js http module `http.STATUS_CODES`](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). + + + +```js +status.message[404] // => 'Not Found' +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + + + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + + + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/statuses/master?label=ci +[ci-url]: https://github.com/jshttp/statuses/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/statuses/master +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[node-version-image]: https://badgen.net/npm/node/statuses +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/statuses +[npm-url]: https://npmjs.org/package/statuses +[npm-version-image]: https://badgen.net/npm/v/statuses +[ossf-scorecard-badge]: https://api.securityscorecards.dev/projects/github.com/jshttp/statuses/badge +[ossf-scorecard-visualizer]: https://kooltheba.github.io/openssf-scorecard-api-visualizer/#/projects/github.com/jshttp/statuses diff --git a/node_modules/statuses/codes.json b/node_modules/statuses/codes.json new file mode 100644 index 000000000..1333ed10b --- /dev/null +++ b/node_modules/statuses/codes.json @@ -0,0 +1,65 @@ +{ + "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" +} diff --git a/node_modules/statuses/index.js b/node_modules/statuses/index.js new file mode 100644 index 000000000..ea351c553 --- /dev/null +++ b/node_modules/statuses/index.js @@ -0,0 +1,146 @@ +/*! + * statuses + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var codes = require('./codes.json') + +/** + * Module exports. + * @public + */ + +module.exports = status + +// status code to message map +status.message = codes + +// status message (lower-case) to code map +status.code = createMessageToStatusCodeMap(codes) + +// array of status codes +status.codes = createStatusCodeList(codes) + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true +} + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true +} + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true +} + +/** + * Create a map of message to status code. + * @private + */ + +function createMessageToStatusCodeMap (codes) { + var map = {} + + Object.keys(codes).forEach(function forEachCode (code) { + var message = codes[code] + var status = Number(code) + + // populate map + map[message.toLowerCase()] = status + }) + + return map +} + +/** + * Create a list of all status codes. + * @private + */ + +function createStatusCodeList (codes) { + return Object.keys(codes).map(function mapCode (code) { + return Number(code) + }) +} + +/** + * Get the status code for given message. + * @private + */ + +function getStatusCode (message) { + var msg = message.toLowerCase() + + if (!Object.prototype.hasOwnProperty.call(status.code, msg)) { + throw new Error('invalid status message: "' + message + '"') + } + + return status.code[msg] +} + +/** + * Get the status message for given code. + * @private + */ + +function getStatusMessage (code) { + if (!Object.prototype.hasOwnProperty.call(status.message, code)) { + throw new Error('invalid status code: ' + code) + } + + return status.message[code] +} + +/** + * Get the status code. + * + * Given a number, this will throw if it is not a known status + * code, otherwise the code will be returned. Given a string, + * the string will be parsed for a number and return the code + * if valid, otherwise will lookup the code assuming this is + * the status message. + * + * @param {string|number} code + * @returns {number} + * @public + */ + +function status (code) { + if (typeof code === 'number') { + return getStatusMessage(code) + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string') + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + return getStatusMessage(n) + } + + return getStatusCode(code) +} diff --git a/node_modules/statuses/package.json b/node_modules/statuses/package.json new file mode 100644 index 000000000..b5d016edd --- /dev/null +++ b/node_modules/statuses/package.json @@ -0,0 +1,49 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "2.0.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "jshttp/statuses", + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "HISTORY.md", + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "4.16.3", + "eslint": "7.19.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.31.0", + "eslint-plugin-markdown": "1.0.2", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0", + "raw-body": "2.5.2", + "stream-to-array": "2.3.0" + }, + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "build": "node scripts/build.js", + "fetch": "node scripts/fetch-apache.js && node scripts/fetch-iana.js && node scripts/fetch-nginx.js && node scripts/fetch-node.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/toidentifier/HISTORY.md b/node_modules/toidentifier/HISTORY.md new file mode 100644 index 000000000..cb7cc8927 --- /dev/null +++ b/node_modules/toidentifier/HISTORY.md @@ -0,0 +1,9 @@ +1.0.1 / 2021-11-14 +================== + + * pref: enable strict mode + +1.0.0 / 2018-07-09 +================== + + * Initial release diff --git a/node_modules/toidentifier/LICENSE b/node_modules/toidentifier/LICENSE new file mode 100644 index 000000000..de22d1597 --- /dev/null +++ b/node_modules/toidentifier/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 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/toidentifier/README.md b/node_modules/toidentifier/README.md new file mode 100644 index 000000000..57e8a78ab --- /dev/null +++ b/node_modules/toidentifier/README.md @@ -0,0 +1,61 @@ +# toidentifier + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][codecov-image]][codecov-url] + +> Convert a string of words to a JavaScript identifier + +## Install + +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): + +```bash +$ npm install toidentifier +``` + +## Example + +```js +var toIdentifier = require('toidentifier') + +console.log(toIdentifier('Bad Request')) +// => "BadRequest" +``` + +## API + +This CommonJS module exports a single default function: `toIdentifier`. + +### toIdentifier(string) + +Given a string as the argument, it will be transformed according to +the following rules and the new string will be returned: + +1. Split into words separated by space characters (`0x20`). +2. Upper case the first character of each word. +3. Join the words together with no separator. +4. Remove all non-word (`[0-9a-z_]`) characters. + +## License + +[MIT](LICENSE) + +[codecov-image]: https://img.shields.io/codecov/c/github/component/toidentifier.svg +[codecov-url]: https://codecov.io/gh/component/toidentifier +[downloads-image]: https://img.shields.io/npm/dm/toidentifier.svg +[downloads-url]: https://npmjs.org/package/toidentifier +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/component/toidentifier/ci/master?label=ci +[github-actions-ci-url]: https://github.com/component/toidentifier?query=workflow%3Aci +[npm-image]: https://img.shields.io/npm/v/toidentifier.svg +[npm-url]: https://npmjs.org/package/toidentifier + + +## + +[npm]: https://www.npmjs.com/ + +[yarn]: https://yarnpkg.com/ diff --git a/node_modules/toidentifier/index.js b/node_modules/toidentifier/index.js new file mode 100644 index 000000000..9295d024a --- /dev/null +++ b/node_modules/toidentifier/index.js @@ -0,0 +1,32 @@ +/*! + * toidentifier + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = toIdentifier + +/** + * Trasform the given string into a JavaScript identifier + * + * @param {string} str + * @returns {string} + * @public + */ + +function toIdentifier (str) { + return str + .split(' ') + .map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }) + .join('') + .replace(/[^ _0-9a-z]/gi, '') +} diff --git a/node_modules/toidentifier/package.json b/node_modules/toidentifier/package.json new file mode 100644 index 000000000..42db1a664 --- /dev/null +++ b/node_modules/toidentifier/package.json @@ -0,0 +1,38 @@ +{ + "name": "toidentifier", + "description": "Convert a string of words to a JavaScript identifier", + "version": "1.0.1", + "author": "Douglas Christopher Wilson ", + "contributors": [ + "Douglas Christopher Wilson ", + "Nick Baugh (http://niftylettuce.com/)" + ], + "repository": "component/toidentifier", + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.3", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.1.3", + "nyc": "15.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "license": "MIT", + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "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", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/type-is/HISTORY.md b/node_modules/type-is/HISTORY.md new file mode 100644 index 000000000..6812655c8 --- /dev/null +++ b/node_modules/type-is/HISTORY.md @@ -0,0 +1,292 @@ +2.0.1 / 2025-03-27 +========== + +2.0.0 / 2024-08-31 +========== + + * Drop node <18 + * Use `content-type@^1.0.5` and `media-typer@^1.0.0` for type validation + - No behavior changes, upgrades `media-typer` + * deps: mime-types@^3.0.0 + - Add `application/toml` with extension `.toml` + - Add `application/ubjson` with extension `.ubj` + - Add `application/x-keepass2` with extension `.kdbx` + - Add deprecated iWorks mime types and extensions + - Add extension `.amr` to `audio/amr` + - Add extension `.cjs` to `application/node` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extension `.opus` to `audio/ogg` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add extension `.trig` to `application/trig` + - Add extensions from IANA for `application/*+xml` types + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add `image/vnd.ms-dds` with extension `.dds` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +1.6.18 / 2019-04-26 +=================== + + * Fix regression passing request object to `typeis.is` + +1.6.17 / 2019-04-25 +=================== + + * deps: mime-types@~2.1.24 + - Add Apple file extensions from IANA + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add extension `.owl` to `application/rdf+xml` + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add extensions from IANA for `image/*` types + - Add extensions from IANA for `model/*` types + - Add extensions to HEIC image types + - Add new mime types + - Add `text/mdx` with extension `.mdx` + * perf: prevent internal `throw` on invalid type + +1.6.16 / 2018-02-16 +=================== + + * deps: mime-types@~2.1.18 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add extension `.mjs` to `application/javascript` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add glTF types and extensions + - Add new mime types + - Update extensions `.md` and `.markdown` to be `text/markdown` + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +1.6.15 / 2017-03-31 +=================== + + * deps: mime-types@~2.1.15 + - Add new mime types + +1.6.14 / 2016-11-18 +=================== + + * deps: mime-types@~2.1.13 + - Add new mime types + +1.6.13 / 2016-05-18 +=================== + + * deps: mime-types@~2.1.11 + - Add new mime types + +1.6.12 / 2016-02-28 +=================== + + * deps: mime-types@~2.1.10 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +1.6.11 / 2016-01-29 +=================== + + * deps: mime-types@~2.1.9 + - Add new mime types + +1.6.10 / 2015-12-01 +=================== + + * deps: mime-types@~2.1.8 + - Add new mime types + +1.6.9 / 2015-09-27 +================== + + * deps: mime-types@~2.1.7 + - Add new mime types + +1.6.8 / 2015-09-04 +================== + + * deps: mime-types@~2.1.6 + - Add new mime types + +1.6.7 / 2015-08-20 +================== + + * Fix type error when given invalid type to match against + * deps: mime-types@~2.1.5 + - Add new mime types + +1.6.6 / 2015-07-31 +================== + + * deps: mime-types@~2.1.4 + - Add new mime types + +1.6.5 / 2015-07-16 +================== + + * deps: mime-types@~2.1.3 + - Add new mime types + +1.6.4 / 2015-07-01 +================== + + * deps: mime-types@~2.1.2 + - Add new mime types + * perf: enable strict mode + * perf: remove argument reassignment + +1.6.3 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - Add new mime types + * perf: reduce try block size + * perf: remove bitwise operations + +1.6.2 / 2015-05-10 +================== + + * deps: mime-types@~2.0.11 + - Add new mime types + +1.6.1 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - Add new mime types + +1.6.0 / 2015-02-12 +================== + + * fix false-positives in `hasBody` `Transfer-Encoding` check + * support wildcard for both type and subtype (`*/*`) + +1.5.7 / 2015-02-09 +================== + + * fix argument reassignment + * deps: mime-types@~2.0.9 + - Add new mime types + +1.5.6 / 2015-01-29 +================== + + * deps: mime-types@~2.0.8 + - Add new mime types + +1.5.5 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - Add new mime types + - Fix missing extensions + - Fix various invalid MIME type entries + - Remove example template MIME types + - deps: mime-db@~1.5.0 + +1.5.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - Add new mime types + - deps: mime-db@~1.3.0 + +1.5.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - Add new mime types + - deps: mime-db@~1.2.0 + +1.5.2 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - Add new mime types + - deps: mime-db@~1.1.0 + +1.5.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + * deps: media-typer@0.3.0 + * deps: mime-types@~2.0.1 + - Support Node.js 0.6 + +1.5.0 / 2014-09-05 +================== + + * fix `hasbody` to be true for `content-length: 0` + +1.4.0 / 2014-09-02 +================== + + * update mime-types + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/node_modules/type-is/LICENSE b/node_modules/type-is/LICENSE new file mode 100644 index 000000000..386b7b694 --- /dev/null +++ b/node_modules/type-is/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-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/type-is/README.md b/node_modules/type-is/README.md new file mode 100644 index 000000000..d23946e60 --- /dev/null +++ b/node_modules/type-is/README.md @@ -0,0 +1,198 @@ +# type-is + +[![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][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Infer the content-type of a request. + +## Install + +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 type-is +``` + +## API + +```js +var http = require('http') +var typeis = require('type-is') + +http.createServer(function (req, res) { + var istext = typeis(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### typeis(request, types) + +Checks if the `request` is one of the `types`. If the request has no body, +even if there is a `Content-Type` header, then `null` is returned. If the +`Content-Type` header is invalid or does not matches any of the `types`, then +`false` is returned. Otherwise, a string of the type that matched is returned. + +The `request` argument is expected to be a Node.js HTTP request. The `types` +argument is an array of type strings. + +Each type in the `types` array can be one of the following: + +- A file extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. + The full mime type will be returned if matched. +- A suffix such as `+json`. This can be combined with a wildcard such as + `*/vnd+json` or `application/*+json`. The full mime type will be returned + if matched. + +Some examples to illustrate the inputs and returned value: + +```js +// req.headers.content-type = 'application/json' + +typeis(req, ['json']) // => 'json' +typeis(req, ['html', 'json']) // => 'json' +typeis(req, ['application/*']) // => 'application/json' +typeis(req, ['application/json']) // => 'application/json' + +typeis(req, ['html']) // => false +``` + +### typeis.hasBody(request) + +Returns a Boolean if the given `request` has a body, regardless of the +`Content-Type` header. + +Having a body has no relation to how large the body is (it may be 0 bytes). +This is similar to how file existence works. If a body does exist, then this +indicates that there is data to read from the Node.js request stream. + +```js +if (typeis.hasBody(req)) { + // read the body, since there is one + + req.on('data', function (chunk) { + // ... + }) +} +``` + +### typeis.is(mediaType, types) + +Checks if the `mediaType` is one of the `types`. If the `mediaType` is invalid +or does not matches any of the `types`, then `false` is returned. Otherwise, a +string of the type that matched is returned. + +The `mediaType` argument is expected to be a +[media type](https://tools.ietf.org/html/rfc6838) string. The `types` argument +is an array of type strings. + +Each type in the `types` array can be one of the following: + +- A file extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. + The full mime type will be returned if matched. +- A suffix such as `+json`. This can be combined with a wildcard such as + `*/vnd+json` or `application/*+json`. The full mime type will be returned + if matched. + +Some examples to illustrate the inputs and returned value: + +```js +var mediaType = 'application/json' + +typeis.is(mediaType, ['json']) // => 'json' +typeis.is(mediaType, ['html', 'json']) // => 'json' +typeis.is(mediaType, ['application/*']) // => 'application/json' +typeis.is(mediaType, ['application/json']) // => 'application/json' + +typeis.is(mediaType, ['html']) // => false +``` + +### typeis.match(expected, actual) + +Match the type string `expected` with `actual`, taking in to account wildcards. +A wildcard can only be in the type of the subtype part of a media type and only +in the `expected` value (as `actual` should be the real media type to match). A +suffix can still be included even with a wildcard subtype. If an input is +malformed, `false` will be returned. + +```js +typeis.match('text/html', 'text/html') // => true +typeis.match('*/html', 'text/html') // => true +typeis.match('text/*', 'text/html') // => true +typeis.match('*/*', 'text/html') // => true +typeis.match('*/*+json', 'application/x-custom+json') // => true +``` + +### typeis.normalize(type) + +Normalize a `type` string. This works by performing the following: + +- If the `type` is not a string, `false` is returned. +- If the string starts with `+` (so it is a `+suffix` shorthand like `+json`), + then it is expanded to contain the complete wildcard notation of `*/*+suffix`. +- If the string contains a `/`, then it is returned as the type. +- Else the string is assumed to be a file extension and the mapped media type is + returned, or `false` is there is no mapping. + +This includes two special mappings: + +- `'multipart'` -> `'multipart/*'` +- `'urlencoded'` -> `'application/x-www-form-urlencoded'` + +## Examples + +### Example body parser + +```js +var express = require('express') +var typeis = require('type-is') + +var app = express() + +app.use(function bodyParser (req, res, next) { + if (!typeis.hasBody(req)) { + return next() + } + + switch (typeis(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + throw new Error('implement urlencoded body parsing') + case 'json': + // parse json body + throw new Error('implement json body parsing') + case 'multipart': + // parse multipart body + throw new Error('implement multipart body parsing') + default: + // 415 error code + res.statusCode = 415 + res.end() + break + } +}) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/type-is/master?label=ci +[ci-url]: https://github.com/jshttp/type-is/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/type-is/master +[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master +[node-version-image]: https://badgen.net/npm/node/type-is +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/type-is +[npm-url]: https://npmjs.org/package/type-is +[npm-version-image]: https://badgen.net/npm/v/type-is +[travis-image]: https://badgen.net/travis/jshttp/type-is/master +[travis-url]: https://travis-ci.org/jshttp/type-is diff --git a/node_modules/type-is/index.js b/node_modules/type-is/index.js new file mode 100644 index 000000000..e77384575 --- /dev/null +++ b/node_modules/type-is/index.js @@ -0,0 +1,250 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var contentType = require('content-type') +var mime = require('mime-types') +var typer = require('media-typer') + +/** + * Module exports. + * @public + */ + +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @public + */ + +function typeis (value, types_) { + var i + var types = types_ + + // remove parameters and normalize + var val = tryNormalizeType(value) + + // no type or invalid + if (!val) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) { + return val + } + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } + } + + // no matches + return false +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @public + */ + +function hasbody (req) { + return req.headers['transfer-encoding'] !== undefined || + !isNaN(req.headers['content-length']) +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {Object} req + * @param {(String|Array)} types... + * @return {(String|false|null)} + * @public + */ + +function typeofrequest (req, types_) { + // no body + if (!hasbody(req)) return null + // support flattened arguments + var types = arguments.length > 2 + ? Array.prototype.slice.call(arguments, 1) + : types_ + // request content type + var value = req.headers['content-type'] + + return typeis(value, types) +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @return {String|false|null} + * @public + */ + +function normalize (type) { + if (typeof type !== 'string') { + // invalid type + return false + } + + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } + + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @public + */ + +function mimeMatch (expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } + + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } + + // validate suffix wildcard + if (expectedParts[1].slice(0, 2) === '*+') { + return expectedParts[1].length <= actualParts[1].length + 1 && + expectedParts[1].slice(1) === actualParts[1].slice(1 - expectedParts[1].length) + } + + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } + + return true +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {(string|null)} + * @private + */ +function normalizeType (value) { + // Parse the type + var type = contentType.parse(value).type + + return typer.test(type) ? type : null +} + +/** + * Try to normalize a type and remove parameters. + * + * @param {string} value + * @return {(string|null)} + * @private + */ +function tryNormalizeType (value) { + try { + return value ? normalizeType(value) : null + } catch (err) { + return null + } +} diff --git a/node_modules/type-is/package.json b/node_modules/type-is/package.json new file mode 100644 index 000000000..08586d233 --- /dev/null +++ b/node_modules/type-is/package.json @@ -0,0 +1,47 @@ +{ + "name": "type-is", + "description": "Infer the content-type of a request.", + "version": "2.0.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/type-is", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test:debug": "mocha --reporter spec --check-leaks --inspect --inspect-brk test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "keywords": [ + "content", + "type", + "checking" + ] +} diff --git a/node_modules/undici/LICENSE b/node_modules/undici/LICENSE new file mode 100644 index 000000000..e7323bb52 --- /dev/null +++ b/node_modules/undici/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Matteo Collina and Undici contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/undici/README.md b/node_modules/undici/README.md new file mode 100644 index 000000000..15dcad7a3 --- /dev/null +++ b/node_modules/undici/README.md @@ -0,0 +1,685 @@ +# undici + +[![Node CI](https://github.com/nodejs/undici/actions/workflows/ci.yml/badge.svg)](https://github.com/nodejs/undici/actions/workflows/nodejs.yml) [![neostandard javascript style](https://img.shields.io/badge/neo-standard-7fffff?style=flat\&labelColor=ff80ff)](https://github.com/neostandard/neostandard) [![npm version](https://badge.fury.io/js/undici.svg)](https://badge.fury.io/js/undici) [![codecov](https://codecov.io/gh/nodejs/undici/branch/main/graph/badge.svg?token=yZL6LtXkOA)](https://codecov.io/gh/nodejs/undici) + +An HTTP/1.1 client, written from scratch for Node.js. + +> Undici means eleven in Italian. 1.1 -> 11 -> Eleven -> Undici. +It is also a Stranger Things reference. + +## How to get involved + +Have a question about using Undici? Open a [Q&A Discussion](https://github.com/nodejs/undici/discussions/new) or join our official OpenJS [Slack](https://openjs-foundation.slack.com/archives/C01QF9Q31QD) channel. + +Looking to contribute? Start by reading the [contributing guide](./CONTRIBUTING.md) + +## Install + +``` +npm i undici +``` + +## Benchmarks + +The benchmark is a simple getting data [example](https://github.com/nodejs/undici/blob/main/benchmarks/benchmark.js) using a +50 TCP connections with a pipelining depth of 10 running on Node 22.11.0. + +``` +┌────────────────────────┬─────────┬────────────────────┬────────────┬─────────────────────────┐ +│ Tests │ Samples │ Result │ Tolerance │ Difference with slowest │ +├────────────────────────┼─────────┼────────────────────┼────────────┼─────────────────────────┤ +│ 'axios' │ 15 │ '5708.26 req/sec' │ '± 2.91 %' │ '-' │ +│ 'http - no keepalive' │ 10 │ '5809.80 req/sec' │ '± 2.30 %' │ '+ 1.78 %' │ +│ 'request' │ 30 │ '5828.80 req/sec' │ '± 2.91 %' │ '+ 2.11 %' │ +│ 'undici - fetch' │ 40 │ '5903.78 req/sec' │ '± 2.87 %' │ '+ 3.43 %' │ +│ 'node-fetch' │ 10 │ '5945.40 req/sec' │ '± 2.13 %' │ '+ 4.15 %' │ +│ 'got' │ 35 │ '6511.45 req/sec' │ '± 2.84 %' │ '+ 14.07 %' │ +│ 'http - keepalive' │ 65 │ '9193.24 req/sec' │ '± 2.92 %' │ '+ 61.05 %' │ +│ 'superagent' │ 35 │ '9339.43 req/sec' │ '± 2.95 %' │ '+ 63.61 %' │ +│ 'undici - pipeline' │ 50 │ '13364.62 req/sec' │ '± 2.93 %' │ '+ 134.13 %' │ +│ 'undici - stream' │ 95 │ '18245.36 req/sec' │ '± 2.99 %' │ '+ 219.63 %' │ +│ 'undici - request' │ 50 │ '18340.17 req/sec' │ '± 2.84 %' │ '+ 221.29 %' │ +│ 'undici - dispatch' │ 40 │ '22234.42 req/sec' │ '± 2.94 %' │ '+ 289.51 %' │ +└────────────────────────┴─────────┴────────────────────┴────────────┴─────────────────────────┘ +``` + +## Undici vs. Fetch + +### Overview + +Node.js includes a built-in `fetch()` implementation powered by undici starting from Node.js v18. However, there are important differences between using the built-in fetch and installing undici as a separate module. + +### Built-in Fetch (Node.js v18+) + +Node.js's built-in fetch is powered by a bundled version of undici: + +```js +// Available globally in Node.js v18+ +const response = await fetch('https://api.example.com/data'); +const data = await response.json(); + +// Check the bundled undici version +console.log(process.versions.undici); // e.g., "5.28.4" +``` + +**Pros:** +- No additional dependencies required +- Works across different JavaScript runtimes +- Automatic compression handling (gzip, deflate, br) +- Built-in caching support (in development) + +**Cons:** +- Limited to the undici version bundled with your Node.js version +- Less control over connection pooling and advanced features +- Error handling follows Web API standards (errors wrapped in `TypeError`) +- Performance overhead due to Web Streams implementation + +### Undici Module + +Installing undici as a separate module gives you access to the latest features and APIs: + +```bash +npm install undici +``` + +```js +import { request, fetch, Agent, setGlobalDispatcher } from 'undici'; + +// Use undici.request for maximum performance +const { statusCode, headers, body } = await request('https://api.example.com/data'); +const data = await body.json(); + +// Or use undici.fetch with custom configuration +const agent = new Agent({ keepAliveTimeout: 10000 }); +setGlobalDispatcher(agent); +const response = await fetch('https://api.example.com/data'); +``` + +**Pros:** +- Latest undici features and bug fixes +- Access to advanced APIs (`request`, `stream`, `pipeline`) +- Fine-grained control over connection pooling +- Better error handling with clearer error messages +- Superior performance, especially with `undici.request` +- HTTP/1.1 pipelining support +- Custom interceptors and middleware +- Advanced features like `ProxyAgent`, `MockAgent` + +**Cons:** +- Additional dependency to manage +- Larger bundle size + +### When to Use Each + +#### Use Built-in Fetch When: +- You want zero dependencies +- Building isomorphic code that runs in browsers and Node.js +- Publishing to npm and want to maximize compatibility with JS runtimes +- Simple HTTP requests without advanced configuration +- You're publishing to npm and you want to maximize compatiblity +- You don't depend on features from a specific version of undici + +#### Use Undici Module When: +- You need the latest undici features and performance improvements +- You require advanced connection pooling configuration +- You need APIs not available in the built-in fetch (`ProxyAgent`, `MockAgent`, etc.) +- Performance is critical (use `undici.request` for maximum speed) +- You want better error handling and debugging capabilities +- You need HTTP/1.1 pipelining or advanced interceptors +- You prefer decoupled protocol and API interfaces + +### Performance Comparison + +Based on benchmarks, here's the typical performance hierarchy: + +1. **`undici.request()`** - Fastest, most efficient +2. **`undici.fetch()`** - Good performance, standard compliance +3. **Node.js `http`/`https`** - Baseline performance + +### Migration Guide + +If you're currently using built-in fetch and want to migrate to undici: + +```js +// Before: Built-in fetch +const response = await fetch('https://api.example.com/data'); + +// After: Undici fetch (drop-in replacement) +import { fetch } from 'undici'; +const response = await fetch('https://api.example.com/data'); + +// Or: Undici request (better performance) +import { request } from 'undici'; +const { statusCode, body } = await request('https://api.example.com/data'); +const data = await body.json(); +``` + +### Version Compatibility + +You can check which version of undici is bundled with your Node.js version: + +```js +console.log(process.versions.undici); +``` + +Installing undici as a module allows you to use a newer version than what's bundled with Node.js, giving you access to the latest features and performance improvements. + +## Quick Start + +### Basic Request + +```js +import { request } from 'undici' + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) +console.log('headers', headers) + +for await (const data of body) { console.log('data', data) } + +console.log('trailers', trailers) +``` + +### Using Cache Interceptor + +Undici provides a powerful HTTP caching interceptor that follows HTTP caching best practices. Here's how to use it: + +```js +import { fetch, Agent, interceptors, cacheStores } from 'undici'; + +// Create a client with cache interceptor +const client = new Agent().compose(interceptors.cache({ + // Optional: Configure cache store (defaults to MemoryCacheStore) + store: new cacheStores.MemoryCacheStore({ + maxSize: 100 * 1024 * 1024, // 100MB + maxCount: 1000, + maxEntrySize: 5 * 1024 * 1024 // 5MB + }), + + // Optional: Specify which HTTP methods to cache (default: ['GET', 'HEAD']) + methods: ['GET', 'HEAD'] +})); + +// Set the global dispatcher to use our caching client +setGlobalDispatcher(client); + +// Now all fetch requests will use the cache +async function getData() { + const response = await fetch('https://api.example.com/data'); + // The server should set appropriate Cache-Control headers in the response + // which the cache will respect based on the cache policy + return response.json(); +} + +// First request - fetches from origin +const data1 = await getData(); + +// Second request - served from cache if within max-age +const data2 = await getData(); +``` + +#### Key Features: +- **Automatic Caching**: Respects `Cache-Control` and `Expires` headers +- **Validation**: Supports `ETag` and `Last-Modified` validation +- **Storage Options**: In-memory or persistent SQLite storage +- **Flexible**: Configure cache size, TTL, and more + +## Global Installation + +Undici provides an `install()` function to add all WHATWG fetch classes to `globalThis`, making them available globally: + +```js +import { install } from 'undici' + +// Install all WHATWG fetch classes globally +install() + +// Now you can use fetch classes globally without importing +const response = await fetch('https://api.example.com/data') +const data = await response.json() + +// All classes are available globally: +const headers = new Headers([['content-type', 'application/json']]) +const request = new Request('https://example.com') +const formData = new FormData() +const ws = new WebSocket('wss://example.com') +const eventSource = new EventSource('https://example.com/events') +``` + +The `install()` function adds the following classes to `globalThis`: + +- `fetch` - The fetch function +- `Headers` - HTTP headers management +- `Response` - HTTP response representation +- `Request` - HTTP request representation +- `FormData` - Form data handling +- `WebSocket` - WebSocket client +- `CloseEvent`, `ErrorEvent`, `MessageEvent` - WebSocket events +- `EventSource` - Server-sent events client + +This is useful for: +- Polyfilling environments that don't have fetch +- Ensuring consistent fetch behavior across different Node.js versions +- Making undici's implementations available globally for libraries that expect them + +## Body Mixins + +The `body` mixins are the most common way to format the request/response body. Mixins include: + +- [`.arrayBuffer()`](https://fetch.spec.whatwg.org/#dom-body-arraybuffer) +- [`.blob()`](https://fetch.spec.whatwg.org/#dom-body-blob) +- [`.bytes()`](https://fetch.spec.whatwg.org/#dom-body-bytes) +- [`.json()`](https://fetch.spec.whatwg.org/#dom-body-json) +- [`.text()`](https://fetch.spec.whatwg.org/#dom-body-text) + +> [!NOTE] +> The body returned from `undici.request` does not implement `.formData()`. + +Example usage: + +```js +import { request } from 'undici' + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) +console.log('headers', headers) +console.log('data', await body.json()) +console.log('trailers', trailers) +``` + +_Note: Once a mixin has been called then the body cannot be reused, thus calling additional mixins on `.body`, e.g. `.body.json(); .body.text()` will result in an error `TypeError: unusable` being thrown and returned through the `Promise` rejection._ + +Should you need to access the `body` in plain-text after using a mixin, the best practice is to use the `.text()` mixin first and then manually parse the text to the desired format. + +For more information about their behavior, please reference the body mixin from the [Fetch Standard](https://fetch.spec.whatwg.org/#body-mixin). + +## Common API Methods + +This section documents our most commonly used API methods. Additional APIs are documented in their own files within the [docs](./docs/) folder and are accessible via the navigation list on the left side of the docs site. + +### `undici.request([url, options]): Promise` + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`RequestOptions`](./docs/docs/api/Dispatcher.md#parameter-requestoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **method** `String` - Default: `PUT` if `options.body`, otherwise `GET` + +Returns a promise with the result of the `Dispatcher.request` method. + +Calls `options.dispatcher.request(options)`. + +See [Dispatcher.request](./docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback) for more details, and [request examples](./docs/examples/README.md) for examples. + +### `undici.stream([url, options, ]factory): Promise` + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`StreamOptions`](./docs/docs/api/Dispatcher.md#parameter-streamoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **method** `String` - Default: `PUT` if `options.body`, otherwise `GET` +* **factory** `Dispatcher.stream.factory` + +Returns a promise with the result of the `Dispatcher.stream` method. + +Calls `options.dispatcher.stream(options, factory)`. + +See [Dispatcher.stream](./docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback) for more details. + +### `undici.pipeline([url, options, ]handler): Duplex` + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`PipelineOptions`](./docs/docs/api/Dispatcher.md#parameter-pipelineoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **method** `String` - Default: `PUT` if `options.body`, otherwise `GET` +* **handler** `Dispatcher.pipeline.handler` + +Returns: `stream.Duplex` + +Calls `options.dispatch.pipeline(options, handler)`. + +See [Dispatcher.pipeline](./docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler) for more details. + +### `undici.connect([url, options]): Promise` + +Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT). + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`ConnectOptions`](./docs/docs/api/Dispatcher.md#parameter-connectoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) +* **callback** `(err: Error | null, data: ConnectData | null) => void` (optional) + +Returns a promise with the result of the `Dispatcher.connect` method. + +Calls `options.dispatch.connect(options)`. + +See [Dispatcher.connect](./docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback) for more details. + +### `undici.fetch(input[, init]): Promise` + +Implements [fetch](https://fetch.spec.whatwg.org/#fetch-method). + +* https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch +* https://fetch.spec.whatwg.org/#fetch-method + +Basic usage example: + +```js +import { fetch } from 'undici' + + +const res = await fetch('https://example.com') +const json = await res.json() +console.log(json) +``` + +You can pass an optional dispatcher to `fetch` as: + +```js +import { fetch, Agent } from 'undici' + +const res = await fetch('https://example.com', { + // Mocks are also supported + dispatcher: new Agent({ + keepAliveTimeout: 10, + keepAliveMaxTimeout: 10 + }) +}) +const json = await res.json() +console.log(json) +``` + +#### `request.body` + +A body can be of the following types: + +- ArrayBuffer +- ArrayBufferView +- AsyncIterables +- Blob +- Iterables +- String +- URLSearchParams +- FormData + +In this implementation of fetch, ```request.body``` now accepts ```Async Iterables```. It is not present in the [Fetch Standard](https://fetch.spec.whatwg.org). + +```js +import { fetch } from 'undici' + +const data = { + async *[Symbol.asyncIterator]() { + yield 'hello' + yield 'world' + }, +} + +await fetch('https://example.com', { body: data, method: 'POST', duplex: 'half' }) +``` + +[FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) besides text data and buffers can also utilize streams via [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects: + +```js +import { openAsBlob } from 'node:fs' + +const file = await openAsBlob('./big.csv') +const body = new FormData() +body.set('file', file, 'big.csv') + +await fetch('http://example.com', { method: 'POST', body }) +``` + +#### `request.duplex` + +- `'half'` + +In this implementation of fetch, `request.duplex` must be set if `request.body` is `ReadableStream` or `Async Iterables`, however, even though the value must be set to `'half'`, it is actually a _full_ duplex. For more detail refer to the [Fetch Standard](https://fetch.spec.whatwg.org/#dom-requestinit-duplex). + +#### `response.body` + +Nodejs has two kinds of streams: [web streams](https://nodejs.org/api/webstreams.html), which follow the API of the WHATWG web standard found in browsers, and an older Node-specific [streams API](https://nodejs.org/api/stream.html). `response.body` returns a readable web stream. If you would prefer to work with a Node stream you can convert a web stream using `.fromWeb()`. + +```js +import { fetch } from 'undici' +import { Readable } from 'node:stream' + +const response = await fetch('https://example.com') +const readableWebStream = response.body +const readableNodeStream = Readable.fromWeb(readableWebStream) +``` + +## Specification Compliance + +This section documents parts of the [HTTP/1.1](https://www.rfc-editor.org/rfc/rfc9110.html) and [Fetch Standard](https://fetch.spec.whatwg.org) that Undici does +not support or does not fully implement. + +#### CORS + +Unlike browsers, Undici does not implement CORS (Cross-Origin Resource Sharing) checks by default. This means: + +- No preflight requests are automatically sent for cross-origin requests +- No validation of `Access-Control-Allow-Origin` headers is performed +- Requests to any origin are allowed regardless of the source + +This behavior is intentional for server-side environments where CORS restrictions are typically unnecessary. If your application requires CORS-like protections, you will need to implement these checks manually. + +#### Garbage Collection + +* https://fetch.spec.whatwg.org/#garbage-collection + +The [Fetch Standard](https://fetch.spec.whatwg.org) allows users to skip consuming the response body by relying on +[garbage collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management#garbage_collection) to release connection resources. + +Garbage collection in Node is less aggressive and deterministic +(due to the lack of clear idle periods that browsers have through the rendering refresh rate) +which means that leaving the release of connection resources to the garbage collector can lead +to excessive connection usage, reduced performance (due to less connection re-use), and even +stalls or deadlocks when running out of connections. +Therefore, __it is important to always either consume or cancel the response body anyway__. + +```js +// Do +const { body, headers } = await fetch(url); +for await (const chunk of body) { + // force consumption of body +} + +// Do not +const { headers } = await fetch(url); +``` + +However, if you want to get only headers, it might be better to use `HEAD` request method. Usage of this method will obviate the need for consumption or cancelling of the response body. See [MDN - HTTP - HTTP request methods - HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) for more details. + +```js +const headers = await fetch(url, { method: 'HEAD' }) + .then(res => res.headers) +``` + +Note that consuming the response body is _mandatory_ for `request`: + +```js +// Do +const { body, headers } = await request(url); +await body.dump(); // force consumption of body + +// Do not +const { headers } = await request(url); +``` + +#### Forbidden and Safelisted Header Names + +* https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name +* https://fetch.spec.whatwg.org/#forbidden-header-name +* https://fetch.spec.whatwg.org/#forbidden-response-header-name +* https://github.com/wintercg/fetch/issues/6 + +The [Fetch Standard](https://fetch.spec.whatwg.org) requires implementations to exclude certain headers from requests and responses. In browser environments, some headers are forbidden so the user agent remains in full control over them. In Undici, these constraints are removed to give more control to the user. + +#### Content-Encoding + +* https://www.rfc-editor.org/rfc/rfc9110#field.content-encoding + +Undici limits the number of `Content-Encoding` layers in a response to **5** to prevent resource exhaustion attacks. If a server responds with more than 5 content-encodings (e.g., `Content-Encoding: gzip, gzip, gzip, gzip, gzip, gzip`), the fetch will be rejected with an error. This limit matches the approach taken by [curl](https://curl.se/docs/CVE-2022-32206.html) and [urllib3](https://github.com/advisories/GHSA-gm62-xv2j-4rw9). + +#### `undici.upgrade([url, options]): Promise` + +Upgrade to a different protocol. See [MDN - HTTP - Protocol upgrade mechanism](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) for more details. + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`UpgradeOptions`](./docs/docs/api/Dispatcher.md#parameter-upgradeoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) +* **callback** `(error: Error | null, data: UpgradeData) => void` (optional) + +Returns a promise with the result of the `Dispatcher.upgrade` method. + +Calls `options.dispatcher.upgrade(options)`. + +See [Dispatcher.upgrade](./docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback) for more details. + +### `undici.setGlobalDispatcher(dispatcher)` + +* dispatcher `Dispatcher` + +Sets the global dispatcher used by Common API Methods. Global dispatcher is shared among compatible undici modules, +including undici that is bundled internally with node.js. + +### `undici.getGlobalDispatcher()` + +Gets the global dispatcher used by Common API Methods. + +Returns: `Dispatcher` + +### `undici.setGlobalOrigin(origin)` + +* origin `string | URL | undefined` + +Sets the global origin used in `fetch`. + +If `undefined` is passed, the global origin will be reset. This will cause `Response.redirect`, `new Request()`, and `fetch` to throw an error when a relative path is passed. + +```js +setGlobalOrigin('http://localhost:3000') + +const response = await fetch('/api/ping') + +console.log(response.url) // http://localhost:3000/api/ping +``` + +### `undici.getGlobalOrigin()` + +Gets the global origin used in `fetch`. + +Returns: `URL` + +### `UrlObject` + +* **port** `string | number` (optional) +* **path** `string` (optional) +* **pathname** `string` (optional) +* **hostname** `string` (optional) +* **origin** `string` (optional) +* **protocol** `string` (optional) +* **search** `string` (optional) + +#### Expect + +Undici does not support the `Expect` request header field. The request +body is always immediately sent and the `100 Continue` response will be +ignored. + +Refs: https://tools.ietf.org/html/rfc7231#section-5.1.1 + +#### Pipelining + +Undici will only use pipelining if configured with a `pipelining` factor +greater than `1`. Also it is important to pass `blocking: false` to the +request options to properly pipeline requests. + +Undici always assumes that connections are persistent and will immediately +pipeline requests, without checking whether the connection is persistent. +Hence, automatic fallback to HTTP/1.0 or HTTP/1.1 without pipelining is +not supported. + +Undici will immediately pipeline when retrying requests after a failed +connection. However, Undici will not retry the first remaining requests in +the prior pipeline and instead error the corresponding callback/promise/stream. + +Undici will abort all running requests in the pipeline when any of them are +aborted. + +* Refs: https://tools.ietf.org/html/rfc2616#section-8.1.2.2 +* Refs: https://tools.ietf.org/html/rfc7230#section-6.3.2 + +#### Manual Redirect + +Since it is not possible to manually follow an HTTP redirect on the server-side, +Undici returns the actual response instead of an `opaqueredirect` filtered one +when invoked with a `manual` redirect. This aligns `fetch()` with the other +implementations in Deno and Cloudflare Workers. + +Refs: https://fetch.spec.whatwg.org/#atomic-http-redirect-handling + +### Workarounds + +#### Network address family autoselection. + +If you experience problem when connecting to a remote server that is resolved by your DNS servers to a IPv6 (AAAA record) +first, there are chances that your local router or ISP might have problem connecting to IPv6 networks. In that case +undici will throw an error with code `UND_ERR_CONNECT_TIMEOUT`. + +If the target server resolves to both a IPv6 and IPv4 (A records) address and you are using a compatible Node version +(18.3.0 and above), you can fix the problem by providing the `autoSelectFamily` option (support by both `undici.request` +and `undici.Agent`) which will enable the family autoselection algorithm when establishing the connection. + +## Collaborators + +* [__Daniele Belardi__](https://github.com/dnlup), +* [__Ethan Arrowood__](https://github.com/ethan-arrowood), +* [__Matteo Collina__](https://github.com/mcollina), +* [__Matthew Aitken__](https://github.com/KhafraDev), +* [__Robert Nagy__](https://github.com/ronag), +* [__Szymon Marczak__](https://github.com/szmarczak), + +## Past Collaborators +* [__Tomas Della Vedova__](https://github.com/delvedor), + +### Releasers + +* [__Ethan Arrowood__](https://github.com/ethan-arrowood), +* [__Matteo Collina__](https://github.com/mcollina), +* [__Robert Nagy__](https://github.com/ronag), +* [__Matthew Aitken__](https://github.com/KhafraDev), + +## Long Term Support + +Undici aligns with the Node.js LTS schedule. The following table shows the supported versions: + +| Undici Version | Bundled in Node.js | Node.js Versions Supported | End of Life | +|----------------|-------------------|----------------------------|-------------| +| 5.x | 18.x | ≥14.0 (tested: 14, 16, 18) | 2024-04-30 | +| 6.x | 20.x, 22.x | ≥18.17 (tested: 18, 20, 21, 22) | 2026-04-30 | +| 7.x | 24.x | ≥20.18.1 (tested: 20, 22, 24) | 2027-04-30 | + +## License + +MIT diff --git a/node_modules/undici/docs/docs/api/Agent.md b/node_modules/undici/docs/docs/api/Agent.md new file mode 100644 index 000000000..0131b1039 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Agent.md @@ -0,0 +1,84 @@ +# Agent + +Extends: `undici.Dispatcher` + +Agent allows dispatching requests against multiple different origins. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new undici.Agent([options])` + +Arguments: + +* **options** `AgentOptions` (optional) + +Returns: `Agent` + +### Parameter: `AgentOptions` + +Extends: [`PoolOptions`](/docs/docs/api/Pool.md#parameter-pooloptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` +* **maxOrigins** `number` (optional) - Default: `Infinity` - Limits the total number of origins that can receive requests at a time, throwing an `MaxOriginsReachedError` error when attempting to dispatch when the max is reached. If `Infinity`, no limit is enforced. + +## Instance Properties + +### `Agent.closed` + +Implements [Client.closed](/docs/docs/api/Client.md#clientclosed) + +### `Agent.destroyed` + +Implements [Client.destroyed](/docs/docs/api/Client.md#clientdestroyed) + +## Instance Methods + +### `Agent.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `Agent.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Agent.dispatch(options, handler: AgentDispatchOptions)` + +Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +#### Parameter: `AgentDispatchOptions` + +Extends: [`DispatchOptions`](/docs/docs/api/Dispatcher.md#parameter-dispatchoptions) + +* **origin** `string | URL` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Agent.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `Agent.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Agent.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Agent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `Agent.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Agent.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). + +### `Agent.stats()` + +Returns an object of stats by origin in the format of `Record` + +See [`PoolStats`](/docs/docs/api/PoolStats.md) and [`ClientStats`](/docs/docs/api/ClientStats.md). diff --git a/node_modules/undici/docs/docs/api/BalancedPool.md b/node_modules/undici/docs/docs/api/BalancedPool.md new file mode 100644 index 000000000..df267fe72 --- /dev/null +++ b/node_modules/undici/docs/docs/api/BalancedPool.md @@ -0,0 +1,99 @@ +# Class: BalancedPool + +Extends: `undici.Dispatcher` + +A pool of [Pool](/docs/docs/api/Pool.md) instances connected to multiple upstreams. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new BalancedPool(upstreams [, options])` + +Arguments: + +* **upstreams** `URL | string | string[]` - It should only include the **protocol, hostname, and port**. +* **options** `BalancedPoolOptions` (optional) + +### Parameter: `BalancedPoolOptions` + +Extends: [`PoolOptions`](/docs/docs/api/Pool.md#parameter-pooloptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` + +The `PoolOptions` are passed to each of the `Pool` instances being created. +## Instance Properties + +### `BalancedPool.upstreams` + +Returns an array of upstreams that were previously added. + +### `BalancedPool.closed` + +Implements [Client.closed](/docs/docs/api/Client.md#clientclosed) + +### `BalancedPool.destroyed` + +Implements [Client.destroyed](/docs/docs/api/Client.md#clientdestroyed) + +### `Pool.stats` + +Returns [`PoolStats`](/docs/docs/api/PoolStats.md) instance for this pool. + +## Instance Methods + +### `BalancedPool.addUpstream(upstream)` + +Add an upstream. + +Arguments: + +* **upstream** `string` - It should only include the **protocol, hostname, and port**. + +### `BalancedPool.removeUpstream(upstream)` + +Removes an upstream that was previously added. + +### `BalancedPool.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `BalancedPool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `BalancedPool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `BalancedPool.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `BalancedPool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `BalancedPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `BalancedPool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `BalancedPool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](/docs/docs/api/Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](/docs/docs/api/Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](/docs/docs/api/Dispatcher.md#event-drain). diff --git a/node_modules/undici/docs/docs/api/CacheStorage.md b/node_modules/undici/docs/docs/api/CacheStorage.md new file mode 100644 index 000000000..08ee99fab --- /dev/null +++ b/node_modules/undici/docs/docs/api/CacheStorage.md @@ -0,0 +1,30 @@ +# CacheStorage + +Undici exposes a W3C spec-compliant implementation of [CacheStorage](https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage) and [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache). + +## Opening a Cache + +Undici exports a top-level CacheStorage instance. You can open a new Cache, or duplicate a Cache with an existing name, by using `CacheStorage.prototype.open`. If you open a Cache with the same name as an already-existing Cache, its list of cached Responses will be shared between both instances. + +```mjs +import { caches } from 'undici' + +const cache_1 = await caches.open('v1') +const cache_2 = await caches.open('v1') + +// Although .open() creates a new instance, +assert(cache_1 !== cache_2) +// The same Response is matched in both. +assert.deepStrictEqual(await cache_1.match('/req'), await cache_2.match('/req')) +``` + +## Deleting a Cache + +If a Cache is deleted, the cached Responses/Requests can still be used. + +```mjs +const response = await cache_1.match('/req') +await caches.delete('v1') + +await response.text() // the Response's body +``` diff --git a/node_modules/undici/docs/docs/api/CacheStore.md b/node_modules/undici/docs/docs/api/CacheStore.md new file mode 100644 index 000000000..00ceb9606 --- /dev/null +++ b/node_modules/undici/docs/docs/api/CacheStore.md @@ -0,0 +1,151 @@ +# Cache Store + +A Cache Store is responsible for storing and retrieving cached responses. +It is also responsible for deciding which specific response to use based off of +a response's `Vary` header (if present). It is expected to be compliant with +[RFC-9111](https://www.rfc-editor.org/rfc/rfc9111.html). + +## Pre-built Cache Stores + +### `MemoryCacheStore` + +The `MemoryCacheStore` stores the responses in-memory. + +**Options** + +- `maxSize` - The maximum total size in bytes of all stored responses. Default `104857600` (100MB). +- `maxCount` - The maximum amount of responses to store. Default `1024`. +- `maxEntrySize` - The maximum size in bytes that a response's body can be. If a response's body is greater than or equal to this, the response will not be cached. Default `5242880` (5MB). + +### Getters + +#### `MemoryCacheStore.size` + +Returns the current total size in bytes of all stored responses. + +### Methods + +#### `MemoryCacheStore.isFull()` + +Returns a boolean indicating whether the cache has reached its maximum size or count. + +### Events + +#### `'maxSizeExceeded'` + +Emitted when the cache exceeds its maximum size or count limits. The event payload contains `size`, `maxSize`, `count`, and `maxCount` properties. + + +### `SqliteCacheStore` + +The `SqliteCacheStore` stores the responses in a SQLite database. +Under the hood, it uses Node.js' [`node:sqlite`](https://nodejs.org/api/sqlite.html) api. +The `SqliteCacheStore` is only exposed if the `node:sqlite` api is present. + +**Options** + +- `location` - The location of the SQLite database to use. Default `:memory:`. +- `maxCount` - The maximum number of entries to store in the database. Default `Infinity`. +- `maxEntrySize` - The maximum size in bytes that a response's body can be. If a response's body is greater than or equal to this, the response will not be cached. Default `Infinity`. + +## Defining a Custom Cache Store + +The store must implement the following functions: + +### Getter: `isFull` + +Optional. This tells the cache interceptor if the store is full or not. If this is true, +the cache interceptor will not attempt to cache the response. + +### Function: `get` + +Parameters: + +* **req** `Dispatcher.RequestOptions` - Incoming request + +Returns: `GetResult | Promise | undefined` - If the request is cached, the cached response is returned. If the request's method is anything other than HEAD, the response is also returned. +If the request isn't cached, `undefined` is returned. + +Response properties: + +* **response** `CacheValue` - The cached response data. +* **body** `Readable | undefined` - The response's body. + +### Function: `createWriteStream` + +Parameters: + +* **req** `Dispatcher.RequestOptions` - Incoming request +* **value** `CacheValue` - Response to store + +Returns: `Writable | undefined` - If the store is full, return `undefined`. Otherwise, return a writable so that the cache interceptor can stream the body and trailers to the store. + +## `CacheValue` + +This is an interface containing the majority of a response's data (minus the body). + +### Property `statusCode` + +`number` - The response's HTTP status code. + +### Property `statusMessage` + +`string` - The response's HTTP status message. + +### Property `rawHeaders` + +`Buffer[]` - The response's headers. + +### Property `vary` + +`Record | undefined` - The headers defined by the response's `Vary` header +and their respective values for later comparison + +For example, for a response like +``` +Vary: content-encoding, accepts +content-encoding: utf8 +accepts: application/json +``` + +This would be +```js +{ + 'content-encoding': 'utf8', + accepts: 'application/json' +} +``` + +### Property `cachedAt` + +`number` - Time in millis that this value was cached. + +### Property `staleAt` + +`number` - Time in millis that this value is considered stale. + +### Property `deleteAt` + +`number` - Time in millis that this value is to be deleted from the cache. This +is either the same sa staleAt or the `max-stale` caching directive. + +The store must not return a response after the time defined in this property. + +## `CacheStoreReadable` + +This extends Node's [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) +and defines extra properties relevant to the cache interceptor. + +### Getter: `value` + +The response's [`CacheStoreValue`](/docs/docs/api/CacheStore.md#cachestorevalue) + +## `CacheStoreWriteable` + +This extends Node's [`Writable`](https://nodejs.org/api/stream.html#class-streamwritable) +and defines extra properties relevant to the cache interceptor. + +### Setter: `rawTrailers` + +If the response has trailers, the cache interceptor will pass them to the cache +interceptor through this method. diff --git a/node_modules/undici/docs/docs/api/Client.md b/node_modules/undici/docs/docs/api/Client.md new file mode 100644 index 000000000..abc02d87d --- /dev/null +++ b/node_modules/undici/docs/docs/api/Client.md @@ -0,0 +1,284 @@ +# Class: Client + +Extends: `undici.Dispatcher` + +A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new Client(url[, options])` + +Arguments: + +* **url** `URL | string` - Should only include the **protocol, hostname, and port**. +* **options** `ClientOptions` (optional) + +Returns: `Client` + +### Parameter: `ClientOptions` + +* **bodyTimeout** `number | null` (optional) - Default: `300e3` - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. Please note the `timeout` will be reset if you keep writing data to the socket everytime. +* **headersTimeout** `number | null` (optional) - Default: `300e3` - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +* **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Defaults to 10 minutes. +* **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds. +* **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `2e3` - A number of milliseconds subtracted from server *keep-alive* hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 2 seconds. +* **maxHeaderSize** `number | null` (optional) - Default: `--max-http-header-size` or `16384` - The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB. +* **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable. +* **pipelining** `number | null` (optional) - Default: `1` - The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Carefully consider your workload and environment before enabling concurrent requests as pipelining may reduce performance if used incorrectly. Pipelining is sensitive to network stack settings as well as head of line blocking caused by e.g. long running requests. Set to `0` to disable keep-alive connections. +* **connect** `ConnectOptions | Function | null` (optional) - Default: `null`. +* **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body. **Security Warning:** Disabling this option can expose your application to HTTP Request Smuggling attacks, where mismatched content-length headers cause servers and proxies to interpret request boundaries differently. This can lead to cache poisoning, credential hijacking, and bypassing security controls. Only disable this in controlled environments where you fully trust the request source. +* **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version. +* **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. +* **allowH2**: `boolean` - Default: `false`. Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. +* **useH2c**: `boolean` - Default: `false`. Enforces h2c for non-https connections. +* **maxConcurrentStreams**: `number` - Default: `100`. Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. +* **initialWindowSize**: `number` (optional) - Default: `262144` (256KB). Sets the HTTP/2 stream-level flow-control window size (SETTINGS_INITIAL_WINDOW_SIZE). Must be a positive integer greater than 0. This default is higher than Node.js core's default (65535 bytes) to improve throughput, Node's choice is very conservative for current high-bandwith networks. See [RFC 7540 Section 6.9.2](https://datatracker.ietf.org/doc/html/rfc7540#section-6.9.2) for more details. +* **connectionWindowSize**: `number` (optional) - Default `524288` (512KB). Sets the HTTP/2 connection-level flow-control window size using `ClientHttp2Session.setLocalWindowSize()`. Must be a positive integer greater than 0. This provides better flow control for the entire connection across multiple streams. See [Node.js HTTP/2 documentation](https://nodejs.org/api/http2.html#clienthttp2sessionsetlocalwindowsize) for more details. + +> **Notes about HTTP/2** +> - It only works under TLS connections. h2c is not supported. +> - The server must support HTTP/2 and choose it as the protocol during the ALPN negotiation. +> - The server must not have a bigger priority for HTTP/1.1 than HTTP/2. +> - Pseudo headers are automatically attached to the request. If you try to set them, they will be overwritten. +> - The `:path` header is automatically set to the request path. +> - The `:method` header is automatically set to the request method. +> - The `:scheme` header is automatically set to the request scheme. +> - The `:authority` header is automatically set to the request `host[:port]`. +> - `PUSH` frames are yet not supported. + +#### Parameter: `ConnectOptions` + +Every Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +Furthermore, the following options can be passed: + +* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: 100. +* **timeout** `number | null` (optional) - In milliseconds, Default `10e3`. +* **servername** `string | null` (optional) +* **keepAlive** `boolean | null` (optional) - Default: `true` - TCP keep-alive enabled +* **keepAliveInitialDelay** `number | null` (optional) - Default: `60000` - TCP keep-alive interval for the socket in milliseconds + +### Example - Basic Client instantiation + +This will instantiate the undici Client, but it will not connect to the origin until something is queued. Consider using `client.connect` to prematurely connect to the origin, or just call `client.request`. + +```js +'use strict' +import { Client } from 'undici' + +const client = new Client('http://localhost:3000') +``` + +### Example - Custom connector + +This will allow you to perform some additional check on the socket that will be used for the next request. + +```js +'use strict' +import { Client, buildConnector } from 'undici' + +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (/* assertion */) { + socket.destroy() + cb(new Error('kaboom')) + } else { + cb(null, socket) + } + }) + } +}) +``` + +## Instance Methods + +### `Client.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `Client.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). + +### `Client.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `Client.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Client.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Client.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `Client.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Client.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Properties + +### `Client.closed` + +* `boolean` + +`true` after `client.close()` has been called. + +### `Client.destroyed` + +* `boolean` + +`true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. + +### `Client.pipelining` + +* `number` + +Property to get and set the pipelining factor. + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](/docs/docs/api/Dispatcher.md#event-connect). + +Parameters: + +* **origin** `URL` +* **targets** `Array` + +Emitted when a socket has been created and connected. The client will connect once `client.size > 0`. + +#### Example - Client connect event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('connect', (origin) => { + console.log(`Connected to ${origin}`) // should print before the request body statement +}) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.setEncoding('utf-8') + body.on('data', console.log) + client.close() + server.close() +} catch (error) { + console.error(error) + client.close() + server.close() +} +``` + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](/docs/docs/api/Dispatcher.md#event-disconnect). + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when socket has disconnected. The error argument of the event is the error which caused the socket to disconnect. The client will reconnect if or once `client.size > 0`. + +#### Example - Client disconnect event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.destroy() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('disconnect', (origin) => { + console.log(`Disconnected from ${origin}`) +}) + +try { + await client.request({ + path: '/', + method: 'GET' + }) +} catch (error) { + console.error(error.message) + client.close() + server.close() +} +``` + +### Event: `'drain'` + +Emitted when pipeline is no longer busy. + +See [Dispatcher Event: `'drain'`](/docs/docs/api/Dispatcher.md#event-drain). + +#### Example - Client drain event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('drain', () => { + console.log('drain event') + client.close() + server.close() +}) + +const requests = [ + client.request({ path: '/', method: 'GET' }), + client.request({ path: '/', method: 'GET' }), + client.request({ path: '/', method: 'GET' }) +] + +await Promise.all(requests) + +console.log('requests completed') +``` + +### Event: `'error'` + +Invoked for users errors such as throwing in the `onError` handler. diff --git a/node_modules/undici/docs/docs/api/ClientStats.md b/node_modules/undici/docs/docs/api/ClientStats.md new file mode 100644 index 000000000..fa899d482 --- /dev/null +++ b/node_modules/undici/docs/docs/api/ClientStats.md @@ -0,0 +1,27 @@ +# Class: ClientStats + +Stats for a [Client](/docs/docs/api/Client.md). + +## `new ClientStats(client)` + +Arguments: + +* **client** `Client` - Client from which to return stats. + +## Instance Properties + +### `ClientStats.connected` + +Boolean if socket as open connection by this client. + +### `ClientStats.pending` + +Number of pending requests of this client. + +### `ClientStats.running` + +Number of currently active requests across this client. + +### `ClientStats.size` + +Number of active, pending, or queued requests of this clients. diff --git a/node_modules/undici/docs/docs/api/Connector.md b/node_modules/undici/docs/docs/api/Connector.md new file mode 100644 index 000000000..56821bd64 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Connector.md @@ -0,0 +1,115 @@ +# Connector + +Undici creates the underlying socket via the connector builder. +Normally, this happens automatically and you don't need to care about this, +but if you need to perform some additional check over the currently used socket, +this is the right place. + +If you want to create a custom connector, you must import the `buildConnector` utility. + +#### Parameter: `buildConnector.BuildOptions` + +Every Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +Furthermore, the following options can be passed: + +* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: `100`. +* **timeout** `number | null` (optional) - In milliseconds. Default `10e3`. +* **servername** `string | null` (optional) + +Once you call `buildConnector`, it will return a connector function, which takes the following parameters. + +#### Parameter: `connector.Options` + +* **hostname** `string` (required) +* **host** `string` (optional) +* **protocol** `string` (required) +* **port** `string` (required) +* **servername** `string` (optional) +* **localAddress** `string | null` (optional) Local address the socket should connect from. +* **httpSocket** `Socket` (optional) Establish secure connection on a given socket rather than creating a new socket. It can only be sent on TLS update. + +### Basic example + +```js +'use strict' + +import { Client, buildConnector } from 'undici' + +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (/* assertion */) { + socket.destroy() + cb(new Error('kaboom')) + } else { + cb(null, socket) + } + }) + } +}) +``` + +### Example: validate the CA fingerprint + +```js +'use strict' + +import { Client, buildConnector } from 'undici' + +const caFingerprint = 'FO:OB:AR' +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (getIssuerCertificate(socket).fingerprint256 !== caFingerprint) { + socket.destroy() + cb(new Error('Fingerprint does not match or malformed certificate')) + } else { + cb(null, socket) + } + }) + } +}) + +client.request({ + path: '/', + method: 'GET' +}, (err, data) => { + if (err) throw err + + const bufs = [] + data.body.on('data', (buf) => { + bufs.push(buf) + }) + data.body.on('end', () => { + console.log(Buffer.concat(bufs).toString('utf8')) + client.close() + }) +}) + +function getIssuerCertificate (socket) { + let certificate = socket.getPeerCertificate(true) + while (certificate && Object.keys(certificate).length > 0) { + // invalid certificate + if (certificate.issuerCertificate == null) { + return null + } + + // We have reached the root certificate. + // In case of self-signed certificates, `issuerCertificate` may be a circular reference. + if (certificate.fingerprint256 === certificate.issuerCertificate.fingerprint256) { + break + } + + // continue the loop + certificate = certificate.issuerCertificate + } + return certificate +} +``` diff --git a/node_modules/undici/docs/docs/api/ContentType.md b/node_modules/undici/docs/docs/api/ContentType.md new file mode 100644 index 000000000..2bcc9f71c --- /dev/null +++ b/node_modules/undici/docs/docs/api/ContentType.md @@ -0,0 +1,57 @@ +# MIME Type Parsing + +## `MIMEType` interface + +* **type** `string` +* **subtype** `string` +* **parameters** `Map` +* **essence** `string` + +## `parseMIMEType(input)` + +Implements [parse a MIME type](https://mimesniff.spec.whatwg.org/#parse-a-mime-type). + +Parses a MIME type, returning its type, subtype, and any associated parameters. If the parser can't parse an input it returns the string literal `'failure'`. + +```js +import { parseMIMEType } from 'undici' + +parseMIMEType('text/html; charset=gbk') +// { +// type: 'text', +// subtype: 'html', +// parameters: Map(1) { 'charset' => 'gbk' }, +// essence: 'text/html' +// } +``` + +Arguments: + +* **input** `string` + +Returns: `MIMEType|'failure'` + +## `serializeAMimeType(input)` + +Implements [serialize a MIME type](https://mimesniff.spec.whatwg.org/#serialize-a-mime-type). + +Serializes a MIMEType object. + +```js +import { serializeAMimeType } from 'undici' + +serializeAMimeType({ + type: 'text', + subtype: 'html', + parameters: new Map([['charset', 'gbk']]), + essence: 'text/html' +}) +// text/html;charset=gbk + +``` + +Arguments: + +* **mimeType** `MIMEType` + +Returns: `string` diff --git a/node_modules/undici/docs/docs/api/Cookies.md b/node_modules/undici/docs/docs/api/Cookies.md new file mode 100644 index 000000000..0cad37914 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Cookies.md @@ -0,0 +1,101 @@ +# Cookie Handling + +## `Cookie` interface + +* **name** `string` +* **value** `string` +* **expires** `Date|number` (optional) +* **maxAge** `number` (optional) +* **domain** `string` (optional) +* **path** `string` (optional) +* **secure** `boolean` (optional) +* **httpOnly** `boolean` (optional) +* **sameSite** `'String'|'Lax'|'None'` (optional) +* **unparsed** `string[]` (optional) Left over attributes that weren't parsed. + +## `deleteCookie(headers, name[, attributes])` + +Sets the expiry time of the cookie to the unix epoch, causing browsers to delete it when received. + +```js +import { deleteCookie, Headers } from 'undici' + +const headers = new Headers() +deleteCookie(headers, 'name') + +console.log(headers.get('set-cookie')) // name=; Expires=Thu, 01 Jan 1970 00:00:00 GMT +``` + +Arguments: + +* **headers** `Headers` +* **name** `string` +* **attributes** `{ path?: string, domain?: string }` (optional) + +Returns: `void` + +## `getCookies(headers)` + +Parses the `Cookie` header and returns a list of attributes and values. + +```js +import { getCookies, Headers } from 'undici' + +const headers = new Headers({ + cookie: 'get=cookies; and=attributes' +}) + +console.log(getCookies(headers)) // { get: 'cookies', and: 'attributes' } +``` + +Arguments: + +* **headers** `Headers` + +Returns: `Record` + +## `getSetCookies(headers)` + +Parses all `Set-Cookie` headers. + +```js +import { getSetCookies, Headers } from 'undici' + +const headers = new Headers({ 'set-cookie': 'undici=getSetCookies; Secure' }) + +console.log(getSetCookies(headers)) +// [ +// { +// name: 'undici', +// value: 'getSetCookies', +// secure: true +// } +// ] + +``` + +Arguments: + +* **headers** `Headers` + +Returns: `Cookie[]` + +## `setCookie(headers, cookie)` + +Appends a cookie to the `Set-Cookie` header. + +```js +import { setCookie, Headers } from 'undici' + +const headers = new Headers() +setCookie(headers, { name: 'undici', value: 'setCookie' }) + +console.log(headers.get('Set-Cookie')) // undici=setCookie +``` + +Arguments: + +* **headers** `Headers` +* **cookie** `Cookie` + +Returns: `void` diff --git a/node_modules/undici/docs/docs/api/Debug.md b/node_modules/undici/docs/docs/api/Debug.md new file mode 100644 index 000000000..69c7d7b4f --- /dev/null +++ b/node_modules/undici/docs/docs/api/Debug.md @@ -0,0 +1,62 @@ +# Debug + +Undici (and subsenquently `fetch` and `websocket`) exposes a debug statement that can be enabled by setting `NODE_DEBUG` within the environment. + +The flags available are: + +## `undici` + +This flag enables debug statements for the core undici library. + +```sh +NODE_DEBUG=undici node script.js + +UNDICI 16241: connecting to nodejs.org using https:h1 +UNDICI 16241: connecting to nodejs.org using https:h1 +UNDICI 16241: connected to nodejs.org using https:h1 +UNDICI 16241: sending request to GET https://nodejs.org/ +UNDICI 16241: received response to GET https://nodejs.org/ - HTTP 307 +UNDICI 16241: connecting to nodejs.org using https:h1 +UNDICI 16241: trailers received from GET https://nodejs.org/ +UNDICI 16241: connected to nodejs.org using https:h1 +UNDICI 16241: sending request to GET https://nodejs.org/en +UNDICI 16241: received response to GET https://nodejs.org/en - HTTP 200 +UNDICI 16241: trailers received from GET https://nodejs.org/en +``` + +## `fetch` + +This flag enables debug statements for the `fetch` API. + +> **Note**: statements are pretty similar to the ones in the `undici` flag, but scoped to `fetch` + +```sh +NODE_DEBUG=fetch node script.js + +FETCH 16241: connecting to nodejs.org using https:h1 +FETCH 16241: connecting to nodejs.org using https:h1 +FETCH 16241: connected to nodejs.org using https:h1 +FETCH 16241: sending request to GET https://nodejs.org/ +FETCH 16241: received response to GET https://nodejs.org/ - HTTP 307 +FETCH 16241: connecting to nodejs.org using https:h1 +FETCH 16241: trailers received from GET https://nodejs.org/ +FETCH 16241: connected to nodejs.org using https:h1 +FETCH 16241: sending request to GET https://nodejs.org/en +FETCH 16241: received response to GET https://nodejs.org/en - HTTP 200 +FETCH 16241: trailers received from GET https://nodejs.org/en +``` + +## `websocket` + +This flag enables debug statements for the `Websocket` API. + +> **Note**: statements can overlap with `UNDICI` ones if `undici` or `fetch` flag has been enabled as well. + +```sh +NODE_DEBUG=websocket node script.js + +WEBSOCKET 18309: connecting to echo.websocket.org using https:h1 +WEBSOCKET 18309: connected to echo.websocket.org using https:h1 +WEBSOCKET 18309: sending request to GET https://echo.websocket.org/ +WEBSOCKET 18309: connection opened +``` diff --git a/node_modules/undici/docs/docs/api/DiagnosticsChannel.md b/node_modules/undici/docs/docs/api/DiagnosticsChannel.md new file mode 100644 index 000000000..acf25e082 --- /dev/null +++ b/node_modules/undici/docs/docs/api/DiagnosticsChannel.md @@ -0,0 +1,313 @@ +# Diagnostics Channel Support + +Stability: Experimental. + +Undici supports the [`diagnostics_channel`](https://nodejs.org/api/diagnostics_channel.html) (currently available only on Node.js v16+). +It is the preferred way to instrument Undici and retrieve internal information. + +The channels available are the following. + +## `undici:request:create` + +This message is published when a new outgoing request is created. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:create').subscribe(({ request }) => { + console.log('origin', request.origin) + console.log('completed', request.completed) + console.log('method', request.method) + console.log('path', request.path) + console.log('headers', request.headers) // array of strings, e.g: ['foo', 'bar'] + request.addHeader('hello', 'world') + console.log('headers', request.headers) // e.g. ['foo', 'bar', 'hello', 'world'] +}) +``` + +Note: a request is only loosely completed to a given socket. + +## `undici:request:bodyChunkSent` + +This message is published when a chunk of the request body is being sent. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:bodyChunkSent').subscribe(({ request, chunk }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:request:bodySent` + +This message is published after the request body has been fully sent. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:bodySent').subscribe(({ request }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:request:headers` + +This message is published after the response headers have been received. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:headers').subscribe(({ request, response }) => { + // request is the same object undici:request:create + console.log('statusCode', response.statusCode) + console.log(response.statusText) + // response.headers are buffers. + console.log(response.headers.map((x) => x.toString())) +}) +``` + +## `undici:request:bodyChunkReceived` + +This message is published after a chunk of the response body has been received. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:bodyChunkReceived').subscribe(({ request, chunk }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:request:trailers` + +This message is published after the response body and trailers have been received, i.e. the response has been completed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:trailers').subscribe(({ request, trailers }) => { + // request is the same object undici:request:create + console.log('completed', request.completed) + // trailers are buffers. + console.log(trailers.map((x) => x.toString())) +}) +``` + +## `undici:request:error` + +This message is published if the request is going to error, but it has not errored yet. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:error').subscribe(({ request, error }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:client:sendHeaders` + +This message is published right before the first byte of the request is written to the socket. + +*Note*: It will publish the exact headers that will be sent to the server in raw format. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(({ request, headers, socket }) => { + // request is the same object undici:request:create + console.log(`Full headers list ${headers.split('\r\n')}`); +}) +``` + +## `undici:client:beforeConnect` + +This message is published before creating a new connection for **any** request. +You can not assume that this event is related to any specific request. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(({ connectParams, connector }) => { + // const { host, hostname, protocol, port, servername, version } = connectParams + // connector is a function that creates the socket +}) +``` + +## `undici:client:connected` + +This message is published after a connection is established. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:connected').subscribe(({ socket, connectParams, connector }) => { + // const { host, hostname, protocol, port, servername, version } = connectParams + // connector is a function that creates the socket +}) +``` + +## `undici:client:connectError` + +This message is published if it did not succeed to create new connection + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:connectError').subscribe(({ error, socket, connectParams, connector }) => { + // const { host, hostname, protocol, port, servername, version } = connectParams + // connector is a function that creates the socket + console.log(`Connect failed with ${error.message}`) +}) +``` + +## `undici:websocket:open` + +This message is published after the client has successfully connected to a server. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:open').subscribe(({ + address, // { address: string, family: string, port: number } + protocol, // string - negotiated subprotocol + extensions, // string - negotiated extensions + websocket, // WebSocket - the WebSocket instance + handshakeResponse // object - HTTP response that upgraded the connection +}) => { + console.log(address) // address, family, and port + console.log(protocol) // negotiated subprotocols + console.log(extensions) // negotiated extensions + console.log(websocket) // the WebSocket instance + + // Handshake response details + console.log(handshakeResponse.status) // 101 for successful WebSocket upgrade + console.log(handshakeResponse.statusText) // 'Switching Protocols' + console.log(handshakeResponse.headers) // Object containing response headers +}) +``` + +### Handshake Response Object + +The `handshakeResponse` object contains the HTTP response that upgraded the connection to WebSocket: + +- `status` (number): The HTTP status code (101 for successful WebSocket upgrade) +- `statusText` (string): The HTTP status message ('Switching Protocols' for successful upgrade) +- `headers` (object): The HTTP response headers from the server, including: + - `upgrade: 'websocket'` + - `connection: 'upgrade'` + - `sec-websocket-accept` and other WebSocket-related headers + +This information is particularly useful for debugging and monitoring WebSocket connections, as it provides access to the initial HTTP handshake response that established the WebSocket connection. + +## `undici:websocket:close` + +This message is published after the connection has closed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:close').subscribe(({ websocket, code, reason }) => { + console.log(websocket) // the WebSocket instance + console.log(code) // the closing status code + console.log(reason) // the closing reason +}) +``` + +## `undici:websocket:socket_error` + +This message is published if the socket experiences an error. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:socket_error').subscribe((error) => { + console.log(error) +}) +``` + +## `undici:websocket:ping` + +This message is published after the client receives a ping frame, if the connection is not closing. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:ping').subscribe(({ payload, websocket }) => { + // a Buffer or undefined, containing the optional application data of the frame + console.log(payload) + console.log(websocket) // the WebSocket instance +}) +``` + +## `undici:websocket:pong` + +This message is published after the client receives a pong frame. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:pong').subscribe(({ payload, websocket }) => { + // a Buffer or undefined, containing the optional application data of the frame + console.log(payload) + console.log(websocket) // the WebSocket instance +}) +``` + +## `undici:proxy:connected` + +This message is published after the `ProxyAgent` establishes a connection to the proxy server. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:proxy:connected').subscribe(({ socket, connectParams }) => { + console.log(socket) + console.log(connectParams) + // const { origin, port, path, signal, headers, servername } = connectParams +}) +``` + +## `undici:request:pending-requests` + +This message is published when the deduplicate interceptor's pending request map changes. This is useful for monitoring and debugging request deduplication behavior. + +The deduplicate interceptor automatically deduplicates concurrent requests for the same resource. When multiple identical requests are made while one is already in-flight, only one request is sent to the origin server, and all waiting handlers receive the same response. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:pending-requests').subscribe(({ type, size, key }) => { + console.log(type) // 'added' or 'removed' + console.log(size) // current number of pending requests + console.log(key) // the deduplication key for this request +}) +``` + +### Event Properties + +- `type` (`string`): Either `'added'` when a new pending request is registered, or `'removed'` when a pending request completes (successfully or with an error). +- `size` (`number`): The current number of pending requests after the change. +- `key` (`string`): The deduplication key for the request, composed of the origin, method, path, and request headers. + +### Example: Monitoring Request Deduplication + +```js +import diagnosticsChannel from 'diagnostics_channel' + +const channel = diagnosticsChannel.channel('undici:request:pending-requests') + +channel.subscribe(({ type, size, key }) => { + if (type === 'added') { + console.log(`New pending request: ${key} (${size} total pending)`) + } else { + console.log(`Request completed: ${key} (${size} remaining)`) + } +}) +``` + +This can be useful for: +- Verifying that request deduplication is working as expected +- Monitoring the number of concurrent in-flight requests +- Debugging deduplication behavior in production environments diff --git a/node_modules/undici/docs/docs/api/Dispatcher.md b/node_modules/undici/docs/docs/api/Dispatcher.md new file mode 100644 index 000000000..f86392678 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Dispatcher.md @@ -0,0 +1,1364 @@ +# Dispatcher + +Extends: `events.EventEmitter` + +Dispatcher is the core API used to dispatch requests. + +Requests are not guaranteed to be dispatched in order of invocation. + +## Instance Methods + +### `Dispatcher.close([callback]): Promise` + +Closes the dispatcher and gracefully waits for enqueued requests to complete before resolving. + +Arguments: + +* **callback** `(error: Error | null, data: null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +```js +dispatcher.close() // -> Promise +dispatcher.close(() => {}) // -> void +``` + +#### Example - Request resolves before Client closes + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('undici') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.setEncoding('utf8') + body.on('data', console.log) +} catch (error) {} + +await client.close() + +console.log('Client closed') +server.close() +``` + +### `Dispatcher.connect(options[, callback])` + +Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT). + +Arguments: + +* **options** `ConnectOptions` +* **callback** `(err: Error | null, data: ConnectData | null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `ConnectOptions` + +* **path** `string` +* **headers** `UndiciHeaders` (optional) - Default: `null` +* **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null` +* **opaque** `unknown` (optional) - This argument parameter is passed through to `ConnectData` + +#### Parameter: `ConnectData` + +* **statusCode** `number` +* **headers** `Record` +* **socket** `stream.Duplex` +* **opaque** `unknown` + +#### Example - Connect request with echo + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + throw Error('should never get here') +}).listen() + +server.on('connect', (req, socket, head) => { + socket.write('HTTP/1.1 200 Connection established\r\n\r\n') + + let data = head.toString() + socket.on('data', (buf) => { + data += buf.toString() + }) + + socket.on('end', () => { + socket.end(data) + }) +}) + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { socket } = await client.connect({ + path: '/' + }) + const wanted = 'Body' + let data = '' + socket.on('data', d => { data += d }) + socket.on('end', () => { + console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`) + client.close() + server.close() + }) + socket.write(wanted) + socket.end() +} catch (error) { } +``` + +### `Dispatcher.destroy([error, callback]): Promise` + +Destroy the dispatcher abruptly with the given error. All the pending and running requests will be asynchronously aborted and error. Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. + +Both arguments are optional; the method can be called in four different ways: + +Arguments: + +* **error** `Error | null` (optional) +* **callback** `(error: Error | null, data: null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +```js +dispatcher.destroy() // -> Promise +dispatcher.destroy(new Error()) // -> Promise +dispatcher.destroy(() => {}) // -> void +dispatcher.destroy(new Error(), () => {}) // -> void +``` + +#### Example - Request is aborted when Client is destroyed + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const request = client.request({ + path: '/', + method: 'GET' + }) + client.destroy() + .then(() => { + console.log('Client destroyed') + server.close() + }) + await request +} catch (error) { + console.error(error) +} +``` + +### `Dispatcher.dispatch(options, handler)` + +This is the low level API which all the preceding APIs are implemented on top of. +This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. +It is primarily intended for library developers who implement higher level APIs on top of this. + +Arguments: + +* **options** `DispatchOptions` +* **handler** `DispatchHandler` + +Returns: `Boolean` - `false` if dispatcher is busy and further dispatch calls won't make any progress until the `'drain'` event has been emitted. + +#### Parameter: `DispatchOptions` + +* **origin** `string | URL` +* **path** `string` +* **method** `string` +* **reset** `boolean` (optional) - Default: `false` - If `false`, the request will attempt to create a long-living connection by sending the `connection: keep-alive` header,otherwise will attempt to close it immediately after response by sending `connection: close` within the request and closing the socket afterwards. +* **body** `string | Buffer | Uint8Array | stream.Readable | Iterable | AsyncIterable | null` (optional) - Default: `null` +* **headers** `UndiciHeaders` (optional) - Default: `null`. +* **query** `Record | null` (optional) - Default: `null` - Query string params to be embedded in the request URL. Note that both keys and values of query are encoded using `encodeURIComponent`. If for some reason you need to send them unencoded, embed query params into path directly instead. +* **idempotent** `boolean` (optional) - Default: `true` if `method` is `'HEAD'` or `'GET'` - Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline has completed. +* **blocking** `boolean` (optional) - Default: `method !== 'HEAD'` - Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. +* **upgrade** `string | null` (optional) - Default: `null` - Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. +* **bodyTimeout** `number | null` (optional) - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. +* **headersTimeout** `number | null` (optional) - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +* **expectContinue** `boolean` (optional) - Default: `false` - For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server + +#### Parameter: `DispatchHandler` + +* **onRequestStart** `(controller: DispatchController, context: object) => void` - Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. +* **onRequestUpgrade** `(controller: DispatchController, statusCode: number, headers: Record, socket: Duplex) => void` (optional) - Invoked when request is upgraded. Required if `DispatchOptions.upgrade` is defined or `DispatchOptions.method === 'CONNECT'`. +* **onResponseStart** `(controller: DispatchController, statusCode: number, headers: Record, statusMessage?: string) => void` - Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. Not required for `upgrade` requests. +* **onResponseData** `(controller: DispatchController, chunk: Buffer) => void` - Invoked when response payload data is received. Not required for `upgrade` requests. +* **onResponseEnd** `(controller: DispatchController, trailers: Record) => void` - Invoked when response payload and trailers have been received and the request has completed. Not required for `upgrade` requests. +* **onResponseError** `(controller: DispatchController, error: Error) => void` - Invoked when an error has occurred. May not throw. + +#### Example 1 - Dispatch GET request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const data = [] + +client.dispatch({ + path: '/', + method: 'GET', + headers: { + 'x-foo': 'bar' + } +}, { + onConnect: () => { + console.log('Connected!') + }, + onError: (error) => { + console.error(error) + }, + onHeaders: (statusCode, headers) => { + console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`) + }, + onData: (chunk) => { + console.log('onData: chunk received') + data.push(chunk) + }, + onComplete: (trailers) => { + console.log(`onComplete | trailers: ${trailers}`) + const res = Buffer.concat(data).toString('utf8') + console.log(`Data: ${res}`) + client.close() + server.close() + } +}) +``` + +#### Example 2 - Dispatch Upgrade Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end() +}).listen() + +await once(server, 'listening') + +server.on('upgrade', (request, socket, head) => { + console.log('Node.js Server - upgrade event') + socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n') + socket.write('Upgrade: WebSocket\r\n') + socket.write('Connection: Upgrade\r\n') + socket.write('\r\n') + socket.end() +}) + +const client = new Client(`http://localhost:${server.address().port}`) + +client.dispatch({ + path: '/', + method: 'GET', + upgrade: 'websocket' +}, { + onConnect: () => { + console.log('Undici Client - onConnect') + }, + onError: (error) => { + console.log('onError') // shouldn't print + }, + onUpgrade: (statusCode, headers, socket) => { + console.log('Undici Client - onUpgrade') + console.log(`onUpgrade Headers: ${headers}`) + socket.on('data', buffer => { + console.log(buffer.toString('utf8')) + }) + socket.on('end', () => { + client.close() + server.close() + }) + socket.end() + } +}) +``` + +#### Example 3 - Dispatch POST request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + request.on('data', (data) => { + console.log(`Request Data: ${data.toString('utf8')}`) + const body = JSON.parse(data) + body.message = 'World' + response.end(JSON.stringify(body)) + }) +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const data = [] + +client.dispatch({ + path: '/', + method: 'POST', + headers: { + 'content-type': 'application/json' + }, + body: JSON.stringify({ message: 'Hello' }) +}, { + onConnect: () => { + console.log('Connected!') + }, + onError: (error) => { + console.error(error) + }, + onHeaders: (statusCode, headers) => { + console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`) + }, + onData: (chunk) => { + console.log('onData: chunk received') + data.push(chunk) + }, + onComplete: (trailers) => { + console.log(`onComplete | trailers: ${trailers}`) + const res = Buffer.concat(data).toString('utf8') + console.log(`Response Data: ${res}`) + client.close() + server.close() + } +}) +``` + +### `Dispatcher.pipeline(options, handler)` + +For easy use with [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback). The `handler` argument should return a `Readable` from which the result will be read. Usually it should just return the `body` argument unless some kind of transformation needs to be performed based on e.g. `headers` or `statusCode`. The `handler` should validate the response and save any required state. If there is an error, it should be thrown. The function returns a `Duplex` which writes to the request and reads from the response. + +Arguments: + +* **options** `PipelineOptions` +* **handler** `(data: PipelineHandlerData) => stream.Readable` + +Returns: `stream.Duplex` + +#### Parameter: PipelineOptions + +Extends: [`RequestOptions`](/docs/docs/api/Dispatcher.md#parameter-requestoptions) + +* **objectMode** `boolean` (optional) - Default: `false` - Set to `true` if the `handler` will return an object stream. + +#### Parameter: PipelineHandlerData + +* **statusCode** `number` +* **headers** `Record` +* **opaque** `unknown` +* **body** `stream.Readable` +* **context** `object` +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +#### Example 1 - Pipeline Echo + +```js +import { Readable, Writable, PassThrough, pipeline } from 'stream' +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + request.pipe(response) +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +let res = '' + +pipeline( + new Readable({ + read () { + this.push(Buffer.from('undici')) + this.push(null) + } + }), + client.pipeline({ + path: '/', + method: 'GET' + }, ({ statusCode, headers, body }) => { + console.log(`response received ${statusCode}`) + console.log('headers', headers) + return pipeline(body, new PassThrough(), () => {}) + }), + new Writable({ + write (chunk, _, callback) { + res += chunk.toString() + callback() + }, + final (callback) { + console.log(`Response pipelined to writable: ${res}`) + callback() + } + }), + error => { + if (error) { + console.error(error) + } + + client.close() + server.close() + } +) +``` + +### `Dispatcher.request(options[, callback])` + +Performs a HTTP request. + +Non-idempotent requests will not be pipelined in order +to avoid indirect failures. + +Idempotent requests will be automatically retried if +they fail due to indirect failure from the request +at the head of the pipeline. This does not apply to +idempotent requests with a stream request body. + +All response bodies must always be fully consumed or destroyed. + +Arguments: + +* **options** `RequestOptions` +* **callback** `(error: Error | null, data: ResponseData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed. + +#### Parameter: `RequestOptions` + +Extends: [`DispatchOptions`](/docs/docs/api/Dispatcher.md#parameter-dispatchoptions) + +* **opaque** `unknown` (optional) - Default: `null` - Used for passing through context to `ResponseData`. +* **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null`. +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +The `RequestOptions.method` property should not be value `'CONNECT'`. + +#### Parameter: `ResponseData` + +* **statusCode** `number` +* **headers** `Record` - Note that all header keys are lower-cased, e.g. `content-type`. +* **body** `stream.Readable` which also implements [the body mixin from the Fetch Standard](https://fetch.spec.whatwg.org/#body-mixin). +* **trailers** `Record` - This object starts out + as empty and will be mutated to contain trailers after `body` has emitted `'end'`. +* **opaque** `unknown` +* **context** `object` + +`body` contains the following additional [body mixin](https://fetch.spec.whatwg.org/#body-mixin) methods and properties: + +* [`.arrayBuffer()`](https://fetch.spec.whatwg.org/#dom-body-arraybuffer) +* [`.blob()`](https://fetch.spec.whatwg.org/#dom-body-blob) +* [`.bytes()`](https://fetch.spec.whatwg.org/#dom-body-bytes) +* [`.json()`](https://fetch.spec.whatwg.org/#dom-body-json) +* [`.text()`](https://fetch.spec.whatwg.org/#dom-body-text) +* `body` +* `bodyUsed` + +`body` can not be consumed twice. For example, calling `text()` after `json()` throws `TypeError`. + +`body` contains the following additional extensions: + +- `dump({ limit: Integer })`, dump the response by reading up to `limit` bytes without killing the socket (optional) - Default: 262144. + +Note that body will still be a `Readable` even if it is empty, but attempting to deserialize it with `json()` will result in an exception. Recommended way to ensure there is a body to deserialize is to check if status code is not 204, and `content-type` header starts with `application/json`. + +#### Example 1 - Basic GET Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body, headers, statusCode, trailers } = await client.request({ + path: '/', + method: 'GET' + }) + console.log(`response received ${statusCode}`) + console.log('headers', headers) + body.setEncoding('utf8') + body.on('data', console.log) + body.on('error', console.error) + body.on('end', () => { + console.log('trailers', trailers) + }) + + client.close() + server.close() +} catch (error) { + console.error(error) +} +``` + +#### Example 2 - Aborting a request + +> Node.js v15+ is required to run this example + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) +const abortController = new AbortController() + +try { + client.request({ + path: '/', + method: 'GET', + signal: abortController.signal + }) +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} + +abortController.abort() +``` + +Alternatively, any `EventEmitter` that emits an `'abort'` event may be used as an abort controller: + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import EventEmitter, { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) +const ee = new EventEmitter() + +try { + client.request({ + path: '/', + method: 'GET', + signal: ee + }) +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} + +ee.emit('abort') +``` + +Destroying the request or response body will have the same effect. + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.destroy() +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} +``` + +#### Example 3 - Conditionally reading the body + +Remember to fully consume the body even in the case when it is not read. + +```js +const { body, statusCode } = await client.request({ + path: '/', + method: 'GET' +}) + +if (statusCode === 200) { + return await body.arrayBuffer() +} + +await body.dump() + +return null +``` + +### `Dispatcher.stream(options, factory[, callback])` + +A faster version of `Dispatcher.request`. This method expects the second argument `factory` to return a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream which the response will be written to. This improves performance by avoiding creating an intermediate [`stream.Readable`](https://nodejs.org/api/stream.html#stream_readable_streams) stream when the user expects to directly pipe the response body to a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream. + +As demonstrated in [Example 1 - Basic GET stream request](/docs/docs/api/Dispatcher.md#example-1-basic-get-stream-request), it is recommended to use the `option.opaque` property to avoid creating a closure for the `factory` method. This pattern works well with Node.js Web Frameworks such as [Fastify](https://fastify.io). See [Example 2 - Stream to Fastify Response](/docs/docs/api/Dispatch.md#example-2-stream-to-fastify-response) for more details. + +Arguments: + +* **options** `RequestOptions` +* **factory** `(data: StreamFactoryData) => stream.Writable` +* **callback** `(error: Error | null, data: StreamData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `StreamFactoryData` + +* **statusCode** `number` +* **headers** `Record` +* **opaque** `unknown` +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +#### Parameter: `StreamData` + +* **opaque** `unknown` +* **trailers** `Record` +* **context** `object` + +#### Example 1 - Basic GET stream request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' +import { Writable } from 'stream' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const bufs = [] + +try { + await client.stream({ + path: '/', + method: 'GET', + opaque: { bufs } + }, ({ statusCode, headers, opaque: { bufs } }) => { + console.log(`response received ${statusCode}`) + console.log('headers', headers) + return new Writable({ + write (chunk, encoding, callback) { + bufs.push(chunk) + callback() + } + }) + }) + + console.log(Buffer.concat(bufs).toString('utf-8')) + + client.close() + server.close() +} catch (error) { + console.error(error) +} +``` + +#### Example 2 - Stream to Fastify Response + +In this example, a (fake) request is made to the fastify server using `fastify.inject()`. This request then executes the fastify route handler which makes a subsequent request to the raw Node.js http server using `undici.dispatcher.stream()`. The fastify response is passed to the `opaque` option so that undici can tap into the underlying writable stream using `response.raw`. This methodology demonstrates how one could use undici and fastify together to create fast-as-possible requests from one backend server to another. + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' +import fastify from 'fastify' + +const nodeServer = createServer((request, response) => { + response.end('Hello, World! From Node.js HTTP Server') +}).listen() + +await once(nodeServer, 'listening') + +console.log('Node Server listening') + +const nodeServerUndiciClient = new Client(`http://localhost:${nodeServer.address().port}`) + +const fastifyServer = fastify() + +fastifyServer.route({ + url: '/', + method: 'GET', + handler: (request, response) => { + nodeServerUndiciClient.stream({ + path: '/', + method: 'GET', + opaque: response + }, ({ opaque }) => opaque.raw) + } +}) + +await fastifyServer.listen() + +console.log('Fastify Server listening') + +const fastifyServerUndiciClient = new Client(`http://localhost:${fastifyServer.server.address().port}`) + +try { + const { statusCode, body } = await fastifyServerUndiciClient.request({ + path: '/', + method: 'GET' + }) + + console.log(`response received ${statusCode}`) + body.setEncoding('utf8') + body.on('data', console.log) + + nodeServerUndiciClient.close() + fastifyServerUndiciClient.close() + fastifyServer.close() + nodeServer.close() +} catch (error) { } +``` + +### `Dispatcher.upgrade(options[, callback])` + +Upgrade to a different protocol. Visit [MDN - HTTP - Protocol upgrade mechanism](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) for more details. + +Arguments: + +* **options** `UpgradeOptions` + +* **callback** `(error: Error | null, data: UpgradeData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `UpgradeOptions` + +* **path** `string` +* **method** `string` (optional) - Default: `'GET'` +* **headers** `UndiciHeaders` (optional) - Default: `null` +* **protocol** `string` (optional) - Default: `'Websocket'` - A string of comma separated protocols, in descending preference order. +* **signal** `AbortSignal | EventEmitter | null` (optional) - Default: `null` + +#### Parameter: `UpgradeData` + +* **headers** `http.IncomingHeaders` +* **socket** `stream.Duplex` +* **opaque** `unknown` + +#### Example 1 - Basic Upgrade Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.statusCode = 101 + response.setHeader('connection', 'upgrade') + response.setHeader('upgrade', request.headers.upgrade) + response.end() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { headers, socket } = await client.upgrade({ + path: '/', + }) + socket.on('end', () => { + console.log(`upgrade: ${headers.upgrade}`) // upgrade: Websocket + client.close() + server.close() + }) + socket.end() +} catch (error) { + console.error(error) + client.close() + server.close() +} +``` + +### `Dispatcher.compose(interceptors[, interceptor])` + +Compose a new dispatcher from the current dispatcher and the given interceptors. + +> _Notes_: +> - The order of the interceptors matters. The last interceptor will be the first to be called. +> - It is important to note that the `interceptor` function should return a function that follows the `Dispatcher.dispatch` signature. +> - Any fork of the chain of `interceptors` can lead to unexpected results. +> +> **Interceptor Stack Visualization:** +> ``` +> compose([interceptor1, interceptor2, interceptor3]) +> +> Request Flow: +> ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ +> │ Request │───▶│interceptor3 │───▶│interceptor2 │───▶│interceptor1 │───▶│ dispatcher │ +> └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │ .dispatch │ +> ▲ ▲ ▲ └─────────────┘ +> │ │ │ ▲ +> (called first) (called second) (called last) │ +> │ +> ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ +> │ Response │◀───│interceptor3 │◀───│interceptor2 │◀───│interceptor1 │◀─────────┘ +> └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ +> +> The interceptors are composed in reverse order due to function composition. +> ``` + +Arguments: + +* **interceptors** `Interceptor[interceptor[]]`: It is an array of `Interceptor` functions passed as only argument, or several interceptors passed as separate arguments. + +Returns: `Dispatcher`. + +#### Parameter: `Interceptor` + +A function that takes a `dispatch` method and returns a `dispatch`-like function. + +#### Example 1 - Basic Compose + +```js +const { Client, RedirectHandler } = require('undici') + +const redirectInterceptor = dispatch => { + return (opts, handler) => { + const { maxRedirections } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler( + dispatch, + maxRedirections, + opts, + handler + ) + opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } +} + +const client = new Client('http://localhost:3000') + .compose(redirectInterceptor) + +await client.request({ path: '/', method: 'GET' }) +``` + +#### Example 2 - Chained Compose + +```js +const { Client, RedirectHandler, RetryHandler } = require('undici') + +const redirectInterceptor = dispatch => { + return (opts, handler) => { + const { maxRedirections } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler( + dispatch, + maxRedirections, + opts, + handler + ) + opts = { ...opts, maxRedirections: 0 } + return dispatch(opts, redirectHandler) + } +} + +const retryInterceptor = dispatch => { + return function retryInterceptor (opts, handler) { + return dispatch( + opts, + new RetryHandler(opts, { + handler, + dispatch + }) + ) + } +} + +const client = new Client('http://localhost:3000') + .compose(redirectInterceptor) + .compose(retryInterceptor) + +await client.request({ path: '/', method: 'GET' }) +``` + +#### Pre-built interceptors + +##### `redirect` + +The `redirect` interceptor allows you to customize the way your dispatcher handles redirects. + +It accepts the same arguments as the [`RedirectHandler` constructor](/docs/docs/api/RedirectHandler.md). + +**Example - Basic Redirect Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { redirect } = interceptors; + +const client = new Client("http://example.com").compose( + redirect({ maxRedirections: 3, throwOnMaxRedirects: true }) +); +client.request({ path: "/" }) +``` + +##### `retry` + +The `retry` interceptor allows you to customize the way your dispatcher handles retries. + +It accepts the same arguments as the [`RetryHandler` constructor](/docs/docs/api/RetryHandler.md). + +**Example - Basic Redirect Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { retry } = interceptors; + +const client = new Client("http://example.com").compose( + retry({ + maxRetries: 3, + minTimeout: 1000, + maxTimeout: 10000, + timeoutFactor: 2, + retryAfter: true, + }) +); +``` + +##### `dump` + +The `dump` interceptor enables you to dump the response body from a request upon a given limit. + +**Options** +- `maxSize` - The maximum size (in bytes) of the response body to dump. If the size of the request's body exceeds this value then the connection will be closed. Default: `1048576`. + +> The `Dispatcher#options` also gets extended with the options `dumpMaxSize`, `abortOnDumped`, and `waitForTrailers` which can be used to configure the interceptor at a request-per-request basis. + +**Example - Basic Dump Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { dump } = interceptors; + +const client = new Client("http://example.com").compose( + dump({ + maxSize: 1024, + }) +); + +// or +client.dispatch( + { + path: "/", + method: "GET", + dumpMaxSize: 1024, + }, + handler +); +``` + +##### `dns` + +The `dns` interceptor enables you to cache DNS lookups for a given duration, per origin. + +>It is well suited for scenarios where you want to cache DNS lookups to avoid the overhead of resolving the same domain multiple times + +**Options** +- `maxTTL` - The maximum time-to-live (in milliseconds) of the DNS cache. It should be a positive integer. Default: `10000`. + - Set `0` to disable TTL. +- `maxItems` - The maximum number of items to cache. It should be a positive integer. Default: `Infinity`. +- `dualStack` - Whether to resolve both IPv4 and IPv6 addresses. Default: `true`. + - It will also attempt a happy-eyeballs-like approach to connect to the available addresses in case of a connection failure. +- `affinity` - Whether to use IPv4 or IPv6 addresses. Default: `4`. + - It can be either `'4` or `6`. + - It will only take effect if `dualStack` is `false`. +- `lookup: (hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, addresses: DNSInterceptorRecord[]) => void) => void` - Custom lookup function. Default: `dns.lookup`. + - For more info see [dns.lookup](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback). +- `pick: (origin: URL, records: DNSInterceptorRecords, affinity: 4 | 6) => DNSInterceptorRecord` - Custom pick function. Default: `RoundRobin`. + - The function should return a single record from the records array. + - By default a simplified version of Round Robin is used. + - The `records` property can be mutated to store the state of the balancing algorithm. +- `storage: DNSStorage` - Custom storage for resolved DNS records + +> The `Dispatcher#options` also gets extended with the options `dns.affinity`, `dns.dualStack`, `dns.lookup` and `dns.pick` which can be used to configure the interceptor at a request-per-request basis. + + +**DNSInterceptorRecord** +It represents a DNS record. +- `family` - (`number`) The IP family of the address. It can be either `4` or `6`. +- `address` - (`string`) The IP address. + +**DNSInterceptorOriginRecords** +It represents a map of DNS IP addresses records for a single origin. +- `4.ips` - (`DNSInterceptorRecord[] | null`) The IPv4 addresses. +- `6.ips` - (`DNSInterceptorRecord[] | null`) The IPv6 addresses. + +**DNSStorage** +It represents a storage object for resolved DNS records. +- `size` - (`number`) current size of the storage. +- `get` - (`(origin: string) => DNSInterceptorOriginRecords | null`) method to get the records for a given origin. +- `set` - (`(origin: string, records: DNSInterceptorOriginRecords | null, options: { ttl: number }) => void`) method to set the records for a given origin. +- `delete` - (`(origin: string) => void`) method to delete records for a given origin. +- `full` - (`() => boolean`) method to check if the storage is full, if returns `true`, DNS lookup will be skipped in this interceptor and new records will not be stored. + +**Example - Basic DNS Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { dns } = interceptors; + +const client = new Agent().compose([ + dns({ ...opts }) +]) + +const response = await client.request({ + origin: `http://localhost:3030`, + ...requestOpts +}) +``` + +**Example - DNS Interceptor and LRU cache as a storage** + +```js +const { Client, interceptors } = require("undici"); +const QuickLRU = require("quick-lru"); +const { dns } = interceptors; + +const lru = new QuickLRU({ maxSize: 100 }); + +const lruAdapter = { + get size() { + return lru.size; + }, + get(origin) { + return lru.get(origin); + }, + set(origin, records, { ttl }) { + lru.set(origin, records, { maxAge: ttl }); + }, + delete(origin) { + lru.delete(origin); + }, + full() { + // For LRU cache, we can always store new records, + // old records will be evicted automatically + return false; + } +} + +const client = new Agent().compose([ + dns({ storage: lruAdapter }) +]) + +const response = await client.request({ + origin: `http://localhost:3030`, + ...requestOpts +}) +``` + +##### `responseError` + +The `responseError` interceptor throws an error for responses with status code errors (>= 400). + +**Example** + +```js +const { Client, interceptors } = require("undici"); +const { responseError } = interceptors; + +const client = new Client("http://example.com").compose( + responseError() +); + +// Will throw a ResponseError for status codes >= 400 +await client.request({ + method: "GET", + path: "/" +}); +``` + +##### `decompress` + +⚠️ The decompress interceptor is experimental and subject to change. + +The `decompress` interceptor automatically decompresses response bodies that are compressed with gzip, deflate, brotli, or zstd compression. It removes the `content-encoding` and `content-length` headers from decompressed responses and supports RFC-9110 compliant multiple encodings. + +**Options** + +- `skipErrorResponses` - Whether to skip decompression for error responses (status codes >= 400). Default: `true`. +- `skipStatusCodes` - Array of status codes to skip decompression for. Default: `[204, 304]`. + +**Example - Basic Decompress Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { decompress } = interceptors; + +const client = new Client("http://example.com").compose( + decompress() +); + +// Automatically decompresses gzip/deflate/brotli/zstd responses +const response = await client.request({ + method: "GET", + path: "/" +}); +``` + +**Example - Custom Options** + +```js +const { Client, interceptors } = require("undici"); +const { decompress } = interceptors; + +const client = new Client("http://example.com").compose( + decompress({ + skipErrorResponses: false, // Decompress 5xx responses + skipStatusCodes: [204, 304, 201] // Skip these status codes + }) +); +``` + +**Supported Encodings** + +- `gzip` / `x-gzip` - GZIP compression +- `deflate` / `x-compress` - DEFLATE compression +- `br` - Brotli compression +- `zstd` - Zstandard compression +- Multiple encodings (e.g., `gzip, deflate`) are supported per RFC-9110 + +**Behavior** + +- Skips decompression for status codes < 200 or >= 400 (configurable) +- Skips decompression for 204 No Content and 304 Not Modified by default +- Removes `content-encoding` and `content-length` headers when decompressing +- Passes through unsupported encodings unchanged +- Handles case-insensitive encoding names +- Supports streaming decompression without buffering + +##### `Cache Interceptor` + +The `cache` interceptor implements client-side response caching as described in +[RFC9111](https://www.rfc-editor.org/rfc/rfc9111.html). + +**Options** + +- `store` - The [`CacheStore`](/docs/docs/api/CacheStore.md) to store and retrieve responses from. Default is [`MemoryCacheStore`](/docs/docs/api/CacheStore.md#memorycachestore). +- `methods` - The [**safe** HTTP methods](https://www.rfc-editor.org/rfc/rfc9110#section-9.2.1) to cache the response of. +- `cacheByDefault` - The default expiration time to cache responses by if they don't have an explicit expiration and cannot have an heuristic expiry computed. If this isn't present, responses neither with an explicit expiration nor heuristically cacheable will not be cached. Default `undefined`. +- `type` - The [type of cache](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching#types_of_caches) for Undici to act as. Can be `shared` or `private`. Default `shared`. `private` implies privately cacheable responses will be cached and potentially shared with other users of your application. + +##### `Deduplicate Interceptor` + +The `deduplicate` interceptor deduplicates concurrent identical requests. When multiple identical requests are made while one is already in-flight, only one request is sent to the origin server, and all waiting handlers receive the same response. This reduces server load and improves performance. + +**Options** + +- `methods` - The [**safe** HTTP methods](https://www.rfc-editor.org/rfc/rfc9110#section-9.2.1) to deduplicate. Default `['GET']`. +- `skipHeaderNames` - Header names that, if present in a request, will cause the request to skip deduplication entirely. Useful for headers like `idempotency-key` where presence indicates unique processing. Header name matching is case-insensitive. Default `[]`. +- `excludeHeaderNames` - Header names to exclude from the deduplication key. Requests with different values for these headers will still be deduplicated together. Useful for headers like `x-request-id` that vary per request but shouldn't affect deduplication. Header name matching is case-insensitive. Default `[]`. + +**Usage** + +```js +const { Client, interceptors } = require("undici"); +const { deduplicate, cache } = interceptors; + +// Deduplicate only +const client = new Client("http://example.com").compose( + deduplicate() +); + +// Deduplicate with caching +const clientWithCache = new Client("http://example.com").compose( + deduplicate(), + cache() +); +``` + +Requests are considered identical if they have the same: +- Origin +- HTTP method +- Path +- Request headers (excluding any headers specified in `excludeHeaderNames`) + +All deduplicated requests receive the complete response including status code, headers, and body. + +For observability, request deduplication events are published to the `undici:request:pending-requests` [diagnostic channel](/docs/docs/api/DiagnosticsChannel.md#undicirequestpending-requests). + +## Instance Events + +### Event: `'connect'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` + +### Event: `'disconnect'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when the dispatcher has been disconnected from the origin. + +> **Note**: For HTTP/2, this event is also emitted when the dispatcher has received the [GOAWAY Frame](https://webconcepts.info/concepts/http2-frame-type/0x7) with an Error with the message `HTTP/2: "GOAWAY" frame received` and the code `UND_ERR_INFO`. +> Due to nature of the protocol of using binary frames, it is possible that requests gets hanging as a frame can be received between the `HEADER` and `DATA` frames. +> It is recommended to handle this event and close the dispatcher to create a new HTTP/2 session. + +### Event: `'connectionError'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when dispatcher fails to connect to +origin. + +### Event: `'drain'` + +Parameters: + +* **origin** `URL` + +Emitted when dispatcher is no longer busy. + +## Parameter: `UndiciHeaders` + +* `Record | string[] | Iterable<[string, string | string[] | undefined]> | null` + +Header arguments such as `options.headers` in [`Client.dispatch`](/docs/docs/api/Client.md#clientdispatchoptions-handlers) can be specified in three forms: +* As an object specified by the `Record` (`IncomingHttpHeaders`) type. +* As an array of strings. An array representation of a header list must have an even length, or an `InvalidArgumentError` will be thrown. +* As an iterable that can encompass `Headers`, `Map`, or a custom iterator returning key-value pairs. +Keys are lowercase and values are not modified. + +Response headers will derive a `host` from the `url` of the [Client](/docs/docs/api/Client.md#class-client) instance if no `host` header was previously specified. + +### Example 1 - Object + +```js +{ + 'content-length': '123', + 'content-type': 'text/plain', + connection: 'keep-alive', + host: 'mysite.com', + accept: '*/*' +} +``` + +### Example 2 - Array + +```js +[ + 'content-length', '123', + 'content-type', 'text/plain', + 'connection', 'keep-alive', + 'host', 'mysite.com', + 'accept', '*/*' +] +``` + +### Example 3 - Iterable + +```js +new Headers({ + 'content-length': '123', + 'content-type': 'text/plain', + connection: 'keep-alive', + host: 'mysite.com', + accept: '*/*' +}) +``` +or +```js +new Map([ + ['content-length', '123'], + ['content-type', 'text/plain'], + ['connection', 'keep-alive'], + ['host', 'mysite.com'], + ['accept', '*/*'] +]) +``` +or +```js +{ + *[Symbol.iterator] () { + yield ['content-length', '123'] + yield ['content-type', 'text/plain'] + yield ['connection', 'keep-alive'] + yield ['host', 'mysite.com'] + yield ['accept', '*/*'] + } +} +``` diff --git a/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md b/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md new file mode 100644 index 000000000..adc2a2424 --- /dev/null +++ b/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md @@ -0,0 +1,159 @@ +# Class: EnvHttpProxyAgent + +Extends: `undici.Dispatcher` + +EnvHttpProxyAgent automatically reads the proxy configuration from the environment variables `http_proxy`, `https_proxy`, and `no_proxy` and sets up the proxy agents accordingly. When `http_proxy` and `https_proxy` are set, `http_proxy` is used for HTTP requests and `https_proxy` is used for HTTPS requests. If only `http_proxy` is set, `http_proxy` is used for both HTTP and HTTPS requests. If only `https_proxy` is set, it is only used for HTTPS requests. + +`no_proxy` is a comma or space-separated list of hostnames that should not be proxied. The list may contain leading wildcard characters (`*`). If `no_proxy` is set, the EnvHttpProxyAgent will bypass the proxy for requests to hosts that match the list. If `no_proxy` is set to `"*"`, the EnvHttpProxyAgent will bypass the proxy for all requests. + +Uppercase environment variables are also supported: `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY`. However, if both the lowercase and uppercase environment variables are set, the uppercase environment variables will be ignored. + +## `new EnvHttpProxyAgent([options])` + +Arguments: + +* **options** `EnvHttpProxyAgentOptions` (optional) - extends the `Agent` options. + +Returns: `EnvHttpProxyAgent` + +### Parameter: `EnvHttpProxyAgentOptions` + +Extends: [`AgentOptions`](/docs/docs/api/Agent.md#parameter-agentoptions) + +* **httpProxy** `string` (optional) - When set, it will override the `HTTP_PROXY` environment variable. +* **httpsProxy** `string` (optional) - When set, it will override the `HTTPS_PROXY` environment variable. +* **noProxy** `string` (optional) - When set, it will override the `NO_PROXY` environment variable. + +Examples: + +```js +import { EnvHttpProxyAgent } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() +// or +const envHttpProxyAgent = new EnvHttpProxyAgent({ httpProxy: 'my.proxy.server:8080', httpsProxy: 'my.proxy.server:8443', noProxy: 'localhost' }) +``` + +#### Example - EnvHttpProxyAgent instantiation + +This will instantiate the EnvHttpProxyAgent. It will not do anything until registered as the agent to use with requests. + +```js +import { EnvHttpProxyAgent } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() +``` + +#### Example - Basic Proxy Fetch with global agent dispatcher + +```js +import { setGlobalDispatcher, fetch, EnvHttpProxyAgent } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() +setGlobalDispatcher(envHttpProxyAgent) + +const { status, json } = await fetch('http://localhost:3000/foo') + +console.log('response received', status) // response received 200 + +const data = await json() // data { foo: "bar" } +``` + +#### Example - Basic Proxy Request with global agent dispatcher + +```js +import { setGlobalDispatcher, request, EnvHttpProxyAgent } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() +setGlobalDispatcher(envHttpProxyAgent) + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with local agent dispatcher + +```js +import { EnvHttpProxyAgent, request } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: envHttpProxyAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Fetch with local agent dispatcher + +```js +import { EnvHttpProxyAgent, fetch } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() + +const { + status, + json +} = await fetch('http://localhost:3000/foo', { dispatcher: envHttpProxyAgent }) + +console.log('response received', status) // response received 200 + +const data = await json() // data { foo: "bar" } +``` + +## Instance Methods + +### `EnvHttpProxyAgent.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `EnvHttpProxyAgent.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `EnvHttpProxyAgent.dispatch(options, handler: AgentDispatchOptions)` + +Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +#### Parameter: `AgentDispatchOptions` + +Extends: [`DispatchOptions`](/docs/docs/api/Dispatcher.md#parameter-dispatchoptions) + +* **origin** `string | URL` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `EnvHttpProxyAgent.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `EnvHttpProxyAgent.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `EnvHttpProxyAgent.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `EnvHttpProxyAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `EnvHttpProxyAgent.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `EnvHttpProxyAgent.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). diff --git a/node_modules/undici/docs/docs/api/Errors.md b/node_modules/undici/docs/docs/api/Errors.md new file mode 100644 index 000000000..9f21e5b0e --- /dev/null +++ b/node_modules/undici/docs/docs/api/Errors.md @@ -0,0 +1,48 @@ +# Errors + +Undici exposes a variety of error objects that you can use to enhance your error handling. +You can find all the error objects inside the `errors` key. + +```js +import { errors } from 'undici' +``` + +| Error | Error Codes | Description | +| ------------------------------------ | ------------------------------------- | ------------------------------------------------------------------------- | +| `UndiciError` | `UND_ERR` | all errors below are extended from `UndiciError`. | +| `ConnectTimeoutError` | `UND_ERR_CONNECT_TIMEOUT` | socket is destroyed due to connect timeout. | +| `HeadersTimeoutError` | `UND_ERR_HEADERS_TIMEOUT` | socket is destroyed due to headers timeout. | +| `HeadersOverflowError` | `UND_ERR_HEADERS_OVERFLOW` | socket is destroyed due to headers' max size being exceeded. | +| `BodyTimeoutError` | `UND_ERR_BODY_TIMEOUT` | socket is destroyed due to body timeout. | +| `InvalidArgumentError` | `UND_ERR_INVALID_ARG` | passed an invalid argument. | +| `InvalidReturnValueError` | `UND_ERR_INVALID_RETURN_VALUE` | returned an invalid value. | +| `RequestAbortedError` | `UND_ERR_ABORTED` | the request has been aborted by the user | +| `ClientDestroyedError` | `UND_ERR_DESTROYED` | trying to use a destroyed client. | +| `ClientClosedError` | `UND_ERR_CLOSED` | trying to use a closed client. | +| `SocketError` | `UND_ERR_SOCKET` | there is an error with the socket. | +| `NotSupportedError` | `UND_ERR_NOT_SUPPORTED` | encountered unsupported functionality. | +| `RequestContentLengthMismatchError` | `UND_ERR_REQ_CONTENT_LENGTH_MISMATCH` | request body does not match content-length header | +| `ResponseContentLengthMismatchError` | `UND_ERR_RES_CONTENT_LENGTH_MISMATCH` | response body does not match content-length header | +| `InformationalError` | `UND_ERR_INFO` | expected error with reason | +| `ResponseExceededMaxSizeError` | `UND_ERR_RES_EXCEEDED_MAX_SIZE` | response body exceed the max size allowed | +| `SecureProxyConnectionError` | `UND_ERR_PRX_TLS` | tls connection to a proxy failed | + +Be aware of the possible difference between the global dispatcher version and the actual undici version you might be using. We recommend to avoid the check `instanceof errors.UndiciError` and seek for the `error.code === ''` instead to avoid inconsistencies. +### `SocketError` + +The `SocketError` has a `.socket` property which holds socket metadata: + +```ts +interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number +} +``` + +Be aware that in some cases the `.socket` property can be `null`. diff --git a/node_modules/undici/docs/docs/api/EventSource.md b/node_modules/undici/docs/docs/api/EventSource.md new file mode 100644 index 000000000..8244aa77e --- /dev/null +++ b/node_modules/undici/docs/docs/api/EventSource.md @@ -0,0 +1,45 @@ +# EventSource + +> ⚠️ Warning: the EventSource API is experimental. + +Undici exposes a WHATWG spec-compliant implementation of [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) +for [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events). + +## Instantiating EventSource + +Undici exports a EventSource class. You can instantiate the EventSource as +follows: + +```mjs +import { EventSource } from 'undici' + +const eventSource = new EventSource('http://localhost:3000') +eventSource.onmessage = (event) => { + console.log(event.data) +} +``` + +## Using a custom Dispatcher + +undici allows you to set your own Dispatcher in the EventSource constructor. + +An example which allows you to modify the request headers is: + +```mjs +import { EventSource, Agent } from 'undici' + +class CustomHeaderAgent extends Agent { + dispatch (opts) { + opts.headers['x-custom-header'] = 'hello world' + return super.dispatch(...arguments) + } +} + +const eventSource = new EventSource('http://localhost:3000', { + dispatcher: new CustomHeaderAgent() +}) + +``` + +More information about the EventSource API can be found on +[MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventSource). diff --git a/node_modules/undici/docs/docs/api/Fetch.md b/node_modules/undici/docs/docs/api/Fetch.md new file mode 100644 index 000000000..00c349847 --- /dev/null +++ b/node_modules/undici/docs/docs/api/Fetch.md @@ -0,0 +1,52 @@ +# Fetch + +Undici exposes a fetch() method starts the process of fetching a resource from the network. + +Documentation and examples can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/fetch). + +## FormData + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/FormData). + +If any parameters are passed to the FormData constructor other than `undefined`, an error will be thrown. Other parameters are ignored. + +## Response + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Response) + +## Request + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Request) + +## Header + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Headers) + +# Body Mixins + +`Response` and `Request` body inherit body mixin methods. These methods include: + +- [`.arrayBuffer()`](https://fetch.spec.whatwg.org/#dom-body-arraybuffer) +- [`.blob()`](https://fetch.spec.whatwg.org/#dom-body-blob) +- [`.bytes()`](https://fetch.spec.whatwg.org/#dom-body-bytes) +- [`.formData()`](https://fetch.spec.whatwg.org/#dom-body-formdata) +- [`.json()`](https://fetch.spec.whatwg.org/#dom-body-json) +- [`.text()`](https://fetch.spec.whatwg.org/#dom-body-text) + +There is an ongoing discussion regarding `.formData()` and its usefulness and performance in server environments. It is recommended to use a dedicated library for parsing `multipart/form-data` bodies, such as [Busboy](https://www.npmjs.com/package/busboy) or [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy). + +These libraries can be interfaced with fetch with the following example code: + +```mjs +import { Busboy } from '@fastify/busboy' +import { Readable } from 'node:stream' + +const response = await fetch('...') +const busboy = new Busboy({ + headers: { + 'content-type': response.headers.get('content-type') + } +}) + +Readable.fromWeb(response.body).pipe(busboy) +``` diff --git a/node_modules/undici/docs/docs/api/GlobalInstallation.md b/node_modules/undici/docs/docs/api/GlobalInstallation.md new file mode 100644 index 000000000..7e4529d8f --- /dev/null +++ b/node_modules/undici/docs/docs/api/GlobalInstallation.md @@ -0,0 +1,91 @@ +# Global Installation + +Undici provides an `install()` function to add all WHATWG fetch classes to `globalThis`, making them available globally without requiring imports. + +## `install()` + +Install all WHATWG fetch classes globally on `globalThis`. + +**Example:** + +```js +import { install } from 'undici' + +// Install all WHATWG fetch classes globally +install() + +// Now you can use fetch classes globally without importing +const response = await fetch('https://api.example.com/data') +const data = await response.json() + +// All classes are available globally: +const headers = new Headers([['content-type', 'application/json']]) +const request = new Request('https://example.com') +const formData = new FormData() +const ws = new WebSocket('wss://example.com') +const eventSource = new EventSource('https://example.com/events') +``` + +## Installed Classes + +The `install()` function adds the following classes to `globalThis`: + +| Class | Description | +|-------|-------------| +| `fetch` | The fetch function for making HTTP requests | +| `Headers` | HTTP headers management | +| `Response` | HTTP response representation | +| `Request` | HTTP request representation | +| `FormData` | Form data handling | +| `WebSocket` | WebSocket client | +| `CloseEvent` | WebSocket close event | +| `ErrorEvent` | WebSocket error event | +| `MessageEvent` | WebSocket message event | +| `EventSource` | Server-sent events client | + +## Use Cases + +Global installation is useful for: + +- **Polyfilling environments** that don't have native fetch support +- **Ensuring consistent behavior** across different Node.js versions +- **Library compatibility** when third-party libraries expect global fetch +- **Migration scenarios** where you want to replace built-in implementations +- **Testing environments** where you need predictable fetch behavior + +## Example: Polyfilling an Environment + +```js +import { install } from 'undici' + +// Check if fetch is available and install if needed +if (typeof globalThis.fetch === 'undefined') { + install() + console.log('Undici fetch installed globally') +} + +// Now fetch is guaranteed to be available +const response = await fetch('https://api.example.com') +``` + +## Example: Testing Environment + +```js +import { install } from 'undici' + +// In test setup, ensure consistent fetch behavior +install() + +// Now all tests use undici's implementations +test('fetch API test', async () => { + const response = await fetch('https://example.com') + expect(response).toBeInstanceOf(Response) +}) +``` + +## Notes + +- The `install()` function overwrites any existing global implementations +- Classes installed are undici's implementations, not Node.js built-ins +- This provides access to undici's latest features and performance improvements +- The global installation persists for the lifetime of the process \ No newline at end of file diff --git a/node_modules/undici/docs/docs/api/H2CClient.md b/node_modules/undici/docs/docs/api/H2CClient.md new file mode 100644 index 000000000..d9ba30891 --- /dev/null +++ b/node_modules/undici/docs/docs/api/H2CClient.md @@ -0,0 +1,262 @@ +# Class: H2CClient + +Extends: `undici.Dispatcher` + +A basic H2C client. + +**Example** + +```js +const { createServer } = require('node:http2') +const { once } = require('node:events') +const { H2CClient } = require('undici') + +const server = createServer((req, res) => { + res.writeHead(200) + res.end('Hello, world!') +}) + +server.listen() +once(server, 'listening').then(() => { + const client = new H2CClient(`http://localhost:${server.address().port}/`) + + const response = await client.request({ path: '/', method: 'GET' }) + console.log(response.statusCode) // 200 + response.body.text.then((text) => { + console.log(text) // Hello, world! + }) +}) +``` + +## `new H2CClient(url[, options])` + +Arguments: + +- **url** `URL | string` - Should only include the **protocol, hostname, and port**. It only supports `http` protocol. +- **options** `H2CClientOptions` (optional) + +Returns: `H2CClient` + +### Parameter: `H2CClientOptions` + +- **bodyTimeout** `number | null` (optional) - Default: `300e3` - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. Please note the `timeout` will be reset if you keep writing data to the socket everytime. +- **headersTimeout** `number | null` (optional) - Default: `300e3` - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +- **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout`, in milliseconds, when overridden by _keep-alive_ hints from the server. Defaults to 10 minutes. +- **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by _keep-alive_ hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds. +- **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `2e3` - A number of milliseconds subtracted from server _keep-alive_ hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 2 seconds. +- **maxHeaderSize** `number | null` (optional) - Default: `--max-http-header-size` or `16384` - The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB. +- **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable. +- **maxConcurrentStreams**: `number` - Default: `100`. Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. +- **pipelining** `number | null` (optional) - Default to `maxConcurrentStreams` - The amount of concurrent requests sent over a single HTTP/2 session in accordance with [RFC-7540](https://httpwg.org/specs/rfc7540.html#StreamsLayer) Stream specification. Streams can be closed up by remote server at any time. +- **connect** `ConnectOptions | null` (optional) - Default: `null`. +- **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body. **Security Warning:** Disabling this option can expose your application to HTTP Request Smuggling attacks, where mismatched content-length headers cause servers and proxies to interpret request boundaries differently. This can lead to cache poisoning, credential hijacking, and bypassing security controls. Only disable this in controlled environments where you fully trust the request source. +- **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version. +- **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. + +#### Parameter: `H2CConnectOptions` + +- **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +- **timeout** `number | null` (optional) - In milliseconds, Default `10e3`. +- **servername** `string | null` (optional) +- **keepAlive** `boolean | null` (optional) - Default: `true` - TCP keep-alive enabled +- **keepAliveInitialDelay** `number | null` (optional) - Default: `60000` - TCP keep-alive interval for the socket in milliseconds + +### Example - Basic Client instantiation + +This will instantiate the undici H2CClient, but it will not connect to the origin until something is queued. Consider using `client.connect` to prematurely connect to the origin, or just call `client.request`. + +```js +"use strict"; +import { H2CClient } from "undici"; + +const client = new H2CClient("http://localhost:3000"); +``` + +## Instance Methods + +### `H2CClient.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `H2CClient.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). + +### `H2CClient.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `H2CClient.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `H2CClient.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `H2CClient.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `H2CClient.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `H2CClient.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Properties + +### `H2CClient.closed` + +- `boolean` + +`true` after `H2CClient.close()` has been called. + +### `H2CClient.destroyed` + +- `boolean` + +`true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. + +### `H2CClient.pipelining` + +- `number` + +Property to get and set the pipelining factor. + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](/docs/docs/api/Dispatcher.md#event-connect). + +Parameters: + +- **origin** `URL` +- **targets** `Array` + +Emitted when a socket has been created and connected. The client will connect once `client.size > 0`. + +#### Example - Client connect event + +```js +import { createServer } from "node:http2"; +import { H2CClient } from "undici"; +import { once } from "events"; + +const server = createServer((request, response) => { + response.end("Hello, World!"); +}).listen(); + +await once(server, "listening"); + +const client = new H2CClient(`http://localhost:${server.address().port}`); + +client.on("connect", (origin) => { + console.log(`Connected to ${origin}`); // should print before the request body statement +}); + +try { + const { body } = await client.request({ + path: "/", + method: "GET", + }); + body.setEncoding("utf-8"); + body.on("data", console.log); + client.close(); + server.close(); +} catch (error) { + console.error(error); + client.close(); + server.close(); +} +``` + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](/docs/docs/api/Dispatcher.md#event-disconnect). + +Parameters: + +- **origin** `URL` +- **targets** `Array` +- **error** `Error` + +Emitted when socket has disconnected. The error argument of the event is the error which caused the socket to disconnect. The client will reconnect if or once `client.size > 0`. + +#### Example - Client disconnect event + +```js +import { createServer } from "node:http2"; +import { H2CClient } from "undici"; +import { once } from "events"; + +const server = createServer((request, response) => { + response.destroy(); +}).listen(); + +await once(server, "listening"); + +const client = new H2CClient(`http://localhost:${server.address().port}`); + +client.on("disconnect", (origin) => { + console.log(`Disconnected from ${origin}`); +}); + +try { + await client.request({ + path: "/", + method: "GET", + }); +} catch (error) { + console.error(error.message); + client.close(); + server.close(); +} +``` + +### Event: `'drain'` + +Emitted when pipeline is no longer busy. + +See [Dispatcher Event: `'drain'`](/docs/docs/api/Dispatcher.md#event-drain). + +#### Example - Client drain event + +```js +import { createServer } from "node:http2"; +import { H2CClient } from "undici"; +import { once } from "events"; + +const server = createServer((request, response) => { + response.end("Hello, World!"); +}).listen(); + +await once(server, "listening"); + +const client = new H2CClient(`http://localhost:${server.address().port}`); + +client.on("drain", () => { + console.log("drain event"); + client.close(); + server.close(); +}); + +const requests = [ + client.request({ path: "/", method: "GET" }), + client.request({ path: "/", method: "GET" }), + client.request({ path: "/", method: "GET" }), +]; + +await Promise.all(requests); + +console.log("requests completed"); +``` + +### Event: `'error'` + +Invoked for users errors such as throwing in the `onError` handler. diff --git a/node_modules/undici/docs/docs/api/MockAgent.md b/node_modules/undici/docs/docs/api/MockAgent.md new file mode 100644 index 000000000..b4ce8106b --- /dev/null +++ b/node_modules/undici/docs/docs/api/MockAgent.md @@ -0,0 +1,603 @@ +# Class: MockAgent + +Extends: `undici.Dispatcher` + +A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. + +## `new MockAgent([options])` + +Arguments: + +* **options** `MockAgentOptions` (optional) - It extends the `Agent` options. + +Returns: `MockAgent` + +### Parameter: `MockAgentOptions` + +Extends: [`AgentOptions`](/docs/docs/api/Agent.md#parameter-agentoptions) + +* **agent** `Agent` (optional) - Default: `new Agent([options])` - a custom agent encapsulated by the MockAgent. + +* **ignoreTrailingSlash** `boolean` (optional) - Default: `false` - set the default value for `ignoreTrailingSlash` for interceptors. + +* **acceptNonStandardSearchParameters** `boolean` (optional) - Default: `false` - set to `true` if the matcher should also accept non standard search parameters such as multi-value items specified with `[]` (e.g. `param[]=1¶m[]=2¶m[]=3`) and multi-value items which values are comma separated (e.g. `param=1,2,3`). + +### Example - Basic MockAgent instantiation + +This will instantiate the MockAgent. It will not do anything until registered as the agent to use with requests and mock interceptions are added. + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() +``` + +### Example - Basic MockAgent instantiation with custom agent + +```js +import { Agent, MockAgent } from 'undici' + +const agent = new Agent() + +const mockAgent = new MockAgent({ agent }) +``` + +## Instance Methods + +### `MockAgent.get(origin)` + +This method creates and retrieves MockPool or MockClient instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. + +For subsequent `MockAgent.get` calls on the same origin, the same mock instance will be returned. + +Arguments: + +* **origin** `string | RegExp | (value) => boolean` - a matcher for the pool origin to be retrieved from the MockAgent. + +| Matcher type | Condition to pass | +|:------------:| -------------------------- | +| `string` | Exact match against string | +| `RegExp` | Regex must pass | +| `Function` | Function must return true | + +Returns: `MockClient | MockPool`. + +| `MockAgentOptions` | Mock instance returned | +| -------------------- | ---------------------- | +| `connections === 1` | `MockClient` | +| `connections` > `1` | `MockPool` | + +#### Example - Basic Mocked Request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock agent dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock pool dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockPool }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock client dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +mockClient.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockClient }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked requests with multiple intercepts + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') +mockPool.intercept({ path: '/hello'}).reply(200, 'hello') + +const result1 = await request('http://localhost:3000/foo') + +console.log('response received', result1.statusCode) // response received 200 + +for await (const data of result1.body) { + console.log('data', data.toString('utf8')) // data foo +} + +const result2 = await request('http://localhost:3000/hello') + +console.log('response received', result2.statusCode) // response received 200 + +for await (const data of result2.body) { + console.log('data', data.toString('utf8')) // data hello +} +``` + +#### Example - Mock different requests within the same file + +```js +const { MockAgent, setGlobalDispatcher } = require('undici'); +const agent = new MockAgent(); +agent.disableNetConnect(); +setGlobalDispatcher(agent); +describe('Test', () => { + it('200', async () => { + const mockAgent = agent.get('http://test.com'); + // your test + }); + it('200', async () => { + const mockAgent = agent.get('http://testing.com'); + // your test + }); +}); +``` + +#### Example - Mocked request with query body, headers and trailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo?hello=there&see=ya', + method: 'POST', + body: 'form1=data1&form2=data2' +}).reply(200, { foo: 'bar' }, { + headers: { 'content-type': 'application/json' }, + trailers: { 'Content-MD5': 'test' } +}) + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo?hello=there&see=ya', { + method: 'POST', + body: 'form1=data1&form2=data2' +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // '{"foo":"bar"}' +} + +console.log('trailers', trailers) // { 'content-md5': 'test' } +``` + +#### Example - Mocked request with origin regex + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get(new RegExp('http://localhost:3000')) +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request with origin function + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get((origin) => origin === 'http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockAgent.close()` + +Closes the mock agent and waits for registered mock pools and clients to also close before resolving. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +await mockAgent.close() +``` + +### `MockAgent.dispatch(options, handlers)` + +Implements [`Agent.dispatch(options, handlers)`](/docs/docs/api/Agent.md#parameter-agentdispatchoptions). + +### `MockAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockAgent request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await mockAgent.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockAgent.deactivate()` + +This method disables mocking in MockAgent. + +Returns: `void` + +#### Example - Deactivate Mocking + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.deactivate() +``` + +### `MockAgent.activate()` + +This method enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. + +Returns: `void` + +#### Example - Activate Mocking + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.deactivate() +// No mocking will occur + +// Later +mockAgent.activate() +``` + +### `MockAgent.enableNetConnect([host])` + +When requests are not matched in a MockAgent intercept, a real HTTP request is attempted. We can control this further through the use of `enableNetConnect`. This is achieved by defining host matchers so only matching requests will be attempted. + +When using a string, it should only include the **hostname and optionally, the port**. In addition, calling this method multiple times with a string will allow all HTTP requests that match these values. + +Arguments: + +* **host** `string | RegExp | (value) => boolean` - (optional) + +Returns: `void` + +#### Example - Allow all non-matching urls to be dispatched in a real HTTP request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect() + +await request('http://example.com') +// A real request is made +``` + +#### Example - Allow requests matching a host string to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect('example-1.com') +mockAgent.enableNetConnect('example-2.com:8080') + +await request('http://example-1.com') +// A real request is made + +await request('http://example-2.com:8080') +// A real request is made + +await request('http://example-3.com') +// Will throw +``` + +#### Example - Allow requests matching a host regex to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect(new RegExp('example.com')) + +await request('http://example.com') +// A real request is made +``` + +#### Example - Allow requests matching a host function to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect((value) => value === 'example.com') + +await request('http://example.com') +// A real request is made +``` + +### `MockAgent.disableNetConnect()` + +This method causes all requests to throw when requests are not matched in a MockAgent intercept. + +Returns: `void` + +#### Example - Disable all non-matching requests by throwing an error for each + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +mockAgent.disableNetConnect() + +await request('http://example.com') +// Will throw +``` + +### `MockAgent.pendingInterceptors()` + +This method returns any pending interceptors registered on a mock agent. A pending interceptor meets one of the following criteria: + +- Is registered with neither `.times()` nor `.persist()`, and has not been invoked; +- Is persistent (i.e., registered with `.persist()`) and has not been invoked; +- Is registered with `.times()` and has not been invoked `` of times. + +Returns: `PendingInterceptor[]` (where `PendingInterceptor` is a `MockDispatch` with an additional `origin: string`) + +#### Example - List all pending interceptors + +```js +const agent = new MockAgent() +agent.disableNetConnect() + +agent + .get('https://example.com') + .intercept({ method: 'GET', path: '/' }) + .reply(200) + +const pendingInterceptors = agent.pendingInterceptors() +// Returns [ +// { +// timesInvoked: 0, +// times: 1, +// persist: false, +// consumed: false, +// pending: true, +// path: '/', +// method: 'GET', +// body: undefined, +// headers: undefined, +// data: { +// error: null, +// statusCode: 200, +// data: '', +// headers: {}, +// trailers: {} +// }, +// origin: 'https://example.com' +// } +// ] +``` + +### `MockAgent.assertNoPendingInterceptors([options])` + +This method throws if the mock agent has any pending interceptors. A pending interceptor meets one of the following criteria: + +- Is registered with neither `.times()` nor `.persist()`, and has not been invoked; +- Is persistent (i.e., registered with `.persist()`) and has not been invoked; +- Is registered with `.times()` and has not been invoked `` of times. + +#### Example - Check that there are no pending interceptors + +```js +const agent = new MockAgent() +agent.disableNetConnect() + +agent + .get('https://example.com') + .intercept({ method: 'GET', path: '/' }) + .reply(200) + +agent.assertNoPendingInterceptors() +// Throws an UndiciError with the following message: +// +// 1 interceptor is pending: +// +// ┌─────────┬────────┬───────────────────────┬──────┬─────────────┬────────────┬─────────────┬───────────┐ +// │ (index) │ Method │ Origin │ Path │ Status code │ Persistent │ Invocations │ Remaining │ +// ├─────────┼────────┼───────────────────────┼──────┼─────────────┼────────────┼─────────────┼───────────┤ +// │ 0 │ 'GET' │ 'https://example.com' │ '/' │ 200 │ '❌' │ 0 │ 1 │ +// └─────────┴────────┴───────────────────────┴──────┴─────────────┴────────────┴─────────────┴───────────┘ +``` + +#### Example - access call history on MockAgent + +You can register every call made within a MockAgent to be able to retrieve the body, headers and so on. + +This is not enabled by default. + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent({ enableCallHistory: true }) +setGlobalDispatcher(mockAgent) + +await request('http://example.com', { query: { item: 1 }}) + +mockAgent.getCallHistory()?.firstCall() +// Returns +// MockCallHistoryLog { +// body: undefined, +// headers: undefined, +// method: 'GET', +// origin: 'http://example.com', +// fullUrl: 'http://example.com/?item=1', +// path: '/', +// searchParams: { item: '1' }, +// protocol: 'http:', +// host: 'example.com', +// port: '' +// } +``` + +#### Example - clear call history + +```js +const mockAgent = new MockAgent() + +mockAgent.clearAllCallHistory() +``` + +#### Example - call history instance class method + +```js +const mockAgent = new MockAgent() + +const mockAgentHistory = mockAgent.getCallHistory() + +mockAgentHistory?.calls() // returns an array of MockCallHistoryLogs +mockAgentHistory?.firstCall() // returns the first MockCallHistoryLogs or undefined +mockAgentHistory?.lastCall() // returns the last MockCallHistoryLogs or undefined +mockAgentHistory?.nthCall(3) // returns the third MockCallHistoryLogs or undefined +mockAgentHistory?.filterCalls({ path: '/endpoint', hash: '#hash-value' }) // returns an Array of MockCallHistoryLogs WHERE path === /endpoint OR hash === #hash-value +mockAgentHistory?.filterCalls({ path: '/endpoint', hash: '#hash-value' }, { operator: 'AND' }) // returns an Array of MockCallHistoryLogs WHERE path === /endpoint AND hash === #hash-value +mockAgentHistory?.filterCalls(/"data": "{}"/) // returns an Array of MockCallHistoryLogs where any value match regexp +mockAgentHistory?.filterCalls('application/json') // returns an Array of MockCallHistoryLogs where any value === 'application/json' +mockAgentHistory?.filterCalls((log) => log.path === '/endpoint') // returns an Array of MockCallHistoryLogs when given function returns true +mockAgentHistory?.clear() // clear the history +``` diff --git a/node_modules/undici/docs/docs/api/MockCallHistory.md b/node_modules/undici/docs/docs/api/MockCallHistory.md new file mode 100644 index 000000000..7473453b1 --- /dev/null +++ b/node_modules/undici/docs/docs/api/MockCallHistory.md @@ -0,0 +1,197 @@ +# Class: MockCallHistory + +Access to an instance with : + +```js +const mockAgent = new MockAgent({ enableCallHistory: true }) +mockAgent.getCallHistory() + +// or +const mockAgent = new MockAgent() +mockAgent.enableMockHistory() +mockAgent.getCallHistory() + +``` + +a MockCallHistory instance implements a **Symbol.iterator** letting you iterate on registered logs : + +```ts +for (const log of mockAgent.getCallHistory()) { + //... +} + +const array: Array = [...mockAgent.getCallHistory()] +const set: Set = new Set(mockAgent.getCallHistory()) +``` + +## class methods + +### clear + +Clear all MockCallHistoryLog registered. This is automatically done when calling `mockAgent.close()` + +```js +mockAgent.clearCallHistory() +// same as +mockAgent.getCallHistory()?.clear() +``` + +### calls + +Get all MockCallHistoryLog registered as an array + +```js +mockAgent.getCallHistory()?.calls() +``` + +### firstCall + +Get the first MockCallHistoryLog registered or undefined + +```js +mockAgent.getCallHistory()?.firstCall() +``` + +### lastCall + +Get the last MockCallHistoryLog registered or undefined + +```js +mockAgent.getCallHistory()?.lastCall() +``` + +### nthCall + +Get the nth MockCallHistoryLog registered or undefined + +```js +mockAgent.getCallHistory()?.nthCall(3) // the third MockCallHistoryLog registered +``` + +### filterCallsByProtocol + +Filter MockCallHistoryLog by protocol. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByProtocol(/https/) +mockAgent.getCallHistory()?.filterCallsByProtocol('https:') +``` + +### filterCallsByHost + +Filter MockCallHistoryLog by host. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByHost(/localhost/) +mockAgent.getCallHistory()?.filterCallsByHost('localhost:3000') +``` + +### filterCallsByPort + +Filter MockCallHistoryLog by port. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByPort(/3000/) +mockAgent.getCallHistory()?.filterCallsByPort('3000') +mockAgent.getCallHistory()?.filterCallsByPort('') +``` + +### filterCallsByOrigin + +Filter MockCallHistoryLog by origin. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByOrigin(/http:\/\/localhost:3000/) +mockAgent.getCallHistory()?.filterCallsByOrigin('http://localhost:3000') +``` + +### filterCallsByPath + +Filter MockCallHistoryLog by path. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByPath(/api\/v1\/graphql/) +mockAgent.getCallHistory()?.filterCallsByPath('/api/v1/graphql') +``` + +### filterCallsByHash + +Filter MockCallHistoryLog by hash. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByPath(/hash/) +mockAgent.getCallHistory()?.filterCallsByPath('#hash') +``` + +### filterCallsByFullUrl + +Filter MockCallHistoryLog by fullUrl. fullUrl contains protocol, host, port, path, hash, and query params + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByFullUrl(/https:\/\/localhost:3000\/\?query=value#hash/) +mockAgent.getCallHistory()?.filterCallsByFullUrl('https://localhost:3000/?query=value#hash') +``` + +### filterCallsByMethod + +Filter MockCallHistoryLog by method. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByMethod(/POST/) +mockAgent.getCallHistory()?.filterCallsByMethod('POST') +``` + +### filterCalls + +This class method is a meta function / alias to apply complex filtering in a single way. + +Parameters : + +- criteria : the first parameter. a function, regexp or object. + - function : filter MockCallHistoryLog when the function returns false + - regexp : filter MockCallHistoryLog when the regexp does not match on MockCallHistoryLog.toString() ([see](./MockCallHistoryLog.md#to-string)) + - object : an object with MockCallHistoryLog properties as keys to apply multiple filters. each values are a [filter parameter](/docs/docs/api/MockCallHistory.md#filter-parameter) +- options : the second parameter. an object. + - options.operator : `'AND'` or `'OR'` (default `'OR'`). Used only if criteria is an object. see below + +```js +mockAgent.getCallHistory()?.filterCalls((log) => log.hash === value && log.headers?.['authorization'] !== undefined) +mockAgent.getCallHistory()?.filterCalls(/"data": "{ "errors": "wrong body" }"/) + +// returns an Array of MockCallHistoryLog which all have +// - a hash containing my-hash +// - OR +// - a path equal to /endpoint +mockAgent.getCallHistory()?.filterCalls({ hash: /my-hash/, path: '/endpoint' }) + +// returns an Array of MockCallHistoryLog which all have +// - a hash containing my-hash +// - AND +// - a path equal to /endpoint +mockAgent.getCallHistory()?.filterCalls({ hash: /my-hash/, path: '/endpoint' }, { operator: 'AND' }) +``` + +## filter parameter + +Can be : + +- string. MockCallHistoryLog filtered if `value !== parameterValue` +- null. MockCallHistoryLog filtered if `value !== parameterValue` +- undefined. MockCallHistoryLog filtered if `value !== parameterValue` +- regexp. MockCallHistoryLog filtered if `!parameterValue.test(value)` diff --git a/node_modules/undici/docs/docs/api/MockCallHistoryLog.md b/node_modules/undici/docs/docs/api/MockCallHistoryLog.md new file mode 100644 index 000000000..3d38bdd29 --- /dev/null +++ b/node_modules/undici/docs/docs/api/MockCallHistoryLog.md @@ -0,0 +1,43 @@ +# Class: MockCallHistoryLog + +Access to an instance with : + +```js +const mockAgent = new MockAgent({ enableCallHistory: true }) +mockAgent.getCallHistory()?.firstCall() +``` + +## class properties + +- body `mockAgent.getCallHistory()?.firstCall()?.body` +- headers `mockAgent.getCallHistory()?.firstCall()?.headers` an object +- method `mockAgent.getCallHistory()?.firstCall()?.method` a string +- fullUrl `mockAgent.getCallHistory()?.firstCall()?.fullUrl` a string containing the protocol, origin, path, query and hash +- origin `mockAgent.getCallHistory()?.firstCall()?.origin` a string containing the protocol and the host +- headers `mockAgent.getCallHistory()?.firstCall()?.headers` an object +- path `mockAgent.getCallHistory()?.firstCall()?.path` a string always starting with `/` +- searchParams `mockAgent.getCallHistory()?.firstCall()?.searchParams` an object +- protocol `mockAgent.getCallHistory()?.firstCall()?.protocol` a string (`https:`) +- host `mockAgent.getCallHistory()?.firstCall()?.host` a string +- port `mockAgent.getCallHistory()?.firstCall()?.port` an empty string or a string containing numbers +- hash `mockAgent.getCallHistory()?.firstCall()?.hash` an empty string or a string starting with `#` + +## class methods + +### toMap + +Returns a Map instance + +```js +mockAgent.getCallHistory()?.firstCall()?.toMap()?.get('hash') +// #hash +``` + +### toString + +Returns a string computed with any class property name and value pair + +```js +mockAgent.getCallHistory()?.firstCall()?.toString() +// protocol->https:|host->localhost:4000|port->4000|origin->https://localhost:4000|path->/endpoint|hash->#here|searchParams->{"query":"value"}|fullUrl->https://localhost:4000/endpoint?query=value#here|method->PUT|body->"{ "data": "hello" }"|headers->{"content-type":"application/json"} +``` diff --git a/node_modules/undici/docs/docs/api/MockClient.md b/node_modules/undici/docs/docs/api/MockClient.md new file mode 100644 index 000000000..0e6c57a1a --- /dev/null +++ b/node_modules/undici/docs/docs/api/MockClient.md @@ -0,0 +1,81 @@ +# Class: MockClient + +Extends: `undici.Client` + +A mock client class that implements the same api as [MockPool](/docs/docs/api/MockPool.md). + +## `new MockClient(origin, [options])` + +Arguments: + +* **origin** `string` - It should only include the **protocol, hostname, and port**. +* **options** `MockClientOptions` - It extends the `Client` options. + +Returns: `MockClient` + +### Parameter: `MockClientOptions` + +Extends: `ClientOptions` + +* **agent** `Agent` - the agent to associate this MockClient with. + +### Example - Basic MockClient instantiation + +We can use MockAgent to instantiate a MockClient ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered. + +```js +import { MockAgent } from 'undici' + +// Connections must be set to 1 to return a MockClient instance +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +``` + +## Instance Methods + +### `MockClient.intercept(options)` + +Implements: [`MockPool.intercept(options)`](/docs/docs/api/MockPool.md#mockpoolinterceptoptions) + +### `MockClient.cleanMocks()` + +Implements: [`MockPool.cleanMocks()`](/docs/docs/api/MockPool.md#mockpoolcleanmocks) + +### `MockClient.close()` + +Implements: [`MockPool.close()`](/docs/docs/api/MockPool.md#mockpoolclose) + +### `MockClient.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `MockClient.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockClient request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +mockClient.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await mockClient.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` diff --git a/node_modules/undici/docs/docs/api/MockErrors.md b/node_modules/undici/docs/docs/api/MockErrors.md new file mode 100644 index 000000000..c1aa3dbee --- /dev/null +++ b/node_modules/undici/docs/docs/api/MockErrors.md @@ -0,0 +1,12 @@ +# MockErrors + +Undici exposes a variety of mock error objects that you can use to enhance your mock error handling. +You can find all the mock error objects inside the `mockErrors` key. + +```js +import { mockErrors } from 'undici' +``` + +| Mock Error | Mock Error Codes | Description | +| --------------------- | ------------------------------- | ---------------------------------------------------------- | +| `MockNotMatchedError` | `UND_MOCK_ERR_MOCK_NOT_MATCHED` | The request does not match any registered mock dispatches. | diff --git a/node_modules/undici/docs/docs/api/MockPool.md b/node_modules/undici/docs/docs/api/MockPool.md new file mode 100644 index 000000000..6656b95d8 --- /dev/null +++ b/node_modules/undici/docs/docs/api/MockPool.md @@ -0,0 +1,554 @@ +# Class: MockPool + +Extends: `undici.Pool` + +A mock Pool class that implements the Pool API and is used by MockAgent to intercept real requests and return mocked responses. + +## `new MockPool(origin, [options])` + +Arguments: + +* **origin** `string` - It should only include the **protocol, hostname, and port**. +* **options** `MockPoolOptions` - It extends the `Pool` options. + +Returns: `MockPool` + +### Parameter: `MockPoolOptions` + +Extends: `PoolOptions` + +* **agent** `Agent` - the agent to associate this MockPool with. + +### Example - Basic MockPool instantiation + +We can use MockAgent to instantiate a MockPool ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered. + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +``` + +## Instance Methods + +### `MockPool.intercept(options)` + +This method defines the interception rules for matching against requests for a MockPool or MockPool. We can intercept multiple times on a single instance, but each intercept is only used once. For example if you expect to make 2 requests inside a test, you need to call `intercept()` twice. Assuming you use `disableNetConnect()` you will get `MockNotMatchedError` on the second request when you only call `intercept()` once. + +When defining interception rules, all the rules must pass for a request to be intercepted. If a request is not intercepted, a real request will be attempted. + +| Matcher type | Condition to pass | +|:------------:| -------------------------- | +| `string` | Exact match against string | +| `RegExp` | Regex must pass | +| `Function` | Function must return true | + +Arguments: + +* **options** `MockPoolInterceptOptions` - Interception options. + +Returns: `MockInterceptor` corresponding to the input options. + +### Parameter: `MockPoolInterceptOptions` + +* **path** `string | RegExp | (path: string) => boolean` - a matcher for the HTTP request path. When a `RegExp` or callback is used, it will match against the request path including all query parameters in alphabetical order. When a `string` is provided, the query parameters can be conveniently specified through the `MockPoolInterceptOptions.query` setting. +* **method** `string | RegExp | (method: string) => boolean` - (optional) - a matcher for the HTTP request method. Defaults to `GET`. +* **body** `string | RegExp | (body: string) => boolean` - (optional) - a matcher for the HTTP request body. +* **headers** `Record boolean`> - (optional) - a matcher for the HTTP request headers. To be intercepted, a request must match all defined headers. Extra headers not defined here may (or may not) be included in the request and do not affect the interception in any way. +* **query** `Record | null` - (optional) - a matcher for the HTTP request query string params. Only applies when a `string` was provided for `MockPoolInterceptOptions.path`. +* **ignoreTrailingSlash** `boolean` - (optional) - set to `true` if the matcher should also match by ignoring potential trailing slashes in `MockPoolInterceptOptions.path`. + +### Return: `MockInterceptor` + +We can define the behaviour of an intercepted request with the following options. + +* **reply** `(statusCode: number, replyData: string | Buffer | object | MockInterceptor.MockResponseDataHandler, responseOptions?: MockResponseOptions) => MockScope` - define a reply for a matching request. You can define the replyData as a callback to read incoming request data. Default for `responseOptions` is `{}`. +* **reply** `(callback: MockInterceptor.MockReplyOptionsCallback) => MockScope` - define a reply for a matching request, allowing dynamic mocking of all reply options rather than just the data. +* **replyWithError** `(error: Error) => MockScope` - define an error for a matching request to throw. +* **defaultReplyHeaders** `(headers: Record) => MockInterceptor` - define default headers to be included in subsequent replies. These are in addition to headers on a specific reply. +* **defaultReplyTrailers** `(trailers: Record) => MockInterceptor` - define default trailers to be included in subsequent replies. These are in addition to trailers on a specific reply. +* **replyContentLength** `() => MockInterceptor` - define automatically calculated `content-length` headers to be included in subsequent replies. + +The reply data of an intercepted request may either be a string, buffer, or JavaScript object. Objects are converted to JSON while strings and buffers are sent as-is. + +By default, `reply` and `replyWithError` define the behaviour for the first matching request only. Subsequent requests will not be affected (this can be changed using the returned `MockScope`). + +### Parameter: `MockResponseOptions` + +* **headers** `Record` - headers to be included on the mocked reply. +* **trailers** `Record` - trailers to be included on the mocked reply. + +### Return: `MockScope` + +A `MockScope` is associated with a single `MockInterceptor`. With this, we can configure the default behaviour of an intercepted reply. + +* **delay** `(waitInMs: number) => MockScope` - delay the associated reply by a set amount in ms. +* **persist** `() => MockScope` - any matching request will always reply with the defined response indefinitely. +* **times** `(repeatTimes: number) => MockScope` - any matching request will reply with the defined response a fixed amount of times. This is overridden by **persist**. + +#### Example - Basic Mocked Request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +// MockPool +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request using reply data callbacks + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/echo', + method: 'GET', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(200, ({ headers }) => ({ message: headers.get('message') })) + +const { statusCode, body, headers } = await request('http://localhost:3000', { + headers: { + message: 'hello world!' + } +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // { "message":"hello world!" } +} +``` + +#### Example - Mocked request using reply options callback + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/echo', + method: 'GET', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(({ headers }) => ({ statusCode: 200, data: { message: headers.get('message') }}))) + +const { statusCode, body, headers } = await request('http://localhost:3000', { + headers: { + message: 'hello world!' + } +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // { "message":"hello world!" } +} +``` + +#### Example - Basic Mocked requests with multiple intercepts + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo') + +mockPool.intercept({ + path: '/hello', + method: 'GET', +}).reply(200, 'hello') + +const result1 = await request('http://localhost:3000/foo') + +console.log('response received', result1.statusCode) // response received 200 + +for await (const data of result1.body) { + console.log('data', data.toString('utf8')) // data foo +} + +const result2 = await request('http://localhost:3000/hello') + +console.log('response received', result2.statusCode) // response received 200 + +for await (const data of result2.body) { + console.log('data', data.toString('utf8')) // data hello +} +``` + +#### Example - Mocked request with query body, request headers and response headers and trailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo?hello=there&see=ya', + method: 'POST', + body: 'form1=data1&form2=data2', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(200, { foo: 'bar' }, { + headers: { 'content-type': 'application/json' }, + trailers: { 'Content-MD5': 'test' } +}) + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo?hello=there&see=ya', { + method: 'POST', + body: 'form1=data1&form2=data2', + headers: { + foo: 'bar', + 'User-Agent': 'undici', + Host: 'example.com' + } + }) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // '{"foo":"bar"}' +} + +console.log('trailers', trailers) // { 'content-md5': 'test' } +``` + +#### Example - Mocked request using different matchers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: /^GET$/, + body: (value) => value === 'form=data', + headers: { + 'User-Agent': 'undici', + Host: /^example.com$/ + } +}).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { + method: 'GET', + body: 'form=data', + headers: { + foo: 'bar', + 'User-Agent': 'undici', + Host: 'example.com' + } +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request with reply with a defined error + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyWithError(new Error('kaboom')) + +try { + await request('http://localhost:3000/foo', { + method: 'GET' + }) +} catch (error) { + console.error(error) // Error: kaboom +} +``` + +#### Example - Mocked request with defaultReplyHeaders + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).defaultReplyHeaders({ foo: 'bar' }) + .reply(200, 'foo') + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { foo: 'bar' } +``` + +#### Example - Mocked request with defaultReplyTrailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).defaultReplyTrailers({ foo: 'bar' }) + .reply(200, 'foo') + +const { trailers } = await request('http://localhost:3000/foo') + +console.log('trailers', trailers) // trailers { foo: 'bar' } +``` + +#### Example - Mocked request with automatic content-length calculation + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyContentLength().reply(200, 'foo') + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { 'content-length': '3' } +``` + +#### Example - Mocked request with automatic content-length calculation on an object + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyContentLength().reply(200, { foo: 'bar' }) + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { 'content-length': '13' } +``` + +#### Example - Mocked request with persist enabled + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo').persist() + +const result1 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result2 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +// Etc +``` + +#### Example - Mocked request with times enabled + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo').times(2) + +const result1 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result2 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result3 = await request('http://localhost:3000/foo') +// Will not match and make attempt a real request +``` + +#### Example - Mocked request with path callback + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' +import querystring from 'querystring' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +const matchPath = requestPath => { + const [pathname, search] = requestPath.split('?') + const requestQuery = querystring.parse(search) + + if (!pathname.startsWith('/foo')) { + return false + } + + if (!Object.keys(requestQuery).includes('foo') || requestQuery.foo !== 'bar') { + return false + } + + return true +} + +mockPool.intercept({ + path: matchPath, + method: 'GET' +}).reply(200, 'foo') + +const result = await request('http://localhost:3000/foo?foo=bar') +// Will match and return mocked data +``` + +### `MockPool.close()` + +Closes the mock pool and de-registers from associated MockAgent. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() +const mockPool = mockAgent.get('http://localhost:3000') + +await mockPool.close() +``` + +### `MockPool.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `MockPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockPool request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ + path: '/foo', + method: 'GET', +}).reply(200, 'foo') + +const { + statusCode, + body +} = await mockPool.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockPool.cleanMocks()` + +This method cleans up all the prepared mocks. + +Returns: `void` diff --git a/node_modules/undici/docs/docs/api/Pool.md b/node_modules/undici/docs/docs/api/Pool.md new file mode 100644 index 000000000..ee0a0d3fe --- /dev/null +++ b/node_modules/undici/docs/docs/api/Pool.md @@ -0,0 +1,84 @@ +# Class: Pool + +Extends: `undici.Dispatcher` + +A pool of [Client](/docs/docs/api/Client.md) instances connected to the same upstream target. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new Pool(url[, options])` + +Arguments: + +* **url** `URL | string` - It should only include the **protocol, hostname, and port**. +* **options** `PoolOptions` (optional) + +### Parameter: `PoolOptions` + +Extends: [`ClientOptions`](/docs/docs/api/Client.md#parameter-clientoptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Client(origin, opts)` +* **connections** `number | null` (optional) - Default: `null` - The number of `Client` instances to create. When set to `null`, the `Pool` instance will create an unlimited amount of `Client` instances. +* **clientTtl** `number | null` (optional) - Default: `null` - The amount of time before a `Client` instance is removed from the `Pool` and closed. When set to `null`, `Client` instances will not be removed or closed based on age. + +## Instance Properties + +### `Pool.closed` + +Implements [Client.closed](/docs/docs/api/Client.md#clientclosed) + +### `Pool.destroyed` + +Implements [Client.destroyed](/docs/docs/api/Client.md#clientdestroyed) + +### `Pool.stats` + +Returns [`PoolStats`](PoolStats.md) instance for this pool. + +## Instance Methods + +### `Pool.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `Pool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Pool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `Pool.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Pool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Pool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `Pool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Pool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](/docs/docs/api/Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](/docs/docs/api/Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](/docs/docs/api/Dispatcher.md#event-drain). diff --git a/node_modules/undici/docs/docs/api/PoolStats.md b/node_modules/undici/docs/docs/api/PoolStats.md new file mode 100644 index 000000000..3cbe0d82e --- /dev/null +++ b/node_modules/undici/docs/docs/api/PoolStats.md @@ -0,0 +1,35 @@ +# Class: PoolStats + +Aggregate stats for a [Pool](/docs/docs/api/Pool.md) or [BalancedPool](/docs/docs/api/BalancedPool.md). + +## `new PoolStats(pool)` + +Arguments: + +* **pool** `Pool` - Pool or BalancedPool from which to return stats. + +## Instance Properties + +### `PoolStats.connected` + +Number of open socket connections in this pool. + +### `PoolStats.free` + +Number of open socket connections in this pool that do not have an active request. + +### `PoolStats.pending` + +Number of pending requests across all clients in this pool. + +### `PoolStats.queued` + +Number of queued requests across all clients in this pool. + +### `PoolStats.running` + +Number of currently active requests across all clients in this pool. + +### `PoolStats.size` + +Number of active, pending, or queued requests across all clients in this pool. diff --git a/node_modules/undici/docs/docs/api/ProxyAgent.md b/node_modules/undici/docs/docs/api/ProxyAgent.md new file mode 100644 index 000000000..8db7221a3 --- /dev/null +++ b/node_modules/undici/docs/docs/api/ProxyAgent.md @@ -0,0 +1,229 @@ +# Class: ProxyAgent + +Extends: `undici.Dispatcher` + +A Proxy Agent class that implements the Agent API. It allows the connection through proxy in a simple way. + +## `new ProxyAgent([options])` + +Arguments: + +* **options** `ProxyAgentOptions` (required) - It extends the `Agent` options. + +Returns: `ProxyAgent` + +### Parameter: `ProxyAgentOptions` + +Extends: [`AgentOptions`](/docs/docs/api/Agent.md#parameter-agentoptions) +> It ommits `AgentOptions#connect`. + +> **Note:** When `AgentOptions#connections` is set, and different from `0`, the non-standard [`proxy-connection` header](https://udger.com/resources/http-request-headers-detail?header=Proxy-Connection) will be set to `keep-alive` in the request. + +* **uri** `string | URL` (required) - The URI of the proxy server. This can be provided as a string, as an instance of the URL class, or as an object with a `uri` property of type string. +If the `uri` is provided as a string or `uri` is an object with an `uri` property of type string, then it will be parsed into a `URL` object according to the [WHATWG URL Specification](https://url.spec.whatwg.org). +For detailed information on the parsing process and potential validation errors, please refer to the ["Writing" section](https://url.spec.whatwg.org/#writing) of the WHATWG URL Specification. +* **token** `string` (optional) - It can be passed by a string of token for authentication. +* **auth** `string` (**deprecated**) - Use token. +* **clientFactory** `(origin: URL, opts: Object) => Dispatcher` (optional) - Default: `(origin, opts) => new Pool(origin, opts)` +* **requestTls** `BuildOptions` (optional) - Options object passed when creating the underlying socket via the connector builder for the request. It extends from [`Client#ConnectOptions`](/docs/docs/api/Client.md#parameter-connectoptions). +* **proxyTls** `BuildOptions` (optional) - Options object passed when creating the underlying socket via the connector builder for the proxy server. It extends from [`Client#ConnectOptions`](/docs/docs/api/Client.md#parameter-connectoptions). +* **proxyTunnel** `boolean` (optional) - For connections involving secure protocols, Undici will always establish a tunnel via the HTTP2 CONNECT extension. If proxyTunnel is set to true, this will occur for unsecured proxy/endpoint connections as well. Currently, there is no way to facilitate HTTP1 IP tunneling as described in https://www.rfc-editor.org/rfc/rfc9484.html#name-http-11-request. If proxyTunnel is set to false (the default), ProxyAgent connections where both the Proxy and Endpoint are unsecured will issue all requests to the Proxy, and prefix the endpoint request path with the endpoint origin address. + +Examples: + +```js +import { ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +// or +const proxyAgent = new ProxyAgent(new URL('my.proxy.server')) +// or +const proxyAgent = new ProxyAgent({ uri: 'my.proxy.server' }) +// or +const proxyAgent = new ProxyAgent({ + uri: new URL('my.proxy.server'), + proxyTls: { + signal: AbortSignal.timeout(1000) + } +}) +``` + +#### Example - Basic ProxyAgent instantiation + +This will instantiate the ProxyAgent. It will not do anything until registered as the agent to use with requests. + +```js +import { ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +``` + +#### Example - Basic Proxy Request with global agent dispatcher + +```js +import { setGlobalDispatcher, request, ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +setGlobalDispatcher(proxyAgent) + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with local agent dispatcher + +```js +import { ProxyAgent, request } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: proxyAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with authentication + +```js +import { setGlobalDispatcher, request, ProxyAgent } from 'undici'; + +const proxyAgent = new ProxyAgent({ + uri: 'my.proxy.server', + // token: 'Bearer xxxx' + token: `Basic ${Buffer.from('username:password').toString('base64')}` +}); +setGlobalDispatcher(proxyAgent); + +const { statusCode, body } = await request('http://localhost:3000/foo'); + +console.log('response received', statusCode); // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')); // data foo +} +``` + +### `ProxyAgent.close()` + +Closes the proxy agent and waits for registered pools and clients to also close before resolving. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { ProxyAgent, setGlobalDispatcher } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +setGlobalDispatcher(proxyAgent) + +await proxyAgent.close() +``` + +### `ProxyAgent.dispatch(options, handlers)` + +Implements [`Agent.dispatch(options, handlers)`](/docs/docs/api/Agent.md#parameter-agentdispatchoptions). + +### `ProxyAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + + +#### Example - ProxyAgent with Fetch + +This example demonstrates how to use `fetch` with a proxy via `ProxyAgent`. It is particularly useful for scenarios requiring proxy tunneling. + +```javascript +import { ProxyAgent, fetch } from 'undici'; + +// Define the ProxyAgent +const proxyAgent = new ProxyAgent('http://localhost:8000'); + +// Make a GET request through the proxy +const response = await fetch('http://localhost:3000/foo', { + dispatcher: proxyAgent, + method: 'GET', +}); + +console.log('Response status:', response.status); +console.log('Response data:', await response.text()); +``` + +--- + +#### Example - ProxyAgent with a Custom Proxy Server + +This example shows how to create a custom proxy server and use it with `ProxyAgent`. + +```javascript +import * as http from 'node:http'; +import { createProxy } from 'proxy'; +import { ProxyAgent, fetch } from 'undici'; + +// Create a proxy server +const proxyServer = createProxy(http.createServer()); +proxyServer.listen(8000, () => { + console.log('Proxy server running on port 8000'); +}); + +// Define and use the ProxyAgent +const proxyAgent = new ProxyAgent('http://localhost:8000'); + +const response = await fetch('http://example.com', { + dispatcher: proxyAgent, + method: 'GET', +}); + +console.log('Response status:', response.status); +console.log('Response data:', await response.text()); +``` + +--- + +#### Example - ProxyAgent with HTTPS Tunneling + +This example demonstrates how to perform HTTPS tunneling using a proxy. + +```javascript +import { ProxyAgent, fetch } from 'undici'; + +// Define a ProxyAgent for HTTPS proxy +const proxyAgent = new ProxyAgent('https://secure.proxy.server'); + +// Make a request to an HTTPS endpoint via the proxy +const response = await fetch('https://secure.endpoint.com/api/data', { + dispatcher: proxyAgent, + method: 'GET', +}); + +console.log('Response status:', response.status); +console.log('Response data:', await response.json()); +``` + +#### Example - ProxyAgent as a Global Dispatcher + +`ProxyAgent` can be configured as a global dispatcher, making it available for all requests without explicitly passing it. This simplifies code and is useful when a single proxy configuration applies to all requests. + +```javascript +import { ProxyAgent, setGlobalDispatcher, fetch } from 'undici'; + +// Define and configure the ProxyAgent +const proxyAgent = new ProxyAgent('http://localhost:8000'); +setGlobalDispatcher(proxyAgent); + +// Make requests without specifying the dispatcher +const response = await fetch('http://example.com'); +console.log('Response status:', response.status); +console.log('Response data:', await response.text()); diff --git a/node_modules/undici/docs/docs/api/RedirectHandler.md b/node_modules/undici/docs/docs/api/RedirectHandler.md new file mode 100644 index 000000000..bb16284ff --- /dev/null +++ b/node_modules/undici/docs/docs/api/RedirectHandler.md @@ -0,0 +1,96 @@ +# Class: RedirectHandler + +A class that handles redirection logic for HTTP requests. + +## `new RedirectHandler(dispatch, maxRedirections, opts, handler, redirectionLimitReached)` + +Arguments: + +- **dispatch** `function` - The dispatch function to be called after every retry. +- **maxRedirections** `number` - Maximum number of redirections allowed. +- **opts** `object` - Options for handling redirection. +- **handler** `object` - An object containing handlers for different stages of the request lifecycle. +- **redirectionLimitReached** `boolean` (default: `false`) - A flag that the implementer can provide to enable or disable the feature. If set to `false`, it indicates that the caller doesn't want to use the feature and prefers the old behavior. + +Returns: `RedirectHandler` + +### Parameters + +- **dispatch** `(options: Dispatch.DispatchOptions, handlers: Dispatch.DispatchHandler) => Promise` (required) - Dispatch function to be called after every redirection. +- **maxRedirections** `number` (required) - Maximum number of redirections allowed. +- **opts** `object` (required) - Options for handling redirection. +- **handler** `object` (required) - Handlers for different stages of the request lifecycle. +- **redirectionLimitReached** `boolean` (default: `false`) - A flag that the implementer can provide to enable or disable the feature. If set to `false`, it indicates that the caller doesn't want to use the feature and prefers the old behavior. + +### Properties + +- **location** `string` - The current redirection location. +- **abort** `function` - The abort function. +- **opts** `object` - The options for handling redirection. +- **maxRedirections** `number` - Maximum number of redirections allowed. +- **handler** `object` - Handlers for different stages of the request lifecycle. +- **history** `Array` - An array representing the history of URLs during redirection. +- **redirectionLimitReached** `boolean` - Indicates whether the redirection limit has been reached. + +### Methods + +#### `onConnect(abort)` + +Called when the connection is established. + +Parameters: + +- **abort** `function` - The abort function. + +#### `onUpgrade(statusCode, headers, socket)` + +Called when an upgrade is requested. + +Parameters: + +- **statusCode** `number` - The HTTP status code. +- **headers** `object` - The headers received in the response. +- **socket** `object` - The socket object. + +#### `onError(error)` + +Called when an error occurs. + +Parameters: + +- **error** `Error` - The error that occurred. + +#### `onHeaders(statusCode, headers, resume, statusText)` + +Called when headers are received. + +Parameters: + +- **statusCode** `number` - The HTTP status code. +- **headers** `object` - The headers received in the response. +- **resume** `function` - The resume function. +- **statusText** `string` - The status text. + +#### `onData(chunk)` + +Called when data is received. + +Parameters: + +- **chunk** `Buffer` - The data chunk received. + +#### `onComplete(trailers)` + +Called when the request is complete. + +Parameters: + +- **trailers** `object` - The trailers received. + +#### `onBodySent(chunk)` + +Called when the request body is sent. + +Parameters: + +- **chunk** `Buffer` - The chunk of the request body sent. diff --git a/node_modules/undici/docs/docs/api/RetryAgent.md b/node_modules/undici/docs/docs/api/RetryAgent.md new file mode 100644 index 000000000..9b423d9f0 --- /dev/null +++ b/node_modules/undici/docs/docs/api/RetryAgent.md @@ -0,0 +1,50 @@ +# Class: RetryAgent + +Extends: `undici.Dispatcher` + +A `undici.Dispatcher` that allows to automatically retry a request. +Wraps a `undici.RetryHandler`. + +## `new RetryAgent(dispatcher, [options])` + +Arguments: + +* **dispatcher** `undici.Dispatcher` (required) - the dispatcher to wrap +* **options** `RetryHandlerOptions` (optional) - the options + +Returns: `ProxyAgent` + +### Parameter: `RetryHandlerOptions` + +- **throwOnError** `boolean` (optional) - Disable to prevent throwing error on last retry attept, useful if you need the body on errors from server or if you have custom error handler. Default: `true` +- **retry** `(err: Error, context: RetryContext, callback: (err?: Error | null) => void) => void` (optional) - Function to be called after every retry. It should pass error if no more retries should be performed. +- **maxRetries** `number` (optional) - Maximum number of retries. Default: `5` +- **maxTimeout** `number` (optional) - Maximum number of milliseconds to wait before retrying. Default: `30000` (30 seconds) +- **minTimeout** `number` (optional) - Minimum number of milliseconds to wait before retrying. Default: `500` (half a second) +- **timeoutFactor** `number` (optional) - Factor to multiply the timeout by for each retry attempt. Default: `2` +- **retryAfter** `boolean` (optional) - It enables automatic retry after the `Retry-After` header is received. Default: `true` +- +- **methods** `string[]` (optional) - Array of HTTP methods to retry. Default: `['GET', 'PUT', 'HEAD', 'OPTIONS', 'DELETE']` +- **statusCodes** `number[]` (optional) - Array of HTTP status codes to retry. Default: `[429, 500, 502, 503, 504]` +- **errorCodes** `string[]` (optional) - Array of Error codes to retry. Default: `['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN','ENETUNREACH', 'EHOSTDOWN', 'UND_ERR_SOCKET']` + +**`RetryContext`** + +- `state`: `RetryState` - Current retry state. It can be mutated. +- `opts`: `Dispatch.DispatchOptions & RetryOptions` - Options passed to the retry handler. + +Example: + +```js +import { Agent, RetryAgent } from 'undici' + +const agent = new RetryAgent(new Agent()) + +const res = await agent.request({ + method: 'GET', + origin: 'http://example.com', + path: '/', +}) +console.log(res.statusCode) +console.log(await res.body.text()) +``` diff --git a/node_modules/undici/docs/docs/api/RetryHandler.md b/node_modules/undici/docs/docs/api/RetryHandler.md new file mode 100644 index 000000000..d7b3e88d0 --- /dev/null +++ b/node_modules/undici/docs/docs/api/RetryHandler.md @@ -0,0 +1,118 @@ +# Class: RetryHandler + +Extends: `undici.DispatcherHandlers` + +A handler class that implements the retry logic for a request. + +## `new RetryHandler(dispatchOptions, retryHandlers, [retryOptions])` + +Arguments: + +- **options** `Dispatch.DispatchOptions & RetryOptions` (required) - It is an intersection of `Dispatcher.DispatchOptions` and `RetryOptions`. +- **retryHandlers** `RetryHandlers` (required) - Object containing the `dispatch` to be used on every retry, and `handler` for handling the `dispatch` lifecycle. + +Returns: `retryHandler` + +### Parameter: `Dispatch.DispatchOptions & RetryOptions` + +Extends: [`Dispatch.DispatchOptions`](/docs/docs/api/Dispatcher.md#parameter-dispatchoptions). + +#### `RetryOptions` + +- **throwOnError** `boolean` (optional) - Disable to prevent throwing error on last retry attept, useful if you need the body on errors from server or if you have custom error handler. +- **retry** `(err: Error, context: RetryContext, callback: (err?: Error | null) => void) => number | null` (optional) - Function to be called after every retry. It should pass error if no more retries should be performed. +- **maxRetries** `number` (optional) - Maximum number of retries. Default: `5` +- **maxTimeout** `number` (optional) - Maximum number of milliseconds to wait before retrying. Default: `30000` (30 seconds) +- **minTimeout** `number` (optional) - Minimum number of milliseconds to wait before retrying. Default: `500` (half a second) +- **timeoutFactor** `number` (optional) - Factor to multiply the timeout by for each retry attempt. Default: `2` +- **retryAfter** `boolean` (optional) - It enables automatic retry after the `Retry-After` header is received. Default: `true` +- +- **methods** `string[]` (optional) - Array of HTTP methods to retry. Default: `['GET', 'PUT', 'HEAD', 'OPTIONS', 'DELETE']` +- **statusCodes** `number[]` (optional) - Array of HTTP status codes to retry. Default: `[429, 500, 502, 503, 504]` +- **errorCodes** `string[]` (optional) - Array of Error codes to retry. Default: `['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN','ENETUNREACH', 'EHOSTDOWN', 'UND_ERR_SOCKET']` + +**`RetryContext`** + +- `state`: `RetryState` - Current retry state. It can be mutated. +- `opts`: `Dispatch.DispatchOptions & RetryOptions` - Options passed to the retry handler. + +**`RetryState`** + +It represents the retry state for a given request. + +- `counter`: `number` - Current retry attempt. + +### Parameter `RetryHandlers` + +- **dispatch** `(options: Dispatch.DispatchOptions, handlers: Dispatch.DispatchHandler) => Promise` (required) - Dispatch function to be called after every retry. +- **handler** Extends [`Dispatch.DispatchHandler`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler) (required) - Handler function to be called after the request is successful or the retries are exhausted. + +>__Note__: The `RetryHandler` does not retry over stateful bodies (e.g. streams, AsyncIterable) as those, once consumed, are left in a state that cannot be reutilized. For these situations the `RetryHandler` will identify +>the body as stateful and will not retry the request rejecting with the error `UND_ERR_REQ_RETRY`. + +Examples: + +```js +const client = new Client(`http://localhost:${server.address().port}`); +const chunks = []; +const handler = new RetryHandler( + { + ...dispatchOptions, + retryOptions: { + // custom retry function + retry: function (err, state, callback) { + counter++; + + if (err.code && err.code === "UND_ERR_DESTROYED") { + callback(err); + return; + } + + if (err.statusCode === 206) { + callback(err); + return; + } + + setTimeout(() => callback(null), 1000); + }, + }, + }, + { + dispatch: (...args) => { + return client.dispatch(...args); + }, + handler: { + onConnect() {}, + onBodySent() {}, + onHeaders(status, _rawHeaders, resume, _statusMessage) { + // do something with headers + }, + onData(chunk) { + chunks.push(chunk); + return true; + }, + onComplete() {}, + onError() { + // handle error properly + }, + }, + } +); +``` + +#### Example - Basic RetryHandler with defaults + +```js +const client = new Client(`http://localhost:${server.address().port}`); +const handler = new RetryHandler(dispatchOptions, { + dispatch: client.dispatch.bind(client), + handler: { + onConnect() {}, + onBodySent() {}, + onHeaders(status, _rawHeaders, resume, _statusMessage) {}, + onData(chunk) {}, + onComplete() {}, + onError(err) {}, + }, +}); +``` diff --git a/node_modules/undici/docs/docs/api/RoundRobinPool.md b/node_modules/undici/docs/docs/api/RoundRobinPool.md new file mode 100644 index 000000000..7221122ae --- /dev/null +++ b/node_modules/undici/docs/docs/api/RoundRobinPool.md @@ -0,0 +1,145 @@ +# Class: RoundRobinPool + +Extends: `undici.Dispatcher` + +A pool of [Client](/docs/docs/api/Client.md) instances connected to the same upstream target with round-robin client selection. + +Unlike [`Pool`](/docs/docs/api/Pool.md), which always selects the first available client, `RoundRobinPool` cycles through clients in a round-robin fashion. This ensures even distribution of requests across all connections, which is particularly useful when the upstream target is behind a load balancer that round-robins TCP connections across multiple backend servers (e.g., Kubernetes Services). + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new RoundRobinPool(url[, options])` + +Arguments: + +* **url** `URL | string` - It should only include the **protocol, hostname, and port**. +* **options** `RoundRobinPoolOptions` (optional) + +### Parameter: `RoundRobinPoolOptions` + +Extends: [`ClientOptions`](/docs/docs/api/Client.md#parameter-clientoptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Client(origin, opts)` +* **connections** `number | null` (optional) - Default: `null` - The number of `Client` instances to create. When set to `null`, the `RoundRobinPool` instance will create an unlimited amount of `Client` instances. +* **clientTtl** `number | null` (optional) - Default: `null` - The amount of time before a `Client` instance is removed from the `RoundRobinPool` and closed. When set to `null`, `Client` instances will not be removed or closed based on age. + +## Use Case + +`RoundRobinPool` is designed for scenarios where: + +1. You connect to a single origin (e.g., `http://my-service.namespace.svc`) +2. That origin is backed by a load balancer distributing TCP connections across multiple servers +3. You want requests evenly distributed across all backend servers + +**Example**: In Kubernetes, when using a Service DNS name with multiple Pod replicas, kube-proxy load balances TCP connections. `RoundRobinPool` ensures each connection (and thus each Pod) receives an equal share of requests. + +### Important: Backend Distribution Considerations + +`RoundRobinPool` distributes **HTTP requests** evenly across **TCP connections**. Whether this translates to even backend server distribution depends on the load balancer's behavior: + +**✓ Works when the load balancer**: +- Assigns different backends to different TCP connections from the same client +- Uses algorithms like: round-robin, random, least-connections (without client affinity) +- Example: Default Kubernetes Services without `sessionAffinity` + +**✗ Does NOT work when**: +- Load balancer has client/source IP affinity (all connections from one IP → same backend) +- Load balancer uses source-IP-hash or sticky sessions + +**How it works:** +1. `RoundRobinPool` creates N TCP connections to the load balancer endpoint +2. Load balancer assigns each TCP connection to a backend (per its algorithm) +3. `RoundRobinPool` cycles HTTP requests across those N connections +4. Result: Requests distributed proportionally to how the LB distributed the connections + +If the load balancer assigns all connections to the same backend (e.g., due to session affinity), `RoundRobinPool` cannot overcome this. In such cases, consider using [`BalancedPool`](/docs/docs/api/BalancedPool.md) with direct backend addresses (e.g., individual pod IPs) instead of a load-balanced endpoint. + +## Instance Properties + +### `RoundRobinPool.closed` + +Implements [Client.closed](/docs/docs/api/Client.md#clientclosed) + +### `RoundRobinPool.destroyed` + +Implements [Client.destroyed](/docs/docs/api/Client.md#clientdestroyed) + +### `RoundRobinPool.stats` + +Returns [`PoolStats`](PoolStats.md) instance for this pool. + +## Instance Methods + +### `RoundRobinPool.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `RoundRobinPool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `RoundRobinPool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `RoundRobinPool.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `RoundRobinPool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `RoundRobinPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `RoundRobinPool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `RoundRobinPool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](/docs/docs/api/Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](/docs/docs/api/Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](/docs/docs/api/Dispatcher.md#event-drain). + +## Example + +```javascript +import { RoundRobinPool } from 'undici' + +const pool = new RoundRobinPool('http://my-service.default.svc.cluster.local', { + connections: 10 +}) + +// Requests will be distributed evenly across all 10 connections +for (let i = 0; i < 100; i++) { + const { body } = await pool.request({ + path: '/api/data', + method: 'GET' + }) + console.log(await body.json()) +} + +await pool.close() +``` + +## See Also + +- [Pool](/docs/docs/api/Pool.md) - Connection pool without round-robin +- [BalancedPool](/docs/docs/api/BalancedPool.md) - Load balancing across multiple origins +- [Issue #3648](https://github.com/nodejs/undici/issues/3648) - Original issue describing uneven distribution + diff --git a/node_modules/undici/docs/docs/api/SnapshotAgent.md b/node_modules/undici/docs/docs/api/SnapshotAgent.md new file mode 100644 index 000000000..e4c8f2484 --- /dev/null +++ b/node_modules/undici/docs/docs/api/SnapshotAgent.md @@ -0,0 +1,616 @@ +# SnapshotAgent + +The `SnapshotAgent` provides a powerful way to record and replay HTTP requests for testing purposes. It extends `MockAgent` to enable automatic snapshot testing, eliminating the need to manually define mock responses. + +## Use Cases + +- **Integration Testing**: Record real API interactions and replay them in tests +- **Offline Development**: Work with APIs without network connectivity +- **Consistent Test Data**: Ensure tests use the same responses across runs +- **API Contract Testing**: Capture and validate API behavior over time + +## Constructor + +```javascript +new SnapshotAgent([options]) +``` + +### Parameters + +- **options** `Object` (optional) + - **mode** `String` - The snapshot mode: `'record'`, `'playback'`, or `'update'`. Default: `'record'` + - **snapshotPath** `String` - Path to the snapshot file for loading/saving + - **maxSnapshots** `Number` - Maximum number of snapshots to keep in memory. Default: `Infinity` + - **autoFlush** `Boolean` - Whether to automatically save snapshots to disk. Default: `false` + - **flushInterval** `Number` - Interval in milliseconds for auto-flush. Default: `30000` + - **matchHeaders** `Array` - Specific headers to include in request matching. Default: all headers + - **ignoreHeaders** `Array` - Headers to ignore during request matching + - **excludeHeaders** `Array` - Headers to exclude from snapshots (for security) + - **matchBody** `Boolean` - Whether to include request body in matching. Default: `true` + - **matchQuery** `Boolean` - Whether to include query parameters in matching. Default: `true` + - **caseSensitive** `Boolean` - Whether header matching is case-sensitive. Default: `false` + - **shouldRecord** `Function` - Callback to determine if a request should be recorded + - **shouldPlayback** `Function` - Callback to determine if a request should be played back + - **excludeUrls** `Array` - URL patterns (strings or RegExp) to exclude from recording/playback + - All other options from `MockAgent` are supported + +### Modes + +#### Record Mode (`'record'`) +Makes real HTTP requests and saves the responses to snapshots. + +```javascript +import { SnapshotAgent, setGlobalDispatcher } from 'undici' + +const agent = new SnapshotAgent({ + mode: 'record', + snapshotPath: './test/snapshots/api-calls.json' +}) +setGlobalDispatcher(agent) + +// Makes real requests and records them +const response = await fetch('https://api.example.com/users') +const users = await response.json() + +// Save recorded snapshots +await agent.saveSnapshots() +``` + +#### Playback Mode (`'playback'`) +Replays recorded responses without making real HTTP requests. + +```javascript +import { SnapshotAgent, setGlobalDispatcher } from 'undici' + +const agent = new SnapshotAgent({ + mode: 'playback', + snapshotPath: './test/snapshots/api-calls.json' +}) +setGlobalDispatcher(agent) + +// Uses recorded response instead of real request +const response = await fetch('https://api.example.com/users') +``` + +#### Update Mode (`'update'`) +Uses existing snapshots when available, but records new ones for missing requests. + +```javascript +import { SnapshotAgent, setGlobalDispatcher } from 'undici' + +const agent = new SnapshotAgent({ + mode: 'update', + snapshotPath: './test/snapshots/api-calls.json' +}) +setGlobalDispatcher(agent) + +// Uses snapshot if exists, otherwise makes real request and records it +const response = await fetch('https://api.example.com/new-endpoint') +``` + +## Instance Methods + +### `agent.saveSnapshots([filePath])` + +Saves all recorded snapshots to a file. + +#### Parameters + +- **filePath** `String` (optional) - Path to save snapshots. Uses constructor `snapshotPath` if not provided. + +#### Returns + +`Promise` + +```javascript +await agent.saveSnapshots('./custom-snapshots.json') +``` + +## Advanced Configuration + +### Header Filtering + +Control which headers are used for request matching and what gets stored in snapshots: + +```javascript +const agent = new SnapshotAgent({ + mode: 'record', + snapshotPath: './snapshots.json', + + // Only match these specific headers + matchHeaders: ['content-type', 'accept'], + + // Ignore these headers during matching (but still store them) + ignoreHeaders: ['user-agent', 'date'], + + // Exclude sensitive headers from snapshots entirely + excludeHeaders: ['authorization', 'x-api-key', 'cookie'] +}) +``` + +### Custom Request/Response Filtering + +Use callback functions to determine what gets recorded or played back: + +```javascript +const agent = new SnapshotAgent({ + mode: 'record', + snapshotPath: './snapshots.json', + + // Only record GET requests to specific endpoints + shouldRecord: (requestOpts) => { + const url = new URL(requestOpts.path, requestOpts.origin) + return requestOpts.method === 'GET' && url.pathname.startsWith('/api/v1/') + }, + + // Skip authentication endpoints during playback + shouldPlayback: (requestOpts) => { + const url = new URL(requestOpts.path, requestOpts.origin) + return !url.pathname.includes('/auth/') + } +}) +``` + +### URL Pattern Exclusion + +Exclude specific URLs from recording/playback using patterns: + +```javascript +const agent = new SnapshotAgent({ + mode: 'record', + snapshotPath: './snapshots.json', + + excludeUrls: [ + 'https://analytics.example.com', // String match + /\/api\/v\d+\/health/, // Regex pattern + 'telemetry' // Substring match + ] +}) +``` + +### Memory Management + +Configure automatic memory and disk management: + +```javascript +const agent = new SnapshotAgent({ + mode: 'record', + snapshotPath: './snapshots.json', + + // Keep only 1000 snapshots in memory + maxSnapshots: 1000, + + // Automatically save to disk every 30 seconds + autoFlush: true, + flushInterval: 30000 +}) +``` + +### Sequential Response Handling + +Handle multiple responses for the same request (similar to nock): + +```javascript +// In record mode, multiple identical requests get recorded as separate responses +const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './sequential.json' }) + +// First call returns response A +await fetch('https://api.example.com/random') + +// Second call returns response B +await fetch('https://api.example.com/random') + +await agent.saveSnapshots() + +// In playback mode, calls return responses in sequence +const playbackAgent = new SnapshotAgent({ mode: 'playback', snapshotPath: './sequential.json' }) + +// Returns response A +const first = await fetch('https://api.example.com/random') + +// Returns response B +const second = await fetch('https://api.example.com/random') + +// Third call repeats the last response (B) +const third = await fetch('https://api.example.com/random') +``` + +## Managing Snapshots + +### Replacing Existing Snapshots + +```javascript +// Load existing snapshots +await agent.loadSnapshots('./old-snapshots.json') + +// Get snapshot data +const recorder = agent.getRecorder() +const snapshots = recorder.getSnapshots() + +// Modify or filter snapshots +const filteredSnapshots = snapshots.filter(s => + !s.request.url.includes('deprecated') +) + +// Replace all snapshots +agent.replaceSnapshots(filteredSnapshots.map((snapshot, index) => ({ + hash: `new-hash-${index}`, + snapshot +}))) + +// Save updated snapshots +await agent.saveSnapshots('./updated-snapshots.json') +``` + +### `agent.loadSnapshots([filePath])` + +Loads snapshots from a file. + +#### Parameters + +- **filePath** `String` (optional) - Path to load snapshots from. Uses constructor `snapshotPath` if not provided. + +#### Returns + +`Promise` + +```javascript +await agent.loadSnapshots('./existing-snapshots.json') +``` + +### `agent.getRecorder()` + +Gets the underlying `SnapshotRecorder` instance. + +#### Returns + +`SnapshotRecorder` + +```javascript +const recorder = agent.getRecorder() +console.log(`Recorded ${recorder.size()} interactions`) +``` + +### `agent.getMode()` + +Gets the current snapshot mode. + +#### Returns + +`String` - The current mode (`'record'`, `'playback'`, or `'update'`) + +### `agent.clearSnapshots()` + +Clears all recorded snapshots from memory. + +```javascript +agent.clearSnapshots() +``` + +## Working with Different Request Types + +### GET Requests + +```javascript +// Record mode +const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './get-snapshots.json' }) +setGlobalDispatcher(agent) + +const response = await fetch('https://jsonplaceholder.typicode.com/posts/1') +const post = await response.json() + +await agent.saveSnapshots() +``` + +### POST Requests with Body + +```javascript +// Record mode +const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './post-snapshots.json' }) +setGlobalDispatcher(agent) + +const response = await fetch('https://jsonplaceholder.typicode.com/posts', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ title: 'Test Post', body: 'Content' }) +}) + +await agent.saveSnapshots() +``` + +### Using with `undici.request` + +SnapshotAgent works with all undici APIs, not just fetch: + +```javascript +import { SnapshotAgent, request, setGlobalDispatcher } from 'undici' + +const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './request-snapshots.json' }) +setGlobalDispatcher(agent) + +const { statusCode, headers, body } = await request('https://api.example.com/data') +const data = await body.json() + +await agent.saveSnapshots() +``` + +## Test Integration + +### Basic Test Setup + +```javascript +import { test } from 'node:test' +import { SnapshotAgent, setGlobalDispatcher, getGlobalDispatcher } from 'undici' + +test('API integration test', async (t) => { + const originalDispatcher = getGlobalDispatcher() + + const agent = new SnapshotAgent({ + mode: 'playback', + snapshotPath: './test/snapshots/api-test.json' + }) + setGlobalDispatcher(agent) + + t.after(() => setGlobalDispatcher(originalDispatcher)) + + // This will use recorded data + const response = await fetch('https://api.example.com/users') + const users = await response.json() + + assert(Array.isArray(users)) + assert(users.length > 0) +}) +``` + +### Environment-Based Mode Selection + +```javascript +const mode = process.env.SNAPSHOT_MODE || 'playback' + +const agent = new SnapshotAgent({ + mode, + snapshotPath: './test/snapshots/integration.json' +}) + +// Run with: SNAPSHOT_MODE=record npm test (to record) +// Run with: npm test (to playback) +``` + +### Test Helper Function + +```javascript +function createSnapshotAgent(testName, mode = 'playback') { + return new SnapshotAgent({ + mode, + snapshotPath: `./test/snapshots/${testName}.json` + }) +} + +test('user API test', async (t) => { + const agent = createSnapshotAgent('user-api') + setGlobalDispatcher(agent) + + // Test implementation... +}) +``` + +## Snapshot File Format + +Snapshots are stored as JSON with the following structure: + +```json +[ + { + "hash": "dGVzdC1oYXNo...", + "snapshot": { + "request": { + "method": "GET", + "url": "https://api.example.com/users", + "headers": { + "authorization": "Bearer token" + }, + "body": undefined + }, + "response": { + "statusCode": 200, + "headers": { + "content-type": "application/json" + }, + "body": "eyJkYXRhIjoidGVzdCJ9", // base64 encoded + "trailers": {} + }, + "timestamp": "2024-01-01T00:00:00.000Z" + } + } +] +``` + +## Security Considerations + +### Sensitive Data in Snapshots + +By default, SnapshotAgent records all headers and request/response data. For production use, always exclude sensitive information: + +```javascript +const agent = new SnapshotAgent({ + mode: 'record', + snapshotPath: './snapshots.json', + + // Exclude sensitive headers from snapshots + excludeHeaders: [ + 'authorization', + 'x-api-key', + 'cookie', + 'set-cookie', + 'x-auth-token', + 'x-csrf-token' + ], + + // Filter out requests with sensitive data + shouldRecord: (requestOpts) => { + const url = new URL(requestOpts.path, requestOpts.origin) + + // Don't record authentication endpoints + if (url.pathname.includes('/auth/') || url.pathname.includes('/login')) { + return false + } + + // Don't record if request contains sensitive body data + if (requestOpts.body && typeof requestOpts.body === 'string') { + const body = requestOpts.body.toLowerCase() + if (body.includes('password') || body.includes('secret')) { + return false + } + } + + return true + } +}) +``` + +### Snapshot File Security + +**Important**: Snapshot files may contain sensitive data. Handle them securely: + +- ✅ Add snapshot files to `.gitignore` if they contain real API data +- ✅ Use environment-specific snapshots (dev/staging/prod) +- ✅ Regularly review snapshot contents for sensitive information +- ✅ Use the `excludeHeaders` option for production snapshots +- ❌ Never commit snapshots with real authentication tokens +- ❌ Don't share snapshot files containing personal data + +```gitignore +# Exclude snapshots with real data +/test/snapshots/production-*.json +/test/snapshots/*-real-data.json + +# Include sanitized test snapshots +!/test/snapshots/mock-*.json +``` + +## Error Handling + +### Missing Snapshots in Playback Mode + +```javascript +try { + const response = await fetch('https://api.example.com/nonexistent') +} catch (error) { + if (error.message.includes('No snapshot found')) { + // Handle missing snapshot + console.log('Snapshot not found for this request') + } +} +``` + +### Handling Network Errors in Record Mode + +```javascript +const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './snapshots.json' }) + +try { + const response = await fetch('https://nonexistent-api.example.com/data') +} catch (error) { + // Network errors are not recorded as snapshots + console.log('Network error:', error.message) +} +``` + +## Best Practices + +### 1. Organize Snapshots by Test Suite + +```javascript +// Use descriptive snapshot file names +const agent = new SnapshotAgent({ + mode: 'playback', + snapshotPath: `./test/snapshots/${testSuiteName}-${testName}.json` +}) +``` + +### 2. Version Control Snapshots + +Add snapshot files to version control to ensure consistent test behavior across environments: + +```gitignore +# Include snapshots in version control +!/test/snapshots/*.json +``` + +### 3. Clean Up Test Data + +```javascript +test('API test', async (t) => { + const agent = new SnapshotAgent({ + mode: 'playback', + snapshotPath: './test/snapshots/temp-test.json' + }) + + // Clean up after test + t.after(() => { + agent.clearSnapshots() + }) +}) +``` + +### 4. Snapshot Validation + +```javascript +test('validate snapshot contents', async (t) => { + const agent = new SnapshotAgent({ + mode: 'playback', + snapshotPath: './test/snapshots/validation.json' + }) + + const recorder = agent.getRecorder() + const snapshots = recorder.getSnapshots() + + // Validate snapshot structure + assert(snapshots.length > 0, 'Should have recorded snapshots') + assert(snapshots[0].request.url.startsWith('https://'), 'Should use HTTPS') +}) +``` + +## Comparison with Other Tools + +### vs Manual MockAgent Setup + +**Manual MockAgent:** +```javascript +const mockAgent = new MockAgent() +const mockPool = mockAgent.get('https://api.example.com') + +mockPool.intercept({ + path: '/users', + method: 'GET' +}).reply(200, [ + { id: 1, name: 'User 1' }, + { id: 2, name: 'User 2' } +]) +``` + +**SnapshotAgent:** +```javascript +// Record once +const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './snapshots.json' }) +// Real API call gets recorded automatically + +// Use in tests +const agent = new SnapshotAgent({ mode: 'playback', snapshotPath: './snapshots.json' }) +// Automatically replays recorded response +``` + +### vs nock + +SnapshotAgent provides similar functionality to nock but is specifically designed for undici: + +- ✅ Works with all undici APIs (`request`, `stream`, `pipeline`, etc.) +- ✅ Supports undici-specific features (RetryAgent, connection pooling) +- ✅ Better TypeScript integration +- ✅ More efficient for high-performance scenarios + +## See Also + +- [MockAgent](./MockAgent.md) - Manual mocking for more control +- [MockCallHistory](./MockCallHistory.md) - Inspecting request history +- [Testing Best Practices](../best-practices/writing-tests.md) - General testing guidance \ No newline at end of file diff --git a/node_modules/undici/docs/docs/api/Util.md b/node_modules/undici/docs/docs/api/Util.md new file mode 100644 index 000000000..53b96e3ed --- /dev/null +++ b/node_modules/undici/docs/docs/api/Util.md @@ -0,0 +1,25 @@ +# Util + +Utility API for third-party implementations of the dispatcher API. + +## `parseHeaders(headers, [obj])` + +Receives a header object and returns the parsed value. + +Arguments: + +- **headers** `(Buffer | string | (Buffer | string)[])[]` (required) - Header object. + +- **obj** `Record` (optional) - Object to specify a proxy object. The parsed value is assigned to this object. But, if **headers** is an object, it is not used. + +Returns: `Record` If **obj** is specified, it is equivalent to **obj**. + +## `headerNameToString(value)` + +Retrieves a header name and returns its lowercase value. + +Arguments: + +- **value** `string | Buffer` (required) - Header name. + +Returns: `string` diff --git a/node_modules/undici/docs/docs/api/WebSocket.md b/node_modules/undici/docs/docs/api/WebSocket.md new file mode 100644 index 000000000..7313b8011 --- /dev/null +++ b/node_modules/undici/docs/docs/api/WebSocket.md @@ -0,0 +1,133 @@ +# Class: WebSocket + +Extends: [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) + +The WebSocket object provides a way to manage a WebSocket connection to a server, allowing bidirectional communication. The API follows the [WebSocket spec](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) and [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455). + +## `new WebSocket(url[, protocol])` + +Arguments: + +* **url** `URL | string` +* **protocol** `string | string[] | WebSocketInit` (optional) - Subprotocol(s) to request the server use, or a [`Dispatcher`](/docs/docs/api/Dispatcher.md). + +### Example: + +This example will not work in browsers or other platforms that don't allow passing an object. + +```mjs +import { WebSocket, ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') + +const ws = new WebSocket('wss://echo.websocket.events', { + dispatcher: proxyAgent, + protocols: ['echo', 'chat'] +}) +``` + +If you do not need a custom Dispatcher, it's recommended to use the following pattern: + +```mjs +import { WebSocket } from 'undici' + +const ws = new WebSocket('wss://echo.websocket.events', ['echo', 'chat']) +``` + +### Example with HTTP/2: + +> ⚠️ Warning: WebSocket over HTTP/2 is experimental, it is likely to change in the future. + +> 🗒️ Note: WebSocket over HTTP/2 may be enabled by default in a future version, +> this will happen by enabling HTTP/2 connections as the default behavior of Undici's Agent as well the global dispatcher. +> Stay tuned to the changelog for more information. + +This example will not work in browsers or other platforms that don't allow passing an object. + +```mjs +import { Agent } from 'undici' + +const agent = new Agent({ allowH2: true }) + +const ws = new WebSocket('wss://echo.websocket.events', { + dispatcher: agent, + protocols: ['echo', 'chat'] +}) +``` + +# Class: WebSocketStream + +> ⚠️ Warning: the WebSocketStream API has not been finalized and is likely to change. + +See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSocketStream) for more information. + +## `new WebSocketStream(url[, protocol])` + +Arguments: + +* **url** `URL | string` +* **options** `WebSocketStreamOptions` (optional) + +### WebSocketStream Example + +```js +const stream = new WebSocketStream('https://echo.websocket.org/') +const { readable, writable } = await stream.opened + +async function read () { + /** @type {ReadableStreamReader} */ + const reader = readable.getReader() + + while (true) { + const { done, value } = await reader.read() + if (done) break + + // do something with value + } +} + +async function write () { + /** @type {WritableStreamDefaultWriter} */ + const writer = writable.getWriter() + writer.write('Hello, world!') + writer.releaseLock() +} + +read() + +setInterval(() => write(), 5000) + +``` + +## ping(websocket, payload) +Arguments: + +* **websocket** `WebSocket` - The WebSocket instance to send the ping frame on +* **payload** `Buffer|undefined` (optional) - Optional payload data to include with the ping frame. Must not exceed 125 bytes. + +Sends a ping frame to the WebSocket server. The server must respond with a pong frame containing the same payload data. This can be used for keepalive purposes or to verify that the connection is still active. + +### Example: + +```js +import { WebSocket, ping } from 'undici' + +const ws = new WebSocket('wss://echo.websocket.events') + +ws.addEventListener('open', () => { + // Send ping with no payload + ping(ws) + + // Send ping with payload + const payload = Buffer.from('hello') + ping(ws, payload) +}) +``` + +**Note**: A ping frame cannot have a payload larger than 125 bytes. The ping will only be sent if the WebSocket connection is in the OPEN state. + +## Read More + +- [MDN - WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +- [The WebSocket Specification](https://www.rfc-editor.org/rfc/rfc6455) +- [The WHATWG WebSocket Specification](https://websockets.spec.whatwg.org/) diff --git a/node_modules/undici/docs/docs/api/api-lifecycle.md b/node_modules/undici/docs/docs/api/api-lifecycle.md new file mode 100644 index 000000000..ee08292cc --- /dev/null +++ b/node_modules/undici/docs/docs/api/api-lifecycle.md @@ -0,0 +1,91 @@ +# Client Lifecycle + +An Undici [Client](/docs/docs/api/Client.md) can be best described as a state machine. The following list is a summary of the various state transitions the `Client` will go through in its lifecycle. This document also contains detailed breakdowns of each state. + +> This diagram is not a perfect representation of the undici Client. Since the Client class is not actually implemented as a state-machine, actual execution may deviate slightly from what is described below. Consider this as a general resource for understanding the inner workings of the Undici client rather than some kind of formal specification. + +## State Transition Overview + +* A `Client` begins in the **idle** state with no socket connection and no requests in queue. + * The *connect* event transitions the `Client` to the **pending** state where requests can be queued prior to processing. + * The *close* and *destroy* events transition the `Client` to the **destroyed** state. Since there are no requests in the queue, the *close* event immediately transitions to the **destroyed** state. +* The **pending** state indicates the underlying socket connection has been successfully established and requests are queueing. + * The *process* event transitions the `Client` to the **processing** state where requests are processed. + * If requests are queued, the *close* event transitions to the **processing** state; otherwise, it transitions to the **destroyed** state. + * The *destroy* event transitions to the **destroyed** state. +* The **processing** state initializes to the **processing.running** state. + * If the current request requires draining, the *needDrain* event transitions the `Client` into the **processing.busy** state which will return to the **processing.running** state with the *drainComplete* event. + * After all queued requests are completed, the *keepalive* event transitions the `Client` back to the **pending** state. If no requests are queued during the timeout, the **close** event transitions the `Client` to the **destroyed** state. + * If the *close* event is fired while the `Client` still has queued requests, the `Client` transitions to the **process.closing** state where it will complete all existing requests before firing the *done* event. + * The *done* event gracefully transitions the `Client` to the **destroyed** state. + * At any point in time, the *destroy* event will transition the `Client` from the **processing** state to the **destroyed** state, destroying any queued requests. +* The **destroyed** state is a final state and the `Client` is no longer functional. + +A state diagram representing an Undici Client instance: + +```mermaid +stateDiagram-v2 + [*] --> idle + idle --> pending : connect + idle --> destroyed : destroy/close + + pending --> idle : timeout + pending --> destroyed : destroy + + state close_fork <> + pending --> close_fork : close + close_fork --> processing + close_fork --> destroyed + + pending --> processing : process + + processing --> pending : keepalive + processing --> destroyed : done + processing --> destroyed : destroy + + destroyed --> [*] + + state processing { + [*] --> running + running --> closing : close + running --> busy : needDrain + busy --> running : drainComplete + running --> [*] : keepalive + closing --> [*] : done + } +``` +## State details + +### idle + +The **idle** state is the initial state of a `Client` instance. While an `origin` is required for instantiating a `Client` instance, the underlying socket connection will not be established until a request is queued using [`Client.dispatch()`](/docs/docs/api/Client.md#clientdispatchoptions-handlers). By calling `Client.dispatch()` directly or using one of the multiple implementations ([`Client.connect()`](Client.md#clientconnectoptions-callback), [`Client.pipeline()`](Client.md#clientpipelineoptions-handler), [`Client.request()`](Client.md#clientrequestoptions-callback), [`Client.stream()`](Client.md#clientstreamoptions-factory-callback), and [`Client.upgrade()`](/docs/docs/api/Client.md#clientupgradeoptions-callback)), the `Client` instance will transition from **idle** to [**pending**](/docs/docs/api/Client.md#pending) and then most likely directly to [**processing**](/docs/docs/api/Client.md#processing). + +Calling [`Client.close()`](/docs/docs/api/Client.md#clientclosecallback) or [`Client.destroy()`](Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](/docs/docs/api/Client.md#destroyed) state since the `Client` instance will have no queued requests in this state. + +### pending + +The **pending** state signifies a non-processing `Client`. Upon entering this state, the `Client` establishes a socket connection and emits the [`'connect'`](/docs/docs/api/Client.md#event-connect) event signalling a connection was successfully established with the `origin` provided during `Client` instantiation. The internal queue is initially empty, and requests can start queueing. + +Calling [`Client.close()`](/docs/docs/api/Client.md#clientclosecallback) with queued requests, transitions the `Client` to the [**processing**](/docs/docs/api/Client.md#processing) state. Without queued requests, it transitions to the [**destroyed**](/docs/docs/api/Client.md#destroyed) state. + +Calling [`Client.destroy()`](/docs/docs/api/Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](/docs/docs/api/Client.md#destroyed) state regardless of existing requests. + +### processing + +The **processing** state is a state machine within itself. It initializes to the [**processing.running**](/docs/docs/api/Client.md#running) state. The [`Client.dispatch()`](/docs/docs/api/Client.md#clientdispatchoptions-handlers), [`Client.close()`](Client.md#clientclosecallback), and [`Client.destroy()`](Client.md#clientdestroyerror-callback) can be called at any time while the `Client` is in this state. `Client.dispatch()` will add more requests to the queue while existing requests continue to be processed. `Client.close()` will transition to the [**processing.closing**](/docs/docs/api/Client.md#closing) state. And `Client.destroy()` will transition to [**destroyed**](/docs/docs/api/Client.md#destroyed). + +#### running + +In the **processing.running** sub-state, queued requests are being processed in a FIFO order. If a request body requires draining, the *needDrain* event transitions to the [**processing.busy**](/docs/docs/api/Client.md#busy) sub-state. The *close* event transitions the Client to the [**process.closing**](/docs/docs/api/Client.md#closing) sub-state. If all queued requests are processed and neither [`Client.close()`](/docs/docs/api/Client.md#clientclosecallback) nor [`Client.destroy()`](Client.md#clientdestroyerror-callback) are called, then the [**processing**](/docs/docs/api/Client.md#processing) machine will trigger a *keepalive* event transitioning the `Client` back to the [**pending**](/docs/docs/api/Client.md#pending) state. During this time, the `Client` is waiting for the socket connection to timeout, and once it does, it triggers the *timeout* event and transitions to the [**idle**](/docs/docs/api/Client.md#idle) state. + +#### busy + +This sub-state is only entered when a request body is an instance of [Stream](https://nodejs.org/api/stream.html) and requires draining. The `Client` cannot process additional requests while in this state and must wait until the currently processing request body is completely drained before transitioning back to [**processing.running**](/docs/docs/api/Client.md#running). + +#### closing + +This sub-state is only entered when a `Client` instance has queued requests and the [`Client.close()`](/docs/docs/api/Client.md#clientclosecallback) method is called. In this state, the `Client` instance continues to process requests as usual, with the one exception that no additional requests can be queued. Once all of the queued requests are processed, the `Client` will trigger the *done* event gracefully entering the [**destroyed**](/docs/docs/api/Client.md#destroyed) state without an error. + +### destroyed + +The **destroyed** state is a final state for the `Client` instance. Once in this state, a `Client` is nonfunctional. Calling any other `Client` methods will result in an `ClientDestroyedError`. diff --git a/node_modules/undici/docs/docs/best-practices/client-certificate.md b/node_modules/undici/docs/docs/best-practices/client-certificate.md new file mode 100644 index 000000000..9ead733af --- /dev/null +++ b/node_modules/undici/docs/docs/best-practices/client-certificate.md @@ -0,0 +1,64 @@ +# Client certificate + +Client certificate authentication can be configured with the `Client`, the required options are passed along through the `connect` option. + +The client certificates must be signed by a trusted CA. The Node.js default is to trust the well-known CAs curated by Mozilla. + +Setting the server option `requestCert: true` tells the server to request the client certificate. + +The server option `rejectUnauthorized: false` allows us to handle any invalid certificate errors in client code. The `authorized` property on the socket of the incoming request will show if the client certificate was valid. The `authorizationError` property will give the reason if the certificate was not valid. + +### Client Certificate Authentication + +```js +const { readFileSync } = require('node:fs') +const { join } = require('node:path') +const { createServer } = require('node:https') +const { Client } = require('undici') + +const serverOptions = { + ca: [ + readFileSync(join(__dirname, 'client-ca-crt.pem'), 'utf8') + ], + key: readFileSync(join(__dirname, 'server-key.pem'), 'utf8'), + cert: readFileSync(join(__dirname, 'server-crt.pem'), 'utf8'), + requestCert: true, + rejectUnauthorized: false +} + +const server = createServer(serverOptions, (req, res) => { + // true if client cert is valid + if(req.client.authorized === true) { + console.log('valid') + } else { + console.error(req.client.authorizationError) + } + res.end() +}) + +server.listen(0, function () { + const tls = { + ca: [ + readFileSync(join(__dirname, 'server-ca-crt.pem'), 'utf8') + ], + key: readFileSync(join(__dirname, 'client-key.pem'), 'utf8'), + cert: readFileSync(join(__dirname, 'client-crt.pem'), 'utf8'), + rejectUnauthorized: false, + servername: 'agent1' + } + const client = new Client(`https://localhost:${server.address().port}`, { + connect: tls + }) + + client.request({ + path: '/', + method: 'GET' + }, (err, { body }) => { + body.on('data', (buf) => {}) + body.on('end', () => { + client.close() + server.close() + }) + }) +}) +``` diff --git a/node_modules/undici/docs/docs/best-practices/crawling.md b/node_modules/undici/docs/docs/best-practices/crawling.md new file mode 100644 index 000000000..96d67b2f0 --- /dev/null +++ b/node_modules/undici/docs/docs/best-practices/crawling.md @@ -0,0 +1,58 @@ +# Crawling + +[RFC 9309](https://datatracker.ietf.org/doc/html/rfc9309) defines crawlers as automated clients. + +Some web servers may reject requests that omit the `User-Agent` header or that use common defaults such as `'curl/7.79.1'`. + +In **undici**, the default user agent is `'undici'`. Since undici is integrated into Node.js core as the implementation of `fetch()`, requests made via `fetch()` use `'node'` as the default user agent. + +It is recommended to specify a **custom `User-Agent` header** when implementing crawlers. Providing a descriptive user agent allows servers to correctly identify the client and reduces the likelihood of requests being denied. + +A user agent string should include sufficient detail to identify the crawler and provide contact information. For example: + +``` +AcmeCo Crawler - acme.co - contact@acme.co +``` + +When adding contact details, avoid using personal identifiers such as your own name or a private email address—especially in a professional or employment context. Instead, use a role-based or organizational contact (e.g., crawler-team@company.com) to protect individual privacy while still enabling communication. + +If a crawler behaves unexpectedly—for example, due to misconfiguration or implementation errors—server administrators can use the information in the user agent to contact the operator and coordinate an appropriate resolution. + +The `User-Agent` header can be set on individual requests or applied globally by configuring a custom dispatcher. + +**Example: setting a `User-Agent` per request** + +```js +import { fetch } from 'undici' + +const headers = { + 'User-Agent': 'AcmeCo Crawler - acme.co - contact@acme.co' +} + +const res = await fetch('https://example.com', { headers }) +``` + +## Best Practices for Crawlers + +When developing a crawler, the following practices are recommended in addition to setting a descriptive `User-Agent` header: + +* **Respect `robots.txt`** + Follow the directives defined in the target site’s `robots.txt` file, including disallowed paths and optional crawl-delay settings (see [W3C guidelines](https://www.w3.org/wiki/Write_Web_Crawler)). + +* **Rate limiting** + Regulate request frequency to avoid imposing excessive load on servers. Introduce delays between requests or limit the number of concurrent requests. The W3C suggests at least one second between requests. + +* **Error handling** + Implement retry logic with exponential backoff for transient failures, and stop requests when persistent errors occur (e.g., HTTP 403 or 429). + +* **Monitoring and logging** + Track request volume, response codes, and error rates to detect misbehavior and address issues proactively. + +* **Contact information** + Always include valid and current contact details in the `User-Agent` string so that administrators can reach the crawler operator if necessary. + +## References and Further Reading + +* [RFC 9309: The Robots Exclusion Protocol](https://datatracker.ietf.org/doc/html/rfc9309) +* [W3C Wiki: Write Web Crawler](https://www.w3.org/wiki/Write_Web_Crawler) +* [Ethical Web Crawling (WWW 2010 Conference Paper)](https://archives.iw3c2.org/www2010/proceedings/www/p1101.pdf) diff --git a/node_modules/undici/docs/docs/best-practices/mocking-request.md b/node_modules/undici/docs/docs/best-practices/mocking-request.md new file mode 100644 index 000000000..ce56a09f5 --- /dev/null +++ b/node_modules/undici/docs/docs/best-practices/mocking-request.md @@ -0,0 +1,190 @@ +# Mocking Request + +Undici has its own mocking [utility](/docs/docs/api/MockAgent.md). It allow us to intercept undici HTTP requests and return mocked values instead. It can be useful for testing purposes. + +Example: + +```js +// bank.mjs +import { request } from 'undici' + +export async function bankTransfer(recipient, amount) { + const { body } = await request('http://localhost:3000/bank-transfer', + { + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient, + amount + }) + } + ) + return await body.json() +} +``` + +And this is what the test file looks like: + +```js +// index.test.mjs +import { strict as assert } from 'node:assert' +import { MockAgent, setGlobalDispatcher, } from 'undici' +import { bankTransfer } from './bank.mjs' + +const mockAgent = new MockAgent(); + +setGlobalDispatcher(mockAgent); + +// Provide the base url to the request +const mockPool = mockAgent.get('http://localhost:3000'); + +// intercept the request +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient: '1234567890', + amount: '100' + }) +}).reply(200, { + message: 'transaction processed' +}) + +const success = await bankTransfer('1234567890', '100') + +assert.deepEqual(success, { message: 'transaction processed' }) + +// if you dont want to check whether the body or the headers contain the same value +// just remove it from interceptor +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', +}).reply(400, { + message: 'bank account not found' +}) + +const badRequest = await bankTransfer('1234567890', '100') + +assert.deepEqual(badRequest, { message: 'bank account not found' }) +``` + +Explore other MockAgent functionality [here](/docs/docs/api/MockAgent.md) + +## Access agent call history + +Using a MockAgent also allows you to make assertions on the configuration used to make your request in your application. + +Here is an example : + +```js +// index.test.mjs +import { strict as assert } from 'node:assert' +import { MockAgent, setGlobalDispatcher, fetch } from 'undici' +import { app } from './app.mjs' + +// given an application server running on http://localhost:3000 +await app.start() + +// enable call history at instantiation +const mockAgent = new MockAgent({ enableCallHistory: true }) +// or after instantiation +mockAgent.enableCallHistory() + +setGlobalDispatcher(mockAgent) + +// this call is made (not intercepted) +await fetch(`http://localhost:3000/endpoint?query='hello'`, { + method: 'POST', + headers: { 'content-type': 'application/json' } + body: JSON.stringify({ data: '' }) +}) + +// access to the call history of the MockAgent (which register every call made intercepted or not) +assert.ok(mockAgent.getCallHistory()?.calls().length === 1) +assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.fullUrl, `http://localhost:3000/endpoint?query='hello'`) +assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.body, JSON.stringify({ data: '' })) +assert.deepStrictEqual(mockAgent.getCallHistory()?.firstCall()?.searchParams, { query: 'hello' }) +assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.port, '3000') +assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.host, 'localhost:3000') +assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.method, 'POST') +assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.path, '/endpoint') +assert.deepStrictEqual(mockAgent.getCallHistory()?.firstCall()?.headers, { 'content-type': 'application/json' }) + +// clear all call history logs +mockAgent.clearCallHistory() + +assert.ok(mockAgent.getCallHistory()?.calls().length === 0) +``` + +Calling `mockAgent.close()` will automatically clear and delete every call history for you. + +Explore other MockAgent functionality [here](/docs/docs/api/MockAgent.md) + +Explore other MockCallHistory functionality [here](/docs/docs/api/MockCallHistory.md) + +Explore other MockCallHistoryLog functionality [here](/docs/docs/api/MockCallHistoryLog.md) + +## Debug Mock Value + +When the interceptor and the request options are not the same, undici will automatically make a real HTTP request. To prevent real requests from being made, use `mockAgent.disableNetConnect()`: + +```js +const mockAgent = new MockAgent(); + +setGlobalDispatcher(mockAgent); +mockAgent.disableNetConnect() + +// Provide the base url to the request +const mockPool = mockAgent.get('http://localhost:3000'); + +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', +}).reply(200, { + message: 'transaction processed' +}) + +const badRequest = await bankTransfer('1234567890', '100') +// Will throw an error +// MockNotMatchedError: Mock dispatch not matched for path '/bank-transfer': +// subsequent request to origin http://localhost:3000 was not allowed (net.connect disabled) +``` + +## Reply with data based on request + +If the mocked response needs to be dynamically derived from the request parameters, you can provide a function instead of an object to `reply`: + +```js +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient: '1234567890', + amount: '100' + }) +}).reply(200, (opts) => { + // do something with opts + + return { message: 'transaction processed' } +}) +``` + +in this case opts will be + +``` +{ + method: 'POST', + headers: { 'X-TOKEN-SECRET': 'SuperSecretToken' }, + body: '{"recipient":"1234567890","amount":"100"}', + origin: 'http://localhost:3000', + path: '/bank-transfer' +} +``` diff --git a/node_modules/undici/docs/docs/best-practices/proxy.md b/node_modules/undici/docs/docs/best-practices/proxy.md new file mode 100644 index 000000000..8b1a7210e --- /dev/null +++ b/node_modules/undici/docs/docs/best-practices/proxy.md @@ -0,0 +1,127 @@ +# Connecting through a proxy + +Connecting through a proxy is possible by: + +- Using [ProxyAgent](/docs/docs/api/ProxyAgent.md). +- Configuring `Client` or `Pool` constructor. + +The proxy url should be passed to the `Client` or `Pool` constructor, while the upstream server url +should be added to every request call in the `path`. +For instance, if you need to send a request to the `/hello` route of your upstream server, +the `path` should be `path: 'http://upstream.server:port/hello?foo=bar'`. + +If you proxy requires basic authentication, you can send it via the `proxy-authorization` header. + +### Connect without authentication + +```js +import { Client } from 'undici' +import { createServer } from 'http' +import { createProxy } from 'proxy' + +const server = await buildServer() +const proxyServer = await buildProxy() + +const serverUrl = `http://localhost:${server.address().port}` +const proxyUrl = `http://localhost:${proxyServer.address().port}` + +server.on('request', (req, res) => { + console.log(req.url) // '/hello?foo=bar' + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ hello: 'world' })) +}) + +const client = new Client(proxyUrl) + +const response = await client.request({ + method: 'GET', + path: serverUrl + '/hello?foo=bar' +}) + +response.body.setEncoding('utf8') +let data = '' +for await (const chunk of response.body) { + data += chunk +} +console.log(response.statusCode) // 200 +console.log(JSON.parse(data)) // { hello: 'world' } + +server.close() +proxyServer.close() +client.close() + +function buildServer () { + return new Promise((resolve, reject) => { + const server = createServer() + server.listen(0, () => resolve(server)) + }) +} + +function buildProxy () { + return new Promise((resolve, reject) => { + const server = createProxy(createServer()) + server.listen(0, () => resolve(server)) + }) +} +``` + +### Connect with authentication + +```js +import { Client } from 'undici' +import { createServer } from 'http' +import { createProxy } from 'proxy' + +const server = await buildServer() +const proxyServer = await buildProxy() + +const serverUrl = `http://localhost:${server.address().port}` +const proxyUrl = `http://localhost:${proxyServer.address().port}` + +proxyServer.authenticate = function (req) { + return req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}` +} + +server.on('request', (req, res) => { + console.log(req.url) // '/hello?foo=bar' + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ hello: 'world' })) +}) + +const client = new Client(proxyUrl) + +const response = await client.request({ + method: 'GET', + path: serverUrl + '/hello?foo=bar', + headers: { + 'proxy-authorization': `Basic ${Buffer.from('user:pass').toString('base64')}` + } +}) + +response.body.setEncoding('utf8') +let data = '' +for await (const chunk of response.body) { + data += chunk +} +console.log(response.statusCode) // 200 +console.log(JSON.parse(data)) // { hello: 'world' } + +server.close() +proxyServer.close() +client.close() + +function buildServer () { + return new Promise((resolve, reject) => { + const server = createServer() + server.listen(0, () => resolve(server)) + }) +} + +function buildProxy () { + return new Promise((resolve, reject) => { + const server = createProxy(createServer()) + server.listen(0, () => resolve(server)) + }) +} +``` + diff --git a/node_modules/undici/docs/docs/best-practices/writing-tests.md b/node_modules/undici/docs/docs/best-practices/writing-tests.md new file mode 100644 index 000000000..57549de63 --- /dev/null +++ b/node_modules/undici/docs/docs/best-practices/writing-tests.md @@ -0,0 +1,20 @@ +# Writing tests + +Undici is tuned for a production use case and its default will keep +a socket open for a few seconds after an HTTP request is completed to +remove the overhead of opening up a new socket. These settings that makes +Undici shine in production are not a good fit for using Undici in automated +tests, as it will result in longer execution times. + +The following are good defaults that will keep the socket open for only 10ms: + +```js +import { request, setGlobalDispatcher, Agent } from 'undici' + +const agent = new Agent({ + keepAliveTimeout: 10, // milliseconds + keepAliveMaxTimeout: 10 // milliseconds +}) + +setGlobalDispatcher(agent) +``` diff --git a/node_modules/undici/index-fetch.js b/node_modules/undici/index-fetch.js new file mode 100644 index 000000000..8f5bb6cea --- /dev/null +++ b/node_modules/undici/index-fetch.js @@ -0,0 +1,35 @@ +'use strict' + +const { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global') +const EnvHttpProxyAgent = require('./lib/dispatcher/env-http-proxy-agent') +const fetchImpl = require('./lib/web/fetch').fetch + +module.exports.fetch = function fetch (init, options = undefined) { + return fetchImpl(init, options).catch(err => { + if (err && typeof err === 'object') { + Error.captureStackTrace(err) + } + throw err + }) +} +module.exports.FormData = require('./lib/web/fetch/formdata').FormData +module.exports.Headers = require('./lib/web/fetch/headers').Headers +module.exports.Response = require('./lib/web/fetch/response').Response +module.exports.Request = require('./lib/web/fetch/request').Request + +const { CloseEvent, ErrorEvent, MessageEvent, createFastMessageEvent } = require('./lib/web/websocket/events') +module.exports.WebSocket = require('./lib/web/websocket/websocket').WebSocket +module.exports.CloseEvent = CloseEvent +module.exports.ErrorEvent = ErrorEvent +module.exports.MessageEvent = MessageEvent +module.exports.createFastMessageEvent = createFastMessageEvent + +module.exports.EventSource = require('./lib/web/eventsource/eventsource').EventSource + +const api = require('./lib/api') +const Dispatcher = require('./lib/dispatcher/dispatcher') +Object.assign(Dispatcher.prototype, api) +// Expose the fetch implementation to be enabled in Node.js core via a flag +module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent +module.exports.getGlobalDispatcher = getGlobalDispatcher +module.exports.setGlobalDispatcher = setGlobalDispatcher diff --git a/node_modules/undici/index.d.ts b/node_modules/undici/index.d.ts new file mode 100644 index 000000000..0883fc7cc --- /dev/null +++ b/node_modules/undici/index.d.ts @@ -0,0 +1,3 @@ +import Undici from './types/index' +export default Undici +export * from './types/index' diff --git a/node_modules/undici/index.js b/node_modules/undici/index.js new file mode 100644 index 000000000..14f439a23 --- /dev/null +++ b/node_modules/undici/index.js @@ -0,0 +1,202 @@ +'use strict' + +const Client = require('./lib/dispatcher/client') +const Dispatcher = require('./lib/dispatcher/dispatcher') +const Pool = require('./lib/dispatcher/pool') +const BalancedPool = require('./lib/dispatcher/balanced-pool') +const RoundRobinPool = require('./lib/dispatcher/round-robin-pool') +const Agent = require('./lib/dispatcher/agent') +const ProxyAgent = require('./lib/dispatcher/proxy-agent') +const EnvHttpProxyAgent = require('./lib/dispatcher/env-http-proxy-agent') +const RetryAgent = require('./lib/dispatcher/retry-agent') +const H2CClient = require('./lib/dispatcher/h2c-client') +const errors = require('./lib/core/errors') +const util = require('./lib/core/util') +const { InvalidArgumentError } = errors +const api = require('./lib/api') +const buildConnector = require('./lib/core/connect') +const MockClient = require('./lib/mock/mock-client') +const { MockCallHistory, MockCallHistoryLog } = require('./lib/mock/mock-call-history') +const MockAgent = require('./lib/mock/mock-agent') +const MockPool = require('./lib/mock/mock-pool') +const SnapshotAgent = require('./lib/mock/snapshot-agent') +const mockErrors = require('./lib/mock/mock-errors') +const RetryHandler = require('./lib/handler/retry-handler') +const { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global') +const DecoratorHandler = require('./lib/handler/decorator-handler') +const RedirectHandler = require('./lib/handler/redirect-handler') + +Object.assign(Dispatcher.prototype, api) + +module.exports.Dispatcher = Dispatcher +module.exports.Client = Client +module.exports.Pool = Pool +module.exports.BalancedPool = BalancedPool +module.exports.RoundRobinPool = RoundRobinPool +module.exports.Agent = Agent +module.exports.ProxyAgent = ProxyAgent +module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent +module.exports.RetryAgent = RetryAgent +module.exports.H2CClient = H2CClient +module.exports.RetryHandler = RetryHandler + +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.interceptors = { + redirect: require('./lib/interceptor/redirect'), + responseError: require('./lib/interceptor/response-error'), + retry: require('./lib/interceptor/retry'), + dump: require('./lib/interceptor/dump'), + dns: require('./lib/interceptor/dns'), + cache: require('./lib/interceptor/cache'), + decompress: require('./lib/interceptor/decompress'), + deduplicate: require('./lib/interceptor/deduplicate') +} + +module.exports.cacheStores = { + MemoryCacheStore: require('./lib/cache/memory-cache-store') +} + +const SqliteCacheStore = require('./lib/cache/sqlite-cache-store') +module.exports.cacheStores.SqliteCacheStore = SqliteCacheStore + +module.exports.buildConnector = buildConnector +module.exports.errors = errors +module.exports.util = { + parseHeaders: util.parseHeaders, + headerNameToString: util.headerNameToString +} + +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null + } + + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') + } + + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } + + let path = opts.path + if (!opts.path.startsWith('/')) { + path = `/${path}` + } + + url = new URL(util.parseOrigin(url).origin + path) + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {} + } + + url = util.parseURL(url) + } + + const { agent, dispatcher = getGlobalDispatcher() } = opts + + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') + } + + return fn.call(dispatcher, { + ...opts, + origin: url.origin, + path: url.search ? `${url.pathname}${url.search}` : url.pathname, + method: opts.method || (opts.body ? 'PUT' : 'GET') + }, handler) + } +} + +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher + +const fetchImpl = require('./lib/web/fetch').fetch + +module.exports.fetch = function fetch (init, options = undefined) { + return fetchImpl(init, options).catch(err => { + if (err && typeof err === 'object') { + Error.captureStackTrace(err) + } + throw err + }) +} +module.exports.Headers = require('./lib/web/fetch/headers').Headers +module.exports.Response = require('./lib/web/fetch/response').Response +module.exports.Request = require('./lib/web/fetch/request').Request +module.exports.FormData = require('./lib/web/fetch/formdata').FormData + +const { setGlobalOrigin, getGlobalOrigin } = require('./lib/web/fetch/global') + +module.exports.setGlobalOrigin = setGlobalOrigin +module.exports.getGlobalOrigin = getGlobalOrigin + +const { CacheStorage } = require('./lib/web/cache/cachestorage') +const { kConstruct } = require('./lib/core/symbols') + +module.exports.caches = new CacheStorage(kConstruct) + +const { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie } = require('./lib/web/cookies') + +module.exports.deleteCookie = deleteCookie +module.exports.getCookies = getCookies +module.exports.getSetCookies = getSetCookies +module.exports.setCookie = setCookie +module.exports.parseCookie = parseCookie + +const { parseMIMEType, serializeAMimeType } = require('./lib/web/fetch/data-url') + +module.exports.parseMIMEType = parseMIMEType +module.exports.serializeAMimeType = serializeAMimeType + +const { CloseEvent, ErrorEvent, MessageEvent } = require('./lib/web/websocket/events') +const { WebSocket, ping } = require('./lib/web/websocket/websocket') +module.exports.WebSocket = WebSocket +module.exports.CloseEvent = CloseEvent +module.exports.ErrorEvent = ErrorEvent +module.exports.MessageEvent = MessageEvent +module.exports.ping = ping + +module.exports.WebSocketStream = require('./lib/web/websocket/stream/websocketstream').WebSocketStream +module.exports.WebSocketError = require('./lib/web/websocket/stream/websocketerror').WebSocketError + +module.exports.request = makeDispatcher(api.request) +module.exports.stream = makeDispatcher(api.stream) +module.exports.pipeline = makeDispatcher(api.pipeline) +module.exports.connect = makeDispatcher(api.connect) +module.exports.upgrade = makeDispatcher(api.upgrade) + +module.exports.MockClient = MockClient +module.exports.MockCallHistory = MockCallHistory +module.exports.MockCallHistoryLog = MockCallHistoryLog +module.exports.MockPool = MockPool +module.exports.MockAgent = MockAgent +module.exports.SnapshotAgent = SnapshotAgent +module.exports.mockErrors = mockErrors + +const { EventSource } = require('./lib/web/eventsource/eventsource') + +module.exports.EventSource = EventSource + +function install () { + globalThis.fetch = module.exports.fetch + globalThis.Headers = module.exports.Headers + globalThis.Response = module.exports.Response + globalThis.Request = module.exports.Request + globalThis.FormData = module.exports.FormData + globalThis.WebSocket = module.exports.WebSocket + globalThis.CloseEvent = module.exports.CloseEvent + globalThis.ErrorEvent = module.exports.ErrorEvent + globalThis.MessageEvent = module.exports.MessageEvent + globalThis.EventSource = module.exports.EventSource +} + +module.exports.install = install diff --git a/node_modules/undici/lib/api/abort-signal.js b/node_modules/undici/lib/api/abort-signal.js new file mode 100644 index 000000000..608170b43 --- /dev/null +++ b/node_modules/undici/lib/api/abort-signal.js @@ -0,0 +1,59 @@ +'use strict' + +const { addAbortListener } = require('../core/util') +const { RequestAbortedError } = require('../core/errors') + +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') + +function abort (self) { + if (self.abort) { + self.abort(self[kSignal]?.reason) + } else { + self.reason = self[kSignal]?.reason ?? new RequestAbortedError() + } + removeSignal(self) +} + +function addSignal (self, signal) { + self.reason = null + + self[kSignal] = null + self[kListener] = null + + if (!signal) { + return + } + + if (signal.aborted) { + abort(self) + return + } + + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } + + addAbortListener(self[kSignal], self[kListener]) +} + +function removeSignal (self) { + if (!self[kSignal]) { + return + } + + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) + } + + self[kSignal] = null + self[kListener] = null +} + +module.exports = { + addSignal, + removeSignal +} diff --git a/node_modules/undici/lib/api/api-connect.js b/node_modules/undici/lib/api/api-connect.js new file mode 100644 index 000000000..c8b86dd7d --- /dev/null +++ b/node_modules/undici/lib/api/api-connect.js @@ -0,0 +1,110 @@ +'use strict' + +const assert = require('node:assert') +const { AsyncResource } = require('node:async_hooks') +const { InvalidArgumentError, SocketError } = require('../core/errors') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') + +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_CONNECT') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason) + return + } + + assert(this.callback) + + this.abort = abort + this.context = context + } + + onHeaders () { + throw new SocketError('bad connect', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this + + removeSignal(this) + + this.callback = null + + let headers = rawHeaders + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + } + + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const connectHandler = new ConnectHandler(opts, callback) + const connectOptions = { ...opts, method: 'CONNECT' } + + this.dispatch(connectOptions, connectHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = connect diff --git a/node_modules/undici/lib/api/api-pipeline.js b/node_modules/undici/lib/api/api-pipeline.js new file mode 100644 index 000000000..77f3520a8 --- /dev/null +++ b/node_modules/undici/lib/api/api-pipeline.js @@ -0,0 +1,252 @@ +'use strict' + +const { + Readable, + Duplex, + PassThrough +} = require('node:stream') +const assert = require('node:assert') +const { AsyncResource } = require('node:async_hooks') +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = require('../core/errors') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') + +function noop () {} + +const kResume = Symbol('resume') + +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) + + this[kResume] = null + } + + _read () { + const { [kResume]: resume } = this + + if (resume) { + this[kResume] = null + resume() + } + } + + _destroy (err, callback) { + this._read() + + callback(err) + } +} + +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } + + _read () { + this[kResume]() + } + + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + callback(err) + } +} + +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } + + const { signal, method, opaque, onInfo, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_PIPELINE') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null + + this.req = new PipelineRequest().on('error', noop) + + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this + + if (body?.resume) { + body.resume() + } + }, + write: (chunk, encoding, callback) => { + const { req } = this + + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() + } else { + req[kResume] = callback + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this + + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (abort && err) { + abort() + } + + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) + + removeSignal(this) + + callback(err) + } + }).on('prefinish', () => { + const { req } = this + + // Node < 15 does not call _final in same tick. + req.push(null) + }) + + this.res = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + const { res } = this + + if (this.reason) { + abort(this.reason) + return + } + + assert(!res, 'pipeline cannot be retried') + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this + + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } + + this.res = new PipelineResponse(resume) + + let body + try { + this.handler = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + body = this.runInAsyncScope(handler, null, { + statusCode, + headers, + opaque, + body: this.res, + context + }) + } catch (err) { + this.res.on('error', noop) + throw err + } + + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } + + body + .on('data', (chunk) => { + const { ret, body } = this + + if (!ret.push(chunk) && body.pause) { + body.pause() + } + }) + .on('error', (err) => { + const { ret } = this + + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this + + ret.push(null) + }) + .on('close', () => { + const { ret } = this + + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) + + this.body = body + } + + onData (chunk) { + const { res } = this + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this + res.push(null) + } + + onError (err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) + } +} + +function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler) + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) + } +} + +module.exports = pipeline diff --git a/node_modules/undici/lib/api/api-request.js b/node_modules/undici/lib/api/api-request.js new file mode 100644 index 000000000..c3461b23c --- /dev/null +++ b/node_modules/undici/lib/api/api-request.js @@ -0,0 +1,213 @@ +'use strict' + +const assert = require('node:assert') +const { AsyncResource } = require('node:async_hooks') +const { Readable } = require('./readable') +const { InvalidArgumentError, RequestAbortedError } = require('../core/errors') +const util = require('../core/util') + +function noop () {} + +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', noop), err) + } + throw err + } + + this.method = method + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.res = null + this.abort = null + this.body = body + this.trailers = {} + this.context = null + this.onInfo = onInfo || null + this.highWaterMark = highWaterMark + this.reason = null + this.removeAbortListener = null + + if (signal?.aborted) { + this.reason = signal.reason ?? new RequestAbortedError() + } else if (signal) { + this.removeAbortListener = util.addAbortListener(signal, () => { + this.reason = signal.reason ?? new RequestAbortedError() + if (this.res) { + util.destroy(this.res.on('error', noop), this.reason) + } else if (this.abort) { + this.abort(this.reason) + } + }) + } + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason) + return + } + + assert(this.callback) + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + const contentLength = parsedHeaders['content-length'] + const res = new Readable({ + resume, + abort, + contentType, + contentLength: this.method !== 'HEAD' && contentLength + ? Number(contentLength) + : null, + highWaterMark + }) + + if (this.removeAbortListener) { + res.on('close', this.removeAbortListener) + this.removeAbortListener = null + } + + this.callback = null + this.res = res + if (callback !== null) { + try { + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + trailers: this.trailers, + opaque, + body: res, + context + }) + } catch (err) { + // If the callback throws synchronously, we need to handle it + // Remove reference to res to allow res being garbage collected + this.res = null + + // Destroy the response stream + util.destroy(res.on('error', noop), err) + + // Use queueMicrotask to re-throw the error so it reaches uncaughtException + queueMicrotask(() => { + throw err + }) + } + } + } + + onData (chunk) { + return this.res.push(chunk) + } + + onComplete (trailers) { + util.parseHeaders(trailers, this.trailers) + this.res.push(null) + } + + onError (err) { + const { res, callback, body, opaque } = this + + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res.on('error', noop), err) + }) + } + + if (body) { + this.body = null + + if (util.isStream(body)) { + body.on('error', noop) + util.destroy(body, err) + } + } + + if (this.removeAbortListener) { + this.removeAbortListener() + this.removeAbortListener = null + } + } +} + +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const handler = new RequestHandler(opts, callback) + + this.dispatch(opts, handler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = request +module.exports.RequestHandler = RequestHandler diff --git a/node_modules/undici/lib/api/api-stream.js b/node_modules/undici/lib/api/api-stream.js new file mode 100644 index 000000000..5d0b3fbe6 --- /dev/null +++ b/node_modules/undici/lib/api/api-stream.js @@ -0,0 +1,209 @@ +'use strict' + +const assert = require('node:assert') +const { finished } = require('node:stream') +const { AsyncResource } = require('node:async_hooks') +const { InvalidArgumentError, InvalidReturnValueError } = require('../core/errors') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') + +function noop () {} + +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_STREAM') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', noop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.factory = factory + this.callback = callback + this.res = null + this.abort = null + this.context = null + this.trailers = null + this.body = body + this.onInfo = onInfo || null + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason) + return + } + + assert(this.callback) + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, responseHeaders } = this + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + this.factory = null + + if (factory === null) { + return + } + + const res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }) + + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } + + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this + + this.res = null + if (err || !res?.readable) { + util.destroy(res, err) + } + + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + + if (err) { + abort() + } + }) + + res.on('drain', resume) + + this.res = res + + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState?.needDrain + + return needDrain !== true + } + + onData (chunk) { + const { res } = this + + return res ? res.write(chunk) : true + } + + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + if (!res) { + return + } + + this.trailers = util.parseHeaders(trailers) + + res.end() + } + + onError (err) { + const { res, callback, opaque, body } = this + + removeSignal(this) + + this.factory = null + + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const handler = new StreamHandler(opts, factory, callback) + + this.dispatch(opts, handler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = stream diff --git a/node_modules/undici/lib/api/api-upgrade.js b/node_modules/undici/lib/api/api-upgrade.js new file mode 100644 index 000000000..2b03f2075 --- /dev/null +++ b/node_modules/undici/lib/api/api-upgrade.js @@ -0,0 +1,111 @@ +'use strict' + +const { InvalidArgumentError, SocketError } = require('../core/errors') +const { AsyncResource } = require('node:async_hooks') +const assert = require('node:assert') +const util = require('../core/util') +const { kHTTP2Stream } = require('../core/symbols') +const { addSignal, removeSignal } = require('./abort-signal') + +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_UPGRADE') + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason) + return + } + + assert(this.callback) + + this.abort = abort + this.context = null + } + + onHeaders () { + throw new SocketError('bad upgrade', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + assert(socket[kHTTP2Stream] === true ? statusCode === 200 : statusCode === 101) + + const { callback, opaque, context } = this + + removeSignal(this) + + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const upgradeHandler = new UpgradeHandler(opts, callback) + const upgradeOpts = { + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + } + + this.dispatch(upgradeOpts, upgradeHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = upgrade diff --git a/node_modules/undici/lib/api/index.js b/node_modules/undici/lib/api/index.js new file mode 100644 index 000000000..8983a5e74 --- /dev/null +++ b/node_modules/undici/lib/api/index.js @@ -0,0 +1,7 @@ +'use strict' + +module.exports.request = require('./api-request') +module.exports.stream = require('./api-stream') +module.exports.pipeline = require('./api-pipeline') +module.exports.upgrade = require('./api-upgrade') +module.exports.connect = require('./api-connect') diff --git a/node_modules/undici/lib/api/readable.js b/node_modules/undici/lib/api/readable.js new file mode 100644 index 000000000..cdede9599 --- /dev/null +++ b/node_modules/undici/lib/api/readable.js @@ -0,0 +1,580 @@ +'use strict' + +const assert = require('node:assert') +const { Readable } = require('node:stream') +const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require('../core/errors') +const util = require('../core/util') +const { ReadableStreamFrom } = require('../core/util') + +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('kAbort') +const kContentType = Symbol('kContentType') +const kContentLength = Symbol('kContentLength') +const kUsed = Symbol('kUsed') +const kBytesRead = Symbol('kBytesRead') + +const noop = () => {} + +/** + * @class + * @extends {Readable} + * @see https://fetch.spec.whatwg.org/#body + */ +class BodyReadable extends Readable { + /** + * @param {object} opts + * @param {(this: Readable, size: number) => void} opts.resume + * @param {() => (void | null)} opts.abort + * @param {string} [opts.contentType = ''] + * @param {number} [opts.contentLength] + * @param {number} [opts.highWaterMark = 64 * 1024] + */ + constructor ({ + resume, + abort, + contentType = '', + contentLength, + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) + + this._readableState.dataEmitted = false + + this[kAbort] = abort + + /** @type {Consume | null} */ + this[kConsume] = null + + /** @type {number} */ + this[kBytesRead] = 0 + + /** @type {ReadableStream|null} */ + this[kBody] = null + + /** @type {boolean} */ + this[kUsed] = false + + /** @type {string} */ + this[kContentType] = contentType + + /** @type {number|null} */ + this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null + + /** + * Is stream being consumed through Readable API? + * This is an optimization so that we avoid checking + * for 'data' and 'readable' listeners in the hot path + * inside push(). + * + * @type {boolean} + */ + this[kReading] = false + } + + /** + * @param {Error|null} err + * @param {(error:(Error|null)) => void} callback + * @returns {void} + */ + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (err) { + this[kAbort]() + } + + // Workaround for Node "bug". If the stream is destroyed in same + // tick as it is created, then a user who is waiting for a + // promise (i.e micro tick) for installing an 'error' listener will + // never get a chance and will always encounter an unhandled exception. + if (!this[kUsed]) { + setImmediate(callback, err) + } else { + callback(err) + } + } + + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + on (event, listener) { + if (event === 'data' || event === 'readable') { + this[kReading] = true + this[kUsed] = true + } + return super.on(event, listener) + } + + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + addListener (event, listener) { + return this.on(event, listener) + } + + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + off (event, listener) { + const ret = super.off(event, listener) + if (event === 'data' || event === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ) + } + return ret + } + + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + removeListener (event, listener) { + return this.off(event, listener) + } + + /** + * @param {Buffer|null} chunk + * @returns {boolean} + */ + push (chunk) { + if (chunk) { + this[kBytesRead] += chunk.length + if (this[kConsume]) { + consumePush(this[kConsume], chunk) + return this[kReading] ? super.push(chunk) : true + } + } + + return super.push(chunk) + } + + /** + * Consumes and returns the body as a string. + * + * @see https://fetch.spec.whatwg.org/#dom-body-text + * @returns {Promise} + */ + text () { + return consume(this, 'text') + } + + /** + * Consumes and returns the body as a JavaScript Object. + * + * @see https://fetch.spec.whatwg.org/#dom-body-json + * @returns {Promise} + */ + json () { + return consume(this, 'json') + } + + /** + * Consumes and returns the body as a Blob + * + * @see https://fetch.spec.whatwg.org/#dom-body-blob + * @returns {Promise} + */ + blob () { + return consume(this, 'blob') + } + + /** + * Consumes and returns the body as an Uint8Array. + * + * @see https://fetch.spec.whatwg.org/#dom-body-bytes + * @returns {Promise} + */ + bytes () { + return consume(this, 'bytes') + } + + /** + * Consumes and returns the body as an ArrayBuffer. + * + * @see https://fetch.spec.whatwg.org/#dom-body-arraybuffer + * @returns {Promise} + */ + arrayBuffer () { + return consume(this, 'arrayBuffer') + } + + /** + * Not implemented + * + * @see https://fetch.spec.whatwg.org/#dom-body-formdata + * @throws {NotSupportedError} + */ + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } + + /** + * Returns true if the body is not null and the body has been consumed. + * Otherwise, returns false. + * + * @see https://fetch.spec.whatwg.org/#dom-body-bodyused + * @readonly + * @returns {boolean} + */ + get bodyUsed () { + return util.isDisturbed(this) + } + + /** + * @see https://fetch.spec.whatwg.org/#dom-body-body + * @readonly + * @returns {ReadableStream} + */ + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStreamFrom(this) + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader() // Ensure stream is locked. + assert(this[kBody].locked) + } + } + return this[kBody] + } + + /** + * Dumps the response body by reading `limit` number of bytes. + * @param {object} opts + * @param {number} [opts.limit = 131072] Number of bytes to read. + * @param {AbortSignal} [opts.signal] An AbortSignal to cancel the dump. + * @returns {Promise} + */ + dump (opts) { + const signal = opts?.signal + + if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) { + return Promise.reject(new InvalidArgumentError('signal must be an AbortSignal')) + } + + const limit = opts?.limit && Number.isFinite(opts.limit) + ? opts.limit + : 128 * 1024 + + if (signal?.aborted) { + return Promise.reject(signal.reason ?? new AbortError()) + } + + if (this._readableState.closeEmitted) { + return Promise.resolve(null) + } + + return new Promise((resolve, reject) => { + if ( + (this[kContentLength] && (this[kContentLength] > limit)) || + this[kBytesRead] > limit + ) { + this.destroy(new AbortError()) + } + + if (signal) { + const onAbort = () => { + this.destroy(signal.reason ?? new AbortError()) + } + signal.addEventListener('abort', onAbort) + this + .on('close', function () { + signal.removeEventListener('abort', onAbort) + if (signal.aborted) { + reject(signal.reason ?? new AbortError()) + } else { + resolve(null) + } + }) + } else { + this.on('close', resolve) + } + + this + .on('error', noop) + .on('data', () => { + if (this[kBytesRead] > limit) { + this.destroy() + } + }) + .resume() + }) + } + + /** + * @param {BufferEncoding} encoding + * @returns {this} + */ + setEncoding (encoding) { + if (Buffer.isEncoding(encoding)) { + this._readableState.encoding = encoding + } + return this + } +} + +/** + * @see https://streams.spec.whatwg.org/#readablestream-locked + * @param {BodyReadable} bodyReadable + * @returns {boolean} + */ +function isLocked (bodyReadable) { + // Consume is an implicit lock. + return bodyReadable[kBody]?.locked === true || bodyReadable[kConsume] !== null +} + +/** + * @see https://fetch.spec.whatwg.org/#body-unusable + * @param {BodyReadable} bodyReadable + * @returns {boolean} + */ +function isUnusable (bodyReadable) { + return util.isDisturbed(bodyReadable) || isLocked(bodyReadable) +} + +/** + * @typedef {'text' | 'json' | 'blob' | 'bytes' | 'arrayBuffer'} ConsumeType + */ + +/** + * @template {ConsumeType} T + * @typedef {T extends 'text' ? string : + * T extends 'json' ? unknown : + * T extends 'blob' ? Blob : + * T extends 'arrayBuffer' ? ArrayBuffer : + * T extends 'bytes' ? Uint8Array : + * never + * } ConsumeReturnType + */ +/** + * @typedef {object} Consume + * @property {ConsumeType} type + * @property {BodyReadable} stream + * @property {((value?: any) => void)} resolve + * @property {((err: Error) => void)} reject + * @property {number} length + * @property {Buffer[]} body + */ + +/** + * @template {ConsumeType} T + * @param {BodyReadable} stream + * @param {T} type + * @returns {Promise>} + */ +function consume (stream, type) { + assert(!stream[kConsume]) + + return new Promise((resolve, reject) => { + if (isUnusable(stream)) { + const rState = stream._readableState + if (rState.destroyed && rState.closeEmitted === false) { + stream + .on('error', reject) + .on('close', () => { + reject(new TypeError('unusable')) + }) + } else { + reject(rState.errored ?? new TypeError('unusable')) + } + } else { + queueMicrotask(() => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + } + + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) + } + }) + + consumeStart(stream[kConsume]) + }) + } + }) +} + +/** + * @param {Consume} consume + * @returns {void} + */ +function consumeStart (consume) { + if (consume.body === null) { + return + } + + const { _readableState: state } = consume.stream + + if (state.bufferIndex) { + const start = state.bufferIndex + const end = state.buffer.length + for (let n = start; n < end; n++) { + consumePush(consume, state.buffer[n]) + } + } else { + for (const chunk of state.buffer) { + consumePush(consume, chunk) + } + } + + if (state.endEmitted) { + consumeEnd(this[kConsume], this._readableState.encoding) + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume], this._readableState.encoding) + }) + } + + consume.stream.resume() + + while (consume.stream.read() != null) { + // Loop + } +} + +/** + * @param {Buffer[]} chunks + * @param {number} length + * @param {BufferEncoding} [encoding='utf8'] + * @returns {string} + */ +function chunksDecode (chunks, length, encoding) { + if (chunks.length === 0 || length === 0) { + return '' + } + const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length) + const bufferLength = buffer.length + + // Skip BOM. + const start = + bufferLength > 2 && + buffer[0] === 0xef && + buffer[1] === 0xbb && + buffer[2] === 0xbf + ? 3 + : 0 + if (!encoding || encoding === 'utf8' || encoding === 'utf-8') { + return buffer.utf8Slice(start, bufferLength) + } else { + return buffer.subarray(start, bufferLength).toString(encoding) + } +} + +/** + * @param {Buffer[]} chunks + * @param {number} length + * @returns {Uint8Array} + */ +function chunksConcat (chunks, length) { + if (chunks.length === 0 || length === 0) { + return new Uint8Array(0) + } + if (chunks.length === 1) { + // fast-path + return new Uint8Array(chunks[0]) + } + const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer) + + let offset = 0 + for (let i = 0; i < chunks.length; ++i) { + const chunk = chunks[i] + buffer.set(chunk, offset) + offset += chunk.length + } + + return buffer +} + +/** + * @param {Consume} consume + * @param {BufferEncoding} encoding + * @returns {void} + */ +function consumeEnd (consume, encoding) { + const { type, body, resolve, stream, length } = consume + + try { + if (type === 'text') { + resolve(chunksDecode(body, length, encoding)) + } else if (type === 'json') { + resolve(JSON.parse(chunksDecode(body, length, encoding))) + } else if (type === 'arrayBuffer') { + resolve(chunksConcat(body, length).buffer) + } else if (type === 'blob') { + resolve(new Blob(body, { type: stream[kContentType] })) + } else if (type === 'bytes') { + resolve(chunksConcat(body, length)) + } + + consumeFinish(consume) + } catch (err) { + stream.destroy(err) + } +} + +/** + * @param {Consume} consume + * @param {Buffer} chunk + * @returns {void} + */ +function consumePush (consume, chunk) { + consume.length += chunk.length + consume.body.push(chunk) +} + +/** + * @param {Consume} consume + * @param {Error} [err] + * @returns {void} + */ +function consumeFinish (consume, err) { + if (consume.body === null) { + return + } + + if (err) { + consume.reject(err) + } else { + consume.resolve() + } + + // Reset the consume object to allow for garbage collection. + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null +} + +module.exports = { + Readable: BodyReadable, + chunksDecode +} diff --git a/node_modules/undici/lib/cache/memory-cache-store.js b/node_modules/undici/lib/cache/memory-cache-store.js new file mode 100644 index 000000000..dba29ae4d --- /dev/null +++ b/node_modules/undici/lib/cache/memory-cache-store.js @@ -0,0 +1,234 @@ +'use strict' + +const { Writable } = require('node:stream') +const { EventEmitter } = require('node:events') +const { assertCacheKey, assertCacheValue } = require('../util/cache.js') + +/** + * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheKey} CacheKey + * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheValue} CacheValue + * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore + * @typedef {import('../../types/cache-interceptor.d.ts').default.GetResult} GetResult + */ + +/** + * @implements {CacheStore} + * @extends {EventEmitter} + */ +class MemoryCacheStore extends EventEmitter { + #maxCount = 1024 + #maxSize = 104857600 // 100MB + #maxEntrySize = 5242880 // 5MB + + #size = 0 + #count = 0 + #entries = new Map() + #hasEmittedMaxSizeEvent = false + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.MemoryCacheStoreOpts | undefined} [opts] + */ + constructor (opts) { + super() + if (opts) { + if (typeof opts !== 'object') { + throw new TypeError('MemoryCacheStore options must be an object') + } + + if (opts.maxCount !== undefined) { + if ( + typeof opts.maxCount !== 'number' || + !Number.isInteger(opts.maxCount) || + opts.maxCount < 0 + ) { + throw new TypeError('MemoryCacheStore options.maxCount must be a non-negative integer') + } + this.#maxCount = opts.maxCount + } + + if (opts.maxSize !== undefined) { + if ( + typeof opts.maxSize !== 'number' || + !Number.isInteger(opts.maxSize) || + opts.maxSize < 0 + ) { + throw new TypeError('MemoryCacheStore options.maxSize must be a non-negative integer') + } + this.#maxSize = opts.maxSize + } + + if (opts.maxEntrySize !== undefined) { + if ( + typeof opts.maxEntrySize !== 'number' || + !Number.isInteger(opts.maxEntrySize) || + opts.maxEntrySize < 0 + ) { + throw new TypeError('MemoryCacheStore options.maxEntrySize must be a non-negative integer') + } + this.#maxEntrySize = opts.maxEntrySize + } + } + } + + /** + * Get the current size of the cache in bytes + * @returns {number} The current size of the cache in bytes + */ + get size () { + return this.#size + } + + /** + * Check if the cache is full (either max size or max count reached) + * @returns {boolean} True if the cache is full, false otherwise + */ + isFull () { + return this.#size >= this.#maxSize || this.#count >= this.#maxCount + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} req + * @returns {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined} + */ + get (key) { + assertCacheKey(key) + + const topLevelKey = `${key.origin}:${key.path}` + + const now = Date.now() + const entries = this.#entries.get(topLevelKey) + + const entry = entries ? findEntry(key, entries, now) : null + + return entry == null + ? undefined + : { + statusMessage: entry.statusMessage, + statusCode: entry.statusCode, + headers: entry.headers, + body: entry.body, + vary: entry.vary ? entry.vary : undefined, + etag: entry.etag, + cacheControlDirectives: entry.cacheControlDirectives, + cachedAt: entry.cachedAt, + staleAt: entry.staleAt, + deleteAt: entry.deleteAt + } + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} val + * @returns {Writable | undefined} + */ + createWriteStream (key, val) { + assertCacheKey(key) + assertCacheValue(val) + + const topLevelKey = `${key.origin}:${key.path}` + + const store = this + const entry = { ...key, ...val, body: [], size: 0 } + + return new Writable({ + write (chunk, encoding, callback) { + if (typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding) + } + + entry.size += chunk.byteLength + + if (entry.size >= store.#maxEntrySize) { + this.destroy() + } else { + entry.body.push(chunk) + } + + callback(null) + }, + final (callback) { + let entries = store.#entries.get(topLevelKey) + if (!entries) { + entries = [] + store.#entries.set(topLevelKey, entries) + } + const previousEntry = findEntry(key, entries, Date.now()) + if (previousEntry) { + const index = entries.indexOf(previousEntry) + entries.splice(index, 1, entry) + store.#size -= previousEntry.size + } else { + entries.push(entry) + store.#count += 1 + } + + store.#size += entry.size + + // Check if cache is full and emit event if needed + if (store.#size > store.#maxSize || store.#count > store.#maxCount) { + // Emit maxSizeExceeded event if we haven't already + if (!store.#hasEmittedMaxSizeEvent) { + store.emit('maxSizeExceeded', { + size: store.#size, + maxSize: store.#maxSize, + count: store.#count, + maxCount: store.#maxCount + }) + store.#hasEmittedMaxSizeEvent = true + } + + // Perform eviction + for (const [key, entries] of store.#entries) { + for (const entry of entries.splice(0, entries.length / 2)) { + store.#size -= entry.size + store.#count -= 1 + } + if (entries.length === 0) { + store.#entries.delete(key) + } + } + + // Reset the event flag after eviction + if (store.#size < store.#maxSize && store.#count < store.#maxCount) { + store.#hasEmittedMaxSizeEvent = false + } + } + + callback(null) + } + }) + } + + /** + * @param {CacheKey} key + */ + delete (key) { + if (typeof key !== 'object') { + throw new TypeError(`expected key to be object, got ${typeof key}`) + } + + const topLevelKey = `${key.origin}:${key.path}` + + for (const entry of this.#entries.get(topLevelKey) ?? []) { + this.#size -= entry.size + this.#count -= 1 + } + this.#entries.delete(topLevelKey) + } +} + +function findEntry (key, entries, now) { + return entries.find((entry) => ( + entry.deleteAt > now && + entry.method === key.method && + (entry.vary == null || Object.keys(entry.vary).every(headerName => { + if (entry.vary[headerName] === null) { + return key.headers[headerName] === undefined + } + + return entry.vary[headerName] === key.headers[headerName] + })) + )) +} + +module.exports = MemoryCacheStore diff --git a/node_modules/undici/lib/cache/sqlite-cache-store.js b/node_modules/undici/lib/cache/sqlite-cache-store.js new file mode 100644 index 000000000..7cb4aa7e2 --- /dev/null +++ b/node_modules/undici/lib/cache/sqlite-cache-store.js @@ -0,0 +1,461 @@ +'use strict' + +const { Writable } = require('node:stream') +const { assertCacheKey, assertCacheValue } = require('../util/cache.js') + +let DatabaseSync + +const VERSION = 3 + +// 2gb +const MAX_ENTRY_SIZE = 2 * 1000 * 1000 * 1000 + +/** + * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore + * @implements {CacheStore} + * + * @typedef {{ + * id: Readonly, + * body?: Uint8Array + * statusCode: number + * statusMessage: string + * headers?: string + * vary?: string + * etag?: string + * cacheControlDirectives?: string + * cachedAt: number + * staleAt: number + * deleteAt: number + * }} SqliteStoreValue + */ +module.exports = class SqliteCacheStore { + #maxEntrySize = MAX_ENTRY_SIZE + #maxCount = Infinity + + /** + * @type {import('node:sqlite').DatabaseSync} + */ + #db + + /** + * @type {import('node:sqlite').StatementSync} + */ + #getValuesQuery + + /** + * @type {import('node:sqlite').StatementSync} + */ + #updateValueQuery + + /** + * @type {import('node:sqlite').StatementSync} + */ + #insertValueQuery + + /** + * @type {import('node:sqlite').StatementSync} + */ + #deleteExpiredValuesQuery + + /** + * @type {import('node:sqlite').StatementSync} + */ + #deleteByUrlQuery + + /** + * @type {import('node:sqlite').StatementSync} + */ + #countEntriesQuery + + /** + * @type {import('node:sqlite').StatementSync | null} + */ + #deleteOldValuesQuery + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.SqliteCacheStoreOpts | undefined} opts + */ + constructor (opts) { + if (opts) { + if (typeof opts !== 'object') { + throw new TypeError('SqliteCacheStore options must be an object') + } + + if (opts.maxEntrySize !== undefined) { + if ( + typeof opts.maxEntrySize !== 'number' || + !Number.isInteger(opts.maxEntrySize) || + opts.maxEntrySize < 0 + ) { + throw new TypeError('SqliteCacheStore options.maxEntrySize must be a non-negative integer') + } + + if (opts.maxEntrySize > MAX_ENTRY_SIZE) { + throw new TypeError('SqliteCacheStore options.maxEntrySize must be less than 2gb') + } + + this.#maxEntrySize = opts.maxEntrySize + } + + if (opts.maxCount !== undefined) { + if ( + typeof opts.maxCount !== 'number' || + !Number.isInteger(opts.maxCount) || + opts.maxCount < 0 + ) { + throw new TypeError('SqliteCacheStore options.maxCount must be a non-negative integer') + } + this.#maxCount = opts.maxCount + } + } + + if (!DatabaseSync) { + DatabaseSync = require('node:sqlite').DatabaseSync + } + this.#db = new DatabaseSync(opts?.location ?? ':memory:') + + this.#db.exec(` + PRAGMA journal_mode = WAL; + PRAGMA synchronous = NORMAL; + PRAGMA temp_store = memory; + PRAGMA optimize; + + CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION} ( + -- Data specific to us + id INTEGER PRIMARY KEY AUTOINCREMENT, + url TEXT NOT NULL, + method TEXT NOT NULL, + + -- Data returned to the interceptor + body BUF NULL, + deleteAt INTEGER NOT NULL, + statusCode INTEGER NOT NULL, + statusMessage TEXT NOT NULL, + headers TEXT NULL, + cacheControlDirectives TEXT NULL, + etag TEXT NULL, + vary TEXT NULL, + cachedAt INTEGER NOT NULL, + staleAt INTEGER NOT NULL + ); + + CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_getValuesQuery ON cacheInterceptorV${VERSION}(url, method, deleteAt); + CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_deleteByUrlQuery ON cacheInterceptorV${VERSION}(deleteAt); + `) + + this.#getValuesQuery = this.#db.prepare(` + SELECT + id, + body, + deleteAt, + statusCode, + statusMessage, + headers, + etag, + cacheControlDirectives, + vary, + cachedAt, + staleAt + FROM cacheInterceptorV${VERSION} + WHERE + url = ? + AND method = ? + ORDER BY + deleteAt ASC + `) + + this.#updateValueQuery = this.#db.prepare(` + UPDATE cacheInterceptorV${VERSION} SET + body = ?, + deleteAt = ?, + statusCode = ?, + statusMessage = ?, + headers = ?, + etag = ?, + cacheControlDirectives = ?, + cachedAt = ?, + staleAt = ? + WHERE + id = ? + `) + + this.#insertValueQuery = this.#db.prepare(` + INSERT INTO cacheInterceptorV${VERSION} ( + url, + method, + body, + deleteAt, + statusCode, + statusMessage, + headers, + etag, + cacheControlDirectives, + vary, + cachedAt, + staleAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `) + + this.#deleteByUrlQuery = this.#db.prepare( + `DELETE FROM cacheInterceptorV${VERSION} WHERE url = ?` + ) + + this.#countEntriesQuery = this.#db.prepare( + `SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION}` + ) + + this.#deleteExpiredValuesQuery = this.#db.prepare( + `DELETE FROM cacheInterceptorV${VERSION} WHERE deleteAt <= ?` + ) + + this.#deleteOldValuesQuery = this.#maxCount === Infinity + ? null + : this.#db.prepare(` + DELETE FROM cacheInterceptorV${VERSION} + WHERE id IN ( + SELECT + id + FROM cacheInterceptorV${VERSION} + ORDER BY cachedAt DESC + LIMIT ? + ) + `) + } + + close () { + this.#db.close() + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @returns {(import('../../types/cache-interceptor.d.ts').default.GetResult & { body?: Buffer }) | undefined} + */ + get (key) { + assertCacheKey(key) + + const value = this.#findValue(key) + return value + ? { + body: value.body ? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength) : undefined, + statusCode: value.statusCode, + statusMessage: value.statusMessage, + headers: value.headers ? JSON.parse(value.headers) : undefined, + etag: value.etag ? value.etag : undefined, + vary: value.vary ? JSON.parse(value.vary) : undefined, + cacheControlDirectives: value.cacheControlDirectives + ? JSON.parse(value.cacheControlDirectives) + : undefined, + cachedAt: value.cachedAt, + staleAt: value.staleAt, + deleteAt: value.deleteAt + } + : undefined + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue & { body: null | Buffer | Array}} value + */ + set (key, value) { + assertCacheKey(key) + + const url = this.#makeValueUrl(key) + const body = Array.isArray(value.body) ? Buffer.concat(value.body) : value.body + const size = body?.byteLength + + if (size && size > this.#maxEntrySize) { + return + } + + const existingValue = this.#findValue(key, true) + if (existingValue) { + // Updating an existing response, let's overwrite it + this.#updateValueQuery.run( + body, + value.deleteAt, + value.statusCode, + value.statusMessage, + value.headers ? JSON.stringify(value.headers) : null, + value.etag ? value.etag : null, + value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null, + value.cachedAt, + value.staleAt, + existingValue.id + ) + } else { + this.#prune() + // New response, let's insert it + this.#insertValueQuery.run( + url, + key.method, + body, + value.deleteAt, + value.statusCode, + value.statusMessage, + value.headers ? JSON.stringify(value.headers) : null, + value.etag ? value.etag : null, + value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null, + value.vary ? JSON.stringify(value.vary) : null, + value.cachedAt, + value.staleAt + ) + } + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} value + * @returns {Writable | undefined} + */ + createWriteStream (key, value) { + assertCacheKey(key) + assertCacheValue(value) + + let size = 0 + /** + * @type {Buffer[] | null} + */ + const body = [] + const store = this + + return new Writable({ + decodeStrings: true, + write (chunk, encoding, callback) { + size += chunk.byteLength + + if (size < store.#maxEntrySize) { + body.push(chunk) + } else { + this.destroy() + } + + callback() + }, + final (callback) { + store.set(key, { ...value, body }) + callback() + } + }) + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + */ + delete (key) { + if (typeof key !== 'object') { + throw new TypeError(`expected key to be object, got ${typeof key}`) + } + + this.#deleteByUrlQuery.run(this.#makeValueUrl(key)) + } + + #prune () { + if (Number.isFinite(this.#maxCount) && this.size <= this.#maxCount) { + return 0 + } + + { + const removed = this.#deleteExpiredValuesQuery.run(Date.now()).changes + if (removed) { + return removed + } + } + + { + const removed = this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes + if (removed) { + return removed + } + } + + return 0 + } + + /** + * Counts the number of rows in the cache + * @returns {Number} + */ + get size () { + const { total } = this.#countEntriesQuery.get() + return total + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @returns {string} + */ + #makeValueUrl (key) { + return `${key.origin}/${key.path}` + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {boolean} [canBeExpired=false] + * @returns {SqliteStoreValue | undefined} + */ + #findValue (key, canBeExpired = false) { + const url = this.#makeValueUrl(key) + const { headers, method } = key + + /** + * @type {SqliteStoreValue[]} + */ + const values = this.#getValuesQuery.all(url, method) + + if (values.length === 0) { + return undefined + } + + const now = Date.now() + for (const value of values) { + if (now >= value.deleteAt && !canBeExpired) { + return undefined + } + + let matches = true + + if (value.vary) { + const vary = JSON.parse(value.vary) + + for (const header in vary) { + if (!headerValueEquals(headers[header], vary[header])) { + matches = false + break + } + } + } + + if (matches) { + return value + } + } + + return undefined + } +} + +/** + * @param {string|string[]|null|undefined} lhs + * @param {string|string[]|null|undefined} rhs + * @returns {boolean} + */ +function headerValueEquals (lhs, rhs) { + if (lhs == null && rhs == null) { + return true + } + + if ((lhs == null && rhs != null) || + (lhs != null && rhs == null)) { + return false + } + + if (Array.isArray(lhs) && Array.isArray(rhs)) { + if (lhs.length !== rhs.length) { + return false + } + + return lhs.every((x, i) => x === rhs[i]) + } + + return lhs === rhs +} diff --git a/node_modules/undici/lib/core/connect.js b/node_modules/undici/lib/core/connect.js new file mode 100644 index 000000000..a49af9148 --- /dev/null +++ b/node_modules/undici/lib/core/connect.js @@ -0,0 +1,137 @@ +'use strict' + +const net = require('node:net') +const assert = require('node:assert') +const util = require('./util') +const { InvalidArgumentError } = require('./errors') + +let tls // include tls conditionally since it is not always available + +// TODO: session re-use does not wait for the first +// connection to resolve the session and might therefore +// resolve the same servername multiple times even when +// re-use is enabled. + +const SessionCache = class WeakSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + this._sessionRegistry = new FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { + return + } + + const ref = this._sessionCache.get(key) + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key) + } + }) + } + + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey) + return ref ? ref.deref() : null + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + this._sessionCache.set(sessionKey, new WeakRef(session)) + this._sessionRegistry.register(session, sessionKey) + } +} + +function buildConnector ({ allowH2, useH2c, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) { + if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { + throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') + } + + const options = { path: socketPath, ...opts } + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) + timeout = timeout == null ? 10e3 : timeout + allowH2 = allowH2 != null ? allowH2 : false + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket + if (protocol === 'https:') { + if (!tls) { + tls = require('node:tls') + } + servername = servername || options.servername || util.getServerName(host) || null + + const sessionKey = servername || hostname + assert(sessionKey) + + const session = customSession || sessionCache.get(sessionKey) || null + + port = port || 443 + + socket = tls.connect({ + highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... + ...options, + servername, + session, + localAddress, + ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], + socket: httpSocket, // upgrade socket connection + port, + host: hostname + }) + + socket + .on('session', function (session) { + // TODO (fix): Can a session become invalid once established? Don't think so? + sessionCache.set(sessionKey, session) + }) + } else { + assert(!httpSocket, 'httpSocket can only be sent on TLS update') + + port = port || 80 + + socket = net.connect({ + highWaterMark: 64 * 1024, // Same as nodejs fs streams. + ...options, + localAddress, + port, + host: hostname + }) + if (useH2c === true) { + socket.alpnProtocol = 'h2' + } + } + + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (options.keepAlive == null || options.keepAlive) { + const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay + socket.setKeepAlive(true, keepAliveInitialDelay) + } + + const clearConnectTimeout = util.setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port }) + + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + queueMicrotask(clearConnectTimeout) + + if (callback) { + const cb = callback + callback = null + cb(null, this) + } + }) + .on('error', function (err) { + queueMicrotask(clearConnectTimeout) + + if (callback) { + const cb = callback + callback = null + cb(err) + } + }) + + return socket + } +} + +module.exports = buildConnector diff --git a/node_modules/undici/lib/core/constants.js b/node_modules/undici/lib/core/constants.js new file mode 100644 index 000000000..088cf47d8 --- /dev/null +++ b/node_modules/undici/lib/core/constants.js @@ -0,0 +1,143 @@ +'use strict' + +/** + * @see https://developer.mozilla.org/docs/Web/HTTP/Headers + */ +const wellknownHeaderNames = /** @type {const} */ ([ + 'Accept', + 'Accept-Encoding', + 'Accept-Language', + 'Accept-Ranges', + 'Access-Control-Allow-Credentials', + 'Access-Control-Allow-Headers', + 'Access-Control-Allow-Methods', + 'Access-Control-Allow-Origin', + 'Access-Control-Expose-Headers', + 'Access-Control-Max-Age', + 'Access-Control-Request-Headers', + 'Access-Control-Request-Method', + 'Age', + 'Allow', + 'Alt-Svc', + 'Alt-Used', + 'Authorization', + 'Cache-Control', + 'Clear-Site-Data', + 'Connection', + 'Content-Disposition', + 'Content-Encoding', + 'Content-Language', + 'Content-Length', + 'Content-Location', + 'Content-Range', + 'Content-Security-Policy', + 'Content-Security-Policy-Report-Only', + 'Content-Type', + 'Cookie', + 'Cross-Origin-Embedder-Policy', + 'Cross-Origin-Opener-Policy', + 'Cross-Origin-Resource-Policy', + 'Date', + 'Device-Memory', + 'Downlink', + 'ECT', + 'ETag', + 'Expect', + 'Expect-CT', + 'Expires', + 'Forwarded', + 'From', + 'Host', + 'If-Match', + 'If-Modified-Since', + 'If-None-Match', + 'If-Range', + 'If-Unmodified-Since', + 'Keep-Alive', + 'Last-Modified', + 'Link', + 'Location', + 'Max-Forwards', + 'Origin', + 'Permissions-Policy', + 'Pragma', + 'Proxy-Authenticate', + 'Proxy-Authorization', + 'RTT', + 'Range', + 'Referer', + 'Referrer-Policy', + 'Refresh', + 'Retry-After', + 'Sec-WebSocket-Accept', + 'Sec-WebSocket-Extensions', + 'Sec-WebSocket-Key', + 'Sec-WebSocket-Protocol', + 'Sec-WebSocket-Version', + 'Server', + 'Server-Timing', + 'Service-Worker-Allowed', + 'Service-Worker-Navigation-Preload', + 'Set-Cookie', + 'SourceMap', + 'Strict-Transport-Security', + 'Supports-Loading-Mode', + 'TE', + 'Timing-Allow-Origin', + 'Trailer', + 'Transfer-Encoding', + 'Upgrade', + 'Upgrade-Insecure-Requests', + 'User-Agent', + 'Vary', + 'Via', + 'WWW-Authenticate', + 'X-Content-Type-Options', + 'X-DNS-Prefetch-Control', + 'X-Frame-Options', + 'X-Permitted-Cross-Domain-Policies', + 'X-Powered-By', + 'X-Requested-With', + 'X-XSS-Protection' +]) + +/** @type {Record, string>} */ +const headerNameLowerCasedRecord = {} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(headerNameLowerCasedRecord, null) + +/** + * @type {Record, Buffer>} + */ +const wellknownHeaderNameBuffers = {} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(wellknownHeaderNameBuffers, null) + +/** + * @param {string} header Lowercased header + * @returns {Buffer} + */ +function getHeaderNameAsBuffer (header) { + let buffer = wellknownHeaderNameBuffers[header] + + if (buffer === undefined) { + buffer = Buffer.from(header) + } + + return buffer +} + +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = wellknownHeaderNames[i] + const lowerCasedKey = key.toLowerCase() + headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = + lowerCasedKey +} + +module.exports = { + wellknownHeaderNames, + headerNameLowerCasedRecord, + getHeaderNameAsBuffer +} diff --git a/node_modules/undici/lib/core/diagnostics.js b/node_modules/undici/lib/core/diagnostics.js new file mode 100644 index 000000000..ccd6870ca --- /dev/null +++ b/node_modules/undici/lib/core/diagnostics.js @@ -0,0 +1,225 @@ +'use strict' + +const diagnosticsChannel = require('node:diagnostics_channel') +const util = require('node:util') + +const undiciDebugLog = util.debuglog('undici') +const fetchDebuglog = util.debuglog('fetch') +const websocketDebuglog = util.debuglog('websocket') + +const channels = { + // Client + beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'), + connected: diagnosticsChannel.channel('undici:client:connected'), + connectError: diagnosticsChannel.channel('undici:client:connectError'), + sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'), + // Request + create: diagnosticsChannel.channel('undici:request:create'), + bodySent: diagnosticsChannel.channel('undici:request:bodySent'), + bodyChunkSent: diagnosticsChannel.channel('undici:request:bodyChunkSent'), + bodyChunkReceived: diagnosticsChannel.channel('undici:request:bodyChunkReceived'), + headers: diagnosticsChannel.channel('undici:request:headers'), + trailers: diagnosticsChannel.channel('undici:request:trailers'), + error: diagnosticsChannel.channel('undici:request:error'), + // WebSocket + open: diagnosticsChannel.channel('undici:websocket:open'), + close: diagnosticsChannel.channel('undici:websocket:close'), + socketError: diagnosticsChannel.channel('undici:websocket:socket_error'), + ping: diagnosticsChannel.channel('undici:websocket:ping'), + pong: diagnosticsChannel.channel('undici:websocket:pong'), + // ProxyAgent + proxyConnected: diagnosticsChannel.channel('undici:proxy:connected') +} + +let isTrackingClientEvents = false + +function trackClientEvents (debugLog = undiciDebugLog) { + if (isTrackingClientEvents) { + return + } + + // Check if any of the channels already have subscribers to prevent duplicate subscriptions + // This can happen when both Node.js built-in undici and undici as a dependency are present + if (channels.beforeConnect.hasSubscribers || channels.connected.hasSubscribers || + channels.connectError.hasSubscribers || channels.sendHeaders.hasSubscribers) { + isTrackingClientEvents = true + return + } + + isTrackingClientEvents = true + + diagnosticsChannel.subscribe('undici:client:beforeConnect', + evt => { + const { + connectParams: { version, protocol, port, host } + } = evt + debugLog( + 'connecting to %s%s using %s%s', + host, + port ? `:${port}` : '', + protocol, + version + ) + }) + + diagnosticsChannel.subscribe('undici:client:connected', + evt => { + const { + connectParams: { version, protocol, port, host } + } = evt + debugLog( + 'connected to %s%s using %s%s', + host, + port ? `:${port}` : '', + protocol, + version + ) + }) + + diagnosticsChannel.subscribe('undici:client:connectError', + evt => { + const { + connectParams: { version, protocol, port, host }, + error + } = evt + debugLog( + 'connection to %s%s using %s%s errored - %s', + host, + port ? `:${port}` : '', + protocol, + version, + error.message + ) + }) + + diagnosticsChannel.subscribe('undici:client:sendHeaders', + evt => { + const { + request: { method, path, origin } + } = evt + debugLog('sending request to %s %s%s', method, origin, path) + }) +} + +let isTrackingRequestEvents = false + +function trackRequestEvents (debugLog = undiciDebugLog) { + if (isTrackingRequestEvents) { + return + } + + // Check if any of the channels already have subscribers to prevent duplicate subscriptions + // This can happen when both Node.js built-in undici and undici as a dependency are present + if (channels.headers.hasSubscribers || channels.trailers.hasSubscribers || + channels.error.hasSubscribers) { + isTrackingRequestEvents = true + return + } + + isTrackingRequestEvents = true + + diagnosticsChannel.subscribe('undici:request:headers', + evt => { + const { + request: { method, path, origin }, + response: { statusCode } + } = evt + debugLog( + 'received response to %s %s%s - HTTP %d', + method, + origin, + path, + statusCode + ) + }) + + diagnosticsChannel.subscribe('undici:request:trailers', + evt => { + const { + request: { method, path, origin } + } = evt + debugLog('trailers received from %s %s%s', method, origin, path) + }) + + diagnosticsChannel.subscribe('undici:request:error', + evt => { + const { + request: { method, path, origin }, + error + } = evt + debugLog( + 'request to %s %s%s errored - %s', + method, + origin, + path, + error.message + ) + }) +} + +let isTrackingWebSocketEvents = false + +function trackWebSocketEvents (debugLog = websocketDebuglog) { + if (isTrackingWebSocketEvents) { + return + } + + // Check if any of the channels already have subscribers to prevent duplicate subscriptions + // This can happen when both Node.js built-in undici and undici as a dependency are present + if (channels.open.hasSubscribers || channels.close.hasSubscribers || + channels.socketError.hasSubscribers || channels.ping.hasSubscribers || + channels.pong.hasSubscribers) { + isTrackingWebSocketEvents = true + return + } + + isTrackingWebSocketEvents = true + + diagnosticsChannel.subscribe('undici:websocket:open', + evt => { + const { + address: { address, port } + } = evt + debugLog('connection opened %s%s', address, port ? `:${port}` : '') + }) + + diagnosticsChannel.subscribe('undici:websocket:close', + evt => { + const { websocket, code, reason } = evt + debugLog( + 'closed connection to %s - %s %s', + websocket.url, + code, + reason + ) + }) + + diagnosticsChannel.subscribe('undici:websocket:socket_error', + err => { + debugLog('connection errored - %s', err.message) + }) + + diagnosticsChannel.subscribe('undici:websocket:ping', + evt => { + debugLog('ping received') + }) + + diagnosticsChannel.subscribe('undici:websocket:pong', + evt => { + debugLog('pong received') + }) +} + +if (undiciDebugLog.enabled || fetchDebuglog.enabled) { + trackClientEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog) + trackRequestEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog) +} + +if (websocketDebuglog.enabled) { + trackClientEvents(undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog) + trackWebSocketEvents(websocketDebuglog) +} + +module.exports = { + channels +} diff --git a/node_modules/undici/lib/core/errors.js b/node_modules/undici/lib/core/errors.js new file mode 100644 index 000000000..4b1a8a101 --- /dev/null +++ b/node_modules/undici/lib/core/errors.js @@ -0,0 +1,448 @@ +'use strict' + +const kUndiciError = Symbol.for('undici.error.UND_ERR') +class UndiciError extends Error { + constructor (message, options) { + super(message, options) + this.name = 'UndiciError' + this.code = 'UND_ERR' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kUndiciError] === true + } + + get [kUndiciError] () { + return true + } +} + +const kConnectTimeoutError = Symbol.for('undici.error.UND_ERR_CONNECT_TIMEOUT') +class ConnectTimeoutError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ConnectTimeoutError' + this.message = message || 'Connect Timeout Error' + this.code = 'UND_ERR_CONNECT_TIMEOUT' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kConnectTimeoutError] === true + } + + get [kConnectTimeoutError] () { + return true + } +} + +const kHeadersTimeoutError = Symbol.for('undici.error.UND_ERR_HEADERS_TIMEOUT') +class HeadersTimeoutError extends UndiciError { + constructor (message) { + super(message) + this.name = 'HeadersTimeoutError' + this.message = message || 'Headers Timeout Error' + this.code = 'UND_ERR_HEADERS_TIMEOUT' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kHeadersTimeoutError] === true + } + + get [kHeadersTimeoutError] () { + return true + } +} + +const kHeadersOverflowError = Symbol.for('undici.error.UND_ERR_HEADERS_OVERFLOW') +class HeadersOverflowError extends UndiciError { + constructor (message) { + super(message) + this.name = 'HeadersOverflowError' + this.message = message || 'Headers Overflow Error' + this.code = 'UND_ERR_HEADERS_OVERFLOW' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kHeadersOverflowError] === true + } + + get [kHeadersOverflowError] () { + return true + } +} + +const kBodyTimeoutError = Symbol.for('undici.error.UND_ERR_BODY_TIMEOUT') +class BodyTimeoutError extends UndiciError { + constructor (message) { + super(message) + this.name = 'BodyTimeoutError' + this.message = message || 'Body Timeout Error' + this.code = 'UND_ERR_BODY_TIMEOUT' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kBodyTimeoutError] === true + } + + get [kBodyTimeoutError] () { + return true + } +} + +const kInvalidArgumentError = Symbol.for('undici.error.UND_ERR_INVALID_ARG') +class InvalidArgumentError extends UndiciError { + constructor (message) { + super(message) + this.name = 'InvalidArgumentError' + this.message = message || 'Invalid Argument Error' + this.code = 'UND_ERR_INVALID_ARG' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kInvalidArgumentError] === true + } + + get [kInvalidArgumentError] () { + return true + } +} + +const kInvalidReturnValueError = Symbol.for('undici.error.UND_ERR_INVALID_RETURN_VALUE') +class InvalidReturnValueError extends UndiciError { + constructor (message) { + super(message) + this.name = 'InvalidReturnValueError' + this.message = message || 'Invalid Return Value Error' + this.code = 'UND_ERR_INVALID_RETURN_VALUE' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kInvalidReturnValueError] === true + } + + get [kInvalidReturnValueError] () { + return true + } +} + +const kAbortError = Symbol.for('undici.error.UND_ERR_ABORT') +class AbortError extends UndiciError { + constructor (message) { + super(message) + this.name = 'AbortError' + this.message = message || 'The operation was aborted' + this.code = 'UND_ERR_ABORT' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kAbortError] === true + } + + get [kAbortError] () { + return true + } +} + +const kRequestAbortedError = Symbol.for('undici.error.UND_ERR_ABORTED') +class RequestAbortedError extends AbortError { + constructor (message) { + super(message) + this.name = 'AbortError' + this.message = message || 'Request aborted' + this.code = 'UND_ERR_ABORTED' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kRequestAbortedError] === true + } + + get [kRequestAbortedError] () { + return true + } +} + +const kInformationalError = Symbol.for('undici.error.UND_ERR_INFO') +class InformationalError extends UndiciError { + constructor (message) { + super(message) + this.name = 'InformationalError' + this.message = message || 'Request information' + this.code = 'UND_ERR_INFO' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kInformationalError] === true + } + + get [kInformationalError] () { + return true + } +} + +const kRequestContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH') +class RequestContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + this.name = 'RequestContentLengthMismatchError' + this.message = message || 'Request body length does not match content-length header' + this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kRequestContentLengthMismatchError] === true + } + + get [kRequestContentLengthMismatchError] () { + return true + } +} + +const kResponseContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH') +class ResponseContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ResponseContentLengthMismatchError' + this.message = message || 'Response body length does not match content-length header' + this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseContentLengthMismatchError] === true + } + + get [kResponseContentLengthMismatchError] () { + return true + } +} + +const kClientDestroyedError = Symbol.for('undici.error.UND_ERR_DESTROYED') +class ClientDestroyedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ClientDestroyedError' + this.message = message || 'The client is destroyed' + this.code = 'UND_ERR_DESTROYED' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kClientDestroyedError] === true + } + + get [kClientDestroyedError] () { + return true + } +} + +const kClientClosedError = Symbol.for('undici.error.UND_ERR_CLOSED') +class ClientClosedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ClientClosedError' + this.message = message || 'The client is closed' + this.code = 'UND_ERR_CLOSED' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kClientClosedError] === true + } + + get [kClientClosedError] () { + return true + } +} + +const kSocketError = Symbol.for('undici.error.UND_ERR_SOCKET') +class SocketError extends UndiciError { + constructor (message, socket) { + super(message) + this.name = 'SocketError' + this.message = message || 'Socket error' + this.code = 'UND_ERR_SOCKET' + this.socket = socket + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kSocketError] === true + } + + get [kSocketError] () { + return true + } +} + +const kNotSupportedError = Symbol.for('undici.error.UND_ERR_NOT_SUPPORTED') +class NotSupportedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'NotSupportedError' + this.message = message || 'Not supported error' + this.code = 'UND_ERR_NOT_SUPPORTED' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kNotSupportedError] === true + } + + get [kNotSupportedError] () { + return true + } +} + +const kBalancedPoolMissingUpstreamError = Symbol.for('undici.error.UND_ERR_BPL_MISSING_UPSTREAM') +class BalancedPoolMissingUpstreamError extends UndiciError { + constructor (message) { + super(message) + this.name = 'MissingUpstreamError' + this.message = message || 'No upstream has been added to the BalancedPool' + this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kBalancedPoolMissingUpstreamError] === true + } + + get [kBalancedPoolMissingUpstreamError] () { + return true + } +} + +const kHTTPParserError = Symbol.for('undici.error.UND_ERR_HTTP_PARSER') +class HTTPParserError extends Error { + constructor (message, code, data) { + super(message) + this.name = 'HTTPParserError' + this.code = code ? `HPE_${code}` : undefined + this.data = data ? data.toString() : undefined + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kHTTPParserError] === true + } + + get [kHTTPParserError] () { + return true + } +} + +const kResponseExceededMaxSizeError = Symbol.for('undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE') +class ResponseExceededMaxSizeError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ResponseExceededMaxSizeError' + this.message = message || 'Response content exceeded max size' + this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseExceededMaxSizeError] === true + } + + get [kResponseExceededMaxSizeError] () { + return true + } +} + +const kRequestRetryError = Symbol.for('undici.error.UND_ERR_REQ_RETRY') +class RequestRetryError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message) + this.name = 'RequestRetryError' + this.message = message || 'Request retry error' + this.code = 'UND_ERR_REQ_RETRY' + this.statusCode = code + this.data = data + this.headers = headers + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kRequestRetryError] === true + } + + get [kRequestRetryError] () { + return true + } +} + +const kResponseError = Symbol.for('undici.error.UND_ERR_RESPONSE') +class ResponseError extends UndiciError { + constructor (message, code, { headers, body }) { + super(message) + this.name = 'ResponseError' + this.message = message || 'Response error' + this.code = 'UND_ERR_RESPONSE' + this.statusCode = code + this.body = body + this.headers = headers + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseError] === true + } + + get [kResponseError] () { + return true + } +} + +const kSecureProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_TLS') +class SecureProxyConnectionError extends UndiciError { + constructor (cause, message, options = {}) { + super(message, { cause, ...options }) + this.name = 'SecureProxyConnectionError' + this.message = message || 'Secure Proxy Connection failed' + this.code = 'UND_ERR_PRX_TLS' + this.cause = cause + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kSecureProxyConnectionError] === true + } + + get [kSecureProxyConnectionError] () { + return true + } +} + +const kMaxOriginsReachedError = Symbol.for('undici.error.UND_ERR_MAX_ORIGINS_REACHED') +class MaxOriginsReachedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'MaxOriginsReachedError' + this.message = message || 'Maximum allowed origins reached' + this.code = 'UND_ERR_MAX_ORIGINS_REACHED' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kMaxOriginsReachedError] === true + } + + get [kMaxOriginsReachedError] () { + return true + } +} + +module.exports = { + AbortError, + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError, + RequestRetryError, + ResponseError, + SecureProxyConnectionError, + MaxOriginsReachedError +} diff --git a/node_modules/undici/lib/core/request.js b/node_modules/undici/lib/core/request.js new file mode 100644 index 000000000..7dbf781b4 --- /dev/null +++ b/node_modules/undici/lib/core/request.js @@ -0,0 +1,412 @@ +'use strict' + +const { + InvalidArgumentError, + NotSupportedError +} = require('./errors') +const assert = require('node:assert') +const { + isValidHTTPToken, + isValidHeaderValue, + isStream, + destroy, + isBuffer, + isFormDataLike, + isIterable, + isBlobLike, + serializePathWithQuery, + assertRequestHandler, + getServerName, + normalizedMethodRecords, + getProtocolFromUrlString +} = require('./util') +const { channels } = require('./diagnostics.js') +const { headerNameLowerCasedRecord } = require('./constants') + +// Verifies that a given path is valid does not contain control chars \x00 to \x20 +const invalidPathRegex = /[^\u0021-\u00ff]/ + +const kHandler = Symbol('handler') + +class Request { + constructor (origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + expectContinue, + servername, + throwOnError, + maxRedirections + }, handler) { + if (typeof path !== 'string') { + throw new InvalidArgumentError('path must be a string') + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { + throw new InvalidArgumentError('path must be an absolute URL or start with a slash') + } else if (invalidPathRegex.test(path)) { + throw new InvalidArgumentError('invalid request path') + } + + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) { + throw new InvalidArgumentError('invalid request method') + } + + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') + } + + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } + + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } + + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') + } + + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') + } + + if (throwOnError != null) { + throw new InvalidArgumentError('invalid throwOnError') + } + + if (maxRedirections != null && maxRedirections !== 0) { + throw new InvalidArgumentError('maxRedirections is not supported, use the redirect interceptor') + } + + this.headersTimeout = headersTimeout + + this.bodyTimeout = bodyTimeout + + this.method = method + + this.abort = null + + if (body == null) { + this.body = null + } else if (isStream(body)) { + this.body = body + + const rState = this.body._readableState + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy () { + destroy(this) + } + this.body.on('end', this.endHandler) + } + + this.errorHandler = err => { + if (this.abort) { + this.abort(err) + } else { + this.error = err + } + } + this.body.on('error', this.errorHandler) + } else if (isBuffer(body)) { + this.body = body.byteLength ? body : null + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null + } else if (typeof body === 'string') { + this.body = body.length ? Buffer.from(body) : null + } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) { + this.body = body + } else { + throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + } + + this.completed = false + this.aborted = false + + this.upgrade = upgrade || null + + this.path = query ? serializePathWithQuery(path, query) : path + + // TODO: shall we maybe standardize it to an URL object? + this.origin = origin + + this.protocol = getProtocolFromUrlString(origin) + + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent + + this.blocking = blocking ?? this.method !== 'HEAD' + + this.reset = reset == null ? null : reset + + this.host = null + + this.contentLength = null + + this.contentType = null + + this.headers = [] + + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]) + } + } else if (headers && typeof headers === 'object') { + if (headers[Symbol.iterator]) { + for (const header of headers) { + if (!Array.isArray(header) || header.length !== 2) { + throw new InvalidArgumentError('headers must be in key-value pair format') + } + processHeader(this, header[0], header[1]) + } + } else { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; ++i) { + processHeader(this, keys[i], headers[keys[i]]) + } + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } + + assertRequestHandler(handler, method, upgrade) + + this.servername = servername || getServerName(this.host) || null + + this[kHandler] = handler + + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) + } + } + + onBodySent (chunk) { + if (channels.bodyChunkSent.hasSubscribers) { + channels.bodyChunkSent.publish({ request: this, chunk }) + } + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk) + } catch (err) { + this.abort(err) + } + } + } + + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) + } + + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent() + } catch (err) { + this.abort(err) + } + } + } + + onConnect (abort) { + assert(!this.aborted) + assert(!this.completed) + + if (this.error) { + abort(this.error) + } else { + this.abort = abort + return this[kHandler].onConnect(abort) + } + } + + onResponseStarted () { + return this[kHandler].onResponseStarted?.() + } + + onHeaders (statusCode, headers, resume, statusText) { + assert(!this.aborted) + assert(!this.completed) + + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } + + try { + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } catch (err) { + this.abort(err) + } + } + + onData (chunk) { + assert(!this.aborted) + assert(!this.completed) + + if (channels.bodyChunkReceived.hasSubscribers) { + channels.bodyChunkReceived.publish({ request: this, chunk }) + } + try { + return this[kHandler].onData(chunk) + } catch (err) { + this.abort(err) + return false + } + } + + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted) + assert(!this.completed) + + return this[kHandler].onUpgrade(statusCode, headers, socket) + } + + onComplete (trailers) { + this.onFinally() + + assert(!this.aborted) + assert(!this.completed) + + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } + + try { + return this[kHandler].onComplete(trailers) + } catch (err) { + // TODO (fix): This might be a bad idea? + this.onError(err) + } + } + + onError (error) { + this.onFinally() + + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } + + if (this.aborted) { + return + } + this.aborted = true + + return this[kHandler].onError(error) + } + + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler) + this.errorHandler = null + } + + if (this.endHandler) { + this.body.off('end', this.endHandler) + this.endHandler = null + } + } + + addHeader (key, value) { + processHeader(this, key, value) + return this + } +} + +function processHeader (request, key, val) { + if (val && (typeof val === 'object' && !Array.isArray(val))) { + throw new InvalidArgumentError(`invalid ${key} header`) + } else if (val === undefined) { + return + } + + let headerName = headerNameLowerCasedRecord[key] + + if (headerName === undefined) { + headerName = key.toLowerCase() + if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) { + throw new InvalidArgumentError('invalid header key') + } + } + + if (Array.isArray(val)) { + const arr = [] + for (let i = 0; i < val.length; i++) { + if (typeof val[i] === 'string') { + if (!isValidHeaderValue(val[i])) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + arr.push(val[i]) + } else if (val[i] === null) { + arr.push('') + } else if (typeof val[i] === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) + } else { + arr.push(`${val[i]}`) + } + } + val = arr + } else if (typeof val === 'string') { + if (!isValidHeaderValue(val)) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + } else if (val === null) { + val = '' + } else { + val = `${val}` + } + + if (request.host === null && headerName === 'host') { + if (typeof val !== 'string') { + throw new InvalidArgumentError('invalid host header') + } + // Consumed by Client + request.host = val + } else if (request.contentLength === null && headerName === 'content-length') { + request.contentLength = parseInt(val, 10) + if (!Number.isFinite(request.contentLength)) { + throw new InvalidArgumentError('invalid content-length header') + } + } else if (request.contentType === null && headerName === 'content-type') { + request.contentType = val + request.headers.push(key, val) + } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') { + throw new InvalidArgumentError(`invalid ${headerName} header`) + } else if (headerName === 'connection') { + const value = typeof val === 'string' ? val.toLowerCase() : null + if (value !== 'close' && value !== 'keep-alive') { + throw new InvalidArgumentError('invalid connection header') + } + + if (value === 'close') { + request.reset = true + } + } else if (headerName === 'expect') { + throw new NotSupportedError('expect header not supported') + } else { + request.headers.push(key, val) + } +} + +module.exports = Request diff --git a/node_modules/undici/lib/core/symbols.js b/node_modules/undici/lib/core/symbols.js new file mode 100644 index 000000000..ec45d7951 --- /dev/null +++ b/node_modules/undici/lib/core/symbols.js @@ -0,0 +1,73 @@ +'use strict' + +module.exports = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kBody: Symbol('abstracted request body'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kResume: Symbol('resume'), + kOnError: Symbol('on error'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelining'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kMaxResponseSize: Symbol('max response size'), + kHTTP2Session: Symbol('http2Session'), + kHTTP2SessionState: Symbol('http2Session state'), + kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), + kConstruct: Symbol('constructable'), + kListeners: Symbol('listeners'), + kHTTPContext: Symbol('http context'), + kMaxConcurrentStreams: Symbol('max concurrent streams'), + kHTTP2InitialWindowSize: Symbol('http2 initial window size'), + kHTTP2ConnectionWindowSize: Symbol('http2 connection window size'), + kEnableConnectProtocol: Symbol('http2session connect protocol'), + kRemoteSettings: Symbol('http2session remote settings'), + kHTTP2Stream: Symbol('http2session client stream'), + kNoProxyAgent: Symbol('no proxy agent'), + kHttpProxyAgent: Symbol('http proxy agent'), + kHttpsProxyAgent: Symbol('https proxy agent') +} diff --git a/node_modules/undici/lib/core/tree.js b/node_modules/undici/lib/core/tree.js new file mode 100644 index 000000000..6eed58aad --- /dev/null +++ b/node_modules/undici/lib/core/tree.js @@ -0,0 +1,160 @@ +'use strict' + +const { + wellknownHeaderNames, + headerNameLowerCasedRecord +} = require('./constants') + +class TstNode { + /** @type {any} */ + value = null + /** @type {null | TstNode} */ + left = null + /** @type {null | TstNode} */ + middle = null + /** @type {null | TstNode} */ + right = null + /** @type {number} */ + code + /** + * @param {string} key + * @param {any} value + * @param {number} index + */ + constructor (key, value, index) { + if (index === undefined || index >= key.length) { + throw new TypeError('Unreachable') + } + const code = this.code = key.charCodeAt(index) + // check code is ascii string + if (code > 0x7F) { + throw new TypeError('key must be ascii string') + } + if (key.length !== ++index) { + this.middle = new TstNode(key, value, index) + } else { + this.value = value + } + } + + /** + * @param {string} key + * @param {any} value + * @returns {void} + */ + add (key, value) { + const length = key.length + if (length === 0) { + throw new TypeError('Unreachable') + } + let index = 0 + /** + * @type {TstNode} + */ + let node = this + while (true) { + const code = key.charCodeAt(index) + // check code is ascii string + if (code > 0x7F) { + throw new TypeError('key must be ascii string') + } + if (node.code === code) { + if (length === ++index) { + node.value = value + break + } else if (node.middle !== null) { + node = node.middle + } else { + node.middle = new TstNode(key, value, index) + break + } + } else if (node.code < code) { + if (node.left !== null) { + node = node.left + } else { + node.left = new TstNode(key, value, index) + break + } + } else if (node.right !== null) { + node = node.right + } else { + node.right = new TstNode(key, value, index) + break + } + } + } + + /** + * @param {Uint8Array} key + * @returns {TstNode | null} + */ + search (key) { + const keylength = key.length + let index = 0 + /** + * @type {TstNode|null} + */ + let node = this + while (node !== null && index < keylength) { + let code = key[index] + // A-Z + // First check if it is bigger than 0x5a. + // Lowercase letters have higher char codes than uppercase ones. + // Also we assume that headers will mostly contain lowercase characters. + if (code <= 0x5a && code >= 0x41) { + // Lowercase for uppercase. + code |= 32 + } + while (node !== null) { + if (code === node.code) { + if (keylength === ++index) { + // Returns Node since it is the last key. + return node + } + node = node.middle + break + } + node = node.code < code ? node.left : node.right + } + } + return null + } +} + +class TernarySearchTree { + /** @type {TstNode | null} */ + node = null + + /** + * @param {string} key + * @param {any} value + * @returns {void} + * */ + insert (key, value) { + if (this.node === null) { + this.node = new TstNode(key, value, 0) + } else { + this.node.add(key, value) + } + } + + /** + * @param {Uint8Array} key + * @returns {any} + */ + lookup (key) { + return this.node?.search(key)?.value ?? null + } +} + +const tree = new TernarySearchTree() + +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]] + tree.insert(key, key) +} + +module.exports = { + TernarySearchTree, + tree +} diff --git a/node_modules/undici/lib/core/util.js b/node_modules/undici/lib/core/util.js new file mode 100644 index 000000000..abfa156f1 --- /dev/null +++ b/node_modules/undici/lib/core/util.js @@ -0,0 +1,976 @@ +'use strict' + +const assert = require('node:assert') +const { kDestroyed, kBodyUsed, kListeners, kBody } = require('./symbols') +const { IncomingMessage } = require('node:http') +const stream = require('node:stream') +const net = require('node:net') +const { stringify } = require('node:querystring') +const { EventEmitter: EE } = require('node:events') +const timers = require('../util/timers') +const { InvalidArgumentError, ConnectTimeoutError } = require('./errors') +const { headerNameLowerCasedRecord } = require('./constants') +const { tree } = require('./tree') + +const [nodeMajor, nodeMinor] = process.versions.node.split('.', 2).map(v => Number(v)) + +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false + } + + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] + } +} + +function noop () {} + +/** + * @param {*} body + * @returns {*} + */ +function wrapRequestBody (body) { + if (isStream(body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (bodyLength(body) === 0) { + body + .on('data', function () { + assert(false) + }) + } + + if (typeof body.readableDidRead !== 'boolean') { + body[kBodyUsed] = false + EE.prototype.on.call(body, 'data', function () { + this[kBodyUsed] = true + }) + } + + return body + } else if (body && typeof body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + return new BodyAsyncIterable(body) + } else if (body && isFormDataLike(body)) { + return body + } else if ( + body && + typeof body !== 'string' && + !ArrayBuffer.isView(body) && + isIterable(body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + return new BodyAsyncIterable(body) + } else { + return body + } +} + +/** + * @param {*} obj + * @returns {obj is import('node:stream').Stream} + */ +function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' +} + +/** + * @param {*} object + * @returns {object is Blob} + * based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) + */ +function isBlobLike (object) { + if (object === null) { + return false + } else if (object instanceof Blob) { + return true + } else if (typeof object !== 'object') { + return false + } else { + const sTag = object[Symbol.toStringTag] + + return (sTag === 'Blob' || sTag === 'File') && ( + ('stream' in object && typeof object.stream === 'function') || + ('arrayBuffer' in object && typeof object.arrayBuffer === 'function') + ) + } +} + +/** + * @param {string} url The path to check for query strings or fragments. + * @returns {boolean} Returns true if the path contains a query string or fragment. + */ +function pathHasQueryOrFragment (url) { + return ( + url.includes('?') || + url.includes('#') + ) +} + +/** + * @param {string} url The URL to add the query params to + * @param {import('node:querystring').ParsedUrlQueryInput} queryParams The object to serialize into a URL query string + * @returns {string} The URL with the query params added + */ +function serializePathWithQuery (url, queryParams) { + if (pathHasQueryOrFragment(url)) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') + } + + const stringified = stringify(queryParams) + + if (stringified) { + url += '?' + stringified + } + + return url +} + +/** + * @param {number|string|undefined} port + * @returns {boolean} + */ +function isValidPort (port) { + const value = parseInt(port, 10) + return ( + value === Number(port) && + value >= 0 && + value <= 65535 + ) +} + +/** + * Check if the value is a valid http or https prefixed string. + * + * @param {string} value + * @returns {boolean} + */ +function isHttpOrHttpsPrefixed (value) { + return ( + value != null && + value[0] === 'h' && + value[1] === 't' && + value[2] === 't' && + value[3] === 'p' && + ( + value[4] === ':' || + ( + value[4] === 's' && + value[5] === ':' + ) + ) + ) +} + +/** + * @param {string|URL|Record} url + * @returns {URL} + */ +function parseURL (url) { + if (typeof url === 'string') { + /** + * @type {URL} + */ + url = new URL(url) + + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url + } + + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') + } + + if (!(url instanceof URL)) { + if (url.port != null && url.port !== '' && isValidPort(url.port) === false) { + throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') + } + + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') + } + + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') + } + + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') + } + + if (url.origin != null && typeof url.origin !== 'string') { + throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') + } + + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + const port = url.port != null + ? url.port + : (url.protocol === 'https:' ? 443 : 80) + let origin = url.origin != null + ? url.origin + : `${url.protocol || ''}//${url.hostname || ''}:${port}` + let path = url.path != null + ? url.path + : `${url.pathname || ''}${url.search || ''}` + + if (origin[origin.length - 1] === '/') { + origin = origin.slice(0, origin.length - 1) + } + + if (path && path[0] !== '/') { + path = `/${path}` + } + // new URL(path, origin) is unsafe when `path` contains an absolute URL + // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: + // If first parameter is a relative URL, second param is required, and will be used as the base URL. + // If first parameter is an absolute URL, a given second param will be ignored. + return new URL(`${origin}${path}`) + } + + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url +} + +/** + * @param {string|URL|Record} url + * @returns {URL} + */ +function parseOrigin (url) { + url = parseURL(url) + + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') + } + + return url +} + +/** + * @param {string} host + * @returns {string} + */ +function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']') + + assert(idx !== -1) + return host.substring(1, idx) + } + + const idx = host.indexOf(':') + if (idx === -1) return host + + return host.substring(0, idx) +} + +/** + * IP addresses are not valid server names per RFC6066 + * Currently, the only server names supported are DNS hostnames + * @param {string|null} host + * @returns {string|null} + */ +function getServerName (host) { + if (!host) { + return null + } + + assert(typeof host === 'string') + + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' + } + + return servername +} + +/** + * @function + * @template T + * @param {T} obj + * @returns {T} + */ +function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) +} + +/** + * @param {*} obj + * @returns {obj is AsyncIterable} + */ +function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') +} + +/** + * @param {*} obj + * @returns {obj is Iterable} + */ +function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) +} + +/** + * @param {Blob|Buffer|import ('stream').Stream} body + * @returns {number|null} + */ +function bodyLength (body) { + if (body == null) { + return 0 + } else if (isStream(body)) { + const state = body._readableState + return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) + ? state.length + : null + } else if (isBlobLike(body)) { + return body.size != null ? body.size : null + } else if (isBuffer(body)) { + return body.byteLength + } + + return null +} + +/** + * @param {import ('stream').Stream} body + * @returns {boolean} + */ +function isDestroyed (body) { + return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body))) +} + +/** + * @param {import ('stream').Stream} stream + * @param {Error} [err] + * @returns {void} + */ +function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return + } + + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null + } + + stream.destroy(err) + } else if (err) { + queueMicrotask(() => { + stream.emit('error', err) + }) + } + + if (stream.destroyed !== true) { + stream[kDestroyed] = true + } +} + +const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ +/** + * @param {string} val + * @returns {number | null} + */ +function parseKeepAliveTimeout (val) { + const m = val.match(KEEPALIVE_TIMEOUT_EXPR) + return m ? parseInt(m[1], 10) * 1000 : null +} + +/** + * Retrieves a header name and returns its lowercase value. + * @param {string | Buffer} value Header name + * @returns {string} + */ +function headerNameToString (value) { + return typeof value === 'string' + ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() + : tree.lookup(value) ?? value.toString('latin1').toLowerCase() +} + +/** + * Receive the buffer as a string and return its lowercase value. + * @param {Buffer} value Header name + * @returns {string} + */ +function bufferToLowerCasedHeaderName (value) { + return tree.lookup(value) ?? value.toString('latin1').toLowerCase() +} + +/** + * @param {(Buffer | string)[]} headers + * @param {Record} [obj] + * @returns {Record} + */ +function parseHeaders (headers, obj) { + if (obj === undefined) obj = {} + + for (let i = 0; i < headers.length; i += 2) { + const key = headerNameToString(headers[i]) + let val = obj[key] + + if (val) { + if (typeof val === 'string') { + val = [val] + obj[key] = val + } + val.push(headers[i + 1].toString('utf8')) + } else { + const headersValue = headers[i + 1] + if (typeof headersValue === 'string') { + obj[key] = headersValue + } else { + obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('utf8')) : headersValue.toString('utf8') + } + } + } + + // See https://github.com/nodejs/node/pull/46528 + if ('content-length' in obj && 'content-disposition' in obj) { + obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') + } + + return obj +} + +/** + * @param {Buffer[]} headers + * @returns {string[]} + */ +function parseRawHeaders (headers) { + const headersLength = headers.length + /** + * @type {string[]} + */ + const ret = new Array(headersLength) + + let hasContentLength = false + let contentDispositionIdx = -1 + let key + let val + let kLen = 0 + + for (let n = 0; n < headersLength; n += 2) { + key = headers[n] + val = headers[n + 1] + + typeof key !== 'string' && (key = key.toString()) + typeof val !== 'string' && (val = val.toString('utf8')) + + kLen = key.length + if (kLen === 14 && key[7] === '-' && (key === 'content-length' || key.toLowerCase() === 'content-length')) { + hasContentLength = true + } else if (kLen === 19 && key[7] === '-' && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { + contentDispositionIdx = n + 1 + } + ret[n] = key + ret[n + 1] = val + } + + // See https://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') + } + + return ret +} + +/** + * @param {string[]} headers + * @param {Buffer[]} headers + */ +function encodeRawHeaders (headers) { + if (!Array.isArray(headers)) { + throw new TypeError('expected headers to be an array') + } + return headers.map(x => Buffer.from(x)) +} + +/** + * @param {*} buffer + * @returns {buffer is Buffer} + */ +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +} + +/** + * Asserts that the handler object is a request handler. + * + * @param {object} handler + * @param {string} method + * @param {string} [upgrade] + * @returns {asserts handler is import('../api/api-request').RequestHandler} + */ +function assertRequestHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + if (typeof handler.onRequestStart === 'function') { + // TODO (fix): More checks... + return + } + + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') + } + + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') + } + + if (upgrade || method === 'CONNECT') { + if (typeof handler.onUpgrade !== 'function') { + throw new InvalidArgumentError('invalid onUpgrade method') + } + } else { + if (typeof handler.onHeaders !== 'function') { + throw new InvalidArgumentError('invalid onHeaders method') + } + + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') + } + + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError('invalid onComplete method') + } + } +} + +/** + * A body is disturbed if it has been read from and it cannot be re-used without + * losing state or data. + * @param {import('node:stream').Readable} body + * @returns {boolean} + */ +function isDisturbed (body) { + // TODO (fix): Why is body[kBodyUsed] needed? + return !!(body && (stream.isDisturbed(body) || body[kBodyUsed])) +} + +/** + * @typedef {object} SocketInfo + * @property {string} [localAddress] + * @property {number} [localPort] + * @property {string} [remoteAddress] + * @property {number} [remotePort] + * @property {string} [remoteFamily] + * @property {number} [timeout] + * @property {number} bytesWritten + * @property {number} bytesRead + */ + +/** + * @param {import('net').Socket} socket + * @returns {SocketInfo} + */ +function getSocketInfo (socket) { + return { + localAddress: socket.localAddress, + localPort: socket.localPort, + remoteAddress: socket.remoteAddress, + remotePort: socket.remotePort, + remoteFamily: socket.remoteFamily, + timeout: socket.timeout, + bytesWritten: socket.bytesWritten, + bytesRead: socket.bytesRead + } +} + +/** + * @param {Iterable} iterable + * @returns {ReadableStream} + */ +function ReadableStreamFrom (iterable) { + // We cannot use ReadableStream.from here because it does not return a byte stream. + + let iterator + return new ReadableStream( + { + start () { + iterator = iterable[Symbol.asyncIterator]() + }, + pull (controller) { + return iterator.next().then(({ done, value }) => { + if (done) { + return queueMicrotask(() => { + controller.close() + controller.byobRequest?.respond(0) + }) + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) + if (buf.byteLength) { + return controller.enqueue(new Uint8Array(buf)) + } else { + return this.pull(controller) + } + } + }) + }, + cancel () { + return iterator.return() + }, + type: 'bytes' + } + ) +} + +/** + * The object should be a FormData instance and contains all the required + * methods. + * @param {*} object + * @returns {object is FormData} + */ +function isFormDataLike (object) { + return ( + object && + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + object[Symbol.toStringTag] === 'FormData' + ) +} + +function addAbortListener (signal, listener) { + if ('addEventListener' in signal) { + signal.addEventListener('abort', listener, { once: true }) + return () => signal.removeEventListener('abort', listener) + } + signal.once('abort', listener) + return () => signal.removeListener('abort', listener) +} + +const validTokenChars = new Uint8Array([ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0-15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32-47 (!"#$%&'()*+,-./) + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48-63 (0-9:;<=>?) + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64-79 (@A-O) + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80-95 (P-Z[\]^_) + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96-111 (`a-o) + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, // 112-127 (p-z{|}~) + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 128-143 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 144-159 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160-175 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 176-191 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 192-207 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 208-223 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 224-239 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 240-255 +]) + +/** + * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 + * @param {number} c + * @returns {boolean} + */ +function isTokenCharCode (c) { + return (validTokenChars[c] === 1) +} + +const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ + +/** + * @param {string} characters + * @returns {boolean} + */ +function isValidHTTPToken (characters) { + if (characters.length >= 12) return tokenRegExp.test(characters) + if (characters.length === 0) return false + + for (let i = 0; i < characters.length; i++) { + if (validTokenChars[characters.charCodeAt(i)] !== 1) { + return false + } + } + return true +} + +// headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js + +/** + * Matches if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ +const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ + +/** + * @param {string} characters + * @returns {boolean} + */ +function isValidHeaderValue (characters) { + return !headerCharRegex.test(characters) +} + +const rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+)?$/ + +/** + * @typedef {object} RangeHeader + * @property {number} start + * @property {number | null} end + * @property {number | null} size + */ + +/** + * Parse accordingly to RFC 9110 + * @see https://www.rfc-editor.org/rfc/rfc9110#field.content-range + * @param {string} [range] + * @returns {RangeHeader|null} + */ +function parseRangeHeader (range) { + if (range == null || range === '') return { start: 0, end: null, size: null } + + const m = range ? range.match(rangeHeaderRegex) : null + return m + ? { + start: parseInt(m[1]), + end: m[2] ? parseInt(m[2]) : null, + size: m[3] ? parseInt(m[3]) : null + } + : null +} + +/** + * @template {import("events").EventEmitter} T + * @param {T} obj + * @param {string} name + * @param {(...args: any[]) => void} listener + * @returns {T} + */ +function addListener (obj, name, listener) { + const listeners = (obj[kListeners] ??= []) + listeners.push([name, listener]) + obj.on(name, listener) + return obj +} + +/** + * @template {import("events").EventEmitter} T + * @param {T} obj + * @returns {T} + */ +function removeAllListeners (obj) { + if (obj[kListeners] != null) { + for (const [name, listener] of obj[kListeners]) { + obj.removeListener(name, listener) + } + obj[kListeners] = null + } + return obj +} + +/** + * @param {import ('../dispatcher/client')} client + * @param {import ('../core/request')} request + * @param {Error} err + */ +function errorRequest (client, request, err) { + try { + request.onError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) + } +} + +/** + * @param {WeakRef} socketWeakRef + * @param {object} opts + * @param {number} opts.timeout + * @param {string} opts.hostname + * @param {number} opts.port + * @returns {() => void} + */ +const setupConnectTimeout = process.platform === 'win32' + ? (socketWeakRef, opts) => { + if (!opts.timeout) { + return noop + } + + let s1 = null + let s2 = null + const fastTimer = timers.setFastTimeout(() => { + // setImmediate is added to make sure that we prioritize socket error events over timeouts + s1 = setImmediate(() => { + // Windows needs an extra setImmediate probably due to implementation differences in the socket logic + s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts)) + }) + }, opts.timeout) + return () => { + timers.clearFastTimeout(fastTimer) + clearImmediate(s1) + clearImmediate(s2) + } + } + : (socketWeakRef, opts) => { + if (!opts.timeout) { + return noop + } + + let s1 = null + const fastTimer = timers.setFastTimeout(() => { + // setImmediate is added to make sure that we prioritize socket error events over timeouts + s1 = setImmediate(() => { + onConnectTimeout(socketWeakRef.deref(), opts) + }) + }, opts.timeout) + return () => { + timers.clearFastTimeout(fastTimer) + clearImmediate(s1) + } + } + +/** + * @param {net.Socket} socket + * @param {object} opts + * @param {number} opts.timeout + * @param {string} opts.hostname + * @param {number} opts.port + */ +function onConnectTimeout (socket, opts) { + // The socket could be already garbage collected + if (socket == null) { + return + } + + let message = 'Connect Timeout Error' + if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) { + message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},` + } else { + message += ` (attempted address: ${opts.hostname}:${opts.port},` + } + + message += ` timeout: ${opts.timeout}ms)` + + destroy(socket, new ConnectTimeoutError(message)) +} + +/** + * @param {string} urlString + * @returns {string} + */ +function getProtocolFromUrlString (urlString) { + if ( + urlString[0] === 'h' && + urlString[1] === 't' && + urlString[2] === 't' && + urlString[3] === 'p' + ) { + switch (urlString[4]) { + case ':': + return 'http:' + case 's': + if (urlString[5] === ':') { + return 'https:' + } + } + } + // fallback if none of the usual suspects + return urlString.slice(0, urlString.indexOf(':') + 1) +} + +const kEnumerableProperty = Object.create(null) +kEnumerableProperty.enumerable = true + +const normalizedMethodRecordsBase = { + delete: 'DELETE', + DELETE: 'DELETE', + get: 'GET', + GET: 'GET', + head: 'HEAD', + HEAD: 'HEAD', + options: 'OPTIONS', + OPTIONS: 'OPTIONS', + post: 'POST', + POST: 'POST', + put: 'PUT', + PUT: 'PUT' +} + +const normalizedMethodRecords = { + ...normalizedMethodRecordsBase, + patch: 'patch', + PATCH: 'PATCH' +} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(normalizedMethodRecordsBase, null) +Object.setPrototypeOf(normalizedMethodRecords, null) + +module.exports = { + kEnumerableProperty, + isDisturbed, + isBlobLike, + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + headerNameToString, + bufferToLowerCasedHeaderName, + addListener, + removeAllListeners, + errorRequest, + parseRawHeaders, + encodeRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone, + ReadableStreamFrom, + isBuffer, + assertRequestHandler, + getSocketInfo, + isFormDataLike, + pathHasQueryOrFragment, + serializePathWithQuery, + addAbortListener, + isValidHTTPToken, + isValidHeaderValue, + isTokenCharCode, + parseRangeHeader, + normalizedMethodRecordsBase, + normalizedMethodRecords, + isValidPort, + isHttpOrHttpsPrefixed, + nodeMajor, + nodeMinor, + safeHTTPMethods: Object.freeze(['GET', 'HEAD', 'OPTIONS', 'TRACE']), + wrapRequestBody, + setupConnectTimeout, + getProtocolFromUrlString +} diff --git a/node_modules/undici/lib/dispatcher/agent.js b/node_modules/undici/lib/dispatcher/agent.js new file mode 100644 index 000000000..781bc8cf0 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/agent.js @@ -0,0 +1,156 @@ +'use strict' + +const { InvalidArgumentError, MaxOriginsReachedError } = require('../core/errors') +const { kClients, kRunning, kClose, kDestroy, kDispatch, kUrl } = require('../core/symbols') +const DispatcherBase = require('./dispatcher-base') +const Pool = require('./pool') +const Client = require('./client') +const util = require('../core/util') + +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kOnDrain = Symbol('onDrain') +const kFactory = Symbol('factory') +const kOptions = Symbol('options') +const kOrigins = Symbol('origins') + +function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) +} + +class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, maxOrigins = Infinity, connect, ...options } = {}) { + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (typeof maxOrigins !== 'number' || Number.isNaN(maxOrigins) || maxOrigins <= 0) { + throw new InvalidArgumentError('maxOrigins must be a number greater than 0') + } + + super() + + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } + + this[kOptions] = { ...util.deepClone(options), maxOrigins, connect } + this[kFactory] = factory + this[kClients] = new Map() + this[kOrigins] = new Set() + + this[kOnDrain] = (origin, targets) => { + this.emit('drain', origin, [this, ...targets]) + } + + this[kOnConnect] = (origin, targets) => { + this.emit('connect', origin, [this, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + this.emit('disconnect', origin, [this, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + this.emit('connectionError', origin, [this, ...targets], err) + } + } + + get [kRunning] () { + let ret = 0 + for (const { dispatcher } of this[kClients].values()) { + ret += dispatcher[kRunning] + } + return ret + } + + [kDispatch] (opts, handler) { + let key + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + key = String(opts.origin) + } else { + throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') + } + + if (this[kOrigins].size >= this[kOptions].maxOrigins && !this[kOrigins].has(key)) { + throw new MaxOriginsReachedError() + } + + const result = this[kClients].get(key) + let dispatcher = result && result.dispatcher + if (!dispatcher) { + const closeClientIfUnused = (connected) => { + const result = this[kClients].get(key) + if (result) { + if (connected) result.count -= 1 + if (result.count <= 0) { + this[kClients].delete(key) + result.dispatcher.close() + } + this[kOrigins].delete(key) + } + } + dispatcher = this[kFactory](opts.origin, this[kOptions]) + .on('drain', this[kOnDrain]) + .on('connect', (origin, targets) => { + const result = this[kClients].get(key) + if (result) { + result.count += 1 + } + this[kOnConnect](origin, targets) + }) + .on('disconnect', (origin, targets, err) => { + closeClientIfUnused(true) + this[kOnDisconnect](origin, targets, err) + }) + .on('connectionError', (origin, targets, err) => { + closeClientIfUnused(false) + this[kOnConnectionError](origin, targets, err) + }) + + this[kClients].set(key, { count: 0, dispatcher }) + this[kOrigins].add(key) + } + + return dispatcher.dispatch(opts, handler) + } + + [kClose] () { + const closePromises = [] + for (const { dispatcher } of this[kClients].values()) { + closePromises.push(dispatcher.close()) + } + this[kClients].clear() + + return Promise.all(closePromises) + } + + [kDestroy] (err) { + const destroyPromises = [] + for (const { dispatcher } of this[kClients].values()) { + destroyPromises.push(dispatcher.destroy(err)) + } + this[kClients].clear() + + return Promise.all(destroyPromises) + } + + get stats () { + const allClientStats = {} + for (const { dispatcher } of this[kClients].values()) { + if (dispatcher.stats) { + allClientStats[dispatcher[kUrl].origin] = dispatcher.stats + } + } + return allClientStats + } +} + +module.exports = Agent diff --git a/node_modules/undici/lib/dispatcher/balanced-pool.js b/node_modules/undici/lib/dispatcher/balanced-pool.js new file mode 100644 index 000000000..d53a26966 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/balanced-pool.js @@ -0,0 +1,216 @@ +'use strict' + +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = require('../core/errors') +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = require('./pool-base') +const Pool = require('./pool') +const { kUrl } = require('../core/symbols') +const { parseOrigin } = require('../core/util') +const kFactory = Symbol('factory') + +const kOptions = Symbol('options') +const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') +const kCurrentWeight = Symbol('kCurrentWeight') +const kIndex = Symbol('kIndex') +const kWeight = Symbol('kWeight') +const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') +const kErrorPenalty = Symbol('kErrorPenalty') + +/** + * Calculate the greatest common divisor of two numbers by + * using the Euclidean algorithm. + * + * @param {number} a + * @param {number} b + * @returns {number} + */ +function getGreatestCommonDivisor (a, b) { + if (a === 0) return b + + while (b !== 0) { + const t = b + b = a % b + a = t + } + return a +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + super() + + this[kOptions] = opts + this[kIndex] = -1 + this[kCurrentWeight] = 0 + + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 + + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] + } + + this[kFactory] = factory + + for (const upstream of upstreams) { + this.addUpstream(upstream) + } + this._updateBalancedPoolStats() + } + + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + if (this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this + } + const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) + + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) + + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) + + pool.on('disconnect', (...args) => { + const err = args[2] + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + } + }) + + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] + } + + this._updateBalancedPoolStats() + + return this + } + + _updateBalancedPoolStats () { + let result = 0 + for (let i = 0; i < this[kClients].length; i++) { + result = getGreatestCommonDivisor(this[kClients][i][kWeight], result) + } + + this[kGreatestCommonDivisor] = result + } + + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) + + if (pool) { + this[kRemoveClient](pool) + } + + return this + } + + getUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + return this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) + } + + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } + + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients].length === 0) { + throw new BalancedPoolMissingUpstreamError() + } + + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + + if (!dispatcher) { + return + } + + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) + + if (allClientsBusy) { + return + } + + let counter = 0 + + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) + + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] + + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex] + } + + // decrease the current weight every `this[kClients].length`. + if (this[kIndex] === 0) { + // Set the current weight to the next lower weight. + this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] + + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } + } + + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] + } +} + +module.exports = BalancedPool diff --git a/node_modules/undici/lib/dispatcher/client-h1.js b/node_modules/undici/lib/dispatcher/client-h1.js new file mode 100644 index 000000000..09d1a7599 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/client-h1.js @@ -0,0 +1,1601 @@ +'use strict' + +/* global WebAssembly */ + +const assert = require('node:assert') +const util = require('../core/util.js') +const { channels } = require('../core/diagnostics.js') +const timers = require('../util/timers.js') +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError +} = require('../core/errors.js') +const { + kUrl, + kReset, + kClient, + kParser, + kBlocking, + kRunning, + kPending, + kSize, + kWriting, + kQueue, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kMaxRequests, + kCounter, + kMaxResponseSize, + kOnError, + kResume, + kHTTPContext, + kClosed +} = require('../core/symbols.js') + +const constants = require('../llhttp/constants.js') +const EMPTY_BUF = Buffer.alloc(0) +const FastBuffer = Buffer[Symbol.species] +const removeAllListeners = util.removeAllListeners + +let extractBody + +function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? require('../llhttp/llhttp-wasm.js') : undefined + + let mod + + // We disable wasm SIMD on ppc64 as it seems to be broken on Power 9 architectures. + let useWasmSIMD = process.arch !== 'ppc64' + // The Env Variable UNDICI_NO_WASM_SIMD allows explicitly overriding the default behavior + if (process.env.UNDICI_NO_WASM_SIMD === '1') { + useWasmSIMD = true + } else if (process.env.UNDICI_NO_WASM_SIMD === '0') { + useWasmSIMD = false + } + + if (useWasmSIMD) { + try { + mod = new WebAssembly.Module(require('../llhttp/llhttp_simd-wasm.js')) + } catch { + } + } + + if (!mod) { + // We could check if the error was caused by the simd option not + // being enabled, but the occurring of this other error + // * https://github.com/emscripten-core/emscripten/issues/11495 + // got me to remove that check to avoid breaking Node 12. + mod = new WebAssembly.Module(llhttpWasmData || require('../llhttp/llhttp-wasm.js')) + } + + return new WebAssembly.Instance(mod, { + env: { + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ + wasm_on_url: (p, at, len) => { + return 0 + }, + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ + wasm_on_status: (p, at, len) => { + assert(currentParser.ptr === p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) + }, + /** + * @param {number} p + * @returns {number} + */ + wasm_on_message_begin: (p) => { + assert(currentParser.ptr === p) + return currentParser.onMessageBegin() + }, + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ + wasm_on_header_field: (p, at, len) => { + assert(currentParser.ptr === p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) + }, + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ + wasm_on_header_value: (p, at, len) => { + assert(currentParser.ptr === p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) + }, + /** + * @param {number} p + * @param {number} statusCode + * @param {0|1} upgrade + * @param {0|1} shouldKeepAlive + * @returns {number} + */ + wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { + assert(currentParser.ptr === p) + return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1) + }, + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ + wasm_on_body: (p, at, len) => { + assert(currentParser.ptr === p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) + }, + /** + * @param {number} p + * @returns {number} + */ + wasm_on_message_complete: (p) => { + assert(currentParser.ptr === p) + return currentParser.onMessageComplete() + } + + } + }) +} + +let llhttpInstance = null + +/** + * @type {Parser|null} + */ +let currentParser = null +let currentBufferRef = null +/** + * @type {number} + */ +let currentBufferSize = 0 +let currentBufferPtr = null + +const USE_NATIVE_TIMER = 0 +const USE_FAST_TIMER = 1 + +// Use fast timers for headers and body to take eventual event loop +// latency into account. +const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER +const TIMEOUT_BODY = 4 | USE_FAST_TIMER + +// Use native timers to ignore event loop latency for keep-alive +// handling. +const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER + +class Parser { + /** + * @param {import('./client.js')} client + * @param {import('net').Socket} socket + * @param {*} llhttp + */ + constructor (client, socket, { exports }) { + this.llhttp = exports + this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) + this.client = client + /** + * @type {import('net').Socket} + */ + this.socket = socket + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + this.statusCode = 0 + this.statusText = '' + this.upgrade = false + this.headers = [] + this.headersSize = 0 + this.headersMaxSize = client[kMaxHeadersSize] + this.shouldKeepAlive = false + this.paused = false + this.resume = this.resume.bind(this) + + this.bytesRead = 0 + + this.keepAlive = '' + this.contentLength = '' + this.connection = '' + this.maxResponseSize = client[kMaxResponseSize] + } + + setTimeout (delay, type) { + // If the existing timer and the new timer are of different timer type + // (fast or native) or have different delay, we need to clear the existing + // timer and set a new one. + if ( + delay !== this.timeoutValue || + (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER) + ) { + // If a timeout is already set, clear it with clearTimeout of the fast + // timer implementation, as it can clear fast and native timers. + if (this.timeout) { + timers.clearTimeout(this.timeout) + this.timeout = null + } + + if (delay) { + if (type & USE_FAST_TIMER) { + this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this)) + } else { + this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this)) + this.timeout?.unref() + } + } + + this.timeoutValue = delay + } else if (this.timeout) { + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + this.timeoutType = type + } + + resume () { + if (this.socket.destroyed || !this.paused) { + return + } + + assert(this.ptr != null) + assert(currentParser === null) + + this.llhttp.llhttp_resume(this.ptr) + + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + this.paused = false + this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. + this.readMore() + } + + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read() + if (chunk === null) { + break + } + this.execute(chunk) + } + } + + /** + * @param {Buffer} chunk + */ + execute (chunk) { + assert(currentParser === null) + assert(this.ptr != null) + assert(!this.paused) + + const { socket, llhttp } = this + + // Allocate a new buffer if the current buffer is too small. + if (chunk.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr) + } + // Allocate a buffer that is a multiple of 4096 bytes. + currentBufferSize = Math.ceil(chunk.length / 4096) * 4096 + currentBufferPtr = llhttp.malloc(currentBufferSize) + } + + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk) + + // Call `execute` on the wasm parser. + // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, + // and finally the length of bytes to parse. + // The return value is an error code or `constants.ERROR.OK`. + try { + let ret + + try { + currentBufferRef = chunk + currentParser = this + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length) + } finally { + currentParser = null + currentBufferRef = null + } + + if (ret !== constants.ERROR.OK) { + const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr) + + if (ret === constants.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data) + } else if (ret === constants.ERROR.PAUSED) { + this.paused = true + socket.unshift(data) + } else { + const ptr = llhttp.llhttp_get_error_reason(this.ptr) + let message = '' + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) + message = + 'Response does not match the HTTP/1.1 protocol (' + + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + + ')' + } + throw new HTTPParserError(message, constants.ERROR[ret], data) + } + } + } catch (err) { + util.destroy(socket, err) + } + } + + destroy () { + assert(currentParser === null) + assert(this.ptr != null) + + this.llhttp.llhttp_free(this.ptr) + this.ptr = null + + this.timeout && timers.clearTimeout(this.timeout) + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + + this.paused = false + } + + /** + * @param {Buffer} buf + * @returns {0} + */ + onStatus (buf) { + this.statusText = buf.toString() + return 0 + } + + /** + * @returns {0|-1} + */ + onMessageBegin () { + const { socket, client } = this + + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + if (!request) { + return -1 + } + request.onResponseStarted() + + return 0 + } + + /** + * @param {Buffer} buf + * @returns {number} + */ + onHeaderField (buf) { + const len = this.headers.length + + if ((len & 1) === 0) { + this.headers.push(buf) + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + this.trackHeader(buf.length) + + return 0 + } + + /** + * @param {Buffer} buf + * @returns {number} + */ + onHeaderValue (buf) { + let len = this.headers.length + + if ((len & 1) === 1) { + this.headers.push(buf) + len += 1 + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + const key = this.headers[len - 2] + if (key.length === 10) { + const headerName = util.bufferToLowerCasedHeaderName(key) + if (headerName === 'keep-alive') { + this.keepAlive += buf.toString() + } else if (headerName === 'connection') { + this.connection += buf.toString() + } + } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') { + this.contentLength += buf.toString() + } + + this.trackHeader(buf.length) + + return 0 + } + + /** + * @param {number} len + */ + trackHeader (len) { + this.headersSize += len + if (this.headersSize >= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()) + } + } + + /** + * @param {Buffer} head + */ + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this + + assert(upgrade) + assert(client[kSocket] === socket) + assert(!socket.destroyed) + assert(!this.paused) + assert((headers.length & 1) === 0) + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + assert(request.upgrade || request.method === 'CONNECT') + + this.statusCode = 0 + this.statusText = '' + this.shouldKeepAlive = false + + this.headers = [] + this.headersSize = 0 + + socket.unshift(head) + + socket[kParser].destroy() + socket[kParser] = null + + socket[kClient] = null + socket[kError] = null + + removeAllListeners(socket) + + client[kSocket] = null + client[kHTTPContext] = null // TODO (fix): This is hacky... + client[kQueue][client[kRunningIdx]++] = null + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) + + try { + request.onUpgrade(statusCode, headers, socket) + } catch (err) { + util.destroy(socket, err) + } + + client[kResume]() + } + + /** + * @param {number} statusCode + * @param {boolean} upgrade + * @param {boolean} shouldKeepAlive + * @returns {number} + */ + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this + + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + + if (!request) { + return -1 + } + + assert(!this.upgrade) + assert(this.statusCode < 200) + + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) + return -1 + } + + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) + return -1 + } + + assert(this.timeoutType === TIMEOUT_HEADERS) + + this.statusCode = statusCode + this.shouldKeepAlive = ( + shouldKeepAlive || + // Override llhttp value which does not allow keepAlive for HEAD. + (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') + ) + + if (this.statusCode >= 200) { + const bodyTimeout = request.bodyTimeout != null + ? request.bodyTimeout + : client[kBodyTimeout] + this.setTimeout(bodyTimeout, TIMEOUT_BODY) + } else if (this.timeout) { + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + if (upgrade) { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + assert((this.headers.length & 1) === 0) + this.headers = [] + this.headersSize = 0 + + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null + + if (keepAliveTimeout != null) { + const timeout = Math.min( + keepAliveTimeout - client[kKeepAliveTimeoutThreshold], + client[kKeepAliveMaxTimeout] + ) + if (timeout <= 0) { + socket[kReset] = true + } else { + client[kKeepAliveTimeoutValue] = timeout + } + } else { + client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] + } + } else { + // Stop more requests from being dispatched. + socket[kReset] = true + } + + const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false + + if (request.aborted) { + return -1 + } + + if (request.method === 'HEAD') { + return 1 + } + + if (statusCode < 200) { + return 1 + } + + if (socket[kBlocking]) { + socket[kBlocking] = false + client[kResume]() + } + + return pause ? constants.ERROR.PAUSED : 0 + } + + /** + * @param {Buffer} buf + * @returns {number} + */ + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this + + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + assert(statusCode >= 200) + + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()) + return -1 + } + + this.bytesRead += buf.length + + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED + } + + return 0 + } + + /** + * @returns {number} + */ + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this + + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } + + if (upgrade) { + return 0 + } + + assert(statusCode >= 100) + assert((this.headers.length & 1) === 0) + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + this.statusCode = 0 + this.statusText = '' + this.bytesRead = 0 + this.contentLength = '' + this.keepAlive = '' + this.connection = '' + + this.headers = [] + this.headersSize = 0 + + if (statusCode < 200) { + return 0 + } + + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()) + return -1 + } + + request.onComplete(headers) + + client[kQueue][client[kRunningIdx]++] = null + + if (socket[kWriting]) { + assert(client[kRunning] === 0) + // Response completed before request. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (!shouldKeepAlive) { + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (socket[kReset] && client[kRunning] === 0) { + // Destroy socket once all requests have completed. + // The request at the tail of the pipeline is the one + // that requested reset and no further requests should + // have been queued since then. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (client[kPipelining] == null || client[kPipelining] === 1) { + // We must wait a full event loop cycle to reuse this socket to make sure + // that non-spec compliant servers are not closing the connection even if they + // said they won't. + setImmediate(client[kResume]) + } else { + client[kResume]() + } + + return 0 + } +} + +function onParserTimeout (parser) { + const { socket, timeoutType, client, paused } = parser.deref() + + if (timeoutType === TIMEOUT_HEADERS) { + if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { + assert(!paused, 'cannot be paused while waiting for headers') + util.destroy(socket, new HeadersTimeoutError()) + } + } else if (timeoutType === TIMEOUT_BODY) { + if (!paused) { + util.destroy(socket, new BodyTimeoutError()) + } + } else if (timeoutType === TIMEOUT_KEEP_ALIVE) { + assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) + util.destroy(socket, new InformationalError('socket idle timeout')) + } +} + +/** + * @param {import ('./client.js')} client + * @param {import('net').Socket} socket + * @returns + */ +function connectH1 (client, socket) { + client[kSocket] = socket + + if (!llhttpInstance) { + llhttpInstance = lazyllhttp() + } + + if (socket.errored) { + throw socket.errored + } + + if (socket.destroyed) { + throw new SocketError('destroyed') + } + + socket[kNoRef] = false + socket[kWriting] = false + socket[kReset] = false + socket[kBlocking] = false + socket[kParser] = new Parser(client, socket, llhttpInstance) + + util.addListener(socket, 'error', onHttpSocketError) + util.addListener(socket, 'readable', onHttpSocketReadable) + util.addListener(socket, 'end', onHttpSocketEnd) + util.addListener(socket, 'close', onHttpSocketClose) + + socket[kClosed] = false + socket.on('close', onSocketClose) + + return { + version: 'h1', + defaultPipelining: 1, + write (request) { + return writeH1(client, request) + }, + resume () { + resumeH1(client) + }, + /** + * @param {Error|undefined} err + * @param {() => void} callback + */ + destroy (err, callback) { + if (socket[kClosed]) { + queueMicrotask(callback) + } else { + socket.on('close', callback) + socket.destroy(err) + } + }, + /** + * @returns {boolean} + */ + get destroyed () { + return socket.destroyed + }, + /** + * @param {import('../core/request.js')} request + * @returns {boolean} + */ + busy (request) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return true + } + + if (request) { + if (client[kRunning] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return true + } + + if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { + // Don't dispatch an upgrade until all preceding requests have completed. + // A misbehaving server might upgrade the connection before all pipelined + // request has completed. + return true + } + + if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && + (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) { + // Request with stream or iterator body can error while other requests + // are inflight and indirectly error those as well. + // Ensure this doesn't happen by waiting for inflight + // to complete before dispatching. + + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return true + } + } + + return false + } + } +} + +function onHttpSocketError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + const parser = this[kParser] + + // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded + // to the user. + if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so for as a valid response. + parser.onMessageComplete() + return + } + + this[kError] = err + + this[kClient][kOnError](err) +} + +function onHttpSocketReadable () { + this[kParser]?.readMore() +} + +function onHttpSocketEnd () { + const parser = this[kParser] + + if (parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + return + } + + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} + +function onHttpSocketClose () { + const parser = this[kParser] + + if (parser) { + if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + } + + this[kParser].destroy() + this[kParser] = null + } + + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) + + const client = this[kClient] + + client[kSocket] = null + client[kHTTPContext] = null // TODO (fix): This is hacky... + + if (client.destroyed) { + assert(client[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + util.errorRequest(client, request, err) + } + } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + + util.errorRequest(client, request, err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + + client[kResume]() +} + +function onSocketClose () { + this[kClosed] = true +} + +/** + * @param {import('./client.js')} client + */ +function resumeH1 (client) { + const socket = client[kSocket] + + if (socket && !socket.destroyed) { + if (client[kSize] === 0) { + if (!socket[kNoRef] && socket.unref) { + socket.unref() + socket[kNoRef] = true + } + } else if (socket[kNoRef] && socket.ref) { + socket.ref() + socket[kNoRef] = false + } + + if (client[kSize] === 0) { + if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { + socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE) + } + } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { + if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { + const request = client[kQueue][client[kRunningIdx]] + const headersTimeout = request.headersTimeout != null + ? request.headersTimeout + : client[kHeadersTimeout] + socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) + } + } + } +} + +// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 +function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' +} + +/** + * @param {import('./client.js')} client + * @param {import('../core/request.js')} request + * @returns + */ +function writeH1 (client, request) { + const { method, path, host, upgrade, blocking, reset } = request + + let { body, headers, contentLength } = request + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' || + method === 'QUERY' || + method === 'PROPFIND' || + method === 'PROPPATCH' + ) + + if (util.isFormDataLike(body)) { + if (!extractBody) { + extractBody = require('../web/fetch/body.js').extractBody + } + + const [bodyStream, contentType] = extractBody(body) + if (request.contentType == null) { + headers.push('content-type', contentType) + } + body = bodyStream.stream + contentLength = bodyStream.length + } else if (util.isBlobLike(body) && request.contentType == null && body.type) { + headers.push('content-type', body.type) + } + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + const bodyLength = util.bodyLength(body) + + contentLength = bodyLength ?? contentLength + + if (contentLength === null) { + contentLength = request.contentLength + } + + if (contentLength === 0 && !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + util.errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + const socket = client[kSocket] + + /** + * @param {Error} [err] + * @returns {void} + */ + const abort = (err) => { + if (request.aborted || request.completed) { + return + } + + util.errorRequest(client, request, err || new RequestAbortedError()) + + util.destroy(body) + util.destroy(socket, new InformationalError('aborted')) + } + + try { + request.onConnect(abort) + } catch (err) { + util.errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + if (method === 'HEAD') { + // https://github.com/mcollina/undici/issues/258 + // Close after a HEAD request to interop with misbehaving servers + // that may send a body in the response. + + socket[kReset] = true + } + + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. + + socket[kReset] = true + } + + if (reset != null) { + socket[kReset] = reset + } + + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true + } + + if (blocking) { + socket[kBlocking] = true + } + + let header = `${method} ${path} HTTP/1.1\r\n` + + if (typeof host === 'string') { + header += `host: ${host}\r\n` + } else { + header += client[kHostHeader] + } + + if (upgrade) { + header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` + } else if (client[kPipelining] && !socket[kReset]) { + header += 'connection: keep-alive\r\n' + } else { + header += 'connection: close\r\n' + } + + if (Array.isArray(headers)) { + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0] + const val = headers[n + 1] + + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + header += `${key}: ${val[i]}\r\n` + } + } else { + header += `${key}: ${val}\r\n` + } + } + } + + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }) + } + + if (!body || bodyLength === 0) { + writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload) + } else if (util.isBuffer(body)) { + writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload) + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload) + } else { + writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload) + } + } else if (util.isStream(body)) { + writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload) + } else if (util.isIterable(body)) { + writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload) + } else { + assert(false) + } + + return true +} + +/** + * @param {AbortCallback} abort + * @param {import('stream').Stream} body + * @param {import('./client.js')} client + * @param {import('../core/request.js')} request + * @param {import('net').Socket} socket + * @param {number} contentLength + * @param {string} header + * @param {boolean} expectsPayload + */ +function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') + + let finished = false + + const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }) + + /** + * @param {Buffer} chunk + * @returns {void} + */ + const onData = function (chunk) { + if (finished) { + return + } + + try { + if (!writer.write(chunk) && this.pause) { + this.pause() + } + } catch (err) { + util.destroy(this, err) + } + } + + /** + * @returns {void} + */ + const onDrain = function () { + if (finished) { + return + } + + if (body.resume) { + body.resume() + } + } + + /** + * @returns {void} + */ + const onClose = function () { + // 'close' might be emitted *before* 'error' for + // broken streams. Wait a tick to avoid this case. + queueMicrotask(() => { + // It's only safe to remove 'error' listener after + // 'close'. + body.removeListener('error', onFinished) + }) + + if (!finished) { + const err = new RequestAbortedError() + queueMicrotask(() => onFinished(err)) + } + } + + /** + * @param {Error} [err] + * @returns + */ + const onFinished = function (err) { + if (finished) { + return + } + + finished = true + + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) + + socket + .off('drain', onDrain) + .off('error', onFinished) + + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('close', onClose) + + if (!err) { + try { + writer.end() + } catch (er) { + err = er + } + } + + writer.destroy(err) + + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err) + } else { + util.destroy(body) + } + } + + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onClose) + + if (body.resume) { + body.resume() + } + + socket + .on('drain', onDrain) + .on('error', onFinished) + + if (body.errorEmitted ?? body.errored) { + setImmediate(onFinished, body.errored) + } else if (body.endEmitted ?? body.readableEnded) { + setImmediate(onFinished, null) + } + + if (body.closeEmitted ?? body.closed) { + setImmediate(onClose) + } +} + +/** + * @typedef AbortCallback + * @type {Function} + * @param {Error} [err] + * @returns {void} + */ + +/** + * @param {AbortCallback} abort + * @param {Uint8Array|null} body + * @param {import('./client.js')} client + * @param {import('../core/request.js')} request + * @param {import('net').Socket} socket + * @param {number} contentLength + * @param {string} header + * @param {boolean} expectsPayload + * @returns {void} + */ +function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) { + try { + if (!body) { + if (contentLength === 0) { + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + assert(contentLength === null, 'no body must not have content length') + socket.write(`${header}\r\n`, 'latin1') + } + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(body) + socket.uncork() + request.onBodySent(body) + + if (!expectsPayload && request.reset !== false) { + socket[kReset] = true + } + } + request.onRequestSent() + + client[kResume]() + } catch (err) { + abort(err) + } +} + +/** + * @param {AbortCallback} abort + * @param {Blob} body + * @param {import('./client.js')} client + * @param {import('../core/request.js')} request + * @param {import('net').Socket} socket + * @param {number} contentLength + * @param {string} header + * @param {boolean} expectsPayload + * @returns {Promise} + */ +async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) { + assert(contentLength === body.size, 'blob body must have content length') + + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()) + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(buffer) + socket.uncork() + + request.onBodySent(buffer) + request.onRequestSent() + + if (!expectsPayload && request.reset !== false) { + socket[kReset] = true + } + + client[kResume]() + } catch (err) { + abort(err) + } +} + +/** + * @param {AbortCallback} abort + * @param {Iterable} body + * @param {import('./client.js')} client + * @param {import('../core/request.js')} request + * @param {import('net').Socket} socket + * @param {number} contentLength + * @param {string} header + * @param {boolean} expectsPayload + * @returns {Promise} + */ +async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') + + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) + + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) + + socket + .on('close', onDrain) + .on('drain', onDrain) + + const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }) + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + if (!writer.write(chunk)) { + await waitForDrain() + } + } + + writer.end() + } catch (err) { + writer.destroy(err) + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain) + } +} + +class AsyncWriter { + /** + * + * @param {object} arg + * @param {AbortCallback} arg.abort + * @param {import('net').Socket} arg.socket + * @param {import('../core/request.js')} arg.request + * @param {number} arg.contentLength + * @param {import('./client.js')} arg.client + * @param {boolean} arg.expectsPayload + * @param {string} arg.header + */ + constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) { + this.socket = socket + this.request = request + this.contentLength = contentLength + this.client = client + this.bytesWritten = 0 + this.expectsPayload = expectsPayload + this.header = header + this.abort = abort + + socket[kWriting] = true + } + + /** + * @param {Buffer} chunk + * @returns + */ + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return false + } + + const len = Buffer.byteLength(chunk) + if (!len) { + return true + } + + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + socket.cork() + + if (bytesWritten === 0) { + if (!expectsPayload && request.reset !== false) { + socket[kReset] = true + } + + if (contentLength === null) { + socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') + } else { + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + } + } + + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') + } + + this.bytesWritten += len + + const ret = socket.write(chunk) + + socket.uncork() + + request.onBodySent(chunk) + + if (!ret) { + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + } + + return ret + } + + /** + * @returns {void} + */ + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this + request.onRequestSent() + + socket[kWriting] = false + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return + } + + if (bytesWritten === 0) { + if (expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. + + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + socket.write(`${header}\r\n`, 'latin1') + } + } else if (contentLength === null) { + socket.write('\r\n0\r\n\r\n', 'latin1') + } + + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + process.emitWarning(new RequestContentLengthMismatchError()) + } + } + + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + + client[kResume]() + } + + /** + * @param {Error} [err] + * @returns {void} + */ + destroy (err) { + const { socket, client, abort } = this + + socket[kWriting] = false + + if (err) { + assert(client[kRunning] <= 1, 'pipeline should only contain this request') + abort(err) + } + } +} + +module.exports = connectH1 diff --git a/node_modules/undici/lib/dispatcher/client-h2.js b/node_modules/undici/lib/dispatcher/client-h2.js new file mode 100644 index 000000000..b77c4cffe --- /dev/null +++ b/node_modules/undici/lib/dispatcher/client-h2.js @@ -0,0 +1,959 @@ +'use strict' + +const assert = require('node:assert') +const { pipeline } = require('node:stream') +const util = require('../core/util.js') +const { + RequestContentLengthMismatchError, + RequestAbortedError, + SocketError, + InformationalError, + InvalidArgumentError +} = require('../core/errors.js') +const { + kUrl, + kReset, + kClient, + kRunning, + kPending, + kQueue, + kPendingIdx, + kRunningIdx, + kError, + kSocket, + kStrictContentLength, + kOnError, + kMaxConcurrentStreams, + kHTTP2Session, + kHTTP2InitialWindowSize, + kHTTP2ConnectionWindowSize, + kResume, + kSize, + kHTTPContext, + kClosed, + kBodyTimeout, + kEnableConnectProtocol, + kRemoteSettings, + kHTTP2Stream +} = require('../core/symbols.js') +const { channels } = require('../core/diagnostics.js') + +const kOpenStreams = Symbol('open streams') + +let extractBody + +/** @type {import('http2')} */ +let http2 +try { + http2 = require('node:http2') +} catch { + // @ts-ignore + http2 = { constants: {} } +} + +const { + constants: { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_CONTENT_LENGTH, + HTTP2_HEADER_EXPECT, + HTTP2_HEADER_STATUS, + HTTP2_HEADER_PROTOCOL, + NGHTTP2_REFUSED_STREAM, + NGHTTP2_CANCEL + } +} = http2 + +function parseH2Headers (headers) { + const result = [] + + for (const [name, value] of Object.entries(headers)) { + // h2 may concat the header value by array + // e.g. Set-Cookie + if (Array.isArray(value)) { + for (const subvalue of value) { + // we need to provide each header value of header name + // because the headers handler expect name-value pair + result.push(Buffer.from(name), Buffer.from(subvalue)) + } + } else { + result.push(Buffer.from(name), Buffer.from(value)) + } + } + + return result +} + +function connectH2 (client, socket) { + client[kSocket] = socket + + const http2InitialWindowSize = client[kHTTP2InitialWindowSize] + const http2ConnectionWindowSize = client[kHTTP2ConnectionWindowSize] + + const session = http2.connect(client[kUrl], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kMaxConcurrentStreams], + settings: { + // TODO(metcoder95): add support for PUSH + enablePush: false, + ...(http2InitialWindowSize != null ? { initialWindowSize: http2InitialWindowSize } : null) + } + }) + + session[kOpenStreams] = 0 + session[kClient] = client + session[kSocket] = socket + session[kHTTP2Session] = null + // We set it to true by default in a best-effort; however once connected to an H2 server + // we will check if extended CONNECT protocol is supported or not + // and set this value accordingly. + session[kEnableConnectProtocol] = false + // States whether or not we have received the remote settings from the server + session[kRemoteSettings] = false + + // Apply connection-level flow control once connected (if supported). + if (http2ConnectionWindowSize) { + util.addListener(session, 'connect', applyConnectionWindowSize.bind(session, http2ConnectionWindowSize)) + } + + util.addListener(session, 'error', onHttp2SessionError) + util.addListener(session, 'frameError', onHttp2FrameError) + util.addListener(session, 'end', onHttp2SessionEnd) + util.addListener(session, 'goaway', onHttp2SessionGoAway) + util.addListener(session, 'close', onHttp2SessionClose) + util.addListener(session, 'remoteSettings', onHttp2RemoteSettings) + // TODO (@metcoder95): implement SETTINGS support + // util.addListener(session, 'localSettings', onHttp2RemoteSettings) + + session.unref() + + client[kHTTP2Session] = session + socket[kHTTP2Session] = session + + util.addListener(socket, 'error', onHttp2SocketError) + util.addListener(socket, 'end', onHttp2SocketEnd) + util.addListener(socket, 'close', onHttp2SocketClose) + + socket[kClosed] = false + socket.on('close', onSocketClose) + + return { + version: 'h2', + defaultPipelining: Infinity, + /** + * @param {import('../core/request.js')} request + * @returns {boolean} + */ + write (request) { + return writeH2(client, request) + }, + /** + * @returns {void} + */ + resume () { + resumeH2(client) + }, + /** + * @param {Error | null} err + * @param {() => void} callback + */ + destroy (err, callback) { + if (socket[kClosed]) { + queueMicrotask(callback) + } else { + socket.destroy(err).on('close', callback) + } + }, + /** + * @type {boolean} + */ + get destroyed () { + return socket.destroyed + }, + /** + * @param {import('../core/request.js')} request + * @returns {boolean} + */ + busy (request) { + if (request != null) { + if (client[kRunning] > 0) { + // We are already processing requests + + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + if (request.idempotent === false) return true + // Don't dispatch an upgrade until all preceding requests have completed. + // Possibly, we do not have remote settings confirmed yet. + if ((request.upgrade === 'websocket' || request.method === 'CONNECT') && session[kRemoteSettings] === false) return true + // Request with stream or iterator body can error while other requests + // are inflight and indirectly error those as well. + // Ensure this doesn't happen by waiting for inflight + // to complete before dispatching. + + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + if (util.bodyLength(request.body) !== 0 && + (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) return true + } else { + return (request.upgrade === 'websocket' || request.method === 'CONNECT') && session[kRemoteSettings] === false + } + } + + return false + } + } +} + +function resumeH2 (client) { + const socket = client[kSocket] + + if (socket?.destroyed === false) { + if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) { + socket.unref() + client[kHTTP2Session].unref() + } else { + socket.ref() + client[kHTTP2Session].ref() + } + } +} + +function applyConnectionWindowSize (connectionWindowSize) { + try { + if (typeof this.setLocalWindowSize === 'function') { + this.setLocalWindowSize(connectionWindowSize) + } + } catch { + // Best-effort only. + } +} + +function onHttp2RemoteSettings (settings) { + // Fallbacks are a safe bet, remote setting will always override + this[kClient][kMaxConcurrentStreams] = settings.maxConcurrentStreams ?? this[kClient][kMaxConcurrentStreams] + /** + * From RFC-8441 + * A sender MUST NOT send a SETTINGS_ENABLE_CONNECT_PROTOCOL parameter + * with the value of 0 after previously sending a value of 1. + */ + // Note: Cannot be tested in Node, it does not supports disabling the extended CONNECT protocol once enabled + if (this[kRemoteSettings] === true && this[kEnableConnectProtocol] === true && settings.enableConnectProtocol === false) { + const err = new InformationalError('HTTP/2: Server disabled extended CONNECT protocol against RFC-8441') + this[kSocket][kError] = err + this[kClient][kOnError](err) + return + } + + this[kEnableConnectProtocol] = settings.enableConnectProtocol ?? this[kEnableConnectProtocol] + this[kRemoteSettings] = true + this[kClient][kResume]() +} + +function onHttp2SessionError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + this[kSocket][kError] = err + this[kClient][kOnError](err) +} + +function onHttp2FrameError (type, code, id) { + if (id === 0) { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + this[kSocket][kError] = err + this[kClient][kOnError](err) + } +} + +function onHttp2SessionEnd () { + const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket])) + this.destroy(err) + util.destroy(this[kSocket], err) +} + +/** + * This is the root cause of #3011 + * We need to handle GOAWAY frames properly, and trigger the session close + * along with the socket right away + * + * @this {import('http2').ClientHttp2Session} + * @param {number} errorCode + */ +function onHttp2SessionGoAway (errorCode) { + // TODO(mcollina): Verify if GOAWAY implements the spec correctly: + // https://datatracker.ietf.org/doc/html/rfc7540#section-6.8 + // Specifically, we do not verify the "valid" stream id. + + const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(this[kSocket])) + const client = this[kClient] + + client[kSocket] = null + client[kHTTPContext] = null + + // this is an HTTP2 session + this.close() + this[kHTTP2Session] = null + + util.destroy(this[kSocket], err) + + // Fail head of pipeline. + if (client[kRunningIdx] < client[kQueue].length) { + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + util.errorRequest(client, request, err) + client[kPendingIdx] = client[kRunningIdx] + } + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + client.emit('connectionError', client[kUrl], [client], err) + + client[kResume]() +} + +function onHttp2SessionClose () { + const { [kClient]: client } = this + const { [kSocket]: socket } = client + + const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket)) + + client[kSocket] = null + client[kHTTPContext] = null + + if (client.destroyed) { + assert(client[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + util.errorRequest(client, request, err) + } + } +} + +function onHttp2SocketClose () { + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) + + const client = this[kHTTP2Session][kClient] + + client[kSocket] = null + client[kHTTPContext] = null + + if (this[kHTTP2Session] !== null) { + this[kHTTP2Session].destroy(err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + + client[kResume]() +} + +function onHttp2SocketError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + this[kError] = err + + this[kClient][kOnError](err) +} + +function onHttp2SocketEnd () { + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} + +function onSocketClose () { + this[kClosed] = true +} + +// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 +function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' +} + +function writeH2 (client, request) { + const requestTimeout = request.bodyTimeout ?? client[kBodyTimeout] + const session = client[kHTTP2Session] + const { method, path, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request + let { body } = request + + if (upgrade != null && upgrade !== 'websocket') { + util.errorRequest(client, request, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`)) + return false + } + + const headers = {} + for (let n = 0; n < reqHeaders.length; n += 2) { + const key = reqHeaders[n + 0] + const val = reqHeaders[n + 1] + + if (key === 'cookie') { + if (headers[key] != null) { + headers[key] = Array.isArray(headers[key]) ? (headers[key].push(val), headers[key]) : [headers[key], val] + } else { + headers[key] = val + } + + continue + } + + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + if (headers[key]) { + headers[key] += `, ${val[i]}` + } else { + headers[key] = val[i] + } + } + } else if (headers[key]) { + headers[key] += `, ${val}` + } else { + headers[key] = val + } + } + + /** @type {import('node:http2').ClientHttp2Stream} */ + let stream = null + + const { hostname, port } = client[kUrl] + + headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}` + headers[HTTP2_HEADER_METHOD] = method + + const abort = (err) => { + if (request.aborted || request.completed) { + return + } + + err = err || new RequestAbortedError() + + util.errorRequest(client, request, err) + + if (stream != null) { + // Some chunks might still come after abort, + // let's ignore them + stream.removeAllListeners('data') + + // On Abort, we close the stream to send RST_STREAM frame + stream.close() + + // We move the running index to the next request + client[kOnError](err) + client[kResume]() + } + + // We do not destroy the socket as we can continue using the session + // the stream gets destroyed and the session remains to create new streams + util.destroy(body, err) + } + + try { + // We are already connected, streams are pending. + // We can call on connect, and wait for abort + request.onConnect(abort) + } catch (err) { + util.errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + if (upgrade || method === 'CONNECT') { + session.ref() + + if (upgrade === 'websocket') { + // We cannot upgrade to websocket if extended CONNECT protocol is not supported + if (session[kEnableConnectProtocol] === false) { + util.errorRequest(client, request, new InformationalError('HTTP/2: Extended CONNECT protocol not supported by server')) + session.unref() + return false + } + + // We force the method to CONNECT + // as per RFC-8441 + // https://datatracker.ietf.org/doc/html/rfc8441#section-4 + headers[HTTP2_HEADER_METHOD] = 'CONNECT' + headers[HTTP2_HEADER_PROTOCOL] = 'websocket' + // :path and :scheme headers must be omitted when sending CONNECT but set if extended-CONNECT + headers[HTTP2_HEADER_PATH] = path + + if (protocol === 'ws:' || protocol === 'wss:') { + headers[HTTP2_HEADER_SCHEME] = protocol === 'ws:' ? 'http' : 'https' + } else { + headers[HTTP2_HEADER_SCHEME] = protocol === 'http:' ? 'http' : 'https' + } + + stream = session.request(headers, { endStream: false, signal }) + stream[kHTTP2Stream] = true + + stream.once('response', (headers, _flags) => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers + + request.onUpgrade(statusCode, parseH2Headers(realHeaders), stream) + + ++session[kOpenStreams] + client[kQueue][client[kRunningIdx]++] = null + }) + + stream.on('error', () => { + if (stream.rstCode === NGHTTP2_REFUSED_STREAM || stream.rstCode === NGHTTP2_CANCEL) { + // NGHTTP2_REFUSED_STREAM (7) or NGHTTP2_CANCEL (8) + // We do not treat those as errors as the server might + // not support websockets and refuse the stream + abort(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)) + } + }) + + stream.once('close', () => { + session[kOpenStreams] -= 1 + if (session[kOpenStreams] === 0) session.unref() + }) + + stream.setTimeout(requestTimeout) + return true + } + + // TODO: consolidate once we support CONNECT properly + // NOTE: We are already connected, streams are pending, first request + // will create a new stream. We trigger a request to create the stream and wait until + // `ready` event is triggered + // We disabled endStream to allow the user to write to the stream + stream = session.request(headers, { endStream: false, signal }) + stream[kHTTP2Stream] = true + stream.on('response', headers => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers + + request.onUpgrade(statusCode, parseH2Headers(realHeaders), stream) + ++session[kOpenStreams] + client[kQueue][client[kRunningIdx]++] = null + }) + stream.once('close', () => { + session[kOpenStreams] -= 1 + if (session[kOpenStreams] === 0) session.unref() + }) + stream.setTimeout(requestTimeout) + + return true + } + + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omitted when sending CONNECT + headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_SCHEME] = protocol === 'http:' ? 'http' : 'https' + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + let contentLength = util.bodyLength(body) + + if (util.isFormDataLike(body)) { + extractBody ??= require('../web/fetch/body.js').extractBody + + const [bodyStream, contentType] = extractBody(body) + headers['content-type'] = contentType + + body = bodyStream.stream + contentLength = bodyStream.length + } + + if (contentLength == null) { + contentLength = request.contentLength + } + + if (!expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + // And for methods that don't expect a payload, omit Content-Length. + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + util.errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + if (contentLength != null) { + assert(body || contentLength === 0, 'no body must not have content length') + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` + } + + session.ref() + + if (channels.sendHeaders.hasSubscribers) { + let header = '' + for (const key in headers) { + header += `${key}: ${headers[key]}\r\n` + } + channels.sendHeaders.publish({ request, headers: header, socket: session[kSocket] }) + } + + // TODO(metcoder95): add support for sending trailers + const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null + if (expectContinue) { + headers[HTTP2_HEADER_EXPECT] = '100-continue' + stream = session.request(headers, { endStream: shouldEndStream, signal }) + stream[kHTTP2Stream] = true + + stream.once('continue', writeBodyH2) + } else { + stream = session.request(headers, { + endStream: shouldEndStream, + signal + }) + stream[kHTTP2Stream] = true + + writeBodyH2() + } + + // Increment counter as we have new streams open + ++session[kOpenStreams] + stream.setTimeout(requestTimeout) + + stream.once('response', headers => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers + request.onResponseStarted() + + // Due to the stream nature, it is possible we face a race condition + // where the stream has been assigned, but the request has been aborted + // the request remains in-flight and headers hasn't been received yet + // for those scenarios, best effort is to destroy the stream immediately + // as there's no value to keep it open. + if (request.aborted) { + stream.removeAllListeners('data') + return + } + + if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) { + stream.pause() + } + }) + + stream.on('data', (chunk) => { + if (request.onData(chunk) === false) { + stream.pause() + } + }) + + stream.once('end', (err) => { + stream.removeAllListeners('data') + // When state is null, it means we haven't consumed body and the stream still do not have + // a state. + // Present specially when using pipeline or stream + if (stream.state?.state == null || stream.state.state < 6) { + // Do not complete the request if it was aborted + // Not prone to happen for as safety net to avoid race conditions with 'trailers' + if (!request.aborted && !request.completed) { + request.onComplete({}) + } + + client[kQueue][client[kRunningIdx]++] = null + client[kResume]() + } else { + // Stream is closed or half-closed-remote (6), decrement counter and cleanup + // It does not have sense to continue working with the stream as we do not + // have yet RST_STREAM support on client-side + --session[kOpenStreams] + if (session[kOpenStreams] === 0) { + session.unref() + } + + abort(err ?? new InformationalError('HTTP/2: stream half-closed (remote)')) + client[kQueue][client[kRunningIdx]++] = null + client[kPendingIdx] = client[kRunningIdx] + client[kResume]() + } + }) + + stream.once('close', () => { + stream.removeAllListeners('data') + session[kOpenStreams] -= 1 + if (session[kOpenStreams] === 0) { + session.unref() + } + }) + + stream.once('error', function (err) { + stream.removeAllListeners('data') + abort(err) + }) + + stream.once('frameError', (type, code) => { + stream.removeAllListeners('data') + abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)) + }) + + stream.on('aborted', () => { + stream.removeAllListeners('data') + }) + + stream.on('timeout', () => { + const err = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`) + stream.removeAllListeners('data') + session[kOpenStreams] -= 1 + + if (session[kOpenStreams] === 0) { + session.unref() + } + + abort(err) + }) + + stream.once('trailers', trailers => { + if (request.aborted || request.completed) { + return + } + + request.onComplete(trailers) + }) + + return true + + function writeBodyH2 () { + if (!body || contentLength === 0) { + writeBuffer( + abort, + stream, + null, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } else if (util.isBuffer(body)) { + writeBuffer( + abort, + stream, + body, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable( + abort, + stream, + body.stream(), + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } else { + writeBlob( + abort, + stream, + body, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } + } else if (util.isStream(body)) { + writeStream( + abort, + client[kSocket], + expectsPayload, + stream, + body, + client, + request, + contentLength + ) + } else if (util.isIterable(body)) { + writeIterable( + abort, + stream, + body, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } else { + assert(false) + } + } +} + +function writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { + try { + if (body != null && util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + h2stream.cork() + h2stream.write(body) + h2stream.uncork() + h2stream.end() + + request.onBodySent(body) + } + + if (!expectsPayload) { + socket[kReset] = true + } + + request.onRequestSent() + client[kResume]() + } catch (error) { + abort(error) + } +} + +function writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') + + // For HTTP/2, is enough to pipe the stream + const pipe = pipeline( + body, + h2stream, + (err) => { + if (err) { + util.destroy(pipe, err) + abort(err) + } else { + util.removeAllListeners(pipe) + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + client[kResume]() + } + } + ) + + util.addListener(pipe, 'data', onPipeData) + + function onPipeData (chunk) { + request.onBodySent(chunk) + } +} + +async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { + assert(contentLength === body.size, 'blob body must have content length') + + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()) + + h2stream.cork() + h2stream.write(buffer) + h2stream.uncork() + h2stream.end() + + request.onBodySent(buffer) + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + client[kResume]() + } catch (err) { + abort(err) + } +} + +async function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') + + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) + + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) + + h2stream + .on('close', onDrain) + .on('drain', onDrain) + + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + const res = h2stream.write(chunk) + request.onBodySent(chunk) + if (!res) { + await waitForDrain() + } + } + + h2stream.end() + + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + client[kResume]() + } catch (err) { + abort(err) + } finally { + h2stream + .off('close', onDrain) + .off('drain', onDrain) + } +} + +module.exports = connectH2 diff --git a/node_modules/undici/lib/dispatcher/client.js b/node_modules/undici/lib/dispatcher/client.js new file mode 100644 index 000000000..e603cfebd --- /dev/null +++ b/node_modules/undici/lib/dispatcher/client.js @@ -0,0 +1,639 @@ +'use strict' + +const assert = require('node:assert') +const net = require('node:net') +const http = require('node:http') +const util = require('../core/util.js') +const { ClientStats } = require('../util/stats.js') +const { channels } = require('../core/diagnostics.js') +const Request = require('../core/request.js') +const DispatcherBase = require('./dispatcher-base') +const { + InvalidArgumentError, + InformationalError, + ClientDestroyedError +} = require('../core/errors.js') +const buildConnector = require('../core/connect.js') +const { + kUrl, + kServerName, + kClient, + kBusy, + kConnect, + kResuming, + kRunning, + kPending, + kSize, + kQueue, + kConnected, + kConnecting, + kNeedDrain, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kConnector, + kMaxRequests, + kCounter, + kClose, + kDestroy, + kDispatch, + kLocalAddress, + kMaxResponseSize, + kOnError, + kHTTPContext, + kMaxConcurrentStreams, + kHTTP2InitialWindowSize, + kHTTP2ConnectionWindowSize, + kResume +} = require('../core/symbols.js') +const connectH1 = require('./client-h1.js') +const connectH2 = require('./client-h2.js') + +const kClosedResolve = Symbol('kClosedResolve') + +const getDefaultNodeMaxHeaderSize = http && + http.maxHeaderSize && + Number.isInteger(http.maxHeaderSize) && + http.maxHeaderSize > 0 + ? () => http.maxHeaderSize + : () => { throw new InvalidArgumentError('http module not available or http.maxHeaderSize invalid') } + +const noop = () => {} + +function getPipelining (client) { + return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1 +} + +/** + * @type {import('../../types/client.js').default} + */ +class Client extends DispatcherBase { + /** + * + * @param {string|URL} url + * @param {import('../../types/client.js').Client.Options} options + */ + constructor (url, { + maxHeaderSize, + headersTimeout, + socketTimeout, + requestTimeout, + connectTimeout, + bodyTimeout, + idleTimeout, + keepAlive, + keepAliveTimeout, + maxKeepAliveTimeout, + keepAliveMaxTimeout, + keepAliveTimeoutThreshold, + socketPath, + pipelining, + tls, + strictContentLength, + maxCachedSessions, + connect, + maxRequestsPerClient, + localAddress, + maxResponseSize, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + // h2 + maxConcurrentStreams, + allowH2, + useH2c, + initialWindowSize, + connectionWindowSize + } = {}) { + if (keepAlive !== undefined) { + throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') + } + + if (socketTimeout !== undefined) { + throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + } + + if (requestTimeout !== undefined) { + throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + } + + if (idleTimeout !== undefined) { + throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') + } + + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') + } + + if (maxHeaderSize != null) { + if (!Number.isInteger(maxHeaderSize) || maxHeaderSize < 1) { + throw new InvalidArgumentError('invalid maxHeaderSize') + } + } else { + // If maxHeaderSize is not provided, use the default value from the http module + // or if that is not available, throw an error. + maxHeaderSize = getDefaultNodeMaxHeaderSize() + } + + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') + } + + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') + } + + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } + + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } + + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') + } + + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') + } + + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') + } + + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') + } + + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') + } + + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } + + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError('allowH2 must be a valid boolean value') + } + + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0') + } + + if (useH2c != null && typeof useH2c !== 'boolean') { + throw new InvalidArgumentError('useH2c must be a valid boolean value') + } + + if (initialWindowSize != null && (!Number.isInteger(initialWindowSize) || initialWindowSize < 1)) { + throw new InvalidArgumentError('initialWindowSize must be a positive integer, greater than 0') + } + + if (connectionWindowSize != null && (!Number.isInteger(connectionWindowSize) || connectionWindowSize < 1)) { + throw new InvalidArgumentError('connectionWindowSize must be a positive integer, greater than 0') + } + + super() + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + useH2c, + socketPath, + timeout: connectTimeout, + ...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + this[kUrl] = util.parseOrigin(url) + this[kConnector] = connect + this[kPipelining] = pipelining != null ? pipelining : 1 + this[kMaxHeadersSize] = maxHeaderSize + this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout + this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout + this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold + this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] + this[kServerName] = null + this[kLocalAddress] = localAddress != null ? localAddress : null + this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` + this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 + this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 + this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength + this[kMaxRequests] = maxRequestsPerClient + this[kClosedResolve] = null + this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 + this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server + // HTTP/2 window sizes are set to higher defaults than Node.js core for better performance: + // - initialWindowSize: 262144 (256KB) vs Node.js default 65535 (64KB - 1) + // Allows more data to be sent before requiring acknowledgment, improving throughput + // especially on high-latency networks. This matches common production HTTP/2 servers. + // - connectionWindowSize: 524288 (512KB) vs Node.js default (none set) + // Provides better flow control for the entire connection across multiple streams. + this[kHTTP2InitialWindowSize] = initialWindowSize != null ? initialWindowSize : 262144 + this[kHTTP2ConnectionWindowSize] = connectionWindowSize != null ? connectionWindowSize : 524288 + this[kHTTPContext] = null + + // kQueue is built up of 3 sections separated by + // the kRunningIdx and kPendingIdx indices. + // | complete | running | pending | + // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length + // kRunningIdx points to the first running element. + // kPendingIdx points to the first pending element. + // This implements a fast queue with an amortized + // time of O(1). + + this[kQueue] = [] + this[kRunningIdx] = 0 + this[kPendingIdx] = 0 + + this[kResume] = (sync) => resume(this, sync) + this[kOnError] = (err) => onError(this, err) + } + + get pipelining () { + return this[kPipelining] + } + + set pipelining (value) { + this[kPipelining] = value + this[kResume](true) + } + + get stats () { + return new ClientStats(this) + } + + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] + } + + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] + } + + get [kSize] () { + return this[kQueue].length - this[kRunningIdx] + } + + get [kConnected] () { + return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed + } + + get [kBusy] () { + return Boolean( + this[kHTTPContext]?.busy(null) || + (this[kSize] >= (getPipelining(this) || 1)) || + this[kPending] > 0 + ) + } + + [kConnect] (cb) { + connect(this) + this.once('connect', cb) + } + + [kDispatch] (opts, handler) { + const request = new Request(this[kUrl].origin, opts, handler) + + this[kQueue].push(request) + if (this[kResuming]) { + // Do nothing. + } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { + // Wait a tick in case stream/iterator is ended in the same tick. + this[kResuming] = 1 + queueMicrotask(() => resume(this)) + } else { + this[kResume](true) + } + + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2 + } + + return this[kNeedDrain] < 2 + } + + [kClose] () { + // TODO: for H2 we need to gracefully flush the remaining enqueued + // request and close each stream. + return new Promise((resolve) => { + if (this[kSize]) { + this[kClosedResolve] = resolve + } else { + resolve(null) + } + }) + } + + [kDestroy] (err) { + return new Promise((resolve) => { + const requests = this[kQueue].splice(this[kPendingIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + util.errorRequest(this, request, err) + } + + const callback = () => { + if (this[kClosedResolve]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve]() + this[kClosedResolve] = null + } + resolve(null) + } + + if (this[kHTTPContext]) { + this[kHTTPContext].destroy(err, callback) + this[kHTTPContext] = null + } else { + queueMicrotask(callback) + } + + this[kResume]() + }) + } +} + +function onError (client, err) { + if ( + client[kRunning] === 0 && + err.code !== 'UND_ERR_INFO' && + err.code !== 'UND_ERR_SOCKET' + ) { + // Error is not caused by running request and not a recoverable + // socket error. + + assert(client[kPendingIdx] === client[kRunningIdx]) + + const requests = client[kQueue].splice(client[kRunningIdx]) + + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + util.errorRequest(client, request, err) + } + assert(client[kSize] === 0) + } +} + +/** + * @param {Client} client + * @returns {void} + */ +function connect (client) { + assert(!client[kConnecting]) + assert(!client[kHTTPContext]) + + let { host, hostname, protocol, port } = client[kUrl] + + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']') + + assert(idx !== -1) + const ip = hostname.substring(1, idx) + + assert(net.isIPv6(ip)) + hostname = ip + } + + client[kConnecting] = true + + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }) + } + + client[kConnector]({ + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, (err, socket) => { + if (err) { + handleConnectError(client, err, { host, hostname, protocol, port }) + client[kResume]() + return + } + + if (client.destroyed) { + util.destroy(socket.on('error', noop), new ClientDestroyedError()) + client[kResume]() + return + } + + assert(socket) + + try { + client[kHTTPContext] = socket.alpnProtocol === 'h2' + ? connectH2(client, socket) + : connectH1(client, socket) + } catch (err) { + socket.destroy().on('error', noop) + handleConnectError(client, err, { host, hostname, protocol, port }) + client[kResume]() + return + } + + client[kConnecting] = false + + socket[kCounter] = 0 + socket[kMaxRequests] = client[kMaxRequests] + socket[kClient] = client + socket[kError] = null + + if (channels.connected.hasSubscribers) { + channels.connected.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + socket + }) + } + + client.emit('connect', client[kUrl], [client]) + client[kResume]() + }) +} + +function handleConnectError (client, err, { host, hostname, protocol, port }) { + if (client.destroyed) { + return + } + + client[kConnecting] = false + + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }) + } + + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + assert(client[kRunning] === 0) + while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { + const request = client[kQueue][client[kPendingIdx]++] + util.errorRequest(client, request, err) + } + } else { + onError(client, err) + } + + client.emit('connectionError', client[kUrl], [client], err) +} + +function emitDrain (client) { + client[kNeedDrain] = 0 + client.emit('drain', client[kUrl], [client]) +} + +function resume (client, sync) { + if (client[kResuming] === 2) { + return + } + + client[kResuming] = 2 + + _resume(client, sync) + client[kResuming] = 0 + + if (client[kRunningIdx] > 256) { + client[kQueue].splice(0, client[kRunningIdx]) + client[kPendingIdx] -= client[kRunningIdx] + client[kRunningIdx] = 0 + } +} + +function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0) + return + } + + if (client[kClosedResolve] && !client[kSize]) { + client[kClosedResolve]() + client[kClosedResolve] = null + return + } + + if (client[kHTTPContext]) { + client[kHTTPContext].resume() + } + + if (client[kBusy]) { + client[kNeedDrain] = 2 + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1 + queueMicrotask(() => emitDrain(client)) + } else { + emitDrain(client) + } + continue + } + + if (client[kPending] === 0) { + return + } + + if (client[kRunning] >= (getPipelining(client) || 1)) { + return + } + + const request = client[kQueue][client[kPendingIdx]] + + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return + } + + client[kServerName] = request.servername + client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => { + client[kHTTPContext] = null + resume(client) + }) + } + + if (client[kConnecting]) { + return + } + + if (!client[kHTTPContext]) { + connect(client) + return + } + + if (client[kHTTPContext].destroyed) { + return + } + + if (client[kHTTPContext].busy(request)) { + return + } + + if (!request.aborted && client[kHTTPContext].write(request)) { + client[kPendingIdx]++ + } else { + client[kQueue].splice(client[kPendingIdx], 1) + } + } +} + +module.exports = Client diff --git a/node_modules/undici/lib/dispatcher/dispatcher-base.js b/node_modules/undici/lib/dispatcher/dispatcher-base.js new file mode 100644 index 000000000..a6f471002 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/dispatcher-base.js @@ -0,0 +1,165 @@ +'use strict' + +const Dispatcher = require('./dispatcher') +const UnwrapHandler = require('../handler/unwrap-handler') +const { + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError +} = require('../core/errors') +const { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require('../core/symbols') + +const kOnDestroyed = Symbol('onDestroyed') +const kOnClosed = Symbol('onClosed') + +class DispatcherBase extends Dispatcher { + /** @type {boolean} */ + [kDestroyed] = false; + + /** @type {Array|null} */ + [kOnClosed] = null + + /** @returns {boolean} */ + get destroyed () { + return this[kDestroyed] + } + + /** @returns {boolean} */ + get closed () { + return this[kClosed] + } + + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + const err = new ClientDestroyedError() + queueMicrotask(() => callback(err, null)) + return + } + + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + this[kClosed] = true + this[kOnClosed] ??= [] + this[kOnClosed].push(callback) + + const onClosed = () => { + const callbacks = this[kOnClosed] + this[kOnClosed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kClose]() + .then(() => this.destroy()) + .then(() => queueMicrotask(onClosed)) + } + + destroy (err, callback) { + if (typeof err === 'function') { + callback = err + err = null + } + + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.destroy(err, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + if (!err) { + err = new ClientDestroyedError() + } + + this[kDestroyed] = true + this[kOnDestroyed] ??= [] + this[kOnDestroyed].push(callback) + + const onDestroyed = () => { + const callbacks = this[kOnDestroyed] + this[kOnDestroyed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kDestroy](err) + .then(() => queueMicrotask(onDestroyed)) + } + + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + handler = UnwrapHandler.unwrap(handler) + + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } + + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError() + } + + if (this[kClosed]) { + throw new ClientClosedError() + } + + return this[kDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw err + } + + handler.onError(err) + + return false + } + } +} + +module.exports = DispatcherBase diff --git a/node_modules/undici/lib/dispatcher/dispatcher.js b/node_modules/undici/lib/dispatcher/dispatcher.js new file mode 100644 index 000000000..824dfb6d8 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/dispatcher.js @@ -0,0 +1,48 @@ +'use strict' +const EventEmitter = require('node:events') +const WrapHandler = require('../handler/wrap-handler') + +const wrapInterceptor = (dispatch) => (opts, handler) => dispatch(opts, WrapHandler.wrap(handler)) + +class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') + } + + close () { + throw new Error('not implemented') + } + + destroy () { + throw new Error('not implemented') + } + + compose (...args) { + // So we handle [interceptor1, interceptor2] or interceptor1, interceptor2, ... + const interceptors = Array.isArray(args[0]) ? args[0] : args + let dispatch = this.dispatch.bind(this) + + for (const interceptor of interceptors) { + if (interceptor == null) { + continue + } + + if (typeof interceptor !== 'function') { + throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`) + } + + dispatch = interceptor(dispatch) + dispatch = wrapInterceptor(dispatch) + + if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) { + throw new TypeError('invalid interceptor') + } + } + + return new Proxy(this, { + get: (target, key) => key === 'dispatch' ? dispatch : target[key] + }) + } +} + +module.exports = Dispatcher diff --git a/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js b/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js new file mode 100644 index 000000000..018bc6ce2 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js @@ -0,0 +1,147 @@ +'use strict' + +const DispatcherBase = require('./dispatcher-base') +const { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require('../core/symbols') +const ProxyAgent = require('./proxy-agent') +const Agent = require('./agent') + +const DEFAULT_PORTS = { + 'http:': 80, + 'https:': 443 +} + +class EnvHttpProxyAgent extends DispatcherBase { + #noProxyValue = null + #noProxyEntries = null + #opts = null + + constructor (opts = {}) { + super() + this.#opts = opts + + const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts + + this[kNoProxyAgent] = new Agent(agentOpts) + + const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY + if (HTTP_PROXY) { + this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY }) + } else { + this[kHttpProxyAgent] = this[kNoProxyAgent] + } + + const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY + if (HTTPS_PROXY) { + this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY }) + } else { + this[kHttpsProxyAgent] = this[kHttpProxyAgent] + } + + this.#parseNoProxy() + } + + [kDispatch] (opts, handler) { + const url = new URL(opts.origin) + const agent = this.#getProxyAgentForUrl(url) + return agent.dispatch(opts, handler) + } + + [kClose] () { + return Promise.all([ + this[kNoProxyAgent].close(), + !this[kHttpProxyAgent][kClosed] && this[kHttpProxyAgent].close(), + !this[kHttpsProxyAgent][kClosed] && this[kHttpsProxyAgent].close() + ]) + } + + [kDestroy] (err) { + return Promise.all([ + this[kNoProxyAgent].destroy(err), + !this[kHttpProxyAgent][kDestroyed] && this[kHttpProxyAgent].destroy(err), + !this[kHttpsProxyAgent][kDestroyed] && this[kHttpsProxyAgent].destroy(err) + ]) + } + + #getProxyAgentForUrl (url) { + let { protocol, host: hostname, port } = url + + // Stripping ports in this way instead of using parsedUrl.hostname to make + // sure that the brackets around IPv6 addresses are kept. + hostname = hostname.replace(/:\d*$/, '').toLowerCase() + port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0 + if (!this.#shouldProxy(hostname, port)) { + return this[kNoProxyAgent] + } + if (protocol === 'https:') { + return this[kHttpsProxyAgent] + } + return this[kHttpProxyAgent] + } + + #shouldProxy (hostname, port) { + if (this.#noProxyChanged) { + this.#parseNoProxy() + } + + if (this.#noProxyEntries.length === 0) { + return true // Always proxy if NO_PROXY is not set or empty. + } + if (this.#noProxyValue === '*') { + return false // Never proxy if wildcard is set. + } + + for (let i = 0; i < this.#noProxyEntries.length; i++) { + const entry = this.#noProxyEntries[i] + if (entry.port && entry.port !== port) { + continue // Skip if ports don't match. + } + if (!/^[.*]/.test(entry.hostname)) { + // No wildcards, so don't proxy only if there is not an exact match. + if (hostname === entry.hostname) { + return false + } + } else { + // Don't proxy if the hostname ends with the no_proxy host. + if (hostname.endsWith(entry.hostname.replace(/^\*/, ''))) { + return false + } + } + } + + return true + } + + #parseNoProxy () { + const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv + const noProxySplit = noProxyValue.split(/[,\s]/) + const noProxyEntries = [] + + for (let i = 0; i < noProxySplit.length; i++) { + const entry = noProxySplit[i] + if (!entry) { + continue + } + const parsed = entry.match(/^(.+):(\d+)$/) + noProxyEntries.push({ + hostname: (parsed ? parsed[1] : entry).toLowerCase(), + port: parsed ? Number.parseInt(parsed[2], 10) : 0 + }) + } + + this.#noProxyValue = noProxyValue + this.#noProxyEntries = noProxyEntries + } + + get #noProxyChanged () { + if (this.#opts.noProxy !== undefined) { + return false + } + return this.#noProxyValue !== this.#noProxyEnv + } + + get #noProxyEnv () { + return process.env.no_proxy ?? process.env.NO_PROXY ?? '' + } +} + +module.exports = EnvHttpProxyAgent diff --git a/node_modules/undici/lib/dispatcher/fixed-queue.js b/node_modules/undici/lib/dispatcher/fixed-queue.js new file mode 100644 index 000000000..f918849c4 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/fixed-queue.js @@ -0,0 +1,135 @@ +'use strict' + +// Extracted from node/lib/internal/fixed_queue.js + +// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. +const kSize = 2048 +const kMask = kSize - 1 + +// The FixedQueue is implemented as a singly-linked list of fixed-size +// circular buffers. It looks something like this: +// +// head tail +// | | +// v v +// +-----------+ <-----\ +-----------+ <------\ +-----------+ +// | [null] | \----- | next | \------- | next | +// +-----------+ +-----------+ +-----------+ +// | item | <-- bottom | item | <-- bottom | undefined | +// | item | | item | | undefined | +// | item | | item | | undefined | +// | item | | item | | undefined | +// | item | | item | bottom --> | item | +// | item | | item | | item | +// | ... | | ... | | ... | +// | item | | item | | item | +// | item | | item | | item | +// | undefined | <-- top | item | | item | +// | undefined | | item | | item | +// | undefined | | undefined | <-- top top --> | undefined | +// +-----------+ +-----------+ +-----------+ +// +// Or, if there is only one circular buffer, it looks something +// like either of these: +// +// head tail head tail +// | | | | +// v v v v +// +-----------+ +-----------+ +// | [null] | | [null] | +// +-----------+ +-----------+ +// | undefined | | item | +// | undefined | | item | +// | item | <-- bottom top --> | undefined | +// | item | | undefined | +// | undefined | <-- top bottom --> | item | +// | undefined | | item | +// +-----------+ +-----------+ +// +// Adding a value means moving `top` forward by one, removing means +// moving `bottom` forward by one. After reaching the end, the queue +// wraps around. +// +// When `top === bottom` the current queue is empty and when +// `top + 1 === bottom` it's full. This wastes a single space of storage +// but allows much quicker checks. + +/** + * @type {FixedCircularBuffer} + * @template T + */ +class FixedCircularBuffer { + /** @type {number} */ + bottom = 0 + /** @type {number} */ + top = 0 + /** @type {Array} */ + list = new Array(kSize).fill(undefined) + /** @type {T|null} */ + next = null + + /** @returns {boolean} */ + isEmpty () { + return this.top === this.bottom + } + + /** @returns {boolean} */ + isFull () { + return ((this.top + 1) & kMask) === this.bottom + } + + /** + * @param {T} data + * @returns {void} + */ + push (data) { + this.list[this.top] = data + this.top = (this.top + 1) & kMask + } + + /** @returns {T|null} */ + shift () { + const nextItem = this.list[this.bottom] + if (nextItem === undefined) { return null } + this.list[this.bottom] = undefined + this.bottom = (this.bottom + 1) & kMask + return nextItem + } +} + +/** + * @template T + */ +module.exports = class FixedQueue { + constructor () { + /** @type {FixedCircularBuffer} */ + this.head = this.tail = new FixedCircularBuffer() + } + + /** @returns {boolean} */ + isEmpty () { + return this.head.isEmpty() + } + + /** @param {T} data */ + push (data) { + if (this.head.isFull()) { + // Head is full: Creates a new queue, sets the old queue's `.next` to it, + // and sets it as the new main queue. + this.head = this.head.next = new FixedCircularBuffer() + } + this.head.push(data) + } + + /** @returns {T|null} */ + shift () { + const tail = this.tail + const next = tail.shift() + if (tail.isEmpty() && tail.next !== null) { + // If there is another queue, it forms the new tail. + this.tail = tail.next + tail.next = null + } + return next + } +} diff --git a/node_modules/undici/lib/dispatcher/h2c-client.js b/node_modules/undici/lib/dispatcher/h2c-client.js new file mode 100644 index 000000000..bd385225e --- /dev/null +++ b/node_modules/undici/lib/dispatcher/h2c-client.js @@ -0,0 +1,51 @@ +'use strict' + +const { InvalidArgumentError } = require('../core/errors') +const Client = require('./client') + +class H2CClient extends Client { + constructor (origin, clientOpts) { + if (typeof origin === 'string') { + origin = new URL(origin) + } + + if (origin.protocol !== 'http:') { + throw new InvalidArgumentError( + 'h2c-client: Only h2c protocol is supported' + ) + } + + const { connect, maxConcurrentStreams, pipelining, ...opts } = + clientOpts ?? {} + let defaultMaxConcurrentStreams = 100 + let defaultPipelining = 100 + + if ( + maxConcurrentStreams != null && + Number.isInteger(maxConcurrentStreams) && + maxConcurrentStreams > 0 + ) { + defaultMaxConcurrentStreams = maxConcurrentStreams + } + + if (pipelining != null && Number.isInteger(pipelining) && pipelining > 0) { + defaultPipelining = pipelining + } + + if (defaultPipelining > defaultMaxConcurrentStreams) { + throw new InvalidArgumentError( + 'h2c-client: pipelining cannot be greater than maxConcurrentStreams' + ) + } + + super(origin, { + ...opts, + maxConcurrentStreams: defaultMaxConcurrentStreams, + pipelining: defaultPipelining, + allowH2: true, + useH2c: true + }) + } +} + +module.exports = H2CClient diff --git a/node_modules/undici/lib/dispatcher/pool-base.js b/node_modules/undici/lib/dispatcher/pool-base.js new file mode 100644 index 000000000..4de14f920 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/pool-base.js @@ -0,0 +1,208 @@ +'use strict' + +const { PoolStats } = require('../util/stats.js') +const DispatcherBase = require('./dispatcher-base') +const FixedQueue = require('./fixed-queue') +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('../core/symbols') + +const kClients = Symbol('clients') +const kNeedDrain = Symbol('needDrain') +const kQueue = Symbol('queue') +const kClosedResolve = Symbol('closed resolve') +const kOnDrain = Symbol('onDrain') +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kGetDispatcher = Symbol('get dispatcher') +const kAddClient = Symbol('add client') +const kRemoveClient = Symbol('remove client') + +class PoolBase extends DispatcherBase { + [kQueue] = new FixedQueue(); + + [kQueued] = 0; + + [kClients] = []; + + [kNeedDrain] = false; + + [kOnDrain] (client, origin, targets) { + const queue = this[kQueue] + + let needDrain = false + + while (!needDrain) { + const item = queue.shift() + if (!item) { + break + } + this[kQueued]-- + needDrain = !client.dispatch(item.opts, item.handler) + } + + client[kNeedDrain] = needDrain + + if (!needDrain && this[kNeedDrain]) { + this[kNeedDrain] = false + this.emit('drain', origin, [this, ...targets]) + } + + if (this[kClosedResolve] && queue.isEmpty()) { + const closeAll = new Array(this[kClients].length) + for (let i = 0; i < this[kClients].length; i++) { + closeAll[i] = this[kClients][i].close() + } + return Promise.all(closeAll) + .then(this[kClosedResolve]) + } + } + + [kOnConnect] = (origin, targets) => { + this.emit('connect', origin, [this, ...targets]) + }; + + [kOnDisconnect] = (origin, targets, err) => { + this.emit('disconnect', origin, [this, ...targets], err) + }; + + [kOnConnectionError] = (origin, targets, err) => { + this.emit('connectionError', origin, [this, ...targets], err) + } + + get [kBusy] () { + return this[kNeedDrain] + } + + get [kConnected] () { + let ret = 0 + for (const { [kConnected]: connected } of this[kClients]) { + ret += connected + } + return ret + } + + get [kFree] () { + let ret = 0 + for (const { [kConnected]: connected, [kNeedDrain]: needDrain } of this[kClients]) { + ret += connected && !needDrain + } + return ret + } + + get [kPending] () { + let ret = this[kQueued] + for (const { [kPending]: pending } of this[kClients]) { + ret += pending + } + return ret + } + + get [kRunning] () { + let ret = 0 + for (const { [kRunning]: running } of this[kClients]) { + ret += running + } + return ret + } + + get [kSize] () { + let ret = this[kQueued] + for (const { [kSize]: size } of this[kClients]) { + ret += size + } + return ret + } + + get stats () { + return new PoolStats(this) + } + + [kClose] () { + if (this[kQueue].isEmpty()) { + const closeAll = new Array(this[kClients].length) + for (let i = 0; i < this[kClients].length; i++) { + closeAll[i] = this[kClients][i].close() + } + return Promise.all(closeAll) + } else { + return new Promise((resolve) => { + this[kClosedResolve] = resolve + }) + } + } + + [kDestroy] (err) { + while (true) { + const item = this[kQueue].shift() + if (!item) { + break + } + item.handler.onError(err) + } + + const destroyAll = new Array(this[kClients].length) + for (let i = 0; i < this[kClients].length; i++) { + destroyAll[i] = this[kClients][i].destroy(err) + } + return Promise.all(destroyAll) + } + + [kDispatch] (opts, handler) { + const dispatcher = this[kGetDispatcher]() + + if (!dispatcher) { + this[kNeedDrain] = true + this[kQueue].push({ opts, handler }) + this[kQueued]++ + } else if (!dispatcher.dispatch(opts, handler)) { + dispatcher[kNeedDrain] = true + this[kNeedDrain] = !this[kGetDispatcher]() + } + + return !this[kNeedDrain] + } + + [kAddClient] (client) { + client + .on('drain', this[kOnDrain].bind(this, client)) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].push(client) + + if (this[kNeedDrain]) { + queueMicrotask(() => { + if (this[kNeedDrain]) { + this[kOnDrain](client, client[kUrl], [client, this]) + } + }) + } + + return this + } + + [kRemoveClient] (client) { + client.close(() => { + const idx = this[kClients].indexOf(client) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + }) + + this[kNeedDrain] = this[kClients].some(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + } +} + +module.exports = { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} diff --git a/node_modules/undici/lib/dispatcher/pool.js b/node_modules/undici/lib/dispatcher/pool.js new file mode 100644 index 000000000..77fd53266 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/pool.js @@ -0,0 +1,118 @@ +'use strict' + +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kGetDispatcher, + kRemoveClient +} = require('./pool-base') +const Client = require('./client') +const { + InvalidArgumentError +} = require('../core/errors') +const util = require('../core/util') +const { kUrl } = require('../core/symbols') +const buildConnector = require('../core/connect') + +const kOptions = Symbol('options') +const kConnections = Symbol('connections') +const kFactory = Symbol('factory') + +function defaultFactory (origin, opts) { + return new Client(origin, opts) +} + +class Pool extends PoolBase { + constructor (origin, { + connections, + factory = defaultFactory, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + allowH2, + clientTtl, + ...options + } = {}) { + if (connections != null && (!Number.isFinite(connections) || connections < 0)) { + throw new InvalidArgumentError('invalid connections') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + super() + + this[kConnections] = connections || null + this[kUrl] = util.parseOrigin(origin) + this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kFactory] = factory + + this.on('connect', (origin, targets) => { + if (clientTtl != null && clientTtl > 0) { + for (const target of targets) { + Object.assign(target, { ttl: Date.now() }) + } + } + }) + + this.on('connectionError', (origin, targets, error) => { + // If a connection error occurs, we remove the client from the pool, + // and emit a connectionError event. They will not be re-used. + // Fixes https://github.com/nodejs/undici/issues/3895 + for (const target of targets) { + // Do not use kRemoveClient here, as it will close the client, + // but the client cannot be closed in this state. + const idx = this[kClients].indexOf(target) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + } + }) + } + + [kGetDispatcher] () { + const clientTtlOption = this[kOptions].clientTtl + for (const client of this[kClients]) { + // check ttl of client and if it's stale, remove it from the pool + if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && ((Date.now() - client.ttl) > clientTtlOption)) { + this[kRemoveClient](client) + } else if (!client[kNeedDrain]) { + return client + } + } + + if (!this[kConnections] || this[kClients].length < this[kConnections]) { + const dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + return dispatcher + } + } +} + +module.exports = Pool diff --git a/node_modules/undici/lib/dispatcher/proxy-agent.js b/node_modules/undici/lib/dispatcher/proxy-agent.js new file mode 100644 index 000000000..4403b8d87 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/proxy-agent.js @@ -0,0 +1,287 @@ +'use strict' + +const { kProxy, kClose, kDestroy, kDispatch } = require('../core/symbols') +const Agent = require('./agent') +const Pool = require('./pool') +const DispatcherBase = require('./dispatcher-base') +const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require('../core/errors') +const buildConnector = require('../core/connect') +const Client = require('./client') +const { channels } = require('../core/diagnostics') + +const kAgent = Symbol('proxy agent') +const kClient = Symbol('proxy client') +const kProxyHeaders = Symbol('proxy headers') +const kRequestTls = Symbol('request tls settings') +const kProxyTls = Symbol('proxy tls settings') +const kConnectEndpoint = Symbol('connect endpoint function') +const kTunnelProxy = Symbol('tunnel proxy') + +function defaultProtocolPort (protocol) { + return protocol === 'https:' ? 443 : 80 +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +const noop = () => {} + +function defaultAgentFactory (origin, opts) { + if (opts.connections === 1) { + return new Client(origin, opts) + } + return new Pool(origin, opts) +} + +class Http1ProxyWrapper extends DispatcherBase { + #client + + constructor (proxyUrl, { headers = {}, connect, factory }) { + if (!proxyUrl) { + throw new InvalidArgumentError('Proxy URL is mandatory') + } + + super() + + this[kProxyHeaders] = headers + if (factory) { + this.#client = factory(proxyUrl, { connect }) + } else { + this.#client = new Client(proxyUrl, { connect }) + } + } + + [kDispatch] (opts, handler) { + const onHeaders = handler.onHeaders + handler.onHeaders = function (statusCode, data, resume) { + if (statusCode === 407) { + if (typeof handler.onError === 'function') { + handler.onError(new InvalidArgumentError('Proxy Authentication Required (407)')) + } + return + } + if (onHeaders) onHeaders.call(this, statusCode, data, resume) + } + + // Rewrite request as an HTTP1 Proxy request, without tunneling. + const { + origin, + path = '/', + headers = {} + } = opts + + opts.path = origin + path + + if (!('host' in headers) && !('Host' in headers)) { + const { host } = new URL(origin) + headers.host = host + } + opts.headers = { ...this[kProxyHeaders], ...headers } + + return this.#client[kDispatch](opts, handler) + } + + [kClose] () { + return this.#client.close() + } + + [kDestroy] (err) { + return this.#client.destroy(err) + } +} + +class ProxyAgent extends DispatcherBase { + constructor (opts) { + if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) { + throw new InvalidArgumentError('Proxy uri is mandatory') + } + + const { clientFactory = defaultFactory } = opts + if (typeof clientFactory !== 'function') { + throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') + } + + const { proxyTunnel = true } = opts + + super() + + const url = this.#getUrl(opts) + const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url + + this[kProxy] = { uri: href, protocol } + this[kRequestTls] = opts.requestTls + this[kProxyTls] = opts.proxyTls + this[kProxyHeaders] = opts.headers || {} + this[kTunnelProxy] = proxyTunnel + + if (opts.auth && opts.token) { + throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') + } else if (opts.auth) { + /* @deprecated in favour of opts.token */ + this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` + } else if (opts.token) { + this[kProxyHeaders]['proxy-authorization'] = opts.token + } else if (username && password) { + this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` + } + + const connect = buildConnector({ ...opts.proxyTls }) + this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) + + const agentFactory = opts.factory || defaultAgentFactory + const factory = (origin, options) => { + const { protocol } = new URL(origin) + if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') { + return new Http1ProxyWrapper(this[kProxy].uri, { + headers: this[kProxyHeaders], + connect, + factory: agentFactory + }) + } + return agentFactory(origin, options) + } + this[kClient] = clientFactory(url, { connect }) + this[kAgent] = new Agent({ + ...opts, + factory, + connect: async (opts, callback) => { + let requestedPath = opts.host + if (!opts.port) { + requestedPath += `:${defaultProtocolPort(opts.protocol)}` + } + try { + const connectParams = { + origin, + port, + path: requestedPath, + signal: opts.signal, + headers: { + ...this[kProxyHeaders], + host: opts.host, + ...(opts.connections == null || opts.connections > 0 ? { 'proxy-connection': 'keep-alive' } : {}) + }, + servername: this[kProxyTls]?.servername || proxyHostname + } + const { socket, statusCode } = await this[kClient].connect(connectParams) + if (statusCode !== 200) { + socket.on('error', noop).destroy() + callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) + return + } + + if (channels.proxyConnected.hasSubscribers) { + channels.proxyConnected.publish({ + socket, + connectParams + }) + } + + if (opts.protocol !== 'https:') { + callback(null, socket) + return + } + let servername + if (this[kRequestTls]) { + servername = this[kRequestTls].servername + } else { + servername = opts.servername + } + this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) + } catch (err) { + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + // Throw a custom error to avoid loop in client.js#connect + callback(new SecureProxyConnectionError(err)) + } else { + callback(err) + } + } + } + }) + } + + dispatch (opts, handler) { + const headers = buildHeaders(opts.headers) + throwIfProxyAuthIsSent(headers) + + if (headers && !('host' in headers) && !('Host' in headers)) { + const { host } = new URL(opts.origin) + headers.host = host + } + + return this[kAgent].dispatch( + { + ...opts, + headers + }, + handler + ) + } + + /** + * @param {import('../../types/proxy-agent').ProxyAgent.Options | string | URL} opts + * @returns {URL} + */ + #getUrl (opts) { + if (typeof opts === 'string') { + return new URL(opts) + } else if (opts instanceof URL) { + return opts + } else { + return new URL(opts.uri) + } + } + + [kClose] () { + return Promise.all([ + this[kAgent].close(), + this[kClient].close() + ]) + } + + [kDestroy] () { + return Promise.all([ + this[kAgent].destroy(), + this[kClient].destroy() + ]) + } +} + +/** + * @param {string[] | Record} headers + * @returns {Record} + */ +function buildHeaders (headers) { + // When using undici.fetch, the headers list is stored + // as an array. + if (Array.isArray(headers)) { + /** @type {Record} */ + const headersPair = {} + + for (let i = 0; i < headers.length; i += 2) { + headersPair[headers[i]] = headers[i + 1] + } + + return headersPair + } + + return headers +} + +/** + * @param {Record} headers + * + * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers + * Nevertheless, it was changed and to avoid a security vulnerability by end users + * this check was created. + * It should be removed in the next major version for performance reasons + */ +function throwIfProxyAuthIsSent (headers) { + const existProxyAuth = headers && Object.keys(headers) + .find((key) => key.toLowerCase() === 'proxy-authorization') + if (existProxyAuth) { + throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') + } +} + +module.exports = ProxyAgent diff --git a/node_modules/undici/lib/dispatcher/retry-agent.js b/node_modules/undici/lib/dispatcher/retry-agent.js new file mode 100644 index 000000000..0c2120d6f --- /dev/null +++ b/node_modules/undici/lib/dispatcher/retry-agent.js @@ -0,0 +1,35 @@ +'use strict' + +const Dispatcher = require('./dispatcher') +const RetryHandler = require('../handler/retry-handler') + +class RetryAgent extends Dispatcher { + #agent = null + #options = null + constructor (agent, options = {}) { + super(options) + this.#agent = agent + this.#options = options + } + + dispatch (opts, handler) { + const retry = new RetryHandler({ + ...opts, + retryOptions: this.#options + }, { + dispatch: this.#agent.dispatch.bind(this.#agent), + handler + }) + return this.#agent.dispatch(opts, retry) + } + + close () { + return this.#agent.close() + } + + destroy () { + return this.#agent.destroy() + } +} + +module.exports = RetryAgent diff --git a/node_modules/undici/lib/dispatcher/round-robin-pool.js b/node_modules/undici/lib/dispatcher/round-robin-pool.js new file mode 100644 index 000000000..b113aa9d0 --- /dev/null +++ b/node_modules/undici/lib/dispatcher/round-robin-pool.js @@ -0,0 +1,137 @@ +'use strict' + +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kGetDispatcher, + kRemoveClient +} = require('./pool-base') +const Client = require('./client') +const { + InvalidArgumentError +} = require('../core/errors') +const util = require('../core/util') +const { kUrl } = require('../core/symbols') +const buildConnector = require('../core/connect') + +const kOptions = Symbol('options') +const kConnections = Symbol('connections') +const kFactory = Symbol('factory') +const kIndex = Symbol('index') + +function defaultFactory (origin, opts) { + return new Client(origin, opts) +} + +class RoundRobinPool extends PoolBase { + constructor (origin, { + connections, + factory = defaultFactory, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + allowH2, + clientTtl, + ...options + } = {}) { + if (connections != null && (!Number.isFinite(connections) || connections < 0)) { + throw new InvalidArgumentError('invalid connections') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + super() + + this[kConnections] = connections || null + this[kUrl] = util.parseOrigin(origin) + this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kFactory] = factory + this[kIndex] = -1 + + this.on('connect', (origin, targets) => { + if (clientTtl != null && clientTtl > 0) { + for (const target of targets) { + Object.assign(target, { ttl: Date.now() }) + } + } + }) + + this.on('connectionError', (origin, targets, error) => { + for (const target of targets) { + const idx = this[kClients].indexOf(target) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + } + }) + } + + [kGetDispatcher] () { + const clientTtlOption = this[kOptions].clientTtl + const clientsLength = this[kClients].length + + // If we have no clients yet, create one + if (clientsLength === 0) { + const dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + return dispatcher + } + + // Round-robin through existing clients + let checked = 0 + while (checked < clientsLength) { + this[kIndex] = (this[kIndex] + 1) % clientsLength + const client = this[kClients][this[kIndex]] + + // Check if client is stale (TTL expired) + if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && ((Date.now() - client.ttl) > clientTtlOption)) { + this[kRemoveClient](client) + checked++ + continue + } + + // Return client if it's not draining + if (!client[kNeedDrain]) { + return client + } + + checked++ + } + + // All clients are busy, create a new one if we haven't reached the limit + if (!this[kConnections] || clientsLength < this[kConnections]) { + const dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + return dispatcher + } + } +} + +module.exports = RoundRobinPool diff --git a/node_modules/undici/lib/encoding/index.js b/node_modules/undici/lib/encoding/index.js new file mode 100644 index 000000000..41f7794d1 --- /dev/null +++ b/node_modules/undici/lib/encoding/index.js @@ -0,0 +1,33 @@ +'use strict' + +const textDecoder = new TextDecoder() + +/** + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Uint8Array} buffer + */ +function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' + } + + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. + + // 2. If buffer is 0xEF 0xBB 0xBF, then read three + // bytes from ioQueue. (Do nothing with those bytes.) + if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + buffer = buffer.subarray(3) + } + + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = textDecoder.decode(buffer) + + // 4. Return output. + return output +} + +module.exports = { + utf8DecodeBytes +} diff --git a/node_modules/undici/lib/global.js b/node_modules/undici/lib/global.js new file mode 100644 index 000000000..b61d779e4 --- /dev/null +++ b/node_modules/undici/lib/global.js @@ -0,0 +1,50 @@ +'use strict' + +// We include a version number for the Dispatcher API. In case of breaking changes, +// this version number must be increased to avoid conflicts. +const globalDispatcher = Symbol.for('undici.globalDispatcher.1') +const { InvalidArgumentError } = require('./core/errors') +const Agent = require('./dispatcher/agent') + +if (getGlobalDispatcher() === undefined) { + setGlobalDispatcher(new Agent()) +} + +function setGlobalDispatcher (agent) { + if (!agent || typeof agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument agent must implement Agent') + } + Object.defineProperty(globalThis, globalDispatcher, { + value: agent, + writable: true, + enumerable: false, + configurable: false + }) +} + +function getGlobalDispatcher () { + return globalThis[globalDispatcher] +} + +// These are the globals that can be installed by undici.install(). +// Not exported by index.js to avoid use outside of this module. +const installedExports = /** @type {const} */ ( + [ + 'fetch', + 'Headers', + 'Response', + 'Request', + 'FormData', + 'WebSocket', + 'CloseEvent', + 'ErrorEvent', + 'MessageEvent', + 'EventSource' + ] +) + +module.exports = { + setGlobalDispatcher, + getGlobalDispatcher, + installedExports +} diff --git a/node_modules/undici/lib/handler/cache-handler.js b/node_modules/undici/lib/handler/cache-handler.js new file mode 100644 index 000000000..d074cb72d --- /dev/null +++ b/node_modules/undici/lib/handler/cache-handler.js @@ -0,0 +1,526 @@ +'use strict' + +const util = require('../core/util') +const { + parseCacheControlHeader, + parseVaryHeader, + isEtagUsable +} = require('../util/cache') +const { parseHttpDate } = require('../util/date.js') + +function noop () {} + +// Status codes that we can use some heuristics on to cache +const HEURISTICALLY_CACHEABLE_STATUS_CODES = [ + 200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501 +] + +// Status codes which semantic is not handled by the cache +// https://datatracker.ietf.org/doc/html/rfc9111#section-3 +// This list should not grow beyond 206 unless the RFC is updated +// by a newer one including more. Please introduce another list if +// implementing caching of responses with the 'must-understand' directive. +const NOT_UNDERSTOOD_STATUS_CODES = [ + 206 +] + +const MAX_RESPONSE_AGE = 2147483647000 + +/** + * @typedef {import('../../types/dispatcher.d.ts').default.DispatchHandler} DispatchHandler + * + * @implements {DispatchHandler} + */ +class CacheHandler { + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey} + */ + #cacheKey + + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions['type']} + */ + #cacheType + + /** + * @type {number | undefined} + */ + #cacheByDefault + + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheStore} + */ + #store + + /** + * @type {import('../../types/dispatcher.d.ts').default.DispatchHandler} + */ + #handler + + /** + * @type {import('node:stream').Writable | undefined} + */ + #writeStream + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} opts + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey + * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler + */ + constructor ({ store, type, cacheByDefault }, cacheKey, handler) { + this.#store = store + this.#cacheType = type + this.#cacheByDefault = cacheByDefault + this.#cacheKey = cacheKey + this.#handler = handler + } + + onRequestStart (controller, context) { + this.#writeStream?.destroy() + this.#writeStream = undefined + this.#handler.onRequestStart?.(controller, context) + } + + onRequestUpgrade (controller, statusCode, headers, socket) { + this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket) + } + + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {number} statusCode + * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders + * @param {string} statusMessage + */ + onResponseStart ( + controller, + statusCode, + resHeaders, + statusMessage + ) { + const downstreamOnHeaders = () => + this.#handler.onResponseStart?.( + controller, + statusCode, + resHeaders, + statusMessage + ) + const handler = this + + if ( + !util.safeHTTPMethods.includes(this.#cacheKey.method) && + statusCode >= 200 && + statusCode <= 399 + ) { + // Successful response to an unsafe method, delete it from cache + // https://www.rfc-editor.org/rfc/rfc9111.html#name-invalidating-stored-response + try { + this.#store.delete(this.#cacheKey)?.catch?.(noop) + } catch { + // Fail silently + } + return downstreamOnHeaders() + } + + const cacheControlHeader = resHeaders['cache-control'] + const heuristicallyCacheable = resHeaders['last-modified'] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode) + if ( + !cacheControlHeader && + !resHeaders['expires'] && + !heuristicallyCacheable && + !this.#cacheByDefault + ) { + // Don't have anything to tell us this response is cachable and we're not + // caching by default + return downstreamOnHeaders() + } + + const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {} + if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives)) { + return downstreamOnHeaders() + } + + const now = Date.now() + const resAge = resHeaders.age ? getAge(resHeaders.age) : undefined + if (resAge && resAge >= MAX_RESPONSE_AGE) { + // Response considered stale + return downstreamOnHeaders() + } + + const resDate = typeof resHeaders.date === 'string' + ? parseHttpDate(resHeaders.date) + : undefined + + const staleAt = + determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? + this.#cacheByDefault + if (staleAt === undefined || (resAge && resAge > staleAt)) { + return downstreamOnHeaders() + } + + const baseTime = resDate ? resDate.getTime() : now + const absoluteStaleAt = staleAt + baseTime + if (now >= absoluteStaleAt) { + // Response is already stale + return downstreamOnHeaders() + } + + let varyDirectives + if (this.#cacheKey.headers && resHeaders.vary) { + varyDirectives = parseVaryHeader(resHeaders.vary, this.#cacheKey.headers) + if (!varyDirectives) { + // Parse error + return downstreamOnHeaders() + } + } + + const deleteAt = determineDeleteAt(baseTime, cacheControlDirectives, absoluteStaleAt) + const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives) + + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheValue} + */ + const value = { + statusCode, + statusMessage, + headers: strippedHeaders, + vary: varyDirectives, + cacheControlDirectives, + cachedAt: resAge ? now - resAge : now, + staleAt: absoluteStaleAt, + deleteAt + } + + // Not modified, re-use the cached value + // https://www.rfc-editor.org/rfc/rfc9111.html#name-handling-304-not-modified + if (statusCode === 304) { + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheValue} + */ + const cachedValue = this.#store.get(this.#cacheKey) + if (!cachedValue) { + // Do not create a new cache entry, as a 304 won't have a body - so cannot be cached. + return downstreamOnHeaders() + } + + // Re-use the cached value: statuscode, statusmessage, headers and body + value.statusCode = cachedValue.statusCode + value.statusMessage = cachedValue.statusMessage + value.etag = cachedValue.etag + value.headers = { ...cachedValue.headers, ...strippedHeaders } + + downstreamOnHeaders() + + this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value) + + if (!this.#writeStream || !cachedValue?.body) { + return + } + + const bodyIterator = cachedValue.body.values() + + const streamCachedBody = () => { + for (const chunk of bodyIterator) { + const full = this.#writeStream.write(chunk) === false + this.#handler.onResponseData?.(controller, chunk) + // when stream is full stop writing until we get a 'drain' event + if (full) { + break + } + } + } + + this.#writeStream + .on('error', function () { + handler.#writeStream = undefined + handler.#store.delete(handler.#cacheKey) + }) + .on('drain', () => { + streamCachedBody() + }) + .on('close', function () { + if (handler.#writeStream === this) { + handler.#writeStream = undefined + } + }) + + streamCachedBody() + } else { + if (typeof resHeaders.etag === 'string' && isEtagUsable(resHeaders.etag)) { + value.etag = resHeaders.etag + } + + this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value) + + if (!this.#writeStream) { + return downstreamOnHeaders() + } + + this.#writeStream + .on('drain', () => controller.resume()) + .on('error', function () { + // TODO (fix): Make error somehow observable? + handler.#writeStream = undefined + + // Delete the value in case the cache store is holding onto state from + // the call to createWriteStream + handler.#store.delete(handler.#cacheKey) + }) + .on('close', function () { + if (handler.#writeStream === this) { + handler.#writeStream = undefined + } + + // TODO (fix): Should we resume even if was paused downstream? + controller.resume() + }) + + downstreamOnHeaders() + } + } + + onResponseData (controller, chunk) { + if (this.#writeStream?.write(chunk) === false) { + controller.pause() + } + + this.#handler.onResponseData?.(controller, chunk) + } + + onResponseEnd (controller, trailers) { + this.#writeStream?.end() + this.#handler.onResponseEnd?.(controller, trailers) + } + + onResponseError (controller, err) { + this.#writeStream?.destroy(err) + this.#writeStream = undefined + this.#handler.onResponseError?.(controller, err) + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen + * + * @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions['type']} cacheType + * @param {number} statusCode + * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives + */ +function canCacheResponse (cacheType, statusCode, resHeaders, cacheControlDirectives) { + // Status code must be final and understood. + if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) { + return false + } + // Responses with neither status codes that are heuristically cacheable, nor "explicit enough" caching + // directives, are not cacheable. "Explicit enough": see https://www.rfc-editor.org/rfc/rfc9111.html#section-3 + if (!HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode) && !resHeaders['expires'] && + !cacheControlDirectives.public && + cacheControlDirectives['max-age'] === undefined && + // RFC 9111: a private response directive, if the cache is not shared + !(cacheControlDirectives.private && cacheType === 'private') && + !(cacheControlDirectives['s-maxage'] !== undefined && cacheType === 'shared') + ) { + return false + } + + if (cacheControlDirectives['no-store']) { + return false + } + + if (cacheType === 'shared' && cacheControlDirectives.private === true) { + return false + } + + // https://www.rfc-editor.org/rfc/rfc9111.html#section-4.1-5 + if (resHeaders.vary?.includes('*')) { + return false + } + + // https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen + if (resHeaders.authorization) { + if (!cacheControlDirectives.public || typeof resHeaders.authorization !== 'string') { + return false + } + + if ( + Array.isArray(cacheControlDirectives['no-cache']) && + cacheControlDirectives['no-cache'].includes('authorization') + ) { + return false + } + + if ( + Array.isArray(cacheControlDirectives['private']) && + cacheControlDirectives['private'].includes('authorization') + ) { + return false + } + } + + return true +} + +/** + * @param {string | string[]} ageHeader + * @returns {number | undefined} + */ +function getAge (ageHeader) { + const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader) + + return isNaN(age) ? undefined : age * 1000 +} + +/** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions['type']} cacheType + * @param {number} now + * @param {number | undefined} age + * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders + * @param {Date | undefined} responseDate + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives + * + * @returns {number | undefined} time that the value is stale at in seconds or undefined if it shouldn't be cached + */ +function determineStaleAt (cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) { + if (cacheType === 'shared') { + // Prioritize s-maxage since we're a shared cache + // s-maxage > max-age > Expire + // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.10-3 + const sMaxAge = cacheControlDirectives['s-maxage'] + if (sMaxAge !== undefined) { + return sMaxAge > 0 ? sMaxAge * 1000 : undefined + } + } + + const maxAge = cacheControlDirectives['max-age'] + if (maxAge !== undefined) { + return maxAge > 0 ? maxAge * 1000 : undefined + } + + if (typeof resHeaders.expires === 'string') { + // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.3 + const expiresDate = parseHttpDate(resHeaders.expires) + if (expiresDate) { + if (now >= expiresDate.getTime()) { + return undefined + } + + if (responseDate) { + if (responseDate >= expiresDate) { + return undefined + } + + if (age !== undefined && age > (expiresDate - responseDate)) { + return undefined + } + } + + return expiresDate.getTime() - now + } + } + + if (typeof resHeaders['last-modified'] === 'string') { + // https://www.rfc-editor.org/rfc/rfc9111.html#name-calculating-heuristic-fresh + const lastModified = new Date(resHeaders['last-modified']) + if (isValidDate(lastModified)) { + if (lastModified.getTime() >= now) { + return undefined + } + + const responseAge = now - lastModified.getTime() + + return responseAge * 0.1 + } + } + + if (cacheControlDirectives.immutable) { + // https://www.rfc-editor.org/rfc/rfc8246.html#section-2.2 + return 31536000 + } + + return undefined +} + +/** + * @param {number} now + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives + * @param {number} staleAt + */ +function determineDeleteAt (now, cacheControlDirectives, staleAt) { + let staleWhileRevalidate = -Infinity + let staleIfError = -Infinity + let immutable = -Infinity + + if (cacheControlDirectives['stale-while-revalidate']) { + staleWhileRevalidate = staleAt + (cacheControlDirectives['stale-while-revalidate'] * 1000) + } + + if (cacheControlDirectives['stale-if-error']) { + staleIfError = staleAt + (cacheControlDirectives['stale-if-error'] * 1000) + } + + if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity) { + immutable = now + 31536000000 + } + + return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable) +} + +/** + * Strips headers required to be removed in cached responses + * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives + * @returns {Record} + */ +function stripNecessaryHeaders (resHeaders, cacheControlDirectives) { + const headersToRemove = [ + 'connection', + 'proxy-authenticate', + 'proxy-authentication-info', + 'proxy-authorization', + 'proxy-connection', + 'te', + 'transfer-encoding', + 'upgrade', + // We'll add age back when serving it + 'age' + ] + + if (resHeaders['connection']) { + if (Array.isArray(resHeaders['connection'])) { + // connection: a + // connection: b + headersToRemove.push(...resHeaders['connection'].map(header => header.trim())) + } else { + // connection: a, b + headersToRemove.push(...resHeaders['connection'].split(',').map(header => header.trim())) + } + } + + if (Array.isArray(cacheControlDirectives['no-cache'])) { + headersToRemove.push(...cacheControlDirectives['no-cache']) + } + + if (Array.isArray(cacheControlDirectives['private'])) { + headersToRemove.push(...cacheControlDirectives['private']) + } + + let strippedHeaders + for (const headerName of headersToRemove) { + if (resHeaders[headerName]) { + strippedHeaders ??= { ...resHeaders } + delete strippedHeaders[headerName] + } + } + + return strippedHeaders ?? resHeaders +} + +/** + * @param {Date} date + * @returns {boolean} + */ +function isValidDate (date) { + return date instanceof Date && Number.isFinite(date.valueOf()) +} + +module.exports = CacheHandler diff --git a/node_modules/undici/lib/handler/cache-revalidation-handler.js b/node_modules/undici/lib/handler/cache-revalidation-handler.js new file mode 100644 index 000000000..393d16d52 --- /dev/null +++ b/node_modules/undici/lib/handler/cache-revalidation-handler.js @@ -0,0 +1,124 @@ +'use strict' + +const assert = require('node:assert') + +/** + * This takes care of revalidation requests we send to the origin. If we get + * a response indicating that what we have is cached (via a HTTP 304), we can + * continue using the cached value. Otherwise, we'll receive the new response + * here, which we then just pass on to the next handler (most likely a + * CacheHandler). Note that this assumes the proper headers were already + * included in the request to tell the origin that we want to revalidate the + * response (i.e. if-modified-since or if-none-match). + * + * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-validation + * + * @implements {import('../../types/dispatcher.d.ts').default.DispatchHandler} + */ +class CacheRevalidationHandler { + #successful = false + + /** + * @type {((boolean, any) => void) | null} + */ + #callback + + /** + * @type {(import('../../types/dispatcher.d.ts').default.DispatchHandler)} + */ + #handler + + #context + + /** + * @type {boolean} + */ + #allowErrorStatusCodes + + /** + * @param {(boolean) => void} callback Function to call if the cached value is valid + * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler + * @param {boolean} allowErrorStatusCodes + */ + constructor (callback, handler, allowErrorStatusCodes) { + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function') + } + + this.#callback = callback + this.#handler = handler + this.#allowErrorStatusCodes = allowErrorStatusCodes + } + + onRequestStart (_, context) { + this.#successful = false + this.#context = context + } + + onRequestUpgrade (controller, statusCode, headers, socket) { + this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket) + } + + onResponseStart ( + controller, + statusCode, + headers, + statusMessage + ) { + assert(this.#callback != null) + + // https://www.rfc-editor.org/rfc/rfc9111.html#name-handling-a-validation-respo + // https://datatracker.ietf.org/doc/html/rfc5861#section-4 + this.#successful = statusCode === 304 || + (this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504) + this.#callback(this.#successful, this.#context) + this.#callback = null + + if (this.#successful) { + return true + } + + this.#handler.onRequestStart?.(controller, this.#context) + this.#handler.onResponseStart?.( + controller, + statusCode, + headers, + statusMessage + ) + } + + onResponseData (controller, chunk) { + if (this.#successful) { + return + } + + return this.#handler.onResponseData?.(controller, chunk) + } + + onResponseEnd (controller, trailers) { + if (this.#successful) { + return + } + + this.#handler.onResponseEnd?.(controller, trailers) + } + + onResponseError (controller, err) { + if (this.#successful) { + return + } + + if (this.#callback) { + this.#callback(false) + this.#callback = null + } + + if (typeof this.#handler.onResponseError === 'function') { + this.#handler.onResponseError(controller, err) + } else { + throw err + } + } +} + +module.exports = CacheRevalidationHandler diff --git a/node_modules/undici/lib/handler/decorator-handler.js b/node_modules/undici/lib/handler/decorator-handler.js new file mode 100644 index 000000000..50fbb0cf8 --- /dev/null +++ b/node_modules/undici/lib/handler/decorator-handler.js @@ -0,0 +1,67 @@ +'use strict' + +const assert = require('node:assert') +const WrapHandler = require('./wrap-handler') + +/** + * @deprecated + */ +module.exports = class DecoratorHandler { + #handler + #onCompleteCalled = false + #onErrorCalled = false + #onResponseStartCalled = false + + constructor (handler) { + if (typeof handler !== 'object' || handler === null) { + throw new TypeError('handler must be an object') + } + this.#handler = WrapHandler.wrap(handler) + } + + onRequestStart (...args) { + this.#handler.onRequestStart?.(...args) + } + + onRequestUpgrade (...args) { + assert(!this.#onCompleteCalled) + assert(!this.#onErrorCalled) + + return this.#handler.onRequestUpgrade?.(...args) + } + + onResponseStart (...args) { + assert(!this.#onCompleteCalled) + assert(!this.#onErrorCalled) + assert(!this.#onResponseStartCalled) + + this.#onResponseStartCalled = true + + return this.#handler.onResponseStart?.(...args) + } + + onResponseData (...args) { + assert(!this.#onCompleteCalled) + assert(!this.#onErrorCalled) + + return this.#handler.onResponseData?.(...args) + } + + onResponseEnd (...args) { + assert(!this.#onCompleteCalled) + assert(!this.#onErrorCalled) + + this.#onCompleteCalled = true + return this.#handler.onResponseEnd?.(...args) + } + + onResponseError (...args) { + this.#onErrorCalled = true + return this.#handler.onResponseError?.(...args) + } + + /** + * @deprecated + */ + onBodySent () {} +} diff --git a/node_modules/undici/lib/handler/deduplication-handler.js b/node_modules/undici/lib/handler/deduplication-handler.js new file mode 100644 index 000000000..33a2c4fdb --- /dev/null +++ b/node_modules/undici/lib/handler/deduplication-handler.js @@ -0,0 +1,216 @@ +'use strict' + +/** + * @typedef {import('../../types/dispatcher.d.ts').default.DispatchHandler} DispatchHandler + */ + +/** + * Handler that buffers response data and notifies multiple waiting handlers. + * Used for request deduplication. + * + * @implements {DispatchHandler} + */ +class DeduplicationHandler { + /** + * @type {DispatchHandler} + */ + #primaryHandler + + /** + * @type {DispatchHandler[]} + */ + #waitingHandlers = [] + + /** + * @type {Buffer[]} + */ + #chunks = [] + + /** + * @type {number} + */ + #statusCode = 0 + + /** + * @type {Record} + */ + #headers = {} + + /** + * @type {string} + */ + #statusMessage = '' + + /** + * @type {boolean} + */ + #aborted = false + + /** + * @type {import('../../types/dispatcher.d.ts').default.DispatchController | null} + */ + #controller = null + + /** + * @type {(() => void) | null} + */ + #onComplete = null + + /** + * @param {DispatchHandler} primaryHandler The primary handler + * @param {() => void} onComplete Callback when request completes + */ + constructor (primaryHandler, onComplete) { + this.#primaryHandler = primaryHandler + this.#onComplete = onComplete + } + + /** + * Add a waiting handler that will receive the buffered response + * @param {DispatchHandler} handler + */ + addWaitingHandler (handler) { + this.#waitingHandlers.push(handler) + } + + /** + * @param {() => void} abort + * @param {any} context + */ + onRequestStart (controller, context) { + this.#controller = controller + this.#primaryHandler.onRequestStart?.(controller, context) + } + + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {number} statusCode + * @param {import('../../types/header.d.ts').IncomingHttpHeaders} headers + * @param {Socket} socket + */ + onRequestUpgrade (controller, statusCode, headers, socket) { + this.#primaryHandler.onRequestUpgrade?.(controller, statusCode, headers, socket) + } + + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {number} statusCode + * @param {Record} headers + * @param {string} statusMessage + */ + onResponseStart (controller, statusCode, headers, statusMessage) { + this.#statusCode = statusCode + this.#headers = headers + this.#statusMessage = statusMessage + this.#primaryHandler.onResponseStart?.(controller, statusCode, headers, statusMessage) + } + + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {Buffer} chunk + */ + onResponseData (controller, chunk) { + // Buffer the chunk for waiting handlers + this.#chunks.push(Buffer.from(chunk)) + this.#primaryHandler.onResponseData?.(controller, chunk) + } + + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {object} trailers + */ + onResponseEnd (controller, trailers) { + this.#primaryHandler.onResponseEnd?.(controller, trailers) + this.#notifyWaitingHandlers() + this.#onComplete?.() + } + + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {Error} err + */ + onResponseError (controller, err) { + this.#aborted = true + this.#primaryHandler.onResponseError?.(controller, err) + this.#notifyWaitingHandlersError(err) + this.#onComplete?.() + } + + /** + * Notify all waiting handlers with the buffered response + */ + #notifyWaitingHandlers () { + const body = Buffer.concat(this.#chunks) + + for (const handler of this.#waitingHandlers) { + // Create a simple controller for each waiting handler + const waitingController = { + resume () {}, + pause () {}, + get paused () { return false }, + get aborted () { return false }, + get reason () { return null }, + abort () {} + } + + try { + handler.onRequestStart?.(waitingController, null) + + if (waitingController.aborted) { + continue + } + + handler.onResponseStart?.( + waitingController, + this.#statusCode, + this.#headers, + this.#statusMessage + ) + + if (waitingController.aborted) { + continue + } + + if (body.length > 0) { + handler.onResponseData?.(waitingController, body) + } + + handler.onResponseEnd?.(waitingController, {}) + } catch { + // Ignore errors from waiting handlers + } + } + + this.#waitingHandlers = [] + this.#chunks = [] + } + + /** + * Notify all waiting handlers of an error + * @param {Error} err + */ + #notifyWaitingHandlersError (err) { + for (const handler of this.#waitingHandlers) { + const waitingController = { + resume () {}, + pause () {}, + get paused () { return false }, + get aborted () { return true }, + get reason () { return err }, + abort () {} + } + + try { + handler.onRequestStart?.(waitingController, null) + handler.onResponseError?.(waitingController, err) + } catch { + // Ignore errors from waiting handlers + } + } + + this.#waitingHandlers = [] + this.#chunks = [] + } +} + +module.exports = DeduplicationHandler diff --git a/node_modules/undici/lib/handler/redirect-handler.js b/node_modules/undici/lib/handler/redirect-handler.js new file mode 100644 index 000000000..dd0f47170 --- /dev/null +++ b/node_modules/undici/lib/handler/redirect-handler.js @@ -0,0 +1,237 @@ +'use strict' + +const util = require('../core/util') +const { kBodyUsed } = require('../core/symbols') +const assert = require('node:assert') +const { InvalidArgumentError } = require('../core/errors') +const EE = require('node:events') + +const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] + +const kBody = Symbol('body') + +const noop = () => {} + +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false + } + + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] + } +} + +class RedirectHandler { + static buildDispatch (dispatcher, maxRedirections) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + const dispatch = dispatcher.dispatch.bind(dispatcher) + return (opts, originalHandler) => dispatch(opts, new RedirectHandler(dispatch, maxRedirections, opts, originalHandler)) + } + + constructor (dispatch, maxRedirections, opts, handler) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + this.dispatch = dispatch + this.location = null + const { maxRedirections: _, ...cleanOpts } = opts + this.opts = cleanOpts // opts must be a copy, exclude maxRedirections + this.maxRedirections = maxRedirections + this.handler = handler + this.history = [] + + if (util.isStream(this.opts.body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (util.bodyLength(this.opts.body) === 0) { + this.opts.body + .on('data', function () { + assert(false) + }) + } + + if (typeof this.opts.body.readableDidRead !== 'boolean') { + this.opts.body[kBodyUsed] = false + EE.prototype.on.call(this.opts.body, 'data', function () { + this[kBodyUsed] = true + }) + } + } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + this.opts.body = new BodyAsyncIterable(this.opts.body) + } else if ( + this.opts.body && + typeof this.opts.body !== 'string' && + !ArrayBuffer.isView(this.opts.body) && + util.isIterable(this.opts.body) && + !util.isFormDataLike(this.opts.body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + this.opts.body = new BodyAsyncIterable(this.opts.body) + } + } + + onRequestStart (controller, context) { + this.handler.onRequestStart?.(controller, { ...context, history: this.history }) + } + + onRequestUpgrade (controller, statusCode, headers, socket) { + this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket) + } + + onResponseStart (controller, statusCode, headers, statusMessage) { + if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) { + throw new Error('max redirects') + } + + // https://tools.ietf.org/html/rfc7231#section-6.4.2 + // https://fetch.spec.whatwg.org/#http-redirect-fetch + // In case of HTTP 301 or 302 with POST, change the method to GET + if ((statusCode === 301 || statusCode === 302) && this.opts.method === 'POST') { + this.opts.method = 'GET' + if (util.isStream(this.opts.body)) { + util.destroy(this.opts.body.on('error', noop)) + } + this.opts.body = null + } + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + // In case of HTTP 303, always replace method to be either HEAD or GET + if (statusCode === 303 && this.opts.method !== 'HEAD') { + this.opts.method = 'GET' + if (util.isStream(this.opts.body)) { + util.destroy(this.opts.body.on('error', noop)) + } + this.opts.body = null + } + + this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) || redirectableStatusCodes.indexOf(statusCode) === -1 + ? null + : headers.location + + if (this.opts.origin) { + this.history.push(new URL(this.opts.path, this.opts.origin)) + } + + if (!this.location) { + this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage) + return + } + + const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) + const path = search ? `${pathname}${search}` : pathname + + // Check for redirect loops by seeing if we've already visited this URL in our history + // This catches the case where Client/Pool try to handle cross-origin redirects but fail + // and keep redirecting to the same URL in an infinite loop + const redirectUrlString = `${origin}${path}` + for (const historyUrl of this.history) { + if (historyUrl.toString() === redirectUrlString) { + throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`) + } + } + + // Remove headers referring to the original URL. + // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. + // https://tools.ietf.org/html/rfc7231#section-6.4 + this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) + this.opts.path = path + this.opts.origin = origin + this.opts.query = null + } + + onResponseData (controller, chunk) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response bodies. + + Redirection is used to serve the requested resource from another URL, so it assumes that + no body is generated (and thus can be ignored). Even though generating a body is not prohibited. + + For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually + (which means it's optional and not mandated) contain just an hyperlink to the value of + the Location response header, so the body can be ignored safely. + + For status 300, which is "Multiple Choices", the spec mentions both generating a Location + response header AND a response body with the other possible location to follow. + Since the spec explicitly chooses not to specify a format for such body and leave it to + servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. + */ + } else { + this.handler.onResponseData?.(controller, chunk) + } + } + + onResponseEnd (controller, trailers) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections + and neither are useful if present. + + See comment on onData method above for more detailed information. + */ + this.dispatch(this.opts, this) + } else { + this.handler.onResponseEnd(controller, trailers) + } + } + + onResponseError (controller, error) { + this.handler.onResponseError?.(controller, error) + } +} + +// https://tools.ietf.org/html/rfc7231#section-6.4.4 +function shouldRemoveHeader (header, removeContent, unknownOrigin) { + if (header.length === 4) { + return util.headerNameToString(header) === 'host' + } + if (removeContent && util.headerNameToString(header).startsWith('content-')) { + return true + } + if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { + const name = util.headerNameToString(header) + return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' + } + return false +} + +// https://tools.ietf.org/html/rfc7231#section-6.4 +function cleanRequestHeaders (headers, removeContent, unknownOrigin) { + const ret = [] + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { + ret.push(headers[i], headers[i + 1]) + } + } + } else if (headers && typeof headers === 'object') { + const entries = typeof headers[Symbol.iterator] === 'function' ? headers : Object.entries(headers) + for (const [key, value] of entries) { + if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { + ret.push(key, value) + } + } + } else { + assert(headers == null, 'headers must be an object or an array') + } + return ret +} + +module.exports = RedirectHandler diff --git a/node_modules/undici/lib/handler/retry-handler.js b/node_modules/undici/lib/handler/retry-handler.js new file mode 100644 index 000000000..1cbc78981 --- /dev/null +++ b/node_modules/undici/lib/handler/retry-handler.js @@ -0,0 +1,394 @@ +'use strict' +const assert = require('node:assert') + +const { kRetryHandlerDefaultRetry } = require('../core/symbols') +const { RequestRetryError } = require('../core/errors') +const WrapHandler = require('./wrap-handler') +const { + isDisturbed, + parseRangeHeader, + wrapRequestBody +} = require('../core/util') + +function calculateRetryAfterHeader (retryAfter) { + const retryTime = new Date(retryAfter).getTime() + return isNaN(retryTime) ? 0 : retryTime - Date.now() +} + +class RetryHandler { + constructor (opts, { dispatch, handler }) { + const { retryOptions, ...dispatchOpts } = opts + const { + // Retry scoped + retry: retryFn, + maxRetries, + maxTimeout, + minTimeout, + timeoutFactor, + // Response scoped + methods, + errorCodes, + retryAfter, + statusCodes, + throwOnError + } = retryOptions ?? {} + + this.error = null + this.dispatch = dispatch + this.handler = WrapHandler.wrap(handler) + this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) } + this.retryOpts = { + throwOnError: throwOnError ?? true, + retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], + retryAfter: retryAfter ?? true, + maxTimeout: maxTimeout ?? 30 * 1000, // 30s, + minTimeout: minTimeout ?? 500, // .5s + timeoutFactor: timeoutFactor ?? 2, + maxRetries: maxRetries ?? 5, + // What errors we should retry + methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + // Indicates which errors to retry + statusCodes: statusCodes ?? [500, 502, 503, 504, 429], + // List of errors to retry + errorCodes: errorCodes ?? [ + 'ECONNRESET', + 'ECONNREFUSED', + 'ENOTFOUND', + 'ENETDOWN', + 'ENETUNREACH', + 'EHOSTDOWN', + 'EHOSTUNREACH', + 'EPIPE', + 'UND_ERR_SOCKET' + ] + } + + this.retryCount = 0 + this.retryCountCheckpoint = 0 + this.headersSent = false + this.start = 0 + this.end = null + this.etag = null + } + + onResponseStartWithRetry (controller, statusCode, headers, statusMessage, err) { + if (this.retryOpts.throwOnError) { + // Preserve old behavior for status codes that are not eligible for retry + if (this.retryOpts.statusCodes.includes(statusCode) === false) { + this.headersSent = true + this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage) + } else { + this.error = err + } + + return + } + + if (isDisturbed(this.opts.body)) { + this.headersSent = true + this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage) + return + } + + function shouldRetry (passedErr) { + if (passedErr) { + this.headersSent = true + this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage) + controller.resume() + return + } + + this.error = err + controller.resume() + } + + controller.pause() + this.retryOpts.retry( + err, + { + state: { counter: this.retryCount }, + opts: { retryOptions: this.retryOpts, ...this.opts } + }, + shouldRetry.bind(this) + ) + } + + onRequestStart (controller, context) { + if (!this.headersSent) { + this.handler.onRequestStart?.(controller, context) + } + } + + onRequestUpgrade (controller, statusCode, headers, socket) { + this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket) + } + + static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { + const { statusCode, code, headers } = err + const { method, retryOptions } = opts + const { + maxRetries, + minTimeout, + maxTimeout, + timeoutFactor, + statusCodes, + errorCodes, + methods + } = retryOptions + const { counter } = state + + // Any code that is not a Undici's originated and allowed to retry + if (code && code !== 'UND_ERR_REQ_RETRY' && !errorCodes.includes(code)) { + cb(err) + return + } + + // If a set of method are provided and the current method is not in the list + if (Array.isArray(methods) && !methods.includes(method)) { + cb(err) + return + } + + // If a set of status code are provided and the current status code is not in the list + if ( + statusCode != null && + Array.isArray(statusCodes) && + !statusCodes.includes(statusCode) + ) { + cb(err) + return + } + + // If we reached the max number of retries + if (counter > maxRetries) { + cb(err) + return + } + + let retryAfterHeader = headers?.['retry-after'] + if (retryAfterHeader) { + retryAfterHeader = Number(retryAfterHeader) + retryAfterHeader = Number.isNaN(retryAfterHeader) + ? calculateRetryAfterHeader(headers['retry-after']) + : retryAfterHeader * 1e3 // Retry-After is in seconds + } + + const retryTimeout = + retryAfterHeader > 0 + ? Math.min(retryAfterHeader, maxTimeout) + : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout) + + setTimeout(() => cb(null), retryTimeout) + } + + onResponseStart (controller, statusCode, headers, statusMessage) { + this.error = null + this.retryCount += 1 + + if (statusCode >= 300) { + const err = new RequestRetryError('Request failed', statusCode, { + headers, + data: { + count: this.retryCount + } + }) + + this.onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err) + return + } + + // Checkpoint for resume from where we left it + if (this.headersSent) { + // Only Partial Content 206 supposed to provide Content-Range, + // any other status code that partially consumed the payload + // should not be retried because it would result in downstream + // wrongly concatenate multiple responses. + if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) { + throw new RequestRetryError('server does not support the range header and the payload was partially consumed', statusCode, { + headers, + data: { count: this.retryCount } + }) + } + + const contentRange = parseRangeHeader(headers['content-range']) + // If no content range + if (!contentRange) { + // We always throw here as we want to indicate that we entred unexpected path + throw new RequestRetryError('Content-Range mismatch', statusCode, { + headers, + data: { count: this.retryCount } + }) + } + + // Let's start with a weak etag check + if (this.etag != null && this.etag !== headers.etag) { + // We always throw here as we want to indicate that we entred unexpected path + throw new RequestRetryError('ETag mismatch', statusCode, { + headers, + data: { count: this.retryCount } + }) + } + + const { start, size, end = size ? size - 1 : null } = contentRange + + assert(this.start === start, 'content-range mismatch') + assert(this.end == null || this.end === end, 'content-range mismatch') + + return + } + + if (this.end == null) { + if (statusCode === 206) { + // First time we receive 206 + const range = parseRangeHeader(headers['content-range']) + + if (range == null) { + this.headersSent = true + this.handler.onResponseStart?.( + controller, + statusCode, + headers, + statusMessage + ) + return + } + + const { start, size, end = size ? size - 1 : null } = range + assert( + start != null && Number.isFinite(start), + 'content-range mismatch' + ) + assert(end != null && Number.isFinite(end), 'invalid content-length') + + this.start = start + this.end = end + } + + // We make our best to checkpoint the body for further range headers + if (this.end == null) { + const contentLength = headers['content-length'] + this.end = contentLength != null ? Number(contentLength) - 1 : null + } + + assert(Number.isFinite(this.start)) + assert( + this.end == null || Number.isFinite(this.end), + 'invalid content-length' + ) + + this.resume = true + this.etag = headers.etag != null ? headers.etag : null + + // Weak etags are not useful for comparison nor cache + // for instance not safe to assume if the response is byte-per-byte + // equal + if ( + this.etag != null && + this.etag[0] === 'W' && + this.etag[1] === '/' + ) { + this.etag = null + } + + this.headersSent = true + this.handler.onResponseStart?.( + controller, + statusCode, + headers, + statusMessage + ) + } else { + throw new RequestRetryError('Request failed', statusCode, { + headers, + data: { count: this.retryCount } + }) + } + } + + onResponseData (controller, chunk) { + if (this.error) { + return + } + + this.start += chunk.length + + this.handler.onResponseData?.(controller, chunk) + } + + onResponseEnd (controller, trailers) { + if (this.error && this.retryOpts.throwOnError) { + throw this.error + } + + if (!this.error) { + this.retryCount = 0 + return this.handler.onResponseEnd?.(controller, trailers) + } + + this.retry(controller) + } + + retry (controller) { + if (this.start !== 0) { + const headers = { range: `bytes=${this.start}-${this.end ?? ''}` } + + // Weak etag check - weak etags will make comparison algorithms never match + if (this.etag != null) { + headers['if-match'] = this.etag + } + + this.opts = { + ...this.opts, + headers: { + ...this.opts.headers, + ...headers + } + } + } + + try { + this.retryCountCheckpoint = this.retryCount + this.dispatch(this.opts, this) + } catch (err) { + this.handler.onResponseError?.(controller, err) + } + } + + onResponseError (controller, err) { + if (controller?.aborted || isDisturbed(this.opts.body)) { + this.handler.onResponseError?.(controller, err) + return + } + + function shouldRetry (returnedErr) { + if (!returnedErr) { + this.retry(controller) + return + } + + this.handler?.onResponseError?.(controller, returnedErr) + } + + // We reconcile in case of a mix between network errors + // and server error response + if (this.retryCount - this.retryCountCheckpoint > 0) { + // We count the difference between the last checkpoint and the current retry count + this.retryCount = + this.retryCountCheckpoint + + (this.retryCount - this.retryCountCheckpoint) + } else { + this.retryCount += 1 + } + + this.retryOpts.retry( + err, + { + state: { counter: this.retryCount }, + opts: { retryOptions: this.retryOpts, ...this.opts } + }, + shouldRetry.bind(this) + ) + } +} + +module.exports = RetryHandler diff --git a/node_modules/undici/lib/handler/unwrap-handler.js b/node_modules/undici/lib/handler/unwrap-handler.js new file mode 100644 index 000000000..865593a32 --- /dev/null +++ b/node_modules/undici/lib/handler/unwrap-handler.js @@ -0,0 +1,96 @@ +'use strict' + +const { parseHeaders } = require('../core/util') +const { InvalidArgumentError } = require('../core/errors') + +const kResume = Symbol('resume') + +class UnwrapController { + #paused = false + #reason = null + #aborted = false + #abort + + [kResume] = null + + constructor (abort) { + this.#abort = abort + } + + pause () { + this.#paused = true + } + + resume () { + if (this.#paused) { + this.#paused = false + this[kResume]?.() + } + } + + abort (reason) { + if (!this.#aborted) { + this.#aborted = true + this.#reason = reason + this.#abort(reason) + } + } + + get aborted () { + return this.#aborted + } + + get reason () { + return this.#reason + } + + get paused () { + return this.#paused + } +} + +module.exports = class UnwrapHandler { + #handler + #controller + + constructor (handler) { + this.#handler = handler + } + + static unwrap (handler) { + // TODO (fix): More checks... + return !handler.onRequestStart ? handler : new UnwrapHandler(handler) + } + + onConnect (abort, context) { + this.#controller = new UnwrapController(abort) + this.#handler.onRequestStart?.(this.#controller, context) + } + + onUpgrade (statusCode, rawHeaders, socket) { + this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket) + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + this.#controller[kResume] = resume + this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage) + return !this.#controller.paused + } + + onData (data) { + this.#handler.onResponseData?.(this.#controller, data) + return !this.#controller.paused + } + + onComplete (rawTrailers) { + this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers)) + } + + onError (err) { + if (!this.#handler.onResponseError) { + throw new InvalidArgumentError('invalid onError method') + } + + this.#handler.onResponseError?.(this.#controller, err) + } +} diff --git a/node_modules/undici/lib/handler/wrap-handler.js b/node_modules/undici/lib/handler/wrap-handler.js new file mode 100644 index 000000000..47caa5fa6 --- /dev/null +++ b/node_modules/undici/lib/handler/wrap-handler.js @@ -0,0 +1,95 @@ +'use strict' + +const { InvalidArgumentError } = require('../core/errors') + +module.exports = class WrapHandler { + #handler + + constructor (handler) { + this.#handler = handler + } + + static wrap (handler) { + // TODO (fix): More checks... + return handler.onRequestStart ? handler : new WrapHandler(handler) + } + + // Unwrap Interface + + onConnect (abort, context) { + return this.#handler.onConnect?.(abort, context) + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + return this.#handler.onHeaders?.(statusCode, rawHeaders, resume, statusMessage) + } + + onUpgrade (statusCode, rawHeaders, socket) { + return this.#handler.onUpgrade?.(statusCode, rawHeaders, socket) + } + + onData (data) { + return this.#handler.onData?.(data) + } + + onComplete (trailers) { + return this.#handler.onComplete?.(trailers) + } + + onError (err) { + if (!this.#handler.onError) { + throw err + } + + return this.#handler.onError?.(err) + } + + // Wrap Interface + + onRequestStart (controller, context) { + this.#handler.onConnect?.((reason) => controller.abort(reason), context) + } + + onRequestUpgrade (controller, statusCode, headers, socket) { + const rawHeaders = [] + for (const [key, val] of Object.entries(headers)) { + rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map(v => Buffer.from(v)) : Buffer.from(val)) + } + + this.#handler.onUpgrade?.(statusCode, rawHeaders, socket) + } + + onResponseStart (controller, statusCode, headers, statusMessage) { + const rawHeaders = [] + for (const [key, val] of Object.entries(headers)) { + rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map(v => Buffer.from(v)) : Buffer.from(val)) + } + + if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) { + controller.pause() + } + } + + onResponseData (controller, data) { + if (this.#handler.onData?.(data) === false) { + controller.pause() + } + } + + onResponseEnd (controller, trailers) { + const rawTrailers = [] + for (const [key, val] of Object.entries(trailers)) { + rawTrailers.push(Buffer.from(key), Array.isArray(val) ? val.map(v => Buffer.from(v)) : Buffer.from(val)) + } + + this.#handler.onComplete?.(rawTrailers) + } + + onResponseError (controller, err) { + if (!this.#handler.onError) { + throw new InvalidArgumentError('invalid onError method') + } + + this.#handler.onError?.(err) + } +} diff --git a/node_modules/undici/lib/interceptor/cache.js b/node_modules/undici/lib/interceptor/cache.js new file mode 100644 index 000000000..b0449374f --- /dev/null +++ b/node_modules/undici/lib/interceptor/cache.js @@ -0,0 +1,493 @@ +'use strict' + +const assert = require('node:assert') +const { Readable } = require('node:stream') +const util = require('../core/util') +const CacheHandler = require('../handler/cache-handler') +const MemoryCacheStore = require('../cache/memory-cache-store') +const CacheRevalidationHandler = require('../handler/cache-revalidation-handler') +const { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require('../util/cache.js') +const { AbortError } = require('../core/errors.js') + +/** + * @param {(string | RegExp)[] | undefined} origins + * @param {string} name + */ +function assertCacheOrigins (origins, name) { + if (origins === undefined) return + if (!Array.isArray(origins)) { + throw new TypeError(`expected ${name} to be an array or undefined, got ${typeof origins}`) + } + for (let i = 0; i < origins.length; i++) { + const origin = origins[i] + if (typeof origin !== 'string' && !(origin instanceof RegExp)) { + throw new TypeError(`expected ${name}[${i}] to be a string or RegExp, got ${typeof origin}`) + } + } +} + +const nop = () => {} + +/** + * @typedef {(options: import('../../types/dispatcher.d.ts').default.DispatchOptions, handler: import('../../types/dispatcher.d.ts').default.DispatchHandler) => void} DispatchFn + */ + +/** + * @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} cacheControlDirectives + * @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts + * @returns {boolean} + */ +function needsRevalidation (result, cacheControlDirectives, { headers = {} }) { + // Always revalidate requests with the no-cache request directive. + if (cacheControlDirectives?.['no-cache']) { + return true + } + + // Always revalidate requests with unqualified no-cache response directive. + if (result.cacheControlDirectives?.['no-cache'] && !Array.isArray(result.cacheControlDirectives['no-cache'])) { + return true + } + + // Always revalidate requests with conditional headers. + if (headers['if-modified-since'] || headers['if-none-match']) { + return true + } + + return false +} + +/** + * @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} cacheControlDirectives + * @returns {boolean} + */ +function isStale (result, cacheControlDirectives) { + const now = Date.now() + if (now > result.staleAt) { + // Response is stale + if (cacheControlDirectives?.['max-stale']) { + // There's a threshold where we can serve stale responses, let's see if + // we're in it + // https://www.rfc-editor.org/rfc/rfc9111.html#name-max-stale + const gracePeriod = result.staleAt + (cacheControlDirectives['max-stale'] * 1000) + return now > gracePeriod + } + + return true + } + + if (cacheControlDirectives?.['min-fresh']) { + // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.1.3 + + // At this point, staleAt is always > now + const timeLeftTillStale = result.staleAt - now + const threshold = cacheControlDirectives['min-fresh'] * 1000 + + return timeLeftTillStale <= threshold + } + + return false +} + +/** + * Check if we're within the stale-while-revalidate window for a stale response + * @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result + * @returns {boolean} + */ +function withinStaleWhileRevalidateWindow (result) { + const staleWhileRevalidate = result.cacheControlDirectives?.['stale-while-revalidate'] + if (!staleWhileRevalidate) { + return false + } + + const now = Date.now() + const staleWhileRevalidateExpiry = result.staleAt + (staleWhileRevalidate * 1000) + return now <= staleWhileRevalidateExpiry +} + +/** + * @param {DispatchFn} dispatch + * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} globalOpts + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey + * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler + * @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} reqCacheControl + */ +function handleUncachedResponse ( + dispatch, + globalOpts, + cacheKey, + handler, + opts, + reqCacheControl +) { + if (reqCacheControl?.['only-if-cached']) { + let aborted = false + try { + if (typeof handler.onConnect === 'function') { + handler.onConnect(() => { + aborted = true + }) + + if (aborted) { + return + } + } + + if (typeof handler.onHeaders === 'function') { + handler.onHeaders(504, [], nop, 'Gateway Timeout') + if (aborted) { + return + } + } + + if (typeof handler.onComplete === 'function') { + handler.onComplete([]) + } + } catch (err) { + if (typeof handler.onError === 'function') { + handler.onError(err) + } + } + + return true + } + + return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler)) +} + +/** + * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler + * @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts + * @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result + * @param {number} age + * @param {any} context + * @param {boolean} isStale + */ +function sendCachedValue (handler, opts, result, age, context, isStale) { + // TODO (perf): Readable.from path can be optimized... + const stream = util.isStream(result.body) + ? result.body + : Readable.from(result.body ?? []) + + assert(!stream.destroyed, 'stream should not be destroyed') + assert(!stream.readableDidRead, 'stream should not be readableDidRead') + + const controller = { + resume () { + stream.resume() + }, + pause () { + stream.pause() + }, + get paused () { + return stream.isPaused() + }, + get aborted () { + return stream.destroyed + }, + get reason () { + return stream.errored + }, + abort (reason) { + stream.destroy(reason ?? new AbortError()) + } + } + + stream + .on('error', function (err) { + if (!this.readableEnded) { + if (typeof handler.onResponseError === 'function') { + handler.onResponseError(controller, err) + } else { + throw err + } + } + }) + .on('close', function () { + if (!this.errored) { + handler.onResponseEnd?.(controller, {}) + } + }) + + handler.onRequestStart?.(controller, context) + + if (stream.destroyed) { + return + } + + // Add the age header + // https://www.rfc-editor.org/rfc/rfc9111.html#name-age + const headers = { ...result.headers, age: String(age) } + + if (isStale) { + // Add warning header + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Warning + headers.warning = '110 - "response is stale"' + } + + handler.onResponseStart?.(controller, result.statusCode, headers, result.statusMessage) + + if (opts.method === 'HEAD') { + stream.destroy() + } else { + stream.on('data', function (chunk) { + handler.onResponseData?.(controller, chunk) + }) + } +} + +/** + * @param {DispatchFn} dispatch + * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} globalOpts + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey + * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler + * @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} reqCacheControl + * @param {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined} result + */ +function handleResult ( + dispatch, + globalOpts, + cacheKey, + handler, + opts, + reqCacheControl, + result +) { + if (!result) { + return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl) + } + + const now = Date.now() + if (now > result.deleteAt) { + // Response is expired, cache store shouldn't have given this to us + return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler)) + } + + const age = Math.round((now - result.cachedAt) / 1000) + if (reqCacheControl?.['max-age'] && age >= reqCacheControl['max-age']) { + // Response is considered expired for this specific request + // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.1.1 + return dispatch(opts, handler) + } + + const stale = isStale(result, reqCacheControl) + const revalidate = needsRevalidation(result, reqCacheControl, opts) + + // Check if the response is stale + if (stale || revalidate) { + if (util.isStream(opts.body) && util.bodyLength(opts.body) !== 0) { + // If body is a stream we can't revalidate... + // TODO (fix): This could be less strict... + return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler)) + } + + // RFC 5861: If we're within stale-while-revalidate window, serve stale immediately + // and revalidate in background, unless immediate revalidation is necessary + if (!revalidate && withinStaleWhileRevalidateWindow(result)) { + // Serve stale response immediately + sendCachedValue(handler, opts, result, age, null, true) + + // Start background revalidation (fire-and-forget) + queueMicrotask(() => { + let headers = { + ...opts.headers, + 'if-modified-since': new Date(result.cachedAt).toUTCString() + } + + if (result.etag) { + headers['if-none-match'] = result.etag + } + + if (result.vary) { + headers = { + ...headers, + ...result.vary + } + } + + // Background revalidation - update cache if we get new data + dispatch( + { + ...opts, + headers + }, + new CacheHandler(globalOpts, cacheKey, { + // Silent handler that just updates the cache + onRequestStart () {}, + onRequestUpgrade () {}, + onResponseStart () {}, + onResponseData () {}, + onResponseEnd () {}, + onResponseError () {} + }) + ) + }) + + return true + } + + let withinStaleIfErrorThreshold = false + const staleIfErrorExpiry = result.cacheControlDirectives['stale-if-error'] ?? reqCacheControl?.['stale-if-error'] + if (staleIfErrorExpiry) { + withinStaleIfErrorThreshold = now < (result.staleAt + (staleIfErrorExpiry * 1000)) + } + + let headers = { + ...opts.headers, + 'if-modified-since': new Date(result.cachedAt).toUTCString() + } + + if (result.etag) { + headers['if-none-match'] = result.etag + } + + if (result.vary) { + headers = { + ...headers, + ...result.vary + } + } + + // We need to revalidate the response + return dispatch( + { + ...opts, + headers + }, + new CacheRevalidationHandler( + (success, context) => { + if (success) { + // TODO: successful revalidation should be considered fresh (not give stale warning). + sendCachedValue(handler, opts, result, age, context, stale) + } else if (util.isStream(result.body)) { + result.body.on('error', nop).destroy() + } + }, + new CacheHandler(globalOpts, cacheKey, handler), + withinStaleIfErrorThreshold + ) + ) + } + + // Dump request body. + if (util.isStream(opts.body)) { + opts.body.on('error', nop).destroy() + } + + sendCachedValue(handler, opts, result, age, null, false) +} + +/** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions} [opts] + * @returns {import('../../types/dispatcher.d.ts').default.DispatcherComposeInterceptor} + */ +module.exports = (opts = {}) => { + const { + store = new MemoryCacheStore(), + methods = ['GET'], + cacheByDefault = undefined, + type = 'shared', + origins = undefined + } = opts + + if (typeof opts !== 'object' || opts === null) { + throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? 'null' : typeof opts}`) + } + + assertCacheStore(store, 'opts.store') + assertCacheMethods(methods, 'opts.methods') + assertCacheOrigins(origins, 'opts.origins') + + if (typeof cacheByDefault !== 'undefined' && typeof cacheByDefault !== 'number') { + throw new TypeError(`expected opts.cacheByDefault to be number or undefined, got ${typeof cacheByDefault}`) + } + + if (typeof type !== 'undefined' && type !== 'shared' && type !== 'private') { + throw new TypeError(`expected opts.type to be shared, private, or undefined, got ${typeof type}`) + } + + const globalOpts = { + store, + methods, + cacheByDefault, + type + } + + const safeMethodsToNotCache = util.safeHTTPMethods.filter(method => methods.includes(method) === false) + + return dispatch => { + return (opts, handler) => { + if (!opts.origin || safeMethodsToNotCache.includes(opts.method)) { + // Not a method we want to cache or we don't have the origin, skip + return dispatch(opts, handler) + } + + // Check if origin is in whitelist + if (origins !== undefined) { + const requestOrigin = opts.origin.toString().toLowerCase() + let isAllowed = false + + for (let i = 0; i < origins.length; i++) { + const allowed = origins[i] + if (typeof allowed === 'string') { + if (allowed.toLowerCase() === requestOrigin) { + isAllowed = true + break + } + } else if (allowed.test(requestOrigin)) { + isAllowed = true + break + } + } + + if (!isAllowed) { + return dispatch(opts, handler) + } + } + + opts = { + ...opts, + headers: normalizeHeaders(opts) + } + + const reqCacheControl = opts.headers?.['cache-control'] + ? parseCacheControlHeader(opts.headers['cache-control']) + : undefined + + if (reqCacheControl?.['no-store']) { + return dispatch(opts, handler) + } + + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey} + */ + const cacheKey = makeCacheKey(opts) + const result = store.get(cacheKey) + + if (result && typeof result.then === 'function') { + return result + .then(result => handleResult(dispatch, + globalOpts, + cacheKey, + handler, + opts, + reqCacheControl, + result + )) + } else { + return handleResult( + dispatch, + globalOpts, + cacheKey, + handler, + opts, + reqCacheControl, + result + ) + } + } + } +} diff --git a/node_modules/undici/lib/interceptor/decompress.js b/node_modules/undici/lib/interceptor/decompress.js new file mode 100644 index 000000000..9d0cc58cf --- /dev/null +++ b/node_modules/undici/lib/interceptor/decompress.js @@ -0,0 +1,262 @@ +'use strict' + +const { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = require('node:zlib') +const { pipeline } = require('node:stream') +const DecoratorHandler = require('../handler/decorator-handler') +const { runtimeFeatures } = require('../util/runtime-features') + +/** @typedef {import('node:stream').Transform} Transform */ +/** @typedef {import('node:stream').Transform} Controller */ +/** @typedef {Transform&import('node:zlib').Zlib} DecompressorStream */ + +/** @type {Record DecompressorStream>} */ +const supportedEncodings = { + gzip: createGunzip, + 'x-gzip': createGunzip, + br: createBrotliDecompress, + deflate: createInflate, + compress: createInflate, + 'x-compress': createInflate, + ...(runtimeFeatures.has('zstd') ? { zstd: createZstdDecompress } : {}) +} + +const defaultSkipStatusCodes = /** @type {const} */ ([204, 304]) + +let warningEmitted = /** @type {boolean} */ (false) + +/** + * @typedef {Object} DecompressHandlerOptions + * @property {number[]|Readonly} [skipStatusCodes=[204, 304]] - List of status codes to skip decompression for + * @property {boolean} [skipErrorResponses] - Whether to skip decompression for error responses (status codes >= 400) + */ + +class DecompressHandler extends DecoratorHandler { + /** @type {Transform[]} */ + #decompressors = [] + /** @type {NodeJS.WritableStream&NodeJS.ReadableStream|null} */ + #pipelineStream + /** @type {Readonly} */ + #skipStatusCodes + /** @type {boolean} */ + #skipErrorResponses + + constructor (handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) { + super(handler) + this.#skipStatusCodes = skipStatusCodes + this.#skipErrorResponses = skipErrorResponses + } + + /** + * Determines if decompression should be skipped based on encoding and status code + * @param {string} contentEncoding - Content-Encoding header value + * @param {number} statusCode - HTTP status code of the response + * @returns {boolean} - True if decompression should be skipped + */ + #shouldSkipDecompression (contentEncoding, statusCode) { + if (!contentEncoding || statusCode < 200) return true + if (this.#skipStatusCodes.includes(statusCode)) return true + if (this.#skipErrorResponses && statusCode >= 400) return true + return false + } + + /** + * Creates a chain of decompressors for multiple content encodings + * + * @param {string} encodings - Comma-separated list of content encodings + * @returns {Array} - Array of decompressor streams + * @throws {Error} - If the number of content-encodings exceeds the maximum allowed + */ + #createDecompressionChain (encodings) { + const parts = encodings.split(',') + + // Limit the number of content-encodings to prevent resource exhaustion. + // CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206). + const maxContentEncodings = 5 + if (parts.length > maxContentEncodings) { + throw new Error(`too many content-encodings in response: ${parts.length}, maximum allowed is ${maxContentEncodings}`) + } + + /** @type {DecompressorStream[]} */ + const decompressors = [] + + for (let i = parts.length - 1; i >= 0; i--) { + const encoding = parts[i].trim() + if (!encoding) continue + + if (!supportedEncodings[encoding]) { + decompressors.length = 0 // Clear if unsupported encoding + return decompressors // Unsupported encoding + } + + decompressors.push(supportedEncodings[encoding]()) + } + + return decompressors + } + + /** + * Sets up event handlers for a decompressor stream using readable events + * @param {DecompressorStream} decompressor - The decompressor stream + * @param {Controller} controller - The controller to coordinate with + * @returns {void} + */ + #setupDecompressorEvents (decompressor, controller) { + decompressor.on('readable', () => { + let chunk + while ((chunk = decompressor.read()) !== null) { + const result = super.onResponseData(controller, chunk) + if (result === false) { + break + } + } + }) + + decompressor.on('error', (error) => { + super.onResponseError(controller, error) + }) + } + + /** + * Sets up event handling for a single decompressor + * @param {Controller} controller - The controller to handle events + * @returns {void} + */ + #setupSingleDecompressor (controller) { + const decompressor = this.#decompressors[0] + this.#setupDecompressorEvents(decompressor, controller) + + decompressor.on('end', () => { + super.onResponseEnd(controller, {}) + }) + } + + /** + * Sets up event handling for multiple chained decompressors using pipeline + * @param {Controller} controller - The controller to handle events + * @returns {void} + */ + #setupMultipleDecompressors (controller) { + const lastDecompressor = this.#decompressors[this.#decompressors.length - 1] + this.#setupDecompressorEvents(lastDecompressor, controller) + + this.#pipelineStream = pipeline(this.#decompressors, (err) => { + if (err) { + super.onResponseError(controller, err) + return + } + super.onResponseEnd(controller, {}) + }) + } + + /** + * Cleans up decompressor references to prevent memory leaks + * @returns {void} + */ + #cleanupDecompressors () { + this.#decompressors.length = 0 + this.#pipelineStream = null + } + + /** + * @param {Controller} controller + * @param {number} statusCode + * @param {Record} headers + * @param {string} statusMessage + * @returns {void} + */ + onResponseStart (controller, statusCode, headers, statusMessage) { + const contentEncoding = headers['content-encoding'] + + // If content encoding is not supported or status code is in skip list + if (this.#shouldSkipDecompression(contentEncoding, statusCode)) { + return super.onResponseStart(controller, statusCode, headers, statusMessage) + } + + const decompressors = this.#createDecompressionChain(contentEncoding.toLowerCase()) + + if (decompressors.length === 0) { + this.#cleanupDecompressors() + return super.onResponseStart(controller, statusCode, headers, statusMessage) + } + + this.#decompressors = decompressors + + // Remove compression headers since we're decompressing + const { 'content-encoding': _, 'content-length': __, ...newHeaders } = headers + + if (this.#decompressors.length === 1) { + this.#setupSingleDecompressor(controller) + } else { + this.#setupMultipleDecompressors(controller) + } + + super.onResponseStart(controller, statusCode, newHeaders, statusMessage) + } + + /** + * @param {Controller} controller + * @param {Buffer} chunk + * @returns {void} + */ + onResponseData (controller, chunk) { + if (this.#decompressors.length > 0) { + this.#decompressors[0].write(chunk) + return + } + super.onResponseData(controller, chunk) + } + + /** + * @param {Controller} controller + * @param {Record | undefined} trailers + * @returns {void} + */ + onResponseEnd (controller, trailers) { + if (this.#decompressors.length > 0) { + this.#decompressors[0].end() + this.#cleanupDecompressors() + return + } + super.onResponseEnd(controller, trailers) + } + + /** + * @param {Controller} controller + * @param {Error} err + * @returns {void} + */ + onResponseError (controller, err) { + if (this.#decompressors.length > 0) { + for (const decompressor of this.#decompressors) { + decompressor.destroy(err) + } + this.#cleanupDecompressors() + } + super.onResponseError(controller, err) + } +} + +/** + * Creates a decompression interceptor for HTTP responses + * @param {DecompressHandlerOptions} [options] - Options for the interceptor + * @returns {Function} - Interceptor function + */ +function createDecompressInterceptor (options = {}) { + // Emit experimental warning only once + if (!warningEmitted) { + process.emitWarning( + 'DecompressInterceptor is experimental and subject to change', + 'ExperimentalWarning' + ) + warningEmitted = true + } + + return (dispatch) => { + return (opts, handler) => { + const decompressHandler = new DecompressHandler(handler, options) + return dispatch(opts, decompressHandler) + } + } +} + +module.exports = createDecompressInterceptor diff --git a/node_modules/undici/lib/interceptor/deduplicate.js b/node_modules/undici/lib/interceptor/deduplicate.js new file mode 100644 index 000000000..9244088fa --- /dev/null +++ b/node_modules/undici/lib/interceptor/deduplicate.js @@ -0,0 +1,109 @@ +'use strict' + +const diagnosticsChannel = require('node:diagnostics_channel') +const util = require('../core/util') +const DeduplicationHandler = require('../handler/deduplication-handler') +const { normalizeHeaders, makeCacheKey, makeDeduplicationKey } = require('../util/cache.js') + +const pendingRequestsChannel = diagnosticsChannel.channel('undici:request:pending-requests') + +/** + * @param {import('../../types/interceptors.d.ts').default.DeduplicateInterceptorOpts} [opts] + * @returns {import('../../types/dispatcher.d.ts').default.DispatcherComposeInterceptor} + */ +module.exports = (opts = {}) => { + const { + methods = ['GET'], + skipHeaderNames = [], + excludeHeaderNames = [] + } = opts + + if (typeof opts !== 'object' || opts === null) { + throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? 'null' : typeof opts}`) + } + + if (!Array.isArray(methods)) { + throw new TypeError(`expected opts.methods to be an array, got ${typeof methods}`) + } + + for (const method of methods) { + if (!util.safeHTTPMethods.includes(method)) { + throw new TypeError(`expected opts.methods to only contain safe HTTP methods, got ${method}`) + } + } + + if (!Array.isArray(skipHeaderNames)) { + throw new TypeError(`expected opts.skipHeaderNames to be an array, got ${typeof skipHeaderNames}`) + } + + if (!Array.isArray(excludeHeaderNames)) { + throw new TypeError(`expected opts.excludeHeaderNames to be an array, got ${typeof excludeHeaderNames}`) + } + + // Convert to lowercase Set for case-insensitive header matching + const skipHeaderNamesSet = new Set(skipHeaderNames.map(name => name.toLowerCase())) + + // Convert to lowercase Set for case-insensitive header exclusion from deduplication key + const excludeHeaderNamesSet = new Set(excludeHeaderNames.map(name => name.toLowerCase())) + + const safeMethodsToNotDeduplicate = util.safeHTTPMethods.filter(method => methods.includes(method) === false) + + /** + * Map of pending requests for deduplication + * @type {Map} + */ + const pendingRequests = new Map() + + return dispatch => { + return (opts, handler) => { + if (!opts.origin || safeMethodsToNotDeduplicate.includes(opts.method)) { + return dispatch(opts, handler) + } + + opts = { + ...opts, + headers: normalizeHeaders(opts) + } + + // Skip deduplication if request contains any of the specified headers + if (skipHeaderNamesSet.size > 0) { + for (const headerName of Object.keys(opts.headers)) { + if (skipHeaderNamesSet.has(headerName.toLowerCase())) { + return dispatch(opts, handler) + } + } + } + + const cacheKey = makeCacheKey(opts) + const dedupeKey = makeDeduplicationKey(cacheKey, excludeHeaderNamesSet) + + // Check if there's already a pending request for this key + const pendingHandler = pendingRequests.get(dedupeKey) + if (pendingHandler) { + // Add this handler to the waiting list + pendingHandler.addWaitingHandler(handler) + return true + } + + // Create a new deduplication handler + const deduplicationHandler = new DeduplicationHandler( + handler, + () => { + // Clean up when request completes + pendingRequests.delete(dedupeKey) + if (pendingRequestsChannel.hasSubscribers) { + pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: 'removed' }) + } + } + ) + + // Register the pending request + pendingRequests.set(dedupeKey, deduplicationHandler) + if (pendingRequestsChannel.hasSubscribers) { + pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: 'added' }) + } + + return dispatch(opts, deduplicationHandler) + } + } +} diff --git a/node_modules/undici/lib/interceptor/dns.js b/node_modules/undici/lib/interceptor/dns.js new file mode 100644 index 000000000..9dba957a6 --- /dev/null +++ b/node_modules/undici/lib/interceptor/dns.js @@ -0,0 +1,474 @@ +'use strict' +const { isIP } = require('node:net') +const { lookup } = require('node:dns') +const DecoratorHandler = require('../handler/decorator-handler') +const { InvalidArgumentError, InformationalError } = require('../core/errors') +const maxInt = Math.pow(2, 31) - 1 + +class DNSStorage { + #maxItems = 0 + #records = new Map() + + constructor (opts) { + this.#maxItems = opts.maxItems + } + + get size () { + return this.#records.size + } + + get (hostname) { + return this.#records.get(hostname) ?? null + } + + set (hostname, records) { + this.#records.set(hostname, records) + } + + delete (hostname) { + this.#records.delete(hostname) + } + + // Delegate to storage decide can we do more lookups or not + full () { + return this.size >= this.#maxItems + } +} + +class DNSInstance { + #maxTTL = 0 + #maxItems = 0 + dualStack = true + affinity = null + lookup = null + pick = null + storage = null + + constructor (opts) { + this.#maxTTL = opts.maxTTL + this.#maxItems = opts.maxItems + this.dualStack = opts.dualStack + this.affinity = opts.affinity + this.lookup = opts.lookup ?? this.#defaultLookup + this.pick = opts.pick ?? this.#defaultPick + this.storage = opts.storage ?? new DNSStorage(opts) + } + + runLookup (origin, opts, cb) { + const ips = this.storage.get(origin.hostname) + + // If full, we just return the origin + if (ips == null && this.storage.full()) { + cb(null, origin) + return + } + + const newOpts = { + affinity: this.affinity, + dualStack: this.dualStack, + lookup: this.lookup, + pick: this.pick, + ...opts.dns, + maxTTL: this.#maxTTL, + maxItems: this.#maxItems + } + + // If no IPs we lookup + if (ips == null) { + this.lookup(origin, newOpts, (err, addresses) => { + if (err || addresses == null || addresses.length === 0) { + cb(err ?? new InformationalError('No DNS entries found')) + return + } + + this.setRecords(origin, addresses) + const records = this.storage.get(origin.hostname) + + const ip = this.pick( + origin, + records, + newOpts.affinity + ) + + let port + if (typeof ip.port === 'number') { + port = `:${ip.port}` + } else if (origin.port !== '') { + port = `:${origin.port}` + } else { + port = '' + } + + cb( + null, + new URL(`${origin.protocol}//${ + ip.family === 6 ? `[${ip.address}]` : ip.address + }${port}`) + ) + }) + } else { + // If there's IPs we pick + const ip = this.pick( + origin, + ips, + newOpts.affinity + ) + + // If no IPs we lookup - deleting old records + if (ip == null) { + this.storage.delete(origin.hostname) + this.runLookup(origin, opts, cb) + return + } + + let port + if (typeof ip.port === 'number') { + port = `:${ip.port}` + } else if (origin.port !== '') { + port = `:${origin.port}` + } else { + port = '' + } + + cb( + null, + new URL(`${origin.protocol}//${ + ip.family === 6 ? `[${ip.address}]` : ip.address + }${port}`) + ) + } + } + + #defaultLookup (origin, opts, cb) { + lookup( + origin.hostname, + { + all: true, + family: this.dualStack === false ? this.affinity : 0, + order: 'ipv4first' + }, + (err, addresses) => { + if (err) { + return cb(err) + } + + const results = new Map() + + for (const addr of addresses) { + // On linux we found duplicates, we attempt to remove them with + // the latest record + results.set(`${addr.address}:${addr.family}`, addr) + } + + cb(null, results.values()) + } + ) + } + + #defaultPick (origin, hostnameRecords, affinity) { + let ip = null + const { records, offset } = hostnameRecords + + let family + if (this.dualStack) { + if (affinity == null) { + // Balance between ip families + if (offset == null || offset === maxInt) { + hostnameRecords.offset = 0 + affinity = 4 + } else { + hostnameRecords.offset++ + affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4 + } + } + + if (records[affinity] != null && records[affinity].ips.length > 0) { + family = records[affinity] + } else { + family = records[affinity === 4 ? 6 : 4] + } + } else { + family = records[affinity] + } + + // If no IPs we return null + if (family == null || family.ips.length === 0) { + return ip + } + + if (family.offset == null || family.offset === maxInt) { + family.offset = 0 + } else { + family.offset++ + } + + const position = family.offset % family.ips.length + ip = family.ips[position] ?? null + + if (ip == null) { + return ip + } + + if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms + // We delete expired records + // It is possible that they have different TTL, so we manage them individually + family.ips.splice(position, 1) + return this.pick(origin, hostnameRecords, affinity) + } + + return ip + } + + pickFamily (origin, ipFamily) { + const records = this.storage.get(origin.hostname)?.records + if (!records) { + return null + } + + const family = records[ipFamily] + if (!family) { + return null + } + + if (family.offset == null || family.offset === maxInt) { + family.offset = 0 + } else { + family.offset++ + } + + const position = family.offset % family.ips.length + const ip = family.ips[position] ?? null + if (ip == null) { + return ip + } + + if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms + // We delete expired records + // It is possible that they have different TTL, so we manage them individually + family.ips.splice(position, 1) + } + + return ip + } + + setRecords (origin, addresses) { + const timestamp = Date.now() + const records = { records: { 4: null, 6: null } } + let minTTL = this.#maxTTL + for (const record of addresses) { + record.timestamp = timestamp + if (typeof record.ttl === 'number') { + // The record TTL is expected to be in ms + record.ttl = Math.min(record.ttl, this.#maxTTL) + minTTL = Math.min(minTTL, record.ttl) + } else { + record.ttl = this.#maxTTL + } + + const familyRecords = records.records[record.family] ?? { ips: [] } + + familyRecords.ips.push(record) + records.records[record.family] = familyRecords + } + + // We provide a default TTL if external storage will be used without TTL per record-level support + this.storage.set(origin.hostname, records, { ttl: minTTL }) + } + + deleteRecords (origin) { + this.storage.delete(origin.hostname) + } + + getHandler (meta, opts) { + return new DNSDispatchHandler(this, meta, opts) + } +} + +class DNSDispatchHandler extends DecoratorHandler { + #state = null + #opts = null + #dispatch = null + #origin = null + #controller = null + #newOrigin = null + #firstTry = true + + constructor (state, { origin, handler, dispatch, newOrigin }, opts) { + super(handler) + this.#origin = origin + this.#newOrigin = newOrigin + this.#opts = { ...opts } + this.#state = state + this.#dispatch = dispatch + } + + onResponseError (controller, err) { + switch (err.code) { + case 'ETIMEDOUT': + case 'ECONNREFUSED': { + if (this.#state.dualStack) { + if (!this.#firstTry) { + super.onResponseError(controller, err) + return + } + this.#firstTry = false + + // Pick an ip address from the other family + const otherFamily = this.#newOrigin.hostname[0] === '[' ? 4 : 6 + const ip = this.#state.pickFamily(this.#origin, otherFamily) + if (ip == null) { + super.onResponseError(controller, err) + return + } + + let port + if (typeof ip.port === 'number') { + port = `:${ip.port}` + } else if (this.#origin.port !== '') { + port = `:${this.#origin.port}` + } else { + port = '' + } + + const dispatchOpts = { + ...this.#opts, + origin: `${this.#origin.protocol}//${ + ip.family === 6 ? `[${ip.address}]` : ip.address + }${port}` + } + this.#dispatch(dispatchOpts, this) + return + } + + // if dual-stack disabled, we error out + super.onResponseError(controller, err) + break + } + case 'ENOTFOUND': + this.#state.deleteRecords(this.#origin) + super.onResponseError(controller, err) + break + default: + super.onResponseError(controller, err) + break + } + } +} + +module.exports = interceptorOpts => { + if ( + interceptorOpts?.maxTTL != null && + (typeof interceptorOpts?.maxTTL !== 'number' || interceptorOpts?.maxTTL < 0) + ) { + throw new InvalidArgumentError('Invalid maxTTL. Must be a positive number') + } + + if ( + interceptorOpts?.maxItems != null && + (typeof interceptorOpts?.maxItems !== 'number' || + interceptorOpts?.maxItems < 1) + ) { + throw new InvalidArgumentError( + 'Invalid maxItems. Must be a positive number and greater than zero' + ) + } + + if ( + interceptorOpts?.affinity != null && + interceptorOpts?.affinity !== 4 && + interceptorOpts?.affinity !== 6 + ) { + throw new InvalidArgumentError('Invalid affinity. Must be either 4 or 6') + } + + if ( + interceptorOpts?.dualStack != null && + typeof interceptorOpts?.dualStack !== 'boolean' + ) { + throw new InvalidArgumentError('Invalid dualStack. Must be a boolean') + } + + if ( + interceptorOpts?.lookup != null && + typeof interceptorOpts?.lookup !== 'function' + ) { + throw new InvalidArgumentError('Invalid lookup. Must be a function') + } + + if ( + interceptorOpts?.pick != null && + typeof interceptorOpts?.pick !== 'function' + ) { + throw new InvalidArgumentError('Invalid pick. Must be a function') + } + + if ( + interceptorOpts?.storage != null && + (typeof interceptorOpts?.storage?.get !== 'function' || + typeof interceptorOpts?.storage?.set !== 'function' || + typeof interceptorOpts?.storage?.full !== 'function' || + typeof interceptorOpts?.storage?.delete !== 'function' + ) + ) { + throw new InvalidArgumentError('Invalid storage. Must be a object with methods: { get, set, full, delete }') + } + + const dualStack = interceptorOpts?.dualStack ?? true + let affinity + if (dualStack) { + affinity = interceptorOpts?.affinity ?? null + } else { + affinity = interceptorOpts?.affinity ?? 4 + } + + const opts = { + maxTTL: interceptorOpts?.maxTTL ?? 10e3, // Expressed in ms + lookup: interceptorOpts?.lookup ?? null, + pick: interceptorOpts?.pick ?? null, + dualStack, + affinity, + maxItems: interceptorOpts?.maxItems ?? Infinity, + storage: interceptorOpts?.storage + } + + const instance = new DNSInstance(opts) + + return dispatch => { + return function dnsInterceptor (origDispatchOpts, handler) { + const origin = + origDispatchOpts.origin.constructor === URL + ? origDispatchOpts.origin + : new URL(origDispatchOpts.origin) + + if (isIP(origin.hostname) !== 0) { + return dispatch(origDispatchOpts, handler) + } + + instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => { + if (err) { + return handler.onResponseError(null, err) + } + + const dispatchOpts = { + ...origDispatchOpts, + servername: origin.hostname, // For SNI on TLS + origin: newOrigin.origin, + headers: { + host: origin.host, + ...origDispatchOpts.headers + } + } + + dispatch( + dispatchOpts, + instance.getHandler( + { origin, dispatch, handler, newOrigin }, + origDispatchOpts + ) + ) + }) + + return true + } + } +} diff --git a/node_modules/undici/lib/interceptor/dump.js b/node_modules/undici/lib/interceptor/dump.js new file mode 100644 index 000000000..4810a09f3 --- /dev/null +++ b/node_modules/undici/lib/interceptor/dump.js @@ -0,0 +1,112 @@ +'use strict' + +const { InvalidArgumentError, RequestAbortedError } = require('../core/errors') +const DecoratorHandler = require('../handler/decorator-handler') + +class DumpHandler extends DecoratorHandler { + #maxSize = 1024 * 1024 + #dumped = false + #size = 0 + #controller = null + aborted = false + reason = false + + constructor ({ maxSize, signal }, handler) { + if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) { + throw new InvalidArgumentError('maxSize must be a number greater than 0') + } + + super(handler) + + this.#maxSize = maxSize ?? this.#maxSize + // this.#handler = handler + } + + #abort (reason) { + this.aborted = true + this.reason = reason + } + + onRequestStart (controller, context) { + controller.abort = this.#abort.bind(this) + this.#controller = controller + + return super.onRequestStart(controller, context) + } + + onResponseStart (controller, statusCode, headers, statusMessage) { + const contentLength = headers['content-length'] + + if (contentLength != null && contentLength > this.#maxSize) { + throw new RequestAbortedError( + `Response size (${contentLength}) larger than maxSize (${ + this.#maxSize + })` + ) + } + + if (this.aborted === true) { + return true + } + + return super.onResponseStart(controller, statusCode, headers, statusMessage) + } + + onResponseError (controller, err) { + if (this.#dumped) { + return + } + + // On network errors before connect, controller will be null + err = this.#controller?.reason ?? err + + super.onResponseError(controller, err) + } + + onResponseData (controller, chunk) { + this.#size = this.#size + chunk.length + + if (this.#size >= this.#maxSize) { + this.#dumped = true + + if (this.aborted === true) { + super.onResponseError(controller, this.reason) + } else { + super.onResponseEnd(controller, {}) + } + } + + return true + } + + onResponseEnd (controller, trailers) { + if (this.#dumped) { + return + } + + if (this.#controller.aborted === true) { + super.onResponseError(controller, this.reason) + return + } + + super.onResponseEnd(controller, trailers) + } +} + +function createDumpInterceptor ( + { maxSize: defaultMaxSize } = { + maxSize: 1024 * 1024 + } +) { + return dispatch => { + return function Intercept (opts, handler) { + const { dumpMaxSize = defaultMaxSize } = opts + + const dumpHandler = new DumpHandler({ maxSize: dumpMaxSize, signal: opts.signal }, handler) + + return dispatch(opts, dumpHandler) + } + } +} + +module.exports = createDumpInterceptor diff --git a/node_modules/undici/lib/interceptor/redirect.js b/node_modules/undici/lib/interceptor/redirect.js new file mode 100644 index 000000000..b7df18043 --- /dev/null +++ b/node_modules/undici/lib/interceptor/redirect.js @@ -0,0 +1,21 @@ +'use strict' + +const RedirectHandler = require('../handler/redirect-handler') + +function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections } = {}) { + return (dispatch) => { + return function Intercept (opts, handler) { + const { maxRedirections = defaultMaxRedirections, ...rest } = opts + + if (maxRedirections == null || maxRedirections === 0) { + return dispatch(opts, handler) + } + + const dispatchOpts = { ...rest } // Stop sub dispatcher from also redirecting. + const redirectHandler = new RedirectHandler(dispatch, maxRedirections, dispatchOpts, handler) + return dispatch(dispatchOpts, redirectHandler) + } + } +} + +module.exports = createRedirectInterceptor diff --git a/node_modules/undici/lib/interceptor/response-error.js b/node_modules/undici/lib/interceptor/response-error.js new file mode 100644 index 000000000..a8105aa14 --- /dev/null +++ b/node_modules/undici/lib/interceptor/response-error.js @@ -0,0 +1,95 @@ +'use strict' + +// const { parseHeaders } = require('../core/util') +const DecoratorHandler = require('../handler/decorator-handler') +const { ResponseError } = require('../core/errors') + +class ResponseErrorHandler extends DecoratorHandler { + #statusCode + #contentType + #decoder + #headers + #body + + constructor (_opts, { handler }) { + super(handler) + } + + #checkContentType (contentType) { + return (this.#contentType ?? '').indexOf(contentType) === 0 + } + + onRequestStart (controller, context) { + this.#statusCode = 0 + this.#contentType = null + this.#decoder = null + this.#headers = null + this.#body = '' + + return super.onRequestStart(controller, context) + } + + onResponseStart (controller, statusCode, headers, statusMessage) { + this.#statusCode = statusCode + this.#headers = headers + this.#contentType = headers['content-type'] + + if (this.#statusCode < 400) { + return super.onResponseStart(controller, statusCode, headers, statusMessage) + } + + if (this.#checkContentType('application/json') || this.#checkContentType('text/plain')) { + this.#decoder = new TextDecoder('utf-8') + } + } + + onResponseData (controller, chunk) { + if (this.#statusCode < 400) { + return super.onResponseData(controller, chunk) + } + + this.#body += this.#decoder?.decode(chunk, { stream: true }) ?? '' + } + + onResponseEnd (controller, trailers) { + if (this.#statusCode >= 400) { + this.#body += this.#decoder?.decode(undefined, { stream: false }) ?? '' + + if (this.#checkContentType('application/json')) { + try { + this.#body = JSON.parse(this.#body) + } catch { + // Do nothing... + } + } + + let err + const stackTraceLimit = Error.stackTraceLimit + Error.stackTraceLimit = 0 + try { + err = new ResponseError('Response Error', this.#statusCode, { + body: this.#body, + headers: this.#headers + }) + } finally { + Error.stackTraceLimit = stackTraceLimit + } + + super.onResponseError(controller, err) + } else { + super.onResponseEnd(controller, trailers) + } + } + + onResponseError (controller, err) { + super.onResponseError(controller, err) + } +} + +module.exports = () => { + return (dispatch) => { + return function Intercept (opts, handler) { + return dispatch(opts, new ResponseErrorHandler(opts, { handler })) + } + } +} diff --git a/node_modules/undici/lib/interceptor/retry.js b/node_modules/undici/lib/interceptor/retry.js new file mode 100644 index 000000000..1c16fd845 --- /dev/null +++ b/node_modules/undici/lib/interceptor/retry.js @@ -0,0 +1,19 @@ +'use strict' +const RetryHandler = require('../handler/retry-handler') + +module.exports = globalOpts => { + return dispatch => { + return function retryInterceptor (opts, handler) { + return dispatch( + opts, + new RetryHandler( + { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } }, + { + handler, + dispatch + } + ) + ) + } + } +} diff --git a/node_modules/undici/lib/llhttp/.gitkeep b/node_modules/undici/lib/llhttp/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/undici/lib/llhttp/constants.d.ts b/node_modules/undici/lib/llhttp/constants.d.ts new file mode 100644 index 000000000..def2436cc --- /dev/null +++ b/node_modules/undici/lib/llhttp/constants.d.ts @@ -0,0 +1,195 @@ +export type IntDict = Record; +export declare const ERROR: IntDict; +export declare const TYPE: IntDict; +export declare const FLAGS: IntDict; +export declare const LENIENT_FLAGS: IntDict; +export declare const METHODS: IntDict; +export declare const STATUSES: IntDict; +export declare const FINISH: IntDict; +export declare const HEADER_STATE: IntDict; +export declare const METHODS_HTTP: number[]; +export declare const METHODS_ICE: number[]; +export declare const METHODS_RTSP: number[]; +export declare const METHOD_MAP: IntDict; +export declare const H_METHOD_MAP: { + [k: string]: number; +}; +export declare const STATUSES_HTTP: number[]; +export type CharList = (string | number)[]; +export declare const ALPHA: CharList; +export declare const NUM_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare const HEX_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; +}; +export declare const NUM: CharList; +export declare const ALPHANUM: CharList; +export declare const MARK: CharList; +export declare const USERINFO_CHARS: CharList; +export declare const URL_CHAR: CharList; +export declare const HEX: CharList; +export declare const TOKEN: CharList; +export declare const HEADER_CHARS: CharList; +export declare const CONNECTION_TOKEN_CHARS: CharList; +export declare const QUOTED_STRING: CharList; +export declare const HTAB_SP_VCHAR_OBS_TEXT: CharList; +export declare const MAJOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare const MINOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare const SPECIAL_HEADERS: { + connection: number; + 'content-length': number; + 'proxy-connection': number; + 'transfer-encoding': number; + upgrade: number; +}; +declare const _default: { + ERROR: IntDict; + TYPE: IntDict; + FLAGS: IntDict; + LENIENT_FLAGS: IntDict; + METHODS: IntDict; + STATUSES: IntDict; + FINISH: IntDict; + HEADER_STATE: IntDict; + ALPHA: CharList; + NUM_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + }; + HEX_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + }; + NUM: CharList; + ALPHANUM: CharList; + MARK: CharList; + USERINFO_CHARS: CharList; + URL_CHAR: CharList; + HEX: CharList; + TOKEN: CharList; + HEADER_CHARS: CharList; + CONNECTION_TOKEN_CHARS: CharList; + QUOTED_STRING: CharList; + HTAB_SP_VCHAR_OBS_TEXT: CharList; + MAJOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + }; + MINOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + }; + SPECIAL_HEADERS: { + connection: number; + 'content-length': number; + 'proxy-connection': number; + 'transfer-encoding': number; + upgrade: number; + }; + METHODS_HTTP: number[]; + METHODS_ICE: number[]; + METHODS_RTSP: number[]; + METHOD_MAP: IntDict; + H_METHOD_MAP: { + [k: string]: number; + }; + STATUSES_HTTP: number[]; +}; +export default _default; diff --git a/node_modules/undici/lib/llhttp/constants.js b/node_modules/undici/lib/llhttp/constants.js new file mode 100644 index 000000000..8b88dfdf6 --- /dev/null +++ b/node_modules/undici/lib/llhttp/constants.js @@ -0,0 +1,531 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SPECIAL_HEADERS = exports.MINOR = exports.MAJOR = exports.HTAB_SP_VCHAR_OBS_TEXT = exports.QUOTED_STRING = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.HEX = exports.URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.STATUSES_HTTP = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.HEADER_STATE = exports.FINISH = exports.STATUSES = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; +const utils_1 = require("./utils"); +// Emums +exports.ERROR = { + OK: 0, + INTERNAL: 1, + STRICT: 2, + CR_EXPECTED: 25, + LF_EXPECTED: 3, + UNEXPECTED_CONTENT_LENGTH: 4, + UNEXPECTED_SPACE: 30, + CLOSED_CONNECTION: 5, + INVALID_METHOD: 6, + INVALID_URL: 7, + INVALID_CONSTANT: 8, + INVALID_VERSION: 9, + INVALID_HEADER_TOKEN: 10, + INVALID_CONTENT_LENGTH: 11, + INVALID_CHUNK_SIZE: 12, + INVALID_STATUS: 13, + INVALID_EOF_STATE: 14, + INVALID_TRANSFER_ENCODING: 15, + CB_MESSAGE_BEGIN: 16, + CB_HEADERS_COMPLETE: 17, + CB_MESSAGE_COMPLETE: 18, + CB_CHUNK_HEADER: 19, + CB_CHUNK_COMPLETE: 20, + PAUSED: 21, + PAUSED_UPGRADE: 22, + PAUSED_H2_UPGRADE: 23, + USER: 24, + CB_URL_COMPLETE: 26, + CB_STATUS_COMPLETE: 27, + CB_METHOD_COMPLETE: 32, + CB_VERSION_COMPLETE: 33, + CB_HEADER_FIELD_COMPLETE: 28, + CB_HEADER_VALUE_COMPLETE: 29, + CB_CHUNK_EXTENSION_NAME_COMPLETE: 34, + CB_CHUNK_EXTENSION_VALUE_COMPLETE: 35, + CB_RESET: 31, + CB_PROTOCOL_COMPLETE: 38, +}; +exports.TYPE = { + BOTH: 0, // default + REQUEST: 1, + RESPONSE: 2, +}; +exports.FLAGS = { + CONNECTION_KEEP_ALIVE: 1 << 0, + CONNECTION_CLOSE: 1 << 1, + CONNECTION_UPGRADE: 1 << 2, + CHUNKED: 1 << 3, + UPGRADE: 1 << 4, + CONTENT_LENGTH: 1 << 5, + SKIPBODY: 1 << 6, + TRAILING: 1 << 7, + // 1 << 8 is unused + TRANSFER_ENCODING: 1 << 9, +}; +exports.LENIENT_FLAGS = { + HEADERS: 1 << 0, + CHUNKED_LENGTH: 1 << 1, + KEEP_ALIVE: 1 << 2, + TRANSFER_ENCODING: 1 << 3, + VERSION: 1 << 4, + DATA_AFTER_CLOSE: 1 << 5, + OPTIONAL_LF_AFTER_CR: 1 << 6, + OPTIONAL_CRLF_AFTER_CHUNK: 1 << 7, + OPTIONAL_CR_BEFORE_LF: 1 << 8, + SPACES_AFTER_CHUNK_SIZE: 1 << 9, +}; +exports.METHODS = { + 'DELETE': 0, + 'GET': 1, + 'HEAD': 2, + 'POST': 3, + 'PUT': 4, + /* pathological */ + 'CONNECT': 5, + 'OPTIONS': 6, + 'TRACE': 7, + /* WebDAV */ + 'COPY': 8, + 'LOCK': 9, + 'MKCOL': 10, + 'MOVE': 11, + 'PROPFIND': 12, + 'PROPPATCH': 13, + 'SEARCH': 14, + 'UNLOCK': 15, + 'BIND': 16, + 'REBIND': 17, + 'UNBIND': 18, + 'ACL': 19, + /* subversion */ + 'REPORT': 20, + 'MKACTIVITY': 21, + 'CHECKOUT': 22, + 'MERGE': 23, + /* upnp */ + 'M-SEARCH': 24, + 'NOTIFY': 25, + 'SUBSCRIBE': 26, + 'UNSUBSCRIBE': 27, + /* RFC-5789 */ + 'PATCH': 28, + 'PURGE': 29, + /* CalDAV */ + 'MKCALENDAR': 30, + /* RFC-2068, section 19.6.1.2 */ + 'LINK': 31, + 'UNLINK': 32, + /* icecast */ + 'SOURCE': 33, + /* RFC-7540, section 11.6 */ + 'PRI': 34, + /* RFC-2326 RTSP */ + 'DESCRIBE': 35, + 'ANNOUNCE': 36, + 'SETUP': 37, + 'PLAY': 38, + 'PAUSE': 39, + 'TEARDOWN': 40, + 'GET_PARAMETER': 41, + 'SET_PARAMETER': 42, + 'REDIRECT': 43, + 'RECORD': 44, + /* RAOP */ + 'FLUSH': 45, + /* DRAFT https://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-02.html */ + 'QUERY': 46, +}; +exports.STATUSES = { + CONTINUE: 100, + SWITCHING_PROTOCOLS: 101, + PROCESSING: 102, + EARLY_HINTS: 103, + RESPONSE_IS_STALE: 110, // Unofficial + REVALIDATION_FAILED: 111, // Unofficial + DISCONNECTED_OPERATION: 112, // Unofficial + HEURISTIC_EXPIRATION: 113, // Unofficial + MISCELLANEOUS_WARNING: 199, // Unofficial + OK: 200, + CREATED: 201, + ACCEPTED: 202, + NON_AUTHORITATIVE_INFORMATION: 203, + NO_CONTENT: 204, + RESET_CONTENT: 205, + PARTIAL_CONTENT: 206, + MULTI_STATUS: 207, + ALREADY_REPORTED: 208, + TRANSFORMATION_APPLIED: 214, // Unofficial + IM_USED: 226, + MISCELLANEOUS_PERSISTENT_WARNING: 299, // Unofficial + MULTIPLE_CHOICES: 300, + MOVED_PERMANENTLY: 301, + FOUND: 302, + SEE_OTHER: 303, + NOT_MODIFIED: 304, + USE_PROXY: 305, + SWITCH_PROXY: 306, // No longer used + TEMPORARY_REDIRECT: 307, + PERMANENT_REDIRECT: 308, + BAD_REQUEST: 400, + UNAUTHORIZED: 401, + PAYMENT_REQUIRED: 402, + FORBIDDEN: 403, + NOT_FOUND: 404, + METHOD_NOT_ALLOWED: 405, + NOT_ACCEPTABLE: 406, + PROXY_AUTHENTICATION_REQUIRED: 407, + REQUEST_TIMEOUT: 408, + CONFLICT: 409, + GONE: 410, + LENGTH_REQUIRED: 411, + PRECONDITION_FAILED: 412, + PAYLOAD_TOO_LARGE: 413, + URI_TOO_LONG: 414, + UNSUPPORTED_MEDIA_TYPE: 415, + RANGE_NOT_SATISFIABLE: 416, + EXPECTATION_FAILED: 417, + IM_A_TEAPOT: 418, + PAGE_EXPIRED: 419, // Unofficial + ENHANCE_YOUR_CALM: 420, // Unofficial + MISDIRECTED_REQUEST: 421, + UNPROCESSABLE_ENTITY: 422, + LOCKED: 423, + FAILED_DEPENDENCY: 424, + TOO_EARLY: 425, + UPGRADE_REQUIRED: 426, + PRECONDITION_REQUIRED: 428, + TOO_MANY_REQUESTS: 429, + REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL: 430, // Unofficial + REQUEST_HEADER_FIELDS_TOO_LARGE: 431, + LOGIN_TIMEOUT: 440, // Unofficial + NO_RESPONSE: 444, // Unofficial + RETRY_WITH: 449, // Unofficial + BLOCKED_BY_PARENTAL_CONTROL: 450, // Unofficial + UNAVAILABLE_FOR_LEGAL_REASONS: 451, + CLIENT_CLOSED_LOAD_BALANCED_REQUEST: 460, // Unofficial + INVALID_X_FORWARDED_FOR: 463, // Unofficial + REQUEST_HEADER_TOO_LARGE: 494, // Unofficial + SSL_CERTIFICATE_ERROR: 495, // Unofficial + SSL_CERTIFICATE_REQUIRED: 496, // Unofficial + HTTP_REQUEST_SENT_TO_HTTPS_PORT: 497, // Unofficial + INVALID_TOKEN: 498, // Unofficial + CLIENT_CLOSED_REQUEST: 499, // Unofficial + INTERNAL_SERVER_ERROR: 500, + NOT_IMPLEMENTED: 501, + BAD_GATEWAY: 502, + SERVICE_UNAVAILABLE: 503, + GATEWAY_TIMEOUT: 504, + HTTP_VERSION_NOT_SUPPORTED: 505, + VARIANT_ALSO_NEGOTIATES: 506, + INSUFFICIENT_STORAGE: 507, + LOOP_DETECTED: 508, + BANDWIDTH_LIMIT_EXCEEDED: 509, + NOT_EXTENDED: 510, + NETWORK_AUTHENTICATION_REQUIRED: 511, + WEB_SERVER_UNKNOWN_ERROR: 520, // Unofficial + WEB_SERVER_IS_DOWN: 521, // Unofficial + CONNECTION_TIMEOUT: 522, // Unofficial + ORIGIN_IS_UNREACHABLE: 523, // Unofficial + TIMEOUT_OCCURED: 524, // Unofficial + SSL_HANDSHAKE_FAILED: 525, // Unofficial + INVALID_SSL_CERTIFICATE: 526, // Unofficial + RAILGUN_ERROR: 527, // Unofficial + SITE_IS_OVERLOADED: 529, // Unofficial + SITE_IS_FROZEN: 530, // Unofficial + IDENTITY_PROVIDER_AUTHENTICATION_ERROR: 561, // Unofficial + NETWORK_READ_TIMEOUT: 598, // Unofficial + NETWORK_CONNECT_TIMEOUT: 599, // Unofficial +}; +exports.FINISH = { + SAFE: 0, + SAFE_WITH_CB: 1, + UNSAFE: 2, +}; +exports.HEADER_STATE = { + GENERAL: 0, + CONNECTION: 1, + CONTENT_LENGTH: 2, + TRANSFER_ENCODING: 3, + UPGRADE: 4, + CONNECTION_KEEP_ALIVE: 5, + CONNECTION_CLOSE: 6, + CONNECTION_UPGRADE: 7, + TRANSFER_ENCODING_CHUNKED: 8, +}; +// C headers +exports.METHODS_HTTP = [ + exports.METHODS.DELETE, + exports.METHODS.GET, + exports.METHODS.HEAD, + exports.METHODS.POST, + exports.METHODS.PUT, + exports.METHODS.CONNECT, + exports.METHODS.OPTIONS, + exports.METHODS.TRACE, + exports.METHODS.COPY, + exports.METHODS.LOCK, + exports.METHODS.MKCOL, + exports.METHODS.MOVE, + exports.METHODS.PROPFIND, + exports.METHODS.PROPPATCH, + exports.METHODS.SEARCH, + exports.METHODS.UNLOCK, + exports.METHODS.BIND, + exports.METHODS.REBIND, + exports.METHODS.UNBIND, + exports.METHODS.ACL, + exports.METHODS.REPORT, + exports.METHODS.MKACTIVITY, + exports.METHODS.CHECKOUT, + exports.METHODS.MERGE, + exports.METHODS['M-SEARCH'], + exports.METHODS.NOTIFY, + exports.METHODS.SUBSCRIBE, + exports.METHODS.UNSUBSCRIBE, + exports.METHODS.PATCH, + exports.METHODS.PURGE, + exports.METHODS.MKCALENDAR, + exports.METHODS.LINK, + exports.METHODS.UNLINK, + exports.METHODS.PRI, + // TODO(indutny): should we allow it with HTTP? + exports.METHODS.SOURCE, + exports.METHODS.QUERY, +]; +exports.METHODS_ICE = [ + exports.METHODS.SOURCE, +]; +exports.METHODS_RTSP = [ + exports.METHODS.OPTIONS, + exports.METHODS.DESCRIBE, + exports.METHODS.ANNOUNCE, + exports.METHODS.SETUP, + exports.METHODS.PLAY, + exports.METHODS.PAUSE, + exports.METHODS.TEARDOWN, + exports.METHODS.GET_PARAMETER, + exports.METHODS.SET_PARAMETER, + exports.METHODS.REDIRECT, + exports.METHODS.RECORD, + exports.METHODS.FLUSH, + // For AirPlay + exports.METHODS.GET, + exports.METHODS.POST, +]; +exports.METHOD_MAP = (0, utils_1.enumToMap)(exports.METHODS); +exports.H_METHOD_MAP = Object.fromEntries(Object.entries(exports.METHODS).filter(([k]) => k.startsWith('H'))); +exports.STATUSES_HTTP = [ + exports.STATUSES.CONTINUE, + exports.STATUSES.SWITCHING_PROTOCOLS, + exports.STATUSES.PROCESSING, + exports.STATUSES.EARLY_HINTS, + exports.STATUSES.RESPONSE_IS_STALE, + exports.STATUSES.REVALIDATION_FAILED, + exports.STATUSES.DISCONNECTED_OPERATION, + exports.STATUSES.HEURISTIC_EXPIRATION, + exports.STATUSES.MISCELLANEOUS_WARNING, + exports.STATUSES.OK, + exports.STATUSES.CREATED, + exports.STATUSES.ACCEPTED, + exports.STATUSES.NON_AUTHORITATIVE_INFORMATION, + exports.STATUSES.NO_CONTENT, + exports.STATUSES.RESET_CONTENT, + exports.STATUSES.PARTIAL_CONTENT, + exports.STATUSES.MULTI_STATUS, + exports.STATUSES.ALREADY_REPORTED, + exports.STATUSES.TRANSFORMATION_APPLIED, + exports.STATUSES.IM_USED, + exports.STATUSES.MISCELLANEOUS_PERSISTENT_WARNING, + exports.STATUSES.MULTIPLE_CHOICES, + exports.STATUSES.MOVED_PERMANENTLY, + exports.STATUSES.FOUND, + exports.STATUSES.SEE_OTHER, + exports.STATUSES.NOT_MODIFIED, + exports.STATUSES.USE_PROXY, + exports.STATUSES.SWITCH_PROXY, + exports.STATUSES.TEMPORARY_REDIRECT, + exports.STATUSES.PERMANENT_REDIRECT, + exports.STATUSES.BAD_REQUEST, + exports.STATUSES.UNAUTHORIZED, + exports.STATUSES.PAYMENT_REQUIRED, + exports.STATUSES.FORBIDDEN, + exports.STATUSES.NOT_FOUND, + exports.STATUSES.METHOD_NOT_ALLOWED, + exports.STATUSES.NOT_ACCEPTABLE, + exports.STATUSES.PROXY_AUTHENTICATION_REQUIRED, + exports.STATUSES.REQUEST_TIMEOUT, + exports.STATUSES.CONFLICT, + exports.STATUSES.GONE, + exports.STATUSES.LENGTH_REQUIRED, + exports.STATUSES.PRECONDITION_FAILED, + exports.STATUSES.PAYLOAD_TOO_LARGE, + exports.STATUSES.URI_TOO_LONG, + exports.STATUSES.UNSUPPORTED_MEDIA_TYPE, + exports.STATUSES.RANGE_NOT_SATISFIABLE, + exports.STATUSES.EXPECTATION_FAILED, + exports.STATUSES.IM_A_TEAPOT, + exports.STATUSES.PAGE_EXPIRED, + exports.STATUSES.ENHANCE_YOUR_CALM, + exports.STATUSES.MISDIRECTED_REQUEST, + exports.STATUSES.UNPROCESSABLE_ENTITY, + exports.STATUSES.LOCKED, + exports.STATUSES.FAILED_DEPENDENCY, + exports.STATUSES.TOO_EARLY, + exports.STATUSES.UPGRADE_REQUIRED, + exports.STATUSES.PRECONDITION_REQUIRED, + exports.STATUSES.TOO_MANY_REQUESTS, + exports.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL, + exports.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE, + exports.STATUSES.LOGIN_TIMEOUT, + exports.STATUSES.NO_RESPONSE, + exports.STATUSES.RETRY_WITH, + exports.STATUSES.BLOCKED_BY_PARENTAL_CONTROL, + exports.STATUSES.UNAVAILABLE_FOR_LEGAL_REASONS, + exports.STATUSES.CLIENT_CLOSED_LOAD_BALANCED_REQUEST, + exports.STATUSES.INVALID_X_FORWARDED_FOR, + exports.STATUSES.REQUEST_HEADER_TOO_LARGE, + exports.STATUSES.SSL_CERTIFICATE_ERROR, + exports.STATUSES.SSL_CERTIFICATE_REQUIRED, + exports.STATUSES.HTTP_REQUEST_SENT_TO_HTTPS_PORT, + exports.STATUSES.INVALID_TOKEN, + exports.STATUSES.CLIENT_CLOSED_REQUEST, + exports.STATUSES.INTERNAL_SERVER_ERROR, + exports.STATUSES.NOT_IMPLEMENTED, + exports.STATUSES.BAD_GATEWAY, + exports.STATUSES.SERVICE_UNAVAILABLE, + exports.STATUSES.GATEWAY_TIMEOUT, + exports.STATUSES.HTTP_VERSION_NOT_SUPPORTED, + exports.STATUSES.VARIANT_ALSO_NEGOTIATES, + exports.STATUSES.INSUFFICIENT_STORAGE, + exports.STATUSES.LOOP_DETECTED, + exports.STATUSES.BANDWIDTH_LIMIT_EXCEEDED, + exports.STATUSES.NOT_EXTENDED, + exports.STATUSES.NETWORK_AUTHENTICATION_REQUIRED, + exports.STATUSES.WEB_SERVER_UNKNOWN_ERROR, + exports.STATUSES.WEB_SERVER_IS_DOWN, + exports.STATUSES.CONNECTION_TIMEOUT, + exports.STATUSES.ORIGIN_IS_UNREACHABLE, + exports.STATUSES.TIMEOUT_OCCURED, + exports.STATUSES.SSL_HANDSHAKE_FAILED, + exports.STATUSES.INVALID_SSL_CERTIFICATE, + exports.STATUSES.RAILGUN_ERROR, + exports.STATUSES.SITE_IS_OVERLOADED, + exports.STATUSES.SITE_IS_FROZEN, + exports.STATUSES.IDENTITY_PROVIDER_AUTHENTICATION_ERROR, + exports.STATUSES.NETWORK_READ_TIMEOUT, + exports.STATUSES.NETWORK_CONNECT_TIMEOUT, +]; +exports.ALPHA = []; +for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { + // Upper case + exports.ALPHA.push(String.fromCharCode(i)); + // Lower case + exports.ALPHA.push(String.fromCharCode(i + 0x20)); +} +exports.NUM_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, +}; +exports.HEX_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, + a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, +}; +exports.NUM = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', +]; +exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); +exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; +exports.USERINFO_CHARS = exports.ALPHANUM + .concat(exports.MARK) + .concat(['%', ';', ':', '&', '=', '+', '$', ',']); +// TODO(indutny): use RFC +exports.URL_CHAR = [ + '!', '"', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', + '@', '[', '\\', ']', '^', '_', + '`', + '{', '|', '}', '~', +].concat(exports.ALPHANUM); +exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); +/* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ +exports.TOKEN = [ + '!', '#', '$', '%', '&', '\'', + '*', '+', '-', '.', + '^', '_', '`', + '|', '~', +].concat(exports.ALPHANUM); +/* + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + */ +exports.HEADER_CHARS = ['\t']; +for (let i = 32; i <= 255; i++) { + if (i !== 127) { + exports.HEADER_CHARS.push(i); + } +} +// ',' = \x44 +exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); +exports.QUOTED_STRING = ['\t', ' ']; +for (let i = 0x21; i <= 0xff; i++) { + if (i !== 0x22 && i !== 0x5c) { // All characters in ASCII except \ and " + exports.QUOTED_STRING.push(i); + } +} +exports.HTAB_SP_VCHAR_OBS_TEXT = ['\t', ' ']; +// VCHAR: https://tools.ietf.org/html/rfc5234#appendix-B.1 +for (let i = 0x21; i <= 0x7E; i++) { + exports.HTAB_SP_VCHAR_OBS_TEXT.push(i); +} +// OBS_TEXT: https://datatracker.ietf.org/doc/html/rfc9110#name-collected-abnf +for (let i = 0x80; i <= 0xff; i++) { + exports.HTAB_SP_VCHAR_OBS_TEXT.push(i); +} +exports.MAJOR = exports.NUM_MAP; +exports.MINOR = exports.MAJOR; +exports.SPECIAL_HEADERS = { + 'connection': exports.HEADER_STATE.CONNECTION, + 'content-length': exports.HEADER_STATE.CONTENT_LENGTH, + 'proxy-connection': exports.HEADER_STATE.CONNECTION, + 'transfer-encoding': exports.HEADER_STATE.TRANSFER_ENCODING, + 'upgrade': exports.HEADER_STATE.UPGRADE, +}; +exports.default = { + ERROR: exports.ERROR, + TYPE: exports.TYPE, + FLAGS: exports.FLAGS, + LENIENT_FLAGS: exports.LENIENT_FLAGS, + METHODS: exports.METHODS, + STATUSES: exports.STATUSES, + FINISH: exports.FINISH, + HEADER_STATE: exports.HEADER_STATE, + ALPHA: exports.ALPHA, + NUM_MAP: exports.NUM_MAP, + HEX_MAP: exports.HEX_MAP, + NUM: exports.NUM, + ALPHANUM: exports.ALPHANUM, + MARK: exports.MARK, + USERINFO_CHARS: exports.USERINFO_CHARS, + URL_CHAR: exports.URL_CHAR, + HEX: exports.HEX, + TOKEN: exports.TOKEN, + HEADER_CHARS: exports.HEADER_CHARS, + CONNECTION_TOKEN_CHARS: exports.CONNECTION_TOKEN_CHARS, + QUOTED_STRING: exports.QUOTED_STRING, + HTAB_SP_VCHAR_OBS_TEXT: exports.HTAB_SP_VCHAR_OBS_TEXT, + MAJOR: exports.MAJOR, + MINOR: exports.MINOR, + SPECIAL_HEADERS: exports.SPECIAL_HEADERS, + METHODS_HTTP: exports.METHODS_HTTP, + METHODS_ICE: exports.METHODS_ICE, + METHODS_RTSP: exports.METHODS_RTSP, + METHOD_MAP: exports.METHOD_MAP, + H_METHOD_MAP: exports.H_METHOD_MAP, + STATUSES_HTTP: exports.STATUSES_HTTP, +}; diff --git a/node_modules/undici/lib/llhttp/llhttp-wasm.js b/node_modules/undici/lib/llhttp/llhttp-wasm.js new file mode 100644 index 000000000..8e8980635 --- /dev/null +++ b/node_modules/undici/lib/llhttp/llhttp-wasm.js @@ -0,0 +1,15 @@ +'use strict' + +const { Buffer } = require('node:buffer') + +const wasmBase64 = 'AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzU0BQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEBAwAAAwAAAAQFAXABExMFAwEAAgYIAX8BQcDZBAsHxQcoBm1lbW9yeQIAC19pbml0aWFsaXplAAgZX19pbmRpcmVjdF9mdW5jdGlvbl90YWJsZQEAC2xsaHR0cF9pbml0AAkYbGxodHRwX3N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NgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgL5YUCAgd/A34gASACaiEEAkAgACIDKAIMIgANACADKAIEBEAgAyABNgIECyMAQRBrIgkkAAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAygCHCICQQJrDvwBAfkBAgMEBQYHCAkKCwwNDg8QERL4ARP3ARQV9gEWF/UBGBkaGxwdHh8g/QH7ASH0ASIjJCUmJygpKivzASwtLi8wMTLyAfEBMzTwAe8BNTY3ODk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AQwRC0HOAQwQC0HPAQwPC0HQAQwOC0HRAQwNC0HSAQwMC0HTAQwLC0HUAQwKC0HVAQwJC0HWAQwIC0HjAQwHC0HXAQwGC0HYAQwFC0HZAQwEC0HaAQwDC0HbAQwCC0HdAQwBC0HcAQshAgNAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJ/AkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAA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E2AhQgA0G+IDYCECADQQI2AgwMkgMLIAMoAgQhAEEAIQIgA0EANgIEIAMgACABIAynaiIBEDIiAEUNKyADQQc2AhwgAyABNgIUIAMgADYCDAyRAwsgAy0ALkHAAHFFDQELQQAhAAJAIAMoAjgiAkUNACACKAJYIgJFDQAgAyACEQAAIQALIABFDSsgAEEVRgRAIANBCjYCHCADIAE2AhQgA0HrGTYCECADQRU2AgxBACECDJADC0EAIQIgA0EANgIcIAMgATYCFCADQZMMNgIQIANBEzYCDAyPAwtBACECIANBADYCHCADIAE2AhQgA0GCFTYCECADQQI2AgwMjgMLQQAhAiADQQA2AhwgAyABNgIUIANB3RQ2AhAgA0EZNgIMDI0DC0EAIQIgA0EANgIcIAMgATYCFCADQeYdNgIQIANBGTYCDAyMAwsgAEEVRg09QQAhAiADQQA2AhwgAyABNgIUIANB0A82AhAgA0EiNgIMDIsDCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFDSggA0ENNgIcIAMgATYCFCADIAA2AgwMigMLIABBFUYNOkEAIQIgA0EANgIcIAMgATYCFCADQdAPNgIQIANBIjYCDAyJAwsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQMyIARQRAIAFBAWohAQwoCyADQQ42AhwgAyAANgIMIAMgAUEBajYCFAyIAwsgAEEVRg03QQAhAiADQQA2AhwgAyABNgIUIANB0A82AhAgA0EiNgIMDIcDCyADKAIEIQBBACECIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDCcLIANBDzYCHCADIAA2AgwgAyABQQFqNgIUDIYDC0EAIQIgA0EANgIcIAMgATYCFCADQeIXNgIQIANBGTYCDAyFAwsgAEEVRg0zQQAhAiADQQA2AhwgAyABNgIUIANB1gw2AhAgA0EjNgIMDIQDCyADKAIEIQBBACECIANBADYCBCADIAAgARA0IgBFDSUgA0ERNgIcIAMgATYCFCADIAA2AgwMgwMLIABBFUYNMEEAIQIgA0EANgIcIAMgATYCFCADQdYMNgIQIANBIzYCDAyCAwsgAygCBCEAQQ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IBRw0AC0EsIQIM7wILQSwhAgzuAgsgASAERgRAQTQhAgzuAgsCQAJAA0ACQCABLQAAQQprDgQCAAADAAsgBCABQQFqIgFHDQALQTQhAgzvAgsgAygCBCEAIANBADYCBCADIAAgARAxIgBFDZ8CIANBMjYCHCADIAE2AhQgAyAANgIMQQAhAgzuAgsgAygCBCEAIANBADYCBCADIAAgARAxIgBFBEAgAUEBaiEBDJ8CCyADQTI2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIM7QILIAEgBEcEQAJAA0AgAS0AAEEwayIAQf8BcUEKTwRAQTohAgzXAgsgAykDICILQpmz5syZs+bMGVYNASADIAtCCn4iCjcDICAKIACtQv8BgyILQn+FVg0BIAMgCiALfDcDICAEIAFBAWoiAUcNAAtBwAAhAgzuAgsgAygCBCEAIANBADYCBCADIAAgAUEBaiIBEDEiAA0XDOICC0HAACECDOwCCyABIARGBEBByQAhAgzsAgsCQANAAkAgAS0AAEEJaw4YAAKiAqICqQKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogIAogILIAQgAUEBaiIBRw0AC0HJACECDOwCCyABQQFqIQEgA0Evai0AAEEBcQ2lAiADQQA2AhwgAyABNgIUIANBlxA2AhAgA0EKNgIMQQAhAgzrAgsgASAERwRAA0AgAS0AAEEgRw0VIAQgAUEBaiIBRw0AC0H4ACECDOsCC0H4ACECDOoCCyADQQI6ACgMOAtBACECIANBADYCHCADQb8LNgIQIANBAjYCDCADIAFBAWo2AhQM6AILQQAhAgzOAgtBDSECDM0CC0ETIQIMzAILQRUhAgzLAgtBFiECDMoCC0EYIQIMyQILQRkhAgzIAgtBGiECDMcCC0EbIQIMxgILQRwhAgzFAgtBHSECDMQCC0EeIQIMwwILQR8hAgzCAgtBICECDMECC0EiIQIMwAILQSMhAgy/AgtBJSECDL4CC0HlACECDL0CCyADQT02AhwgAyABNgIUIAMgADYCDEEAIQIM1QILIANBGzYCHCADIAE2AhQgA0GkHDYCECADQRU2AgxBACECDNQCCyADQSA2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzTAgsgA0ETNgIcIAMgATYCFCADQZgaNgIQIANBFTYCDEEAIQIM0gILIANBCzYCHCADIAE2AhQgA0GYGjYCECADQRU2AgxBACECDNECCyADQRA2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzQAgsgA0EgNgIcIAMgATYCFCADQaQcNgIQIANBFTYCDEEAIQIMzwILIANBCzYCHCADIAE2AhQgA0GkHDYCECADQRU2AgxBACECDM4CCyADQQw2AhwgAyABNgIUIANBpBw2AhAgA0EVNgIMQQAhAgzNAgtBACECIANBADYCHCADIAE2AhQgA0HdDjYCECADQRI2AgwMzAILAkADQAJAIAEtAABBCmsOBAACAgACCyAEIAFBAWoiAUcNAAtB/QEhAgzMAgsCQAJAIAMtADZBAUcNAEEAIQACQCADKAI4IgJFDQAgAigCYCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUcNASADQfwBNgIcIAMgATYCFCADQdwZNgIQIANBFTYCDEEAIQIMzQILQdwBIQIMswILIANBADYCHCADIAE2AhQgA0H5CzYCECADQR82AgxBACECDMsCCwJAAkAgAy0AKEEBaw4CBAEAC0HbASECDLICC0HUASECDLECCyADQQI6ADFBACEAAkAgAygCOCICRQ0AIAIoAgAiAkUNACADIAIRAAAhAAsgAEUEQEHdASECDLECCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQbQMNgIQIANBEDYCDEEAIQIMygILIANB+wE2AhwgAyABNgIUIANBgRo2AhAgA0EVNgIMQQAhAgzJAgsgASAERgRAQfoBIQIMyQILIAEtAABByABGDQEgA0EBOgAoC0HAASECDK4CC0HaASECDK0CCyABIARHBEAgA0EMNgIIIAMgATYCBEHZASECDK0CC0H5ASECDMUCCyABIARGBEBB+AEhAgzFAgsgAS0AAEHIAEcNBCABQQFqIQFB2AEhAgyrAgsgASAERgRAQfcBIQIMxAILAkACQCABLQAAQcUAaw4QAAUFBQUFBQUFBQUFBQUFAQULIAFBAWohAUHWASECDKsCC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ACyADIAY2AgAMuAILQe4BIQIgASAERg23AiADKAIAIgAgBCABa2ohBiABIABrQQJqIQUDQCABLQAAIABBsNUAai0AAEcNAiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMtwILIAMoAgQhACADQgA3AwAgAyAAIAVBAWoiARArIgBFDQIgA0HsATYCHCADIAE2AhQgAyAANgIMQQAhAgy2AgsgA0EANgIACyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNnAIgA0HtATYCHCADIAE2AhQgAyAANgIMQQAhAgy0AgtBzwEhAgyaAgtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDLQCC0HOASECDJoCCyADQesBNgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMsgILIAEgBEYEQEHrASECDLICCyABLQAAQS9GBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GyODYCECADQQg2AgxBACECDLECC0HNASECDJcCCyABIARHBEAgA0EONgIIIAMgATYCBEHMASECDJcCC0HqASECDK8CCyABIARGBEBB6QEhAgyvAgsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFBywEhAgyWAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZcCIANB6AE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILIAEgBEYEQEHnASECDK4CCwJAIAEtAABBLkYEQCABQQFqIQEMAQsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZgCIANB5gE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILQcoBIQIMlAILIAEgBEYEQEHlASECDK0CC0EAIQBBASEFQQEhB0EAIQICQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQCABLQAAQTBrDgoKCQABAgMEBQYICwtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshAkEAIQVBACEHDAILQQkhAkEBIQBBACEFQQAhBwwBC0EAIQVBASECCyADIAI6ACsgAUEBaiEBAkACQCADLQAuQRBxDQACQAJAAkAgAy0AKg4DAQACBAsgB0UNAwwCCyAADQEMAgsgBUUNAQsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDQIgA0HiATYCHCADIAE2AhQgAyAANgIMQQAhAgyvAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZoCIANB4wE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ2YAiADQeQBNgIcIAMgATYCFCADIAA2AgwMrQILQckBIQIMkwILQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANBpA02AhAgA0EhNgIMQQAhAgytAgtByAEhAgyTAgsgA0HhATYCHCADIAE2AhQgA0HQGjYCECADQRU2AgxBACECDKsCCyABIARGBEBB4QEhAgyrAgsCQCABLQAAQSBGBEAgA0EAOwE0IAFBAWohAQwBCyADQQA2AhwgAyABNgIUIANBmRE2AhAgA0EJNgIMQQAhAgyrAgtBxwEhAgyRAgsgASAERgRAQeABIQIMqgILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDAyrAgsgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDEEAIQIMqgILQcYBIQIMkAILIAEgBEYEQEHfASECDKkCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgwMqgILIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgxBACECDKkCC0HFASEC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ARw0rIAFBAWohAUGgASECDOQBCyABIARGBEBBuAEhAgz9AQsCQAJAIAEtAABBxgBrDgsALCwsLCwsLCwsASwLIAFBAWohAUGeASECDOQBCyABQQFqIQFBnwEhAgzjAQtBtwEhAiABIARGDfsBIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQezUAGotAABHDSggAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPwBCyADQQA2AgAgBkEBaiEBQQ0MKAtBtgEhAiABIARGDfoBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQaHVAGotAABHDScgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPsBCyADQQA2AgAgBkEBaiEBQQwMJwtBtQEhAiABIARGDfkBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQerUAGotAABHDSYgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPoBCyADQQA2AgAgBkEBaiEBQQMMJgtBtAEhAiABIARGDfgBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQejUAGotAABHDSUgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPkBCyADQQA2AgAgBkEBaiEBQSYMJQsgASAERgRAQbMBIQIM+AELAkACQCABLQAAQdQAaw4CAAEnCyABQQFqIQFBmQEhAgzfAQsgAUEBaiEBQZoBIQIM3gELQbIBIQIgASAERg32ASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHm1ABqLQAARw0jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz3AQsgA0EANgIAIAZBAWohAUEnDCMLQbEBIQIgASAERg31ASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHk1ABqLQAARw0iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz2AQs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aiEGAkADQCABLQAAIABBytQAai0AAEcNGSAAQQZGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM7QELIANBADYCACAGQQFqIQFBFQwZC0GnASECIAEgBEYN6wEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBx9QAai0AAEcNGCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM7AELIANBADYCACAGQQFqIQFBFwwYC0GmASECIAEgBEYN6gEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBwdQAai0AAEcNFyAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6wELIANBADYCACAGQQFqIQFBGAwXCyABIARGBEBBpQEhAgzqAQsCQAJAIAEtAABByQBrDgcAGRkZGRkBGQsgAUEBaiEBQYsBIQIM0QELIAFBAWohAUGMASECDNABC0GkASECIAEgBEYN6AEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBptUAai0AAEcNFSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6QELIANBADYCACAGQQFqIQFBCQwVC0GjASECIAEgBEYN5wEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBpNUAai0AAEcNFCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6AELIANBADYCACAGQQFqIQFBHwwUC0GiASECIAEgBEYN5gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBvtQAai0AAEcNEyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM5wELIANBADYCACAGQQFqIQFBAgwTC0GhASECIAEgBEYN5QEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGA0AgAS0AACAAQbzUAGotAABHDREgAEEBRg0CIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADOUBCyABIARGBEBBoAEhA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gBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEGs1ABqLQAARw0GIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzaAQsgA0EANgIAIAZBAWohAUEFDAYLQZUBIQIgASAERg3YASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGm1ABqLQAARw0FIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzZAQsgA0EANgIAIAZBAWohAUEWDAULQZQBIQIgASAERg3XASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGh1QBqLQAARw0EIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzYAQsgA0EANgIAIAZBAWohAUEQDAQLIAEgBEYEQEGTASECDNcBCwJAAkAgAS0AAEHDAGsODAAGBgYGBgYGBgYGAQYLIAFBAWohAUH5ACECDL4BCyABQQFqIQFB+gAhAgy9AQtBkgEhAiABIARGDdUBIAMoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQaDUAGotAABHDQIgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNYBCyADQQA2AgAgBkEBaiEBQSQMAgsgA0EANgIADAILIAEgBEYEQEGRASECDNQBCyABLQAAQcwARw0BIAFBAWohAUETCzoAKSADKAIEIQAgA0EANgIEIAMgACABEC4iAA0CDAELQQAhAiADQQA2AhwgAyABNgIUIANB/h82AhAgA0EGNgIMDNEBC0H4ACECDLcBCyADQZABNgIcIAMgATYCFCADIAA2AgxBACECDM8BC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUYNASADQQA2AhwgAyABNgIUIANBgg82AhAgA0EgNgIMQQAhAgzOAQtB9wAhAgy0AQsgA0GPATYCHCADIAE2AhQgA0HsGzYCECADQRU2AgxBACECDMwBCyABIARGBEBBjwEhAgzMAQsCQCABLQAAQSBGBEAgAUEBaiEBD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CDEEAIQIMqgELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0IIANB+gA2AhwgAyABNgIUIAMgADYCDEEAIQIMqQELIANBADYCHCADIAE2AhQgA0GNFDYCECADQQc2AgxBACECDKgBCwJAAkACQAJAA0AgAS0AAEGgygBqLQAAIgBBBUcEQAJAIABBAWsOBi4DBAUGAAYLQegAIQIMlAELIAQgAUEBaiIBRw0AC0H9ACECDKsBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNByADQdsANgIcIAMgATYCFCADIAA2AgxBACECDKoBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNByADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDKkBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNByADQfoANgIcIAMgATYCFCADIAA2AgxBACECDKgBCyADQQA2AhwgAyABNgIUIANB5Ag2AhAgA0EHNgIMQQAhAgynAQsgASAERg0BIAFBAWoLIQFBBiECDIwBC0H8ACECDKQBCwJAAkACQAJAA0AgAS0AAEGgyABqLQAAIgBBBUcEQCAAQQFrDgQpAgMEBQsgBCABQQFqIgFHDQALQfsAIQIMpwELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0DIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMpgELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0DIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMpQELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0DIANB+gA2AhwgAyABNgIUIAMgADYCDEEAIQIMpAELIANBADYCHCADIAE2AhQgA0G8CjYCECADQQc2AgxBACECDKMBC0HPACECDIkBC0HRACECDIgBC0HnACECDIcBCyABIARGBEBB+gAhAgygAQsCQCABLQAAQQlrDgQgAAAgAAsgAUEBaiEBQeYAIQIMhgELIAEgBEYEQEH5ACECDJ8BCwJAIAEtAABBCWsOBB8AAB8AC0EAIQACQCADKAI4IgJFDQAgAigCOCICRQ0AIAMgAhEAACEACyAARQRAQeIBIQIMhgELIABBFUcEQCADQQA2AhwgAyABNgIUIANByQ02AhAgA0EaNgIMQQAhAgyfAQsgA0H4ADYCHCADIAE2AhQgA0HqGjYCECADQRU2AgxBACECDJ4BCyABIARHBEAgA0ENNgIIIAMgATYCBEHkACECDIUBC0H3ACECDJ0BCyABIARGBEBB9gAhAgydAQsCQAJAAkAgAS0AAEHIAGsOCwABCwsLCwsLCwsCCwsgAUEBaiEBQd0AIQIMhQELIAFBAWohAUHgACECDIQBCyABQQFqIQFB4wAhAgyDAQtB9QAhAiABIARGDZsBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbXVAGotAABHDQggAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJwBCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQKyIABEAgA0H0ADYCHCADIAE2AhQgAyAANgIMQQAhAgycAQtB4gAhAgyCAQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJwBC0HhACECDIIBCyADQfMANgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMmgELIAMtACkiAEEja0ELSQ0JAkAgAEEGSw0AQQEgAHRBygBxRQ0ADAoLQQAhAiADQQA2AhwgAyABNgIUIANB7Qk2AhAgA0EINgIMDJkBC0HyACECIAEgBEYNmAEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBs9UAai0AAEcNBSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMmQELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgAEQCADQfEANgIcIAMgATYCFCADIAA2AgxBACECDJkBC0HfACECDH8LQQAhAAJAIAMoAjgiAkUNACACKAI0IgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANB6g02AhAgA0EmNgIMQQAhAgyZAQtB3gAhAgx/CyADQfAANgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMlwELIAMtAClBIUYNBiADQQA2AhwgAyABNgIUIANBkQo2AhAgA0EINgIMQQAhAgyWAQtB7wAhAiABIARGDZUBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbDVAGotAABHDQIgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJYBCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQKyIARQ0CIANB7QA2AhwgAyABNgIUIAMgADYCDEEAIQIMlQELIANBADYCAAsgAygCBCEAIANBADYCBCADIAAgARArIgBFDYABIANB7gA2AhwgAyABNgIUIAMgADYCDEEAIQIMkwELQdwAIQIMeQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJMBC0HbACECDHkLIANB7AA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyRAQsgAy0AKSIAQSNJDQAgAEEuRg0AIANBADYCHCADIAE2AhQgA0HJCTYCECADQQg2AgxBACECDJABC0HaACECDHYLIAEgBEYEQEHrACECDI8BCwJAIAEtAABBL0YEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQbI4NgIQIANBCDYCDEEAIQIMjwELQdkAIQIMdQsgASAERwRAIANBDjYCCCADIAE2AgRB2AAhAgx1C0HqACECDI0BCyABIARGBEBB6QAhAgyNAQsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFB1wAhAgx0CyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNeiADQegANgIcIAMgATYCFCADIAA2AgxBACECDIwBCyABIARGBEBB5wAhAgyMAQsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ17IANB5gA2AhwgAyABNgIUIAMgADYCDEEAIQIMjAELQdYAIQIMcgsgASAERgRAQeUAIQIMiwELQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNAiADQeIANgIcIAMgATYCFCADIAA2AgxBACECDI0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNfSADQeMANgIcIAMgATYCFCADIAA2AgxBACECDIwBCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNeyADQeQANgIcIAMgATYCFCADIAA2AgwMiwELQdQAIQIMcQsgAy0AKUEiRg2GAUHTACECDHALQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALIABFBEBB1QAhAgxwCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQaQNNgIQIANBITYCDEEAIQIMiQELIANB4QA2AhwgAyABNgIUIANB0Bo2AhAgA0EVNgIMQQAhAgyIAQsgASAERgRAQeAAIQIMiAELAkACQAJAAkACQCABLQAAQQprDgQBBAQABAsgAUEBaiEBDAELIAFBAWohASADQS9qLQAAQQFxRQ0BC0HSACECDHALIANBADYCHCADIAE2AhQgA0G2ETYCECADQQk2AgxBACECDIgBCyADQQA2AhwgAyABNgIUIANBthE2AhAgA0EJNgIMQQAhAgyHAQsgASAERgRAQd8AIQIMhwELIAEtAABBCkYEQCABQQFqIQEMCQsgAy0ALkHAAHENCCADQQA2AhwgAyABNgIUIANBthE2AhAgA0ECNgIMQQAhAgyGAQsgASAERgRAQd0AIQIMhgELIAEtAAAiAkENRgRAIAFBAWohAUHQACECDG0LIAEhACACQQlrDgQFAQEFAQsgBCABIgBGBEBB3AAhAgyFAQsgAC0AAEEKRw0AIABBAWoMAgtBACECIANBADYCHCADIAA2AhQgA0HKLTYCECADQQc2AgwMgwELIAEgBEYEQEHbACECDIMBCwJAIAEtAABBCWsOBAMAAAMACyABQQFqCyEBQc4AIQIMaAsgASAERgRAQdoAIQIMgQELIAEtAABBCWsOBAABAQABC0EAIQIgA0EANgIcIANBmhI2AhAgA0EHNgIMIAMgAUEBajYCFAx/CyADQYASOwEqQQAhAAJAIAMoAjgiAkUNACACKAI4IgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB2QA2AhwgAyABNgIUIANB6ho2AhAgA0EVNgIMQQAhAgx+C0HNACECDGQLIANBADYCHCADIAE2AhQgA0HJDTYCECADQRo2AgxBACECDHwLIAEgBEYEQEHZACECDHwLIAEtAABBIEcNPSABQQFqIQEgAy0ALkEBcQ09IANBADYCHCADIAE2AhQgA0HCHDYCECADQR42AgxBACECDHsLIAEgBEYEQEHYACECDHsLAkACQAJAAkACQCABLQAAIgBBCmsOBAIDAwABCyABQQFqIQFBLCECDGULIABBOkcNASADQQA2AhwgAyABNgIUIANB5xE2AhAgA0EKNgIMQQAhAgx9CyABQQFqIQEgA0Evai0AAEEBcUUNcyADLQAyQYABcUUEQCADQTJqIQIgAxA1QQAhAAJAIAMoAjgiBkUNACAGKAIoIgZFDQAgAyAGEQAAIQALAkACQCAADhZNTEsBAQEBAQEBAQEBAQEBAQEBAQEAAQsgA0EpNgIcIAMgATYCFCADQawZNgIQIANBFTYCDEEAIQIMfgsgA0EANgIcIAMgATYCFCADQeULNgIQIANBETYCDEEAIQIMfQtBACEAAkAgAygCOCICRQ0AIAIoAlwiAkUNACADIAIRAAAhAAsgAEUNWSAAQRVHDQEgA0EFNgIcIAMgATYCFCADQZsbNgIQIANBFTYCDEEAIQIMfAtBywAhAgxiC0EAIQIgA0EANgIcIAMgATYCFCADQZAONgIQIANBFDYCDAx6CyADIAMvATJBgAFyOwEyDDsL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BQECAAEDAEHAzgALXwQFAAAFBQUFBQUFBQUFBQYFBQUFBQUFBQUFBQUABQAHCAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQAFAAUABQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAAAAFAEGp0AALBQEBAAEBAEHA0AALAQEAQdrQAAtBAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQanSAAsFAQEAAQEAQcDSAAsBAQBBytIACwYCAAAAAAIAQeHSAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBBoNQAC50BTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRVVFUllPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFVFRQQ0VUU1BBRFRQLw==' + +let wasmBuffer + +Object.defineProperty(module, 'exports', { + get: () => { + return wasmBuffer + ? wasmBuffer + : (wasmBuffer = Buffer.from(wasmBase64, 'base64')) + } +}) diff --git a/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js b/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js new file mode 100644 index 000000000..4508cb14d --- /dev/null +++ b/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js @@ -0,0 +1,15 @@ +'use strict' + +const { Buffer } = require('node:buffer') + +const wasmBase64 = 'AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV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QezVAGohAAJ/QcTVACgCACICQQEgBEEDdnQiA3FFBEBBxNUAIAIgA3I2AgAgAAwBCyAAKAIICyICIAE2AgwgACABNgIIIAEgADYCDCABIAI2AggMAQtBHyECIARB////B00EQCAEQSYgBEEIdmciAGt2QQFxIABBAXRrQT5qIQILIAEgAjYCHCABQgA3AhAgAkECdEH01wBqIQACQEHI1QAoAgAiA0EBIAJ0IgdxRQRAIAAgATYCAEHI1QAgAyAHcjYCACABIAA2AhggASABNgIIIAEgATYCDAwBCyAEQRkgAkEBdmtBACACQR9HG3QhAiAAKAIAIQACQANAIAAiAygCBEF4cSAERg0BIAJBHXYhACACQQF0IQIgAyAAQQRxakEQaiIHKAIAIgANAAsgByABNgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgLhocCAwd/A34BeyABIAJqIQQCQCAAIgMoAgwiAA0AIAMoAgQEQCADIAE2AgQLIwBBEGsiCSQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJA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ADYCDCADIAFBAWo2AhQM9QILIABBFUYNH0EAIQIgA0EANgIcIAMgATYCFCADQdAPNgIQIANBIjYCDAz0AgsgAygCBCEAIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDBsLIANBHDYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgzzAgsgAygCBCEAIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDOsCCyADQR02AhwgAyAANgIMIAMgAUEBajYCFEEAIQIM8gILIABBO0cNASABQQFqIQELQSYhAgzXAgtBACECIANBADYCHCADIAE2AhQgA0GfFTYCECADQQw2AgwM7wILIAEgBEcEQANAIAEtAABBIEcNhAIgBCABQQFqIgFHDQALQSwhAgzvAgtBLCECDO4CCyABIARGBEBBNCECDO4CCwJAAkADQAJAIAEtAABBCmsOBAIAAAMACyAEIAFBAWoiAUcNAAtBNCECDO8CCyADKAIEIQAgA0EANgIEIAMgACABEDEiAEUNnwIgA0EyNgIcIAMgATYCFCADIAA2AgxBACECDO4CCyADKAIEIQAgA0EANgIEIAMgACABEDEiAEUEQCABQQFqIQEMnwILIANBMjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgztAgsgASAERwRAAkADQCABLQAAQTBrIgBB/wFxQQpPBEBBOiECDNcCCyADKQMgIgtCmbPmzJmz5swZVg0BIAMgC0IKfiIKNwMgIAogAK1C/wGDIgtCf4VWDQEgAyAKIAt8NwMgIAQgAUEBaiIBRw0AC0HAACECDO4CCyADKAIEIQAgA0EANgIEIAMgACABQQFqIgEQMSIADRcM4gILQcAAIQIM7AILIAEgBEYEQEHJACECDOwCCwJAA0ACQCABLQAAQQlrDhgAAqICogKpAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAgCiAgsgBCABQQFqIgFHDQALQckAIQIM7AILIAFBAWohASADQS9qLQAAQQFxDaUCIANBADYCHCADIAE2AhQgA0GXEDYCECADQQo2AgxBACECDOsCCyABIARHBEADQCABLQAAQSBHDRUgBCABQQFqIgFHDQALQfgAIQIM6w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d0BIQIMsQILIABBFUcEQCADQQA2AhwgAyABNgIUIANBtAw2AhAgA0EQNgIMQQAhAgzKAgsgA0H7ATYCHCADIAE2AhQgA0GBGjYCECADQRU2AgxBACECDMkCCyABIARGBEBB+gEhAgzJAgsgAS0AAEHIAEYNASADQQE6ACgLQcABIQIMrgILQdoBIQIMrQILIAEgBEcEQCADQQw2AgggAyABNgIEQdkBIQIMrQILQfkBIQIMxQILIAEgBEYEQEH4ASECDMUCCyABLQAAQcgARw0EIAFBAWohAUHYASECDKsCCyABIARGBEBB9wEhAgzEAgsCQAJAIAEtAABBxQBrDhAABQUFBQUFBQUFBQUFBQUBBQsgAUEBaiEBQdYBIQIMqwILIAFBAWohAUHXASECDKoCC0H2ASECIAEgBEYNwgIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABButUAai0AAEcNAyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMwwILIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAuIgBFBEBB4wEhAgyqAgsgA0H1ATYCHCADIAE2AhQgAyAANgIMQQAhAgzCAgtB9AEhAiABIARGDcECIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbjVAGotAABHDQIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMICCyADQYEEOwEoIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAuIgANAwwCCyADQQA2AgALQQAhAiADQQA2AhwgAyABNgIUIANB5R82AhAgA0EINgIMDL8CC0HVASECDKUCCyADQfMBNgIcIAMgATYCFCADIAA2AgxBACECDL0CC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQ1uIABBFUcEQCADQQA2AhwgAyABNgIUIANBgg82AhAgA0EgNgIMQQAhAgy9AgsgA0GPATYCHCADIAE2AhQgA0HsGzYCECADQRU2AgxBACECDLwCCyABIARHBEAgA0ENNgIIIAMgATYCBEHTASECDKMCC0HyASECDLsCCyABIARGBEBB8QEhAgy7AgsCQAJAAkAgAS0AAEHIAGsOCwABCAgICAgICAgCCAsgAUEBaiEBQdABIQIMowILIAFBAWohAUHRASECDKICCyABQQFqIQFB0gEhAgyhAgtB8AEhAiABIARGDbkCIAMoAgAiACAEIAFraiEGIAEgAGtBAmohBQNAIAEtAAAgAEG11QBqLQAARw0EIABBAkYNAyAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy5AgtB7wEhAiABIARGDbgCIAMoAgAiACAEIAFraiEGIAEgAGtBAWohBQNAIAEtAAAgAEGz1QBqLQAARw0DIABBAUYNAiAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy4AgtB7gEhAiABIARGDbcCIAMoAgAiACAEIAFraiEGIAEgAGtBAmohBQNAIAEtAAAgAEGw1QBqLQAARw0CIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy3AgsgAygCBCEAIANCADcDACADIAAgBUEBaiIBECsiAEUNAiADQewBNgIcIAMgATYCFCADIAA2AgxBACECDLYCCyADQQA2AgALIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ2cAiADQe0BNgIcIAMgATYCFCADIAA2AgxBACECDLQCC0HPASECDJoCC0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMtAILQc4BIQIMmgILIANB6wE2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyyAgsgASAERgRAQesBIQIMsgILIAEtAABBL0YEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQbI4NgIQIANBCDYCDEEAIQIMsQILQc0BIQIMlwILIAEgBEcEQCADQQ42AgggAyABNgIEQcwBIQIMlwILQeoBIQIMrwILIAEgBEYEQEHpASECDK8CCyABLQAAQTBrIgBB/wFxQQpJBEAgAyAAOgAqIAFBAWohAUHLASECDJYCCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNlwIgA0HoATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgsgASAERgRAQecBIQIMrgILAkAgAS0AAEEuRgRAIAFBAWohAQwBCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNmAIgA0HmATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgtBygEhAgyUAgsgASAERgRAQeUBIQIMrQILQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNAiADQeIBNgIcIAMgATYCFCADIAA2AgxBACECDK8CCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNmgIgA0HjATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZgCIANB5AE2AhwgAyABNgIUIAMgADYCDAytAgtByQEhAgyTAgtBACEAAkAgAygCOCICRQ0AIAIoAkQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0GkDTYCECADQSE2AgxBACECDK0CC0HIASECDJMCCyADQeEBNgIcIAMgATYCFCADQdAaNgIQIANBFTYCDEEAIQIMqwILIAEgBEYEQEHhASECDKsCCwJAIAEtAABBIEYEQCADQQA7ATQgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GZETYCECADQQk2AgxBACECDKsCC0HHASECDJECCyABIARGBEBB4AEhAgyqAgsCQCABLQAAQTBrQf8BcSICQQpJBEAgAUEBaiEBAkAgAy8BNCIAQZkzSw0AIAMgAEEKbCIAOwE0IABB/v8DcSACQf//A3NLDQAgAyAAIAJqOwE0DAILQQAhAiADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMDKsCCyADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMQQAhAgyqAgtBxgEhAgyQAgsgASAERgRAQd8BIQIMqQILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDAyqAgsgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDEEAIQIMqQILQcUBIQIMjwILIAEgBEYEQEHeASECDKgCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgwMqQILIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgxBACECDKgCC0HEASECDI4CCyABIARGBEBB3QEhAgynAgsCQAJAAkACQCABLQAAQQprDhcCAwMAAwMDAwMDAwMDAwMDAwMDAwMDAQMLIAFBAWoMBQsgAUEBaiEBQcMBIQIMjwILIAFBAWohASADQS9qLQAAQQFxDQggA0EANgIcIAMgATYCFCADQY0LNgIQIANBDTYCDEEAIQIMpwILIANBADYCHCADIAE2AhQgA0GNCzYCECADQQ02AgxBACECDKYCCyABIARHBEAgA0EPNgIIIAMgATYCBEEBIQIMjQILQdwBIQIMpQILAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0HbASECDKYCCyADKAIEIQAgA0EANgIEIAMgACABEC0iAEUEQCABQQFqIQEMBAsgA0HaATYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgylAgsgAygCBCEAIANBADYCBCADIAAgARAtIgANASABQQFqCy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IQAgBCABQQFqIgFHDQALIAMgBTYCAAySAgsgA0EANgIAIAZBAWohAUEoDD4LIAEgBEYEQEHMASECDJECCwJAAkACQCABLQAAQcUAaw4RAEFBQUFBQUFBQQFBQUFBQQJBCyABQQFqIQFBsQEhAgz5AQsgAUEBaiEBQbIBIQIM+AELIAFBAWohAUGzASECDPcBC0HLASECIAEgBEYNjwIgAygCACIAIAQgAWtqIQUgASAAa0EGaiEGAkADQCABLQAAIABBkdUAai0AAEcNPCAAQQZGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMkAILIANBADYCACAGQQFqIQFBGgw8C0HKASECIAEgBEYNjgIgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBjdUAai0AAEcNOyAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMjwILIANBADYCACAGQQFqIQFBIQw7CyABIARGBEBByQEhAgyOAgsCQAJAIAEtAABBwQBrDhQAPT09PT09PT09PT09PT09PT09AT0LIAFBAWohAUGtASECDPUBCyABQQFqIQFBsAEhAgz0AQsgASAERgRAQcgBIQIMjQILAkACQCABLQAAQdUAaw4LADw8PDw8PDw8PAE8CyABQQFqIQFBrgEhAgz0AQsgAUEBaiEBQa8BIQIM8wELQccBIQIgASAERg2LAiADKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEGE1QBqLQAARw04IABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyMAgsgA0EANgIAIAZBAWohAUEqDDgLIAEgBEYEQEHGASECDIsCCyABLQAAQdAARw04IAFBAWohAUElDDcLQcUBIQIgASAERg2JAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGB1QBqLQAARw02IABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyKAgsgA0EANgIAIAZBAWohAUEODDYLIAEgBEYEQEHEASECDIkCCyABLQAAQcUARw02IAFBAWohAUGrASEC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IM2AELIAFBAWohAUGTASECDNcBCyABIARGBEBBqwEhAgzwAQsCQAJAIAEtAABBwQBrDg8AHx8fHx8fHx8fHx8fHwEfCyABQQFqIQFBkQEhAgzXAQsgAUEBaiEBQZIBIQIM1gELIAEgBEYEQEGqASECDO8BCyABLQAAQcwARw0cIAFBAWohAUEKDBsLQakBIQIgASAERg3tASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHR1ABqLQAARw0aIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzuAQsgA0EANgIAIAZBAWohAUEeDBoLQagBIQIgASAERg3sASADKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIAEtAAAgAEHK1ABqLQAARw0ZIABBBkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAztAQsgA0EANgIAIAZBAWohAUEVDBkLQacBIQIgASAERg3rASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHH1ABqLQAARw0YIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzsAQsgA0EANgIAIAZBAWohAUEXDBgLQaYBIQIgASAERg3qASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHB1ABqLQAARw0XIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzrAQsgA0EANgIAIAZBAWohAUEYDBcLIAEgBEYEQEGlASECDOoBCwJAAkAgAS0AAEHJAGsOBwAZGRkZGQEZCyABQQFqIQFBiwEhAgzRAQsgAUEBaiEBQYwBIQIM0AELQaQBIQIgASAERg3oASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGm1QBqLQAARw0VIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzpAQsgA0EANgIAIAZBAWohAUEJDBULQaMBIQIgASAERg3nASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGk1QBqLQAARw0UIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzoAQsgA0EANgIAIAZBAWohAUEfDBQLQaIBIQIgASAERg3mASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEG+1ABqLQAARw0TIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAznAQsgA0EANgIAIAZBAWohAUECDBMLQaEBIQIgASAERg3lASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYDQCABLQAAIABBvNQAai0AAEcNESAAQQFGDQIgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM5QELIAEgBEYEQEGgASECDOUBC0EBIAEtAABB3wBHDREaIAFBAWohAUGHASECDMsBCyADQQA2AgAgBkEBaiEBQYgBIQIMygELQZ8BIQIgASAERg3iASADKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEGE1QBqLQAARw0PIABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzjAQsgA0EANgIAIAZBAWohAUEpDA8LQZ4BIQIgASAERg3hASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEG41ABqLQAARw0OIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAziAQsgA0EANgIAIAZBAWohAUEtDA4LIAEgBEYEQEGdASECDOEBCyABLQAAQcUARw0OIAFBAWohAUGEASECDMcBCyABIARGBEBBnAEhAgzgAQsCQAJAIAEtAABBzABrDggADw8PDw8PAQ8LIAFBAWohAUGCASECDMcBCyABQQFqIQFBgwEhAgzGAQtBmwEhAiABIARGDd4BIAMoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQbPUAGotAABHDQsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADN8BCyADQQA2AgAgBkEBaiEBQSMMCwtBmgEhAiABIARGDd0BIAMoAgAiACAEIAFraiEFIAEgAGtBAm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QEgAUEBaiEBQRMLOgApIAMoAgQhACADQQA2AgQgAyAAIAEQLiIADQIMAQtBACECIANBADYCHCADIAE2AhQgA0H+HzYCECADQQY2AgwM0QELQfgAIQIMtwELIANBkAE2AhwgAyABNgIUIAMgADYCDEEAIQIMzwELQQAhAAJAIAMoAjgiAkUNACACKAJAIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRg0BIANBADYCHCADIAE2AhQgA0GCDzYCECADQSA2AgxBACECDM4BC0H3ACECDLQBCyADQY8BNgIcIAMgATYCFCADQewbNgIQIANBFTYCDEEAIQIMzAELIAEgBEYEQEGPASECDMwBCwJAIAEtAABBIEYEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQZsfNgIQIANBBjYCDEEAIQIMzAELQQIhAgyyAQsDQCABLQAAQSBHDQIgBCABQQFqIgFHDQALQY4BIQIMygELIAEgBEYEQEGNASECDMoBCwJAIAEtAABBCWsOBEoAAEoAC0H1ACECDLABCyADLQApQQVGBEBB9gAhAgywAQtB9AAhAgyvAQsgASAERgRAQYwBIQIMyAELIANBEDYCCCADIAE2AgQMCgsgASAERgRAQYsBIQIMxwELAkAgAS0AAEEJaw4ERwAARwALQfMAIQIMrQELIAEgBEcEQCADQRA2AgggAyABNgIEQfEAIQIMrQELQYoBIQIMxQELAkAgASAERwRAA0AgAS0AAEGg0ABqLQAAIgBBA0cEQAJAIABBAWsOAkkABAtB8AAhAgyvAQsgBCABQQFqIgFHDQALQYgBIQIMxgELQYgBIQIMxQELIANBADYCHCADIAE2AhQgA0HbIDYCECADQQc2AgxBACECDMQBCyABIARGBEBBiQEhAgzEAQsCQAJAAkAgAS0AAEGg0gBqLQAAQQFrDgNGAgABC0HyACECDKwBCyADQQA2AhwgAyABNgIUIANBtBI2AhAgA0EHNgIMQQAhAgzEAQtB6gAhAgyqAQsgASAERwRAIAFBAWohAUHvACECDKoBC0GHASECDMIBCyAEIAEiAEYEQEGGASECDMIBCyAALQAAIgFBL0YEQCAAQQFqIQFB7gAhAgypAQsgAUEJayICQRdLDQEgACEBQQEgAnRBm4CABHENQQwBCyAEIAEiAEYEQEGFASECDMEBCyAALQAAQS9HDQAgAEEBaiEBDAMLQQAhAiADQQA2AhwgAyAANgIUIANB2yA2AhAgA0EHNgIMDL8BCwJAAkACQAJAAkADQCABLQAAQaDOAGotAAAiAEEFRwRAAkACQCAAQQFrDghHBQYHCAAEAQgLQesAIQIMrQELIAFBAWohAUHtACECDKwBCyAEIAFBAWoiAUcNAAtBhAEhAgzDAQsgAUEBagwUCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQdsANgIcIAMgATYCFCADIAA2AgxBACECDMEBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDMABCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQfoANgIcIAMgATYCFCADIAA2AgxBACECDL8BCyADQQA2AhwgAyABNgIUIANB+Q82AhAgA0EHNgIMQQAhAgy+AQsgASAERgRAQYMBIQIMvgELAkAgAS0AAEGgzgBqLQAAQQFrDgg+BAUGAAgCAwcLIAFBAWohAQtBAyECDKMBCyABQQFqDA0LQQAhAiADQQA2AhwgA0HREjYCECADQQc2AgwgAyABQQFqNgIUDLoBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQdsANgIcIAMgATYCFCADIAA2AgxBACECDLkBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDLgBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQfoANgIcIAMgATYCFCADIAA2AgxBACECDLcBCyADQQA2AhwgAyABNgIUIANB+Q82AhAgA0EHNgIMQQAhAgy2AQtB7AAhAgycAQsgASAERgRAQYIBIQIMtQELIAFBAWoMAgsgASAERgRAQYEBIQIMtAELIAFBAWoMAQsgASAERg0BIAFBAWoLIQFBBCECDJgBC0GAASECDLABCwNAIAEtAABBoMwAai0AACIAQQJHBEAgAEEBRwRAQekAIQIMmQELDDELIAQgAUEBaiIBRw0AC0H/ACECDK8BCyABIARGBEBB/gAhAgyvAQsCQCABLQAAQQlrDjcvAwYvBAYGBgYGBgYGBgYGBgYGBgYGBgUGBgIGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYABgsgAUEBagshAUEFIQIMlAELIAFBAWoMBgsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgyrAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyqAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0H6ADYCHCADIAE2AhQgAyAANgIMQQAhAgypAQsgA0EANgIcIAMgATYCFCADQY0UNgIQIANBBzYCDEEAIQIMqAELAkACQAJAAkADQCABLQAAQaDKAGotAAAiAEEFRwRAAkAgAEEBaw4GLgMEBQYABgtB6AAhAgyUAQsgBCABQQFqIgFHDQALQf0AIQIMqwELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMqgELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMqQELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB+gA2AhwgAyABNgIUIAMgADYCDEEAIQIMqAELIANBADYCHCADIAE2AhQgA0HkCDYCECADQQc2AgxBACECDKcBCyABIARGDQEgAUEBagshAUEGIQIMjAELQfwAIQIMpAELAkACQAJAAkADQCABLQAAQaDIAGotAAAiAEEFRwRAIABBAWsOBCkCAwQFCyAEIAFBAWoiAUcNAAtB+wAhAgynAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgymAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgylAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0H6ADYCHCADIAE2AhQgAyAANgIMQQAhAgykAQsgA0EANgIcIAMgATYCFCADQbwKNgIQIANBBzYCDEEAIQIMowELQc8AIQIMiQELQdEAIQIMiAELQecAIQIMhwELIAEgBEYEQEH6ACECDKABCwJAIAEtAABBCWsOBCAAACAACyABQQFqIQFB5gAhAgyGAQsgASAERgRAQfkAIQIMnwELAkAgAS0AAEEJaw4EHwAAHwALQQAhAAJAIAMoAjgiAkUNACACKAI4IgJFDQAgAyACEQAAIQALIABFBEBB4gEhAgyGAQsgAEEVRwRAIANBADYCHCADIAE2AhQgA0HJDTYCECADQRo2AgxBACECDJ8BCyADQfgANgIcIAMgATYCFCADQeoaNgIQIANBFTYCDEEAIQIMngELIAEgBEcEQCADQQ02AgggAyABNgIEQeQAIQIMhQELQfcAIQIMnQELIAEgBEYEQEH2ACECDJ0BCwJAAkACQCABLQAAQcgAaw4LAAELCwsLCwsLCwILCyABQQFqIQFB3QAhAgyFAQsgAUEBaiEBQeAAIQIMhAELIAFBAWohAUHjACECDIMBC0H1ACECIAEgBEYNmwEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBtdUAai0AAEcNCCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMnAELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgAEQCADQfQANgIcIAMgATYCFCADIAA2AgxBACECDJwBC0HiACECDIIBC0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMnAELQeEAIQIMggELIANB8wA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyaAQsgAy0AKSIAQSNrQQtJDQkCQCAAQQZLDQBBASAAdEHKAHFFDQAMCgtBACECIANBADYCHCADIAE2AhQgA0HtCTYCECADQQg2AgwMmQELQfIAIQIgASAERg2YASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGz1QBqLQAARw0FIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyZAQsgAygCBCEAIANCADcDACADIAAgBkEBaiIBECsiAARAIANB8QA2AhwgAyABNgIUIAMgADYCDEEAIQIMmQELQd8AIQIMfwtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJkBC0HeACECDH8LIANB8AA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyXAQsgAy0AKUEhRg0GIANBADYCHCADIAE2AhQgA0GRCjYCECADQQg2AgxBACECDJYBC0HvACECIAEgBEYNlQEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBsNUAai0AAEcNAiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMlgELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgBFDQIgA0HtADYCHCADIAE2AhQgAyAANgIMQQAhAgyVAQsgA0EANgIACyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNgAEgA0HuADYCHCADIAE2AhQgAyAANgIMQQAhAgyTAQtB3AAhAgx5C0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMkwELQdsAIQIMeQsgA0HsADYCHCADIAE2AhQgA0GAGzYCECADQRU2AgxBACECDJEBCyADLQApIgBBI0kNACAAQS5GDQAgA0EANgIcIAMgATYCFCADQckJNgIQIANBCDYCDEEAIQIMkAELQdoAIQIMdgsgASAERgRAQesAIQIMjwELAkAgAS0AAEEvRgRAIAFBAWohAQwBCyADQQA2AhwgAyABNgIUIANBsjg2AhAgA0EINgIMQQAh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xoC0EAIQACQCADKAI4IgJFDQAgAigCSCICRQ0AIAMgAhEAACEACyAARQRAQcEAIQIMTwsgAEEVRwRAIANBADYCHCADIAE2AhQgA0GmDzYCECADQRw2AgxBACECDGgLIANBygA2AhwgAyABNgIUIANBhRw2AhAgA0EVNgIMQQAhAgxnCyABIARHBEAgASECA0AgBCACIgFrQRBOBEAgAUEQaiEC/Qz/////////////////////IAH9AAAAIg1BB/1sIA39DODg4ODg4ODg4ODg4ODg4OD9bv0MX19fX19fX19fX19fX19fX/0mIA39DAkJCQkJCQkJCQkJCQkJCQn9I/1Q/VL9ZEF/c2giAEEQRg0BIAAgAWohAQwYCyABIARGBEBBxAAhAgxpCyABLQAAQcDBAGotAABBAUcNFyAEIAFBAWoiAkcNAAtBxAAhAgxnC0HEACECDGYLIAEgBEcEQANAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXEiAEEJRg0AIABBIEYNAAJAAkACQAJAIABB4wBrDhMAAwMDAwMDAwEDAwMDAwMDAwMCAwsgAUEBaiEBQTYhAgxSCyABQQFqIQFBNyECDFELIAFBAWohAUE4IQIMUAsMFQsgBCABQQFqIgFHDQALQTwhAgxmC0E8IQIMZQsgASAERgRAQcgAIQIMZQsgA0ESNgIIIAMgATYCBAJAAkACQAJAAkAgAy0ALEEBaw4EFAABAgkLIAMtADJBIHENA0HgASECDE8LAkAgAy8BMiIAQQhxRQ0AIAMtAChBAUcNACADLQAuQQhxRQ0CCyADIABB9/sDcUGABHI7ATIMCwsgAyADLwEyQRByOwEyDAQLIANBADYCBCADIAEgARAxIgAEQCADQcEANgIcIAMgADYCDCADIAFBAWo2AhRBACECDGYLIAFBAWohAQxYCyADQQA2AhwgAyABNgIUIANB9BM2AhAgA0EENgIMQQAhAgxkC0HHACECIAEgBEYNYyADKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIABBwMUAai0AACABLQAAQSByRw0BIABBBkYNSiAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAA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NgIUIANBxBg2AhAgA0ECNgIMDAQLIANBAjYCHCADIAE2AhQgA0GpHjYCECADQRY2AgxBACECDAMLQd4AIQIgASAERg0CIAlBCGohByADKAIAIQUCQAJAIAEgBEcEQCAFQZbIAGohCCAEIAVqIAFrIQYgBUF/c0EKaiIFIAFqIQADQCABLQAAIAgtAABHBEBBAiEIDAMLIAVFBEBBACEIIAAhAQwDCyAFQQFrIQUgCEEBaiEIIAQgAUEBaiIBRw0ACyAGIQUgBCEBCyAHQQE2AgAgAyAFNgIADAELIANBADYCACAHIAg2AgALIAcgATYCBCAJKAIMIQACQAJAIAkoAghBAWsOAgQBAAsgA0EANgIcIANBwh42AhAgA0EXNgIMIAMgAEEBajYCFEEAIQIMAwsgA0EANgIcIAMgADYCFCADQdceNgIQIANBCTYCDEEAIQIMAgsgASAERgRAQSghAgwCCyADQQk2AgggAyABNgIEQSchAgwBCyABIARGBEBBASECDAELA0ACQAJAAkAgAS0AAEEKaw4EAAEBAAELIAFBAWohAQwBCyABQQFqIQEgAy0ALkEgcQ0AQQAhAiADQQA2AhwgAyABNgIUIANBoSE2AhAgA0EFNgIMDAILQQEhAiABIARHDQALCyAJQRBqJAAgAkUEQCADKAIMIQAMAQsgAyACNgIcQQAhACADKAIEIgFFDQAgAyABIAQgAygCCBEBACIBRQ0AIAMgBDYCFCADIAE2AgwgASEACyAAC74CAQJ/IABBADoAACAAQeQAaiIBQQFrQQA6AAAgAEEAOgACIABBADoAASABQQNrQQA6AAAgAUECa0EAOgAAIABBADoAAyABQQRrQQA6AABBACAAa0EDcSIBIABqIgBBADYCAEHkACABa0F8cSICIABqIgFBBGtBADYCAAJAIAJBCUkNACAAQQA2AgggAEEANgIEIAFBCGtBADYCACABQQxrQQA2AgAgAkEZSQ0AIABBADYCGCAAQQA2AhQgAEEANgIQIABBADYCDCABQRBrQQA2AgAgAUEUa0EANgIAIAFBGGtBADYCACABQRxrQQA2AgAgAiAAQQRxQRhyIgJrIgFBIEkNACAAIAJqIQADQCA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DVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRVVFUllPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFVFRQQ0VUU1BBRFRQLw==' + +let wasmBuffer + +Object.defineProperty(module, 'exports', { + get: () => { + return wasmBuffer + ? wasmBuffer + : (wasmBuffer = Buffer.from(wasmBase64, 'base64')) + } +}) diff --git a/node_modules/undici/lib/llhttp/utils.d.ts b/node_modules/undici/lib/llhttp/utils.d.ts new file mode 100644 index 000000000..681b22b94 --- /dev/null +++ b/node_modules/undici/lib/llhttp/utils.d.ts @@ -0,0 +1,2 @@ +import type { IntDict } from './constants'; +export declare function enumToMap(obj: IntDict, filter?: readonly number[], exceptions?: readonly number[]): IntDict; diff --git a/node_modules/undici/lib/llhttp/utils.js b/node_modules/undici/lib/llhttp/utils.js new file mode 100644 index 000000000..95081ead5 --- /dev/null +++ b/node_modules/undici/lib/llhttp/utils.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.enumToMap = enumToMap; +function enumToMap(obj, filter = [], exceptions = []) { + const emptyFilter = (filter?.length ?? 0) === 0; + const emptyExceptions = (exceptions?.length ?? 0) === 0; + return Object.fromEntries(Object.entries(obj).filter(([, value]) => { + return (typeof value === 'number' && + (emptyFilter || filter.includes(value)) && + (emptyExceptions || !exceptions.includes(value))); + })); +} diff --git a/node_modules/undici/lib/mock/mock-agent.js b/node_modules/undici/lib/mock/mock-agent.js new file mode 100644 index 000000000..61449e077 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-agent.js @@ -0,0 +1,232 @@ +'use strict' + +const { kClients } = require('../core/symbols') +const Agent = require('../dispatcher/agent') +const { + kAgent, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory, + kMockAgentRegisterCallHistory, + kMockAgentIsCallHistoryEnabled, + kMockAgentAddCallHistoryLog, + kMockAgentMockCallHistoryInstance, + kMockAgentAcceptsNonStandardSearchParameters, + kMockCallHistoryAddLog, + kIgnoreTrailingSlash +} = require('./mock-symbols') +const MockClient = require('./mock-client') +const MockPool = require('./mock-pool') +const { matchValue, normalizeSearchParams, buildAndValidateMockOptions, normalizeOrigin } = require('./mock-utils') +const { InvalidArgumentError, UndiciError } = require('../core/errors') +const Dispatcher = require('../dispatcher/dispatcher') +const PendingInterceptorsFormatter = require('./pending-interceptors-formatter') +const { MockCallHistory } = require('./mock-call-history') + +class MockAgent extends Dispatcher { + constructor (opts = {}) { + super(opts) + + const mockOptions = buildAndValidateMockOptions(opts) + + this[kNetConnect] = true + this[kIsMockActive] = true + this[kMockAgentIsCallHistoryEnabled] = mockOptions.enableCallHistory ?? false + this[kMockAgentAcceptsNonStandardSearchParameters] = mockOptions.acceptNonStandardSearchParameters ?? false + this[kIgnoreTrailingSlash] = mockOptions.ignoreTrailingSlash ?? false + + // Instantiate Agent and encapsulate + if (opts?.agent && typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + const agent = opts?.agent ? opts.agent : new Agent(opts) + this[kAgent] = agent + + this[kClients] = agent[kClients] + this[kOptions] = mockOptions + + if (this[kMockAgentIsCallHistoryEnabled]) { + this[kMockAgentRegisterCallHistory]() + } + } + + get (origin) { + // Normalize origin to handle URL objects and case-insensitive hostnames + const normalizedOrigin = normalizeOrigin(origin) + const originKey = this[kIgnoreTrailingSlash] ? normalizedOrigin.replace(/\/$/, '') : normalizedOrigin + + let dispatcher = this[kMockAgentGet](originKey) + + if (!dispatcher) { + dispatcher = this[kFactory](originKey) + this[kMockAgentSet](originKey, dispatcher) + } + return dispatcher + } + + dispatch (opts, handler) { + opts.origin = normalizeOrigin(opts.origin) + + // Call MockAgent.get to perform additional setup before dispatching as normal + this.get(opts.origin) + + this[kMockAgentAddCallHistoryLog](opts) + + const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters] + + const dispatchOpts = { ...opts } + + if (acceptNonStandardSearchParameters && dispatchOpts.path) { + const [path, searchParams] = dispatchOpts.path.split('?') + const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters) + dispatchOpts.path = `${path}?${normalizedSearchParams}` + } + + return this[kAgent].dispatch(dispatchOpts, handler) + } + + async close () { + this.clearCallHistory() + await this[kAgent].close() + this[kClients].clear() + } + + deactivate () { + this[kIsMockActive] = false + } + + activate () { + this[kIsMockActive] = true + } + + enableNetConnect (matcher) { + if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { + if (Array.isArray(this[kNetConnect])) { + this[kNetConnect].push(matcher) + } else { + this[kNetConnect] = [matcher] + } + } else if (typeof matcher === 'undefined') { + this[kNetConnect] = true + } else { + throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') + } + } + + disableNetConnect () { + this[kNetConnect] = false + } + + enableCallHistory () { + this[kMockAgentIsCallHistoryEnabled] = true + + return this + } + + disableCallHistory () { + this[kMockAgentIsCallHistoryEnabled] = false + + return this + } + + getCallHistory () { + return this[kMockAgentMockCallHistoryInstance] + } + + clearCallHistory () { + if (this[kMockAgentMockCallHistoryInstance] !== undefined) { + this[kMockAgentMockCallHistoryInstance].clear() + } + } + + // This is required to bypass issues caused by using global symbols - see: + // https://github.com/nodejs/undici/issues/1447 + get isMockActive () { + return this[kIsMockActive] + } + + [kMockAgentRegisterCallHistory] () { + if (this[kMockAgentMockCallHistoryInstance] === undefined) { + this[kMockAgentMockCallHistoryInstance] = new MockCallHistory() + } + } + + [kMockAgentAddCallHistoryLog] (opts) { + if (this[kMockAgentIsCallHistoryEnabled]) { + // additional setup when enableCallHistory class method is used after mockAgent instantiation + this[kMockAgentRegisterCallHistory]() + + // add call history log on every call (intercepted or not) + this[kMockAgentMockCallHistoryInstance][kMockCallHistoryAddLog](opts) + } + } + + [kMockAgentSet] (origin, dispatcher) { + this[kClients].set(origin, { count: 0, dispatcher }) + } + + [kFactory] (origin) { + const mockOptions = Object.assign({ agent: this }, this[kOptions]) + return this[kOptions] && this[kOptions].connections === 1 + ? new MockClient(origin, mockOptions) + : new MockPool(origin, mockOptions) + } + + [kMockAgentGet] (origin) { + // First check if we can immediately find it + const result = this[kClients].get(origin) + if (result?.dispatcher) { + return result.dispatcher + } + + // If the origin is not a string create a dummy parent pool and return to user + if (typeof origin !== 'string') { + const dispatcher = this[kFactory]('http://localhost:9999') + this[kMockAgentSet](origin, dispatcher) + return dispatcher + } + + // If we match, create a pool and assign the same dispatches + for (const [keyMatcher, result] of Array.from(this[kClients])) { + if (result && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { + const dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + dispatcher[kDispatches] = result.dispatcher[kDispatches] + return dispatcher + } + } + } + + [kGetNetConnect] () { + return this[kNetConnect] + } + + pendingInterceptors () { + const mockAgentClients = this[kClients] + + return Array.from(mockAgentClients.entries()) + .flatMap(([origin, result]) => result.dispatcher[kDispatches].map(dispatch => ({ ...dispatch, origin }))) + .filter(({ pending }) => pending) + } + + assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { + const pending = this.pendingInterceptors() + + if (pending.length === 0) { + return + } + + throw new UndiciError( + pending.length === 1 + ? `1 interceptor is pending:\n\n${pendingInterceptorsFormatter.format(pending)}`.trim() + : `${pending.length} interceptors are pending:\n\n${pendingInterceptorsFormatter.format(pending)}`.trim() + ) + } +} + +module.exports = MockAgent diff --git a/node_modules/undici/lib/mock/mock-call-history.js b/node_modules/undici/lib/mock/mock-call-history.js new file mode 100644 index 000000000..d4a92b2b2 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-call-history.js @@ -0,0 +1,248 @@ +'use strict' + +const { kMockCallHistoryAddLog } = require('./mock-symbols') +const { InvalidArgumentError } = require('../core/errors') + +function handleFilterCallsWithOptions (criteria, options, handler, store) { + switch (options.operator) { + case 'OR': + store.push(...handler(criteria)) + + return store + case 'AND': + return handler.call({ logs: store }, criteria) + default: + // guard -- should never happens because buildAndValidateFilterCallsOptions is called before + throw new InvalidArgumentError('options.operator must to be a case insensitive string equal to \'OR\' or \'AND\'') + } +} + +function buildAndValidateFilterCallsOptions (options = {}) { + const finalOptions = {} + + if ('operator' in options) { + if (typeof options.operator !== 'string' || (options.operator.toUpperCase() !== 'OR' && options.operator.toUpperCase() !== 'AND')) { + throw new InvalidArgumentError('options.operator must to be a case insensitive string equal to \'OR\' or \'AND\'') + } + + return { + ...finalOptions, + operator: options.operator.toUpperCase() + } + } + + return finalOptions +} + +function makeFilterCalls (parameterName) { + return (parameterValue) => { + if (typeof parameterValue === 'string' || parameterValue == null) { + return this.logs.filter((log) => { + return log[parameterName] === parameterValue + }) + } + if (parameterValue instanceof RegExp) { + return this.logs.filter((log) => { + return parameterValue.test(log[parameterName]) + }) + } + + throw new InvalidArgumentError(`${parameterName} parameter should be one of string, regexp, undefined or null`) + } +} +function computeUrlWithMaybeSearchParameters (requestInit) { + // path can contains query url parameters + // or query can contains query url parameters + try { + const url = new URL(requestInit.path, requestInit.origin) + + // requestInit.path contains query url parameters + // requestInit.query is then undefined + if (url.search.length !== 0) { + return url + } + + // requestInit.query can be populated here + url.search = new URLSearchParams(requestInit.query).toString() + + return url + } catch (error) { + throw new InvalidArgumentError('An error occurred when computing MockCallHistoryLog.url', { cause: error }) + } +} + +class MockCallHistoryLog { + constructor (requestInit = {}) { + this.body = requestInit.body + this.headers = requestInit.headers + this.method = requestInit.method + + const url = computeUrlWithMaybeSearchParameters(requestInit) + + this.fullUrl = url.toString() + this.origin = url.origin + this.path = url.pathname + this.searchParams = Object.fromEntries(url.searchParams) + this.protocol = url.protocol + this.host = url.host + this.port = url.port + this.hash = url.hash + } + + toMap () { + return new Map([ + ['protocol', this.protocol], + ['host', this.host], + ['port', this.port], + ['origin', this.origin], + ['path', this.path], + ['hash', this.hash], + ['searchParams', this.searchParams], + ['fullUrl', this.fullUrl], + ['method', this.method], + ['body', this.body], + ['headers', this.headers]] + ) + } + + toString () { + const options = { betweenKeyValueSeparator: '->', betweenPairSeparator: '|' } + let result = '' + + this.toMap().forEach((value, key) => { + if (typeof value === 'string' || value === undefined || value === null) { + result = `${result}${key}${options.betweenKeyValueSeparator}${value}${options.betweenPairSeparator}` + } + if ((typeof value === 'object' && value !== null) || Array.isArray(value)) { + result = `${result}${key}${options.betweenKeyValueSeparator}${JSON.stringify(value)}${options.betweenPairSeparator}` + } + // maybe miss something for non Record / Array headers and searchParams here + }) + + // delete last betweenPairSeparator + return result.slice(0, -1) + } +} + +class MockCallHistory { + logs = [] + + calls () { + return this.logs + } + + firstCall () { + return this.logs.at(0) + } + + lastCall () { + return this.logs.at(-1) + } + + nthCall (number) { + if (typeof number !== 'number') { + throw new InvalidArgumentError('nthCall must be called with a number') + } + if (!Number.isInteger(number)) { + throw new InvalidArgumentError('nthCall must be called with an integer') + } + if (Math.sign(number) !== 1) { + throw new InvalidArgumentError('nthCall must be called with a positive value. use firstCall or lastCall instead') + } + + // non zero based index. this is more human readable + return this.logs.at(number - 1) + } + + filterCalls (criteria, options) { + // perf + if (this.logs.length === 0) { + return this.logs + } + if (typeof criteria === 'function') { + return this.logs.filter(criteria) + } + if (criteria instanceof RegExp) { + return this.logs.filter((log) => { + return criteria.test(log.toString()) + }) + } + if (typeof criteria === 'object' && criteria !== null) { + // no criteria - returning all logs + if (Object.keys(criteria).length === 0) { + return this.logs + } + + const finalOptions = { operator: 'OR', ...buildAndValidateFilterCallsOptions(options) } + + let maybeDuplicatedLogsFiltered = [] + if ('protocol' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered) + } + if ('host' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered) + } + if ('port' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered) + } + if ('origin' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered) + } + if ('path' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered) + } + if ('hash' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered) + } + if ('fullUrl' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered) + } + if ('method' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered) + } + + const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)] + + return uniqLogsFiltered + } + + throw new InvalidArgumentError('criteria parameter should be one of function, regexp, or object') + } + + filterCallsByProtocol = makeFilterCalls.call(this, 'protocol') + + filterCallsByHost = makeFilterCalls.call(this, 'host') + + filterCallsByPort = makeFilterCalls.call(this, 'port') + + filterCallsByOrigin = makeFilterCalls.call(this, 'origin') + + filterCallsByPath = makeFilterCalls.call(this, 'path') + + filterCallsByHash = makeFilterCalls.call(this, 'hash') + + filterCallsByFullUrl = makeFilterCalls.call(this, 'fullUrl') + + filterCallsByMethod = makeFilterCalls.call(this, 'method') + + clear () { + this.logs = [] + } + + [kMockCallHistoryAddLog] (requestInit) { + const log = new MockCallHistoryLog(requestInit) + + this.logs.push(log) + + return log + } + + * [Symbol.iterator] () { + for (const log of this.calls()) { + yield log + } + } +} + +module.exports.MockCallHistory = MockCallHistory +module.exports.MockCallHistoryLog = MockCallHistoryLog diff --git a/node_modules/undici/lib/mock/mock-client.js b/node_modules/undici/lib/mock/mock-client.js new file mode 100644 index 000000000..b3be7ab3b --- /dev/null +++ b/node_modules/undici/lib/mock/mock-client.js @@ -0,0 +1,68 @@ +'use strict' + +const { promisify } = require('node:util') +const Client = require('../dispatcher/client') +const { buildMockDispatch } = require('./mock-utils') +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected, + kIgnoreTrailingSlash +} = require('./mock-symbols') +const { MockInterceptor } = require('./mock-interceptor') +const Symbols = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') + +/** + * MockClient provides an API that extends the Client to influence the mockDispatches. + */ +class MockClient extends Client { + constructor (origin, opts) { + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + super(origin, opts) + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor( + opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts }, + this[kDispatches] + ) + } + + cleanMocks () { + this[kDispatches] = [] + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockClient diff --git a/node_modules/undici/lib/mock/mock-errors.js b/node_modules/undici/lib/mock/mock-errors.js new file mode 100644 index 000000000..69e4f9cc3 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-errors.js @@ -0,0 +1,29 @@ +'use strict' + +const { UndiciError } = require('../core/errors') + +const kMockNotMatchedError = Symbol.for('undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED') + +/** + * The request does not match any registered mock dispatches. + */ +class MockNotMatchedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'MockNotMatchedError' + this.message = message || 'The request does not match any registered mock dispatches' + this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kMockNotMatchedError] === true + } + + get [kMockNotMatchedError] () { + return true + } +} + +module.exports = { + MockNotMatchedError +} diff --git a/node_modules/undici/lib/mock/mock-interceptor.js b/node_modules/undici/lib/mock/mock-interceptor.js new file mode 100644 index 000000000..1ea7aac48 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-interceptor.js @@ -0,0 +1,209 @@ +'use strict' + +const { getResponseData, buildKey, addMockDispatch } = require('./mock-utils') +const { + kDispatches, + kDispatchKey, + kDefaultHeaders, + kDefaultTrailers, + kContentLength, + kMockDispatch, + kIgnoreTrailingSlash +} = require('./mock-symbols') +const { InvalidArgumentError } = require('../core/errors') +const { serializePathWithQuery } = require('../core/util') + +/** + * Defines the scope API for an interceptor reply + */ +class MockScope { + constructor (mockDispatch) { + this[kMockDispatch] = mockDispatch + } + + /** + * Delay a reply by a set amount in ms. + */ + delay (waitInMs) { + if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { + throw new InvalidArgumentError('waitInMs must be a valid integer > 0') + } + + this[kMockDispatch].delay = waitInMs + return this + } + + /** + * For a defined reply, never mark as consumed. + */ + persist () { + this[kMockDispatch].persist = true + return this + } + + /** + * Allow one to define a reply for a set amount of matching requests. + */ + times (repeatTimes) { + if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { + throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') + } + + this[kMockDispatch].times = repeatTimes + return this + } +} + +/** + * Defines an interceptor for a Mock + */ +class MockInterceptor { + constructor (opts, mockDispatches) { + if (typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object') + } + if (typeof opts.path === 'undefined') { + throw new InvalidArgumentError('opts.path must be defined') + } + if (typeof opts.method === 'undefined') { + opts.method = 'GET' + } + // See https://github.com/nodejs/undici/issues/1245 + // As per RFC 3986, clients are not supposed to send URI + // fragments to servers when they retrieve a document, + if (typeof opts.path === 'string') { + if (opts.query) { + opts.path = serializePathWithQuery(opts.path, opts.query) + } else { + // Matches https://github.com/nodejs/undici/blob/main/lib/web/fetch/index.js#L1811 + const parsedURL = new URL(opts.path, 'data://') + opts.path = parsedURL.pathname + parsedURL.search + } + } + if (typeof opts.method === 'string') { + opts.method = opts.method.toUpperCase() + } + + this[kDispatchKey] = buildKey(opts) + this[kDispatches] = mockDispatches + this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false + this[kDefaultHeaders] = {} + this[kDefaultTrailers] = {} + this[kContentLength] = false + } + + createMockScopeDispatchData ({ statusCode, data, responseOptions }) { + const responseData = getResponseData(data) + const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} + const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } + const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } + + return { statusCode, data, headers, trailers } + } + + validateReplyParameters (replyParameters) { + if (typeof replyParameters.statusCode === 'undefined') { + throw new InvalidArgumentError('statusCode must be defined') + } + if (typeof replyParameters.responseOptions !== 'object' || replyParameters.responseOptions === null) { + throw new InvalidArgumentError('responseOptions must be an object') + } + } + + /** + * Mock an undici request with a defined reply. + */ + reply (replyOptionsCallbackOrStatusCode) { + // Values of reply aren't available right now as they + // can only be available when the reply callback is invoked. + if (typeof replyOptionsCallbackOrStatusCode === 'function') { + // We'll first wrap the provided callback in another function, + // this function will properly resolve the data from the callback + // when invoked. + const wrappedDefaultsCallback = (opts) => { + // Our reply options callback contains the parameter for statusCode, data and options. + const resolvedData = replyOptionsCallbackOrStatusCode(opts) + + // Check if it is in the right format + if (typeof resolvedData !== 'object' || resolvedData === null) { + throw new InvalidArgumentError('reply options callback must return an object') + } + + const replyParameters = { data: '', responseOptions: {}, ...resolvedData } + this.validateReplyParameters(replyParameters) + // Since the values can be obtained immediately we return them + // from this higher order function that will be resolved later. + return { + ...this.createMockScopeDispatchData(replyParameters) + } + } + + // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] }) + return new MockScope(newMockDispatch) + } + + // We can have either one or three parameters, if we get here, + // we should have 1-3 parameters. So we spread the arguments of + // this function to obtain the parameters, since replyData will always + // just be the statusCode. + const replyParameters = { + statusCode: replyOptionsCallbackOrStatusCode, + data: arguments[1] === undefined ? '' : arguments[1], + responseOptions: arguments[2] === undefined ? {} : arguments[2] + } + this.validateReplyParameters(replyParameters) + + // Send in-already provided data like usual + const dispatchData = this.createMockScopeDispatchData(replyParameters) + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] }) + return new MockScope(newMockDispatch) + } + + /** + * Mock an undici request with a defined error. + */ + replyWithError (error) { + if (typeof error === 'undefined') { + throw new InvalidArgumentError('error must be defined') + } + + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] }) + return new MockScope(newMockDispatch) + } + + /** + * Set default reply headers on the interceptor for subsequent replies + */ + defaultReplyHeaders (headers) { + if (typeof headers === 'undefined') { + throw new InvalidArgumentError('headers must be defined') + } + + this[kDefaultHeaders] = headers + return this + } + + /** + * Set default reply trailers on the interceptor for subsequent replies + */ + defaultReplyTrailers (trailers) { + if (typeof trailers === 'undefined') { + throw new InvalidArgumentError('trailers must be defined') + } + + this[kDefaultTrailers] = trailers + return this + } + + /** + * Set reply content length header for replies on the interceptor + */ + replyContentLength () { + this[kContentLength] = true + return this + } +} + +module.exports.MockInterceptor = MockInterceptor +module.exports.MockScope = MockScope diff --git a/node_modules/undici/lib/mock/mock-pool.js b/node_modules/undici/lib/mock/mock-pool.js new file mode 100644 index 000000000..2121e3c99 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-pool.js @@ -0,0 +1,68 @@ +'use strict' + +const { promisify } = require('node:util') +const Pool = require('../dispatcher/pool') +const { buildMockDispatch } = require('./mock-utils') +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected, + kIgnoreTrailingSlash +} = require('./mock-symbols') +const { MockInterceptor } = require('./mock-interceptor') +const Symbols = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') + +/** + * MockPool provides an API that extends the Pool to influence the mockDispatches. + */ +class MockPool extends Pool { + constructor (origin, opts) { + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + super(origin, opts) + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor( + opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts }, + this[kDispatches] + ) + } + + cleanMocks () { + this[kDispatches] = [] + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockPool diff --git a/node_modules/undici/lib/mock/mock-symbols.js b/node_modules/undici/lib/mock/mock-symbols.js new file mode 100644 index 000000000..940dbe6e3 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-symbols.js @@ -0,0 +1,31 @@ +'use strict' + +module.exports = { + kAgent: Symbol('agent'), + kOptions: Symbol('options'), + kFactory: Symbol('factory'), + kDispatches: Symbol('dispatches'), + kDispatchKey: Symbol('dispatch key'), + kDefaultHeaders: Symbol('default headers'), + kDefaultTrailers: Symbol('default trailers'), + kContentLength: Symbol('content length'), + kMockAgent: Symbol('mock agent'), + kMockAgentSet: Symbol('mock agent set'), + kMockAgentGet: Symbol('mock agent get'), + kMockDispatch: Symbol('mock dispatch'), + kClose: Symbol('close'), + kOriginalClose: Symbol('original agent close'), + kOriginalDispatch: Symbol('original dispatch'), + kOrigin: Symbol('origin'), + kIsMockActive: Symbol('is mock active'), + kNetConnect: Symbol('net connect'), + kGetNetConnect: Symbol('get net connect'), + kConnected: Symbol('connected'), + kIgnoreTrailingSlash: Symbol('ignore trailing slash'), + kMockAgentMockCallHistoryInstance: Symbol('mock agent mock call history name'), + kMockAgentRegisterCallHistory: Symbol('mock agent register mock call history'), + kMockAgentAddCallHistoryLog: Symbol('mock agent add call history log'), + kMockAgentIsCallHistoryEnabled: Symbol('mock agent is call history enabled'), + kMockAgentAcceptsNonStandardSearchParameters: Symbol('mock agent accepts non standard search parameters'), + kMockCallHistoryAddLog: Symbol('mock call history add log') +} diff --git a/node_modules/undici/lib/mock/mock-utils.js b/node_modules/undici/lib/mock/mock-utils.js new file mode 100644 index 000000000..e1e3f0406 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-utils.js @@ -0,0 +1,447 @@ +'use strict' + +const { MockNotMatchedError } = require('./mock-errors') +const { + kDispatches, + kMockAgent, + kOriginalDispatch, + kOrigin, + kGetNetConnect +} = require('./mock-symbols') +const { serializePathWithQuery } = require('../core/util') +const { STATUS_CODES } = require('node:http') +const { + types: { + isPromise + } +} = require('node:util') +const { InvalidArgumentError } = require('../core/errors') + +function matchValue (match, value) { + if (typeof match === 'string') { + return match === value + } + if (match instanceof RegExp) { + return match.test(value) + } + if (typeof match === 'function') { + return match(value) === true + } + return false +} + +function lowerCaseEntries (headers) { + return Object.fromEntries( + Object.entries(headers).map(([headerName, headerValue]) => { + return [headerName.toLocaleLowerCase(), headerValue] + }) + ) +} + +/** + * @param {import('../../index').Headers|string[]|Record} headers + * @param {string} key + */ +function getHeaderByName (headers, key) { + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { + return headers[i + 1] + } + } + + return undefined + } else if (typeof headers.get === 'function') { + return headers.get(key) + } else { + return lowerCaseEntries(headers)[key.toLocaleLowerCase()] + } +} + +/** @param {string[]} headers */ +function buildHeadersFromArray (headers) { // fetch HeadersList + const clone = headers.slice() + const entries = [] + for (let index = 0; index < clone.length; index += 2) { + entries.push([clone[index], clone[index + 1]]) + } + return Object.fromEntries(entries) +} + +function matchHeaders (mockDispatch, headers) { + if (typeof mockDispatch.headers === 'function') { + if (Array.isArray(headers)) { // fetch HeadersList + headers = buildHeadersFromArray(headers) + } + return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) + } + if (typeof mockDispatch.headers === 'undefined') { + return true + } + if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { + return false + } + + for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { + const headerValue = getHeaderByName(headers, matchHeaderName) + + if (!matchValue(matchHeaderValue, headerValue)) { + return false + } + } + return true +} + +function normalizeSearchParams (query) { + if (typeof query !== 'string') { + return query + } + + const originalQp = new URLSearchParams(query) + const normalizedQp = new URLSearchParams() + + for (let [key, value] of originalQp.entries()) { + key = key.replace('[]', '') + + const valueRepresentsString = /^(['"]).*\1$/.test(value) + if (valueRepresentsString) { + normalizedQp.append(key, value) + continue + } + + if (value.includes(',')) { + const values = value.split(',') + for (const v of values) { + normalizedQp.append(key, v) + } + continue + } + + normalizedQp.append(key, value) + } + + return normalizedQp +} + +function safeUrl (path) { + if (typeof path !== 'string') { + return path + } + const pathSegments = path.split('?', 3) + if (pathSegments.length !== 2) { + return path + } + + const qp = new URLSearchParams(pathSegments.pop()) + qp.sort() + return [...pathSegments, qp.toString()].join('?') +} + +function matchKey (mockDispatch, { path, method, body, headers }) { + const pathMatch = matchValue(mockDispatch.path, path) + const methodMatch = matchValue(mockDispatch.method, method) + const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true + const headersMatch = matchHeaders(mockDispatch, headers) + return pathMatch && methodMatch && bodyMatch && headersMatch +} + +function getResponseData (data) { + if (Buffer.isBuffer(data)) { + return data + } else if (data instanceof Uint8Array) { + return data + } else if (data instanceof ArrayBuffer) { + return data + } else if (typeof data === 'object') { + return JSON.stringify(data) + } else if (data) { + return data.toString() + } else { + return '' + } +} + +function getMockDispatch (mockDispatches, key) { + const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path + const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath + + const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath) + + // Match path + let matchedMockDispatches = mockDispatches + .filter(({ consumed }) => !consumed) + .filter(({ path, ignoreTrailingSlash }) => { + return ignoreTrailingSlash + ? matchValue(removeTrailingSlash(safeUrl(path)), resolvedPathWithoutTrailingSlash) + : matchValue(safeUrl(path), resolvedPath) + }) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) + } + + // Match method + matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`) + } + + // Match body + matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`) + } + + // Match headers + matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) + if (matchedMockDispatches.length === 0) { + const headers = typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers + throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`) + } + + return matchedMockDispatches[0] +} + +function addMockDispatch (mockDispatches, key, data, opts) { + const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false, ...opts } + const replyData = typeof data === 'function' ? { callback: data } : { ...data } + const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } + mockDispatches.push(newMockDispatch) + return newMockDispatch +} + +function deleteMockDispatch (mockDispatches, key) { + const index = mockDispatches.findIndex(dispatch => { + if (!dispatch.consumed) { + return false + } + return matchKey(dispatch, key) + }) + if (index !== -1) { + mockDispatches.splice(index, 1) + } +} + +/** + * @param {string} path Path to remove trailing slash from + */ +function removeTrailingSlash (path) { + while (path.endsWith('/')) { + path = path.slice(0, -1) + } + + if (path.length === 0) { + path = '/' + } + + return path +} + +function buildKey (opts) { + const { path, method, body, headers, query } = opts + + return { + path, + method, + body, + headers, + query + } +} + +function generateKeyValues (data) { + const keys = Object.keys(data) + const result = [] + for (let i = 0; i < keys.length; ++i) { + const key = keys[i] + const value = data[key] + const name = Buffer.from(`${key}`) + if (Array.isArray(value)) { + for (let j = 0; j < value.length; ++j) { + result.push(name, Buffer.from(`${value[j]}`)) + } + } else { + result.push(name, Buffer.from(`${value}`)) + } + } + return result +} + +/** + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + * @param {number} statusCode + */ +function getStatusText (statusCode) { + return STATUS_CODES[statusCode] || 'unknown' +} + +async function getResponse (body) { + const buffers = [] + for await (const data of body) { + buffers.push(data) + } + return Buffer.concat(buffers).toString('utf8') +} + +/** + * Mock dispatch function used to simulate undici dispatches + */ +function mockDispatch (opts, handler) { + // Get mock dispatch from built key + const key = buildKey(opts) + const mockDispatch = getMockDispatch(this[kDispatches], key) + + mockDispatch.timesInvoked++ + + // Here's where we resolve a callback if a callback is present for the dispatch data. + if (mockDispatch.data.callback) { + mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } + } + + // Parse mockDispatch data + const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch + const { timesInvoked, times } = mockDispatch + + // If it's used up and not persistent, mark as consumed + mockDispatch.consumed = !persist && timesInvoked >= times + mockDispatch.pending = timesInvoked < times + + // If specified, trigger dispatch error + if (error !== null) { + deleteMockDispatch(this[kDispatches], key) + handler.onError(error) + return true + } + + // Handle the request with a delay if necessary + if (typeof delay === 'number' && delay > 0) { + setTimeout(() => { + handleReply(this[kDispatches]) + }, delay) + } else { + handleReply(this[kDispatches]) + } + + function handleReply (mockDispatches, _data = data) { + // fetch's HeadersList is a 1D string array + const optsHeaders = Array.isArray(opts.headers) + ? buildHeadersFromArray(opts.headers) + : opts.headers + const body = typeof _data === 'function' + ? _data({ ...opts, headers: optsHeaders }) + : _data + + // util.types.isPromise is likely needed for jest. + if (isPromise(body)) { + // If handleReply is asynchronous, throwing an error + // in the callback will reject the promise, rather than + // synchronously throw the error, which breaks some tests. + // Rather, we wait for the callback to resolve if it is a + // promise, and then re-run handleReply with the new body. + return body.then((newData) => handleReply(mockDispatches, newData)) + } + + const responseData = getResponseData(body) + const responseHeaders = generateKeyValues(headers) + const responseTrailers = generateKeyValues(trailers) + + handler.onConnect?.(err => handler.onError(err), null) + handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode)) + handler.onData?.(Buffer.from(responseData)) + handler.onComplete?.(responseTrailers) + deleteMockDispatch(mockDispatches, key) + } + + function resume () {} + + return true +} + +function buildMockDispatch () { + const agent = this[kMockAgent] + const origin = this[kOrigin] + const originalDispatch = this[kOriginalDispatch] + + return function dispatch (opts, handler) { + if (agent.isMockActive) { + try { + mockDispatch.call(this, opts, handler) + } catch (error) { + if (error.code === 'UND_MOCK_ERR_MOCK_NOT_MATCHED') { + const netConnect = agent[kGetNetConnect]() + if (netConnect === false) { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) + } + if (checkNetConnect(netConnect, origin)) { + originalDispatch.call(this, opts, handler) + } else { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) + } + } else { + throw error + } + } + } else { + originalDispatch.call(this, opts, handler) + } + } +} + +function checkNetConnect (netConnect, origin) { + const url = new URL(origin) + if (netConnect === true) { + return true + } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { + return true + } + return false +} + +function normalizeOrigin (origin) { + if (typeof origin !== 'string' && !(origin instanceof URL)) { + return origin + } + + if (origin instanceof URL) { + return origin.origin + } + + return origin.toLowerCase() +} + +function buildAndValidateMockOptions (opts) { + const { agent, ...mockOptions } = opts + + if ('enableCallHistory' in mockOptions && typeof mockOptions.enableCallHistory !== 'boolean') { + throw new InvalidArgumentError('options.enableCallHistory must to be a boolean') + } + + if ('acceptNonStandardSearchParameters' in mockOptions && typeof mockOptions.acceptNonStandardSearchParameters !== 'boolean') { + throw new InvalidArgumentError('options.acceptNonStandardSearchParameters must to be a boolean') + } + + if ('ignoreTrailingSlash' in mockOptions && typeof mockOptions.ignoreTrailingSlash !== 'boolean') { + throw new InvalidArgumentError('options.ignoreTrailingSlash must to be a boolean') + } + + return mockOptions +} + +module.exports = { + getResponseData, + getMockDispatch, + addMockDispatch, + deleteMockDispatch, + buildKey, + generateKeyValues, + matchValue, + getResponse, + getStatusText, + mockDispatch, + buildMockDispatch, + checkNetConnect, + buildAndValidateMockOptions, + getHeaderByName, + buildHeadersFromArray, + normalizeSearchParams, + normalizeOrigin +} diff --git a/node_modules/undici/lib/mock/pending-interceptors-formatter.js b/node_modules/undici/lib/mock/pending-interceptors-formatter.js new file mode 100644 index 000000000..ccca95119 --- /dev/null +++ b/node_modules/undici/lib/mock/pending-interceptors-formatter.js @@ -0,0 +1,43 @@ +'use strict' + +const { Transform } = require('node:stream') +const { Console } = require('node:console') + +const PERSISTENT = process.versions.icu ? '✅' : 'Y ' +const NOT_PERSISTENT = process.versions.icu ? '❌' : 'N ' + +/** + * Gets the output of `console.table(…)` as a string. + */ +module.exports = class PendingInterceptorsFormatter { + constructor ({ disableColors } = {}) { + this.transform = new Transform({ + transform (chunk, _enc, cb) { + cb(null, chunk) + } + }) + + this.logger = new Console({ + stdout: this.transform, + inspectOptions: { + colors: !disableColors && !process.env.CI + } + }) + } + + format (pendingInterceptors) { + const withPrettyHeaders = pendingInterceptors.map( + ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + Method: method, + Origin: origin, + Path: path, + 'Status code': statusCode, + Persistent: persist ? PERSISTENT : NOT_PERSISTENT, + Invocations: timesInvoked, + Remaining: persist ? Infinity : times - timesInvoked + })) + + this.logger.table(withPrettyHeaders) + return this.transform.read().toString() + } +} diff --git a/node_modules/undici/lib/mock/snapshot-agent.js b/node_modules/undici/lib/mock/snapshot-agent.js new file mode 100644 index 000000000..802801119 --- /dev/null +++ b/node_modules/undici/lib/mock/snapshot-agent.js @@ -0,0 +1,353 @@ +'use strict' + +const Agent = require('../dispatcher/agent') +const MockAgent = require('./mock-agent') +const { SnapshotRecorder } = require('./snapshot-recorder') +const WrapHandler = require('../handler/wrap-handler') +const { InvalidArgumentError, UndiciError } = require('../core/errors') +const { validateSnapshotMode } = require('./snapshot-utils') + +const kSnapshotRecorder = Symbol('kSnapshotRecorder') +const kSnapshotMode = Symbol('kSnapshotMode') +const kSnapshotPath = Symbol('kSnapshotPath') +const kSnapshotLoaded = Symbol('kSnapshotLoaded') +const kRealAgent = Symbol('kRealAgent') + +// Static flag to ensure warning is only emitted once per process +let warningEmitted = false + +class SnapshotAgent extends MockAgent { + constructor (opts = {}) { + // Emit experimental warning only once + if (!warningEmitted) { + process.emitWarning( + 'SnapshotAgent is experimental and subject to change', + 'ExperimentalWarning' + ) + warningEmitted = true + } + + const { + mode = 'record', + snapshotPath = null, + ...mockAgentOpts + } = opts + + super(mockAgentOpts) + + validateSnapshotMode(mode) + + // Validate snapshotPath is provided when required + if ((mode === 'playback' || mode === 'update') && !snapshotPath) { + throw new InvalidArgumentError(`snapshotPath is required when mode is '${mode}'`) + } + + this[kSnapshotMode] = mode + this[kSnapshotPath] = snapshotPath + + this[kSnapshotRecorder] = new SnapshotRecorder({ + snapshotPath: this[kSnapshotPath], + mode: this[kSnapshotMode], + maxSnapshots: opts.maxSnapshots, + autoFlush: opts.autoFlush, + flushInterval: opts.flushInterval, + matchHeaders: opts.matchHeaders, + ignoreHeaders: opts.ignoreHeaders, + excludeHeaders: opts.excludeHeaders, + matchBody: opts.matchBody, + matchQuery: opts.matchQuery, + caseSensitive: opts.caseSensitive, + shouldRecord: opts.shouldRecord, + shouldPlayback: opts.shouldPlayback, + excludeUrls: opts.excludeUrls + }) + this[kSnapshotLoaded] = false + + // For recording/update mode, we need a real agent to make actual requests + // For playback mode, we need a real agent if there are excluded URLs + if (this[kSnapshotMode] === 'record' || this[kSnapshotMode] === 'update' || + (this[kSnapshotMode] === 'playback' && opts.excludeUrls && opts.excludeUrls.length > 0)) { + this[kRealAgent] = new Agent(opts) + } + + // Auto-load snapshots in playback/update mode + if ((this[kSnapshotMode] === 'playback' || this[kSnapshotMode] === 'update') && this[kSnapshotPath]) { + this.loadSnapshots().catch(() => { + // Ignore load errors - file might not exist yet + }) + } + } + + dispatch (opts, handler) { + handler = WrapHandler.wrap(handler) + const mode = this[kSnapshotMode] + + // Check if URL should be excluded (pass through without mocking/recording) + if (this[kSnapshotRecorder].isUrlExcluded(opts)) { + // Real agent is guaranteed by constructor when excludeUrls is configured + return this[kRealAgent].dispatch(opts, handler) + } + + if (mode === 'playback' || mode === 'update') { + // Ensure snapshots are loaded + if (!this[kSnapshotLoaded]) { + // Need to load asynchronously, delegate to async version + return this.#asyncDispatch(opts, handler) + } + + // Try to find existing snapshot (synchronous) + const snapshot = this[kSnapshotRecorder].findSnapshot(opts) + + if (snapshot) { + // Use recorded response (synchronous) + return this.#replaySnapshot(snapshot, handler) + } else if (mode === 'update') { + // Make real request and record it (async required) + return this.#recordAndReplay(opts, handler) + } else { + // Playback mode but no snapshot found + const error = new UndiciError(`No snapshot found for ${opts.method || 'GET'} ${opts.path}`) + if (handler.onError) { + handler.onError(error) + return + } + throw error + } + } else if (mode === 'record') { + // Record mode - make real request and save response (async required) + return this.#recordAndReplay(opts, handler) + } + } + + /** + * Async version of dispatch for when we need to load snapshots first + */ + async #asyncDispatch (opts, handler) { + await this.loadSnapshots() + return this.dispatch(opts, handler) + } + + /** + * Records a real request and replays the response + */ + #recordAndReplay (opts, handler) { + const responseData = { + statusCode: null, + headers: {}, + trailers: {}, + body: [] + } + + const self = this // Capture 'this' context for use within nested handler callbacks + + const recordingHandler = { + onRequestStart (controller, context) { + return handler.onRequestStart(controller, { ...context, history: this.history }) + }, + + onRequestUpgrade (controller, statusCode, headers, socket) { + return handler.onRequestUpgrade(controller, statusCode, headers, socket) + }, + + onResponseStart (controller, statusCode, headers, statusMessage) { + responseData.statusCode = statusCode + responseData.headers = headers + return handler.onResponseStart(controller, statusCode, headers, statusMessage) + }, + + onResponseData (controller, chunk) { + responseData.body.push(chunk) + return handler.onResponseData(controller, chunk) + }, + + onResponseEnd (controller, trailers) { + responseData.trailers = trailers + + // Record the interaction using captured 'self' context (fire and forget) + const responseBody = Buffer.concat(responseData.body) + self[kSnapshotRecorder].record(opts, { + statusCode: responseData.statusCode, + headers: responseData.headers, + body: responseBody, + trailers: responseData.trailers + }) + .then(() => handler.onResponseEnd(controller, trailers)) + .catch((error) => handler.onResponseError(controller, error)) + } + } + + // Use composed agent if available (includes interceptors), otherwise use real agent + const agent = this[kRealAgent] + return agent.dispatch(opts, recordingHandler) + } + + /** + * Replays a recorded response + * + * @param {Object} snapshot - The recorded snapshot to replay. + * @param {Object} handler - The handler to call with the response data. + * @returns {void} + */ + #replaySnapshot (snapshot, handler) { + try { + const { response } = snapshot + + const controller = { + pause () { }, + resume () { }, + abort (reason) { + this.aborted = true + this.reason = reason + }, + + aborted: false, + paused: false + } + + handler.onRequestStart(controller) + + handler.onResponseStart(controller, response.statusCode, response.headers) + + // Body is always stored as base64 string + const body = Buffer.from(response.body, 'base64') + handler.onResponseData(controller, body) + + handler.onResponseEnd(controller, response.trailers) + } catch (error) { + handler.onError?.(error) + } + } + + /** + * Loads snapshots from file + * + * @param {string} [filePath] - Optional file path to load snapshots from. + * @returns {Promise} - Resolves when snapshots are loaded. + */ + async loadSnapshots (filePath) { + await this[kSnapshotRecorder].loadSnapshots(filePath || this[kSnapshotPath]) + this[kSnapshotLoaded] = true + + // In playback mode, set up MockAgent interceptors for all snapshots + if (this[kSnapshotMode] === 'playback') { + this.#setupMockInterceptors() + } + } + + /** + * Saves snapshots to file + * + * @param {string} [filePath] - Optional file path to save snapshots to. + * @returns {Promise} - Resolves when snapshots are saved. + */ + async saveSnapshots (filePath) { + return this[kSnapshotRecorder].saveSnapshots(filePath || this[kSnapshotPath]) + } + + /** + * Sets up MockAgent interceptors based on recorded snapshots. + * + * This method creates MockAgent interceptors for each recorded snapshot, + * allowing the SnapshotAgent to fall back to MockAgent's standard intercept + * mechanism in playback mode. Each interceptor is configured to persist + * (remain active for multiple requests) and responds with the recorded + * response data. + * + * Called automatically when loading snapshots in playback mode. + * + * @returns {void} + */ + #setupMockInterceptors () { + for (const snapshot of this[kSnapshotRecorder].getSnapshots()) { + const { request, responses, response } = snapshot + const url = new URL(request.url) + + const mockPool = this.get(url.origin) + + // Handle both new format (responses array) and legacy format (response object) + const responseData = responses ? responses[0] : response + if (!responseData) continue + + mockPool.intercept({ + path: url.pathname + url.search, + method: request.method, + headers: request.headers, + body: request.body + }).reply(responseData.statusCode, responseData.body, { + headers: responseData.headers, + trailers: responseData.trailers + }).persist() + } + } + + /** + * Gets the snapshot recorder + * @return {SnapshotRecorder} - The snapshot recorder instance + */ + getRecorder () { + return this[kSnapshotRecorder] + } + + /** + * Gets the current mode + * @return {import('./snapshot-utils').SnapshotMode} - The current snapshot mode + */ + getMode () { + return this[kSnapshotMode] + } + + /** + * Clears all snapshots + * @returns {void} + */ + clearSnapshots () { + this[kSnapshotRecorder].clear() + } + + /** + * Resets call counts for all snapshots (useful for test cleanup) + * @returns {void} + */ + resetCallCounts () { + this[kSnapshotRecorder].resetCallCounts() + } + + /** + * Deletes a specific snapshot by request options + * @param {import('./snapshot-recorder').SnapshotRequestOptions} requestOpts - Request options to identify the snapshot + * @return {Promise} - Returns true if the snapshot was deleted, false if not found + */ + deleteSnapshot (requestOpts) { + return this[kSnapshotRecorder].deleteSnapshot(requestOpts) + } + + /** + * Gets information about a specific snapshot + * @returns {import('./snapshot-recorder').SnapshotInfo|null} - Snapshot information or null if not found + */ + getSnapshotInfo (requestOpts) { + return this[kSnapshotRecorder].getSnapshotInfo(requestOpts) + } + + /** + * Replaces all snapshots with new data (full replacement) + * @param {Array<{hash: string; snapshot: import('./snapshot-recorder').SnapshotEntryshotEntry}>|Record} snapshotData - New snapshot data to replace existing snapshots + * @returns {void} + */ + replaceSnapshots (snapshotData) { + this[kSnapshotRecorder].replaceSnapshots(snapshotData) + } + + /** + * Closes the agent, saving snapshots and cleaning up resources. + * + * @returns {Promise} + */ + async close () { + await this[kSnapshotRecorder].close() + await this[kRealAgent]?.close() + await super.close() + } +} + +module.exports = SnapshotAgent diff --git a/node_modules/undici/lib/mock/snapshot-recorder.js b/node_modules/undici/lib/mock/snapshot-recorder.js new file mode 100644 index 000000000..b5d07fae3 --- /dev/null +++ b/node_modules/undici/lib/mock/snapshot-recorder.js @@ -0,0 +1,588 @@ +'use strict' + +const { writeFile, readFile, mkdir } = require('node:fs/promises') +const { dirname, resolve } = require('node:path') +const { setTimeout, clearTimeout } = require('node:timers') +const { InvalidArgumentError, UndiciError } = require('../core/errors') +const { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require('./snapshot-utils') + +/** + * @typedef {Object} SnapshotRequestOptions + * @property {string} method - HTTP method (e.g. 'GET', 'POST', etc.) + * @property {string} path - Request path + * @property {string} origin - Request origin (base URL) + * @property {import('./snapshot-utils').Headers|import('./snapshot-utils').UndiciHeaders} headers - Request headers + * @property {import('./snapshot-utils').NormalizedHeaders} _normalizedHeaders - Request headers as a lowercase object + * @property {string|Buffer} [body] - Request body (optional) + */ + +/** + * @typedef {Object} SnapshotEntryRequest + * @property {string} method - HTTP method (e.g. 'GET', 'POST', etc.) + * @property {string} url - Full URL of the request + * @property {import('./snapshot-utils').NormalizedHeaders} headers - Normalized headers as a lowercase object + * @property {string|Buffer} [body] - Request body (optional) + */ + +/** + * @typedef {Object} SnapshotEntryResponse + * @property {number} statusCode - HTTP status code of the response + * @property {import('./snapshot-utils').NormalizedHeaders} headers - Normalized response headers as a lowercase object + * @property {string} body - Response body as a base64url encoded string + * @property {Object} [trailers] - Optional response trailers + */ + +/** + * @typedef {Object} SnapshotEntry + * @property {SnapshotEntryRequest} request - The request object + * @property {Array} responses - Array of response objects + * @property {number} callCount - Number of times this snapshot has been called + * @property {string} timestamp - ISO timestamp of when the snapshot was created + */ + +/** + * @typedef {Object} SnapshotRecorderMatchOptions + * @property {Array} [matchHeaders=[]] - Headers to match (empty array means match all headers) + * @property {Array} [ignoreHeaders=[]] - Headers to ignore for matching + * @property {Array} [excludeHeaders=[]] - Headers to exclude from matching + * @property {boolean} [matchBody=true] - Whether to match request body + * @property {boolean} [matchQuery=true] - Whether to match query properties + * @property {boolean} [caseSensitive=false] - Whether header matching is case-sensitive + */ + +/** + * @typedef {Object} SnapshotRecorderOptions + * @property {string} [snapshotPath] - Path to save/load snapshots + * @property {import('./snapshot-utils').SnapshotMode} [mode='record'] - Mode: 'record' or 'playback' + * @property {number} [maxSnapshots=Infinity] - Maximum number of snapshots to keep + * @property {boolean} [autoFlush=false] - Whether to automatically flush snapshots to disk + * @property {number} [flushInterval=30000] - Auto-flush interval in milliseconds (default: 30 seconds) + * @property {Array} [excludeUrls=[]] - URLs to exclude from recording + * @property {function} [shouldRecord=null] - Function to filter requests for recording + * @property {function} [shouldPlayback=null] - Function to filter requests + */ + +/** + * @typedef {Object} SnapshotFormattedRequest + * @property {string} method - HTTP method (e.g. 'GET', 'POST', etc.) + * @property {string} url - Full URL of the request (with query parameters if matchQuery is true) + * @property {import('./snapshot-utils').NormalizedHeaders} headers - Normalized headers as a lowercase object + * @property {string} body - Request body (optional, only if matchBody is true) + */ + +/** + * @typedef {Object} SnapshotInfo + * @property {string} hash - Hash key for the snapshot + * @property {SnapshotEntryRequest} request - The request object + * @property {number} responseCount - Number of responses recorded for this request + * @property {number} callCount - Number of times this snapshot has been called + * @property {string} timestamp - ISO timestamp of when the snapshot was created + */ + +/** + * Formats a request for consistent snapshot storage + * Caches normalized headers to avoid repeated processing + * + * @param {SnapshotRequestOptions} opts - Request options + * @param {import('./snapshot-utils').HeaderFilters} headerFilters - Cached header sets for performance + * @param {SnapshotRecorderMatchOptions} [matchOptions] - Matching options for headers and body + * @returns {SnapshotFormattedRequest} - Formatted request object + */ +function formatRequestKey (opts, headerFilters, matchOptions = {}) { + const url = new URL(opts.path, opts.origin) + + // Cache normalized headers if not already done + const normalized = opts._normalizedHeaders || normalizeHeaders(opts.headers) + if (!opts._normalizedHeaders) { + opts._normalizedHeaders = normalized + } + + return { + method: opts.method || 'GET', + url: matchOptions.matchQuery !== false ? url.toString() : `${url.origin}${url.pathname}`, + headers: filterHeadersForMatching(normalized, headerFilters, matchOptions), + body: matchOptions.matchBody !== false && opts.body ? String(opts.body) : '' + } +} + +/** + * Filters headers based on matching configuration + * + * @param {import('./snapshot-utils').Headers} headers - Headers to filter + * @param {import('./snapshot-utils').HeaderFilters} headerFilters - Cached sets for ignore, exclude, and match headers + * @param {SnapshotRecorderMatchOptions} [matchOptions] - Matching options for headers + */ +function filterHeadersForMatching (headers, headerFilters, matchOptions = {}) { + if (!headers || typeof headers !== 'object') return {} + + const { + caseSensitive = false + } = matchOptions + + const filtered = {} + const { ignore, exclude, match } = headerFilters + + for (const [key, value] of Object.entries(headers)) { + const headerKey = caseSensitive ? key : key.toLowerCase() + + // Skip if in exclude list (for security) + if (exclude.has(headerKey)) continue + + // Skip if in ignore list (for matching) + if (ignore.has(headerKey)) continue + + // If matchHeaders is specified, only include those headers + if (match.size !== 0) { + if (!match.has(headerKey)) continue + } + + filtered[headerKey] = value + } + + return filtered +} + +/** + * Filters headers for storage (only excludes sensitive headers) + * + * @param {import('./snapshot-utils').Headers} headers - Headers to filter + * @param {import('./snapshot-utils').HeaderFilters} headerFilters - Cached sets for ignore, exclude, and match headers + * @param {SnapshotRecorderMatchOptions} [matchOptions] - Matching options for headers + */ +function filterHeadersForStorage (headers, headerFilters, matchOptions = {}) { + if (!headers || typeof headers !== 'object') return {} + + const { + caseSensitive = false + } = matchOptions + + const filtered = {} + const { exclude: excludeSet } = headerFilters + + for (const [key, value] of Object.entries(headers)) { + const headerKey = caseSensitive ? key : key.toLowerCase() + + // Skip if in exclude list (for security) + if (excludeSet.has(headerKey)) continue + + filtered[headerKey] = value + } + + return filtered +} + +/** + * Creates a hash key for request matching + * Properly orders headers to avoid conflicts and uses crypto hashing when available + * + * @param {SnapshotFormattedRequest} formattedRequest - Request object + * @returns {string} - Base64url encoded hash of the request + */ +function createRequestHash (formattedRequest) { + const parts = [ + formattedRequest.method, + formattedRequest.url + ] + + // Process headers in a deterministic way to avoid conflicts + if (formattedRequest.headers && typeof formattedRequest.headers === 'object') { + const headerKeys = Object.keys(formattedRequest.headers).sort() + for (const key of headerKeys) { + const values = Array.isArray(formattedRequest.headers[key]) + ? formattedRequest.headers[key] + : [formattedRequest.headers[key]] + + // Add header name + parts.push(key) + + // Add all values for this header, sorted for consistency + for (const value of values.sort()) { + parts.push(String(value)) + } + } + } + + // Add body + parts.push(formattedRequest.body) + + const content = parts.join('|') + + return hashId(content) +} + +class SnapshotRecorder { + /** @type {NodeJS.Timeout | null} */ + #flushTimeout + + /** @type {import('./snapshot-utils').IsUrlExcluded} */ + #isUrlExcluded + + /** @type {Map} */ + #snapshots = new Map() + + /** @type {string|undefined} */ + #snapshotPath + + /** @type {number} */ + #maxSnapshots = Infinity + + /** @type {boolean} */ + #autoFlush = false + + /** @type {import('./snapshot-utils').HeaderFilters} */ + #headerFilters + + /** + * Creates a new SnapshotRecorder instance + * @param {SnapshotRecorderOptions&SnapshotRecorderMatchOptions} [options={}] - Configuration options for the recorder + */ + constructor (options = {}) { + this.#snapshotPath = options.snapshotPath + this.#maxSnapshots = options.maxSnapshots || Infinity + this.#autoFlush = options.autoFlush || false + this.flushInterval = options.flushInterval || 30000 // 30 seconds default + this._flushTimer = null + + // Matching configuration + /** @type {Required} */ + this.matchOptions = { + matchHeaders: options.matchHeaders || [], // empty means match all headers + ignoreHeaders: options.ignoreHeaders || [], + excludeHeaders: options.excludeHeaders || [], + matchBody: options.matchBody !== false, // default: true + matchQuery: options.matchQuery !== false, // default: true + caseSensitive: options.caseSensitive || false + } + + // Cache processed header sets to avoid recreating them on every request + this.#headerFilters = createHeaderFilters(this.matchOptions) + + // Request filtering callbacks + this.shouldRecord = options.shouldRecord || (() => true) // function(requestOpts) -> boolean + this.shouldPlayback = options.shouldPlayback || (() => true) // function(requestOpts) -> boolean + + // URL pattern filtering + this.#isUrlExcluded = isUrlExcludedFactory(options.excludeUrls) // Array of regex patterns or strings + + // Start auto-flush timer if enabled + if (this.#autoFlush && this.#snapshotPath) { + this.#startAutoFlush() + } + } + + /** + * Records a request-response interaction + * @param {SnapshotRequestOptions} requestOpts - Request options + * @param {SnapshotEntryResponse} response - Response data to record + * @return {Promise} - Resolves when the recording is complete + */ + async record (requestOpts, response) { + // Check if recording should be filtered out + if (!this.shouldRecord(requestOpts)) { + return // Skip recording + } + + // Check URL exclusion patterns + if (this.isUrlExcluded(requestOpts)) { + return // Skip recording + } + + const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions) + const hash = createRequestHash(request) + + // Extract response data - always store body as base64 + const normalizedHeaders = normalizeHeaders(response.headers) + + /** @type {SnapshotEntryResponse} */ + const responseData = { + statusCode: response.statusCode, + headers: filterHeadersForStorage(normalizedHeaders, this.#headerFilters, this.matchOptions), + body: Buffer.isBuffer(response.body) + ? response.body.toString('base64') + : Buffer.from(String(response.body || '')).toString('base64'), + trailers: response.trailers + } + + // Remove oldest snapshot if we exceed maxSnapshots limit + if (this.#snapshots.size >= this.#maxSnapshots && !this.#snapshots.has(hash)) { + const oldestKey = this.#snapshots.keys().next().value + this.#snapshots.delete(oldestKey) + } + + // Support sequential responses - if snapshot exists, add to responses array + const existingSnapshot = this.#snapshots.get(hash) + if (existingSnapshot && existingSnapshot.responses) { + existingSnapshot.responses.push(responseData) + existingSnapshot.timestamp = new Date().toISOString() + } else { + this.#snapshots.set(hash, { + request, + responses: [responseData], // Always store as array for consistency + callCount: 0, + timestamp: new Date().toISOString() + }) + } + + // Auto-flush if enabled + if (this.#autoFlush && this.#snapshotPath) { + this.#scheduleFlush() + } + } + + /** + * Checks if a URL should be excluded from recording/playback + * @param {SnapshotRequestOptions} requestOpts - Request options to check + * @returns {boolean} - True if URL is excluded + */ + isUrlExcluded (requestOpts) { + const url = new URL(requestOpts.path, requestOpts.origin).toString() + return this.#isUrlExcluded(url) + } + + /** + * Finds a matching snapshot for the given request + * Returns the appropriate response based on call count for sequential responses + * + * @param {SnapshotRequestOptions} requestOpts - Request options to match + * @returns {SnapshotEntry&Record<'response', SnapshotEntryResponse>|undefined} - Matching snapshot response or undefined if not found + */ + findSnapshot (requestOpts) { + // Check if playback should be filtered out + if (!this.shouldPlayback(requestOpts)) { + return undefined // Skip playback + } + + // Check URL exclusion patterns + if (this.isUrlExcluded(requestOpts)) { + return undefined // Skip playback + } + + const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions) + const hash = createRequestHash(request) + const snapshot = this.#snapshots.get(hash) + + if (!snapshot) return undefined + + // Handle sequential responses + const currentCallCount = snapshot.callCount || 0 + const responseIndex = Math.min(currentCallCount, snapshot.responses.length - 1) + snapshot.callCount = currentCallCount + 1 + + return { + ...snapshot, + response: snapshot.responses[responseIndex] + } + } + + /** + * Loads snapshots from file + * @param {string} [filePath] - Optional file path to load snapshots from + * @return {Promise} - Resolves when snapshots are loaded + */ + async loadSnapshots (filePath) { + const path = filePath || this.#snapshotPath + if (!path) { + throw new InvalidArgumentError('Snapshot path is required') + } + + try { + const data = await readFile(resolve(path), 'utf8') + const parsed = JSON.parse(data) + + // Convert array format back to Map + if (Array.isArray(parsed)) { + this.#snapshots.clear() + for (const { hash, snapshot } of parsed) { + this.#snapshots.set(hash, snapshot) + } + } else { + // Legacy object format + this.#snapshots = new Map(Object.entries(parsed)) + } + } catch (error) { + if (error.code === 'ENOENT') { + // File doesn't exist yet - that's ok for recording mode + this.#snapshots.clear() + } else { + throw new UndiciError(`Failed to load snapshots from ${path}`, { cause: error }) + } + } + } + + /** + * Saves snapshots to file + * + * @param {string} [filePath] - Optional file path to save snapshots + * @returns {Promise} - Resolves when snapshots are saved + */ + async saveSnapshots (filePath) { + const path = filePath || this.#snapshotPath + if (!path) { + throw new InvalidArgumentError('Snapshot path is required') + } + + const resolvedPath = resolve(path) + + // Ensure directory exists + await mkdir(dirname(resolvedPath), { recursive: true }) + + // Convert Map to serializable format + const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({ + hash, + snapshot + })) + + await writeFile(resolvedPath, JSON.stringify(data, null, 2), { flush: true }) + } + + /** + * Clears all recorded snapshots + * @returns {void} + */ + clear () { + this.#snapshots.clear() + } + + /** + * Gets all recorded snapshots + * @return {Array} - Array of all recorded snapshots + */ + getSnapshots () { + return Array.from(this.#snapshots.values()) + } + + /** + * Gets snapshot count + * @return {number} - Number of recorded snapshots + */ + size () { + return this.#snapshots.size + } + + /** + * Resets call counts for all snapshots (useful for test cleanup) + * @returns {void} + */ + resetCallCounts () { + for (const snapshot of this.#snapshots.values()) { + snapshot.callCount = 0 + } + } + + /** + * Deletes a specific snapshot by request options + * @param {SnapshotRequestOptions} requestOpts - Request options to match + * @returns {boolean} - True if snapshot was deleted, false if not found + */ + deleteSnapshot (requestOpts) { + const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions) + const hash = createRequestHash(request) + return this.#snapshots.delete(hash) + } + + /** + * Gets information about a specific snapshot + * @param {SnapshotRequestOptions} requestOpts - Request options to match + * @returns {SnapshotInfo|null} - Snapshot information or null if not found + */ + getSnapshotInfo (requestOpts) { + const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions) + const hash = createRequestHash(request) + const snapshot = this.#snapshots.get(hash) + + if (!snapshot) return null + + return { + hash, + request: snapshot.request, + responseCount: snapshot.responses ? snapshot.responses.length : (snapshot.response ? 1 : 0), // .response for legacy snapshots + callCount: snapshot.callCount || 0, + timestamp: snapshot.timestamp + } + } + + /** + * Replaces all snapshots with new data (full replacement) + * @param {Array<{hash: string; snapshot: SnapshotEntry}>|Record} snapshotData - New snapshot data to replace existing ones + * @returns {void} + */ + replaceSnapshots (snapshotData) { + this.#snapshots.clear() + + if (Array.isArray(snapshotData)) { + for (const { hash, snapshot } of snapshotData) { + this.#snapshots.set(hash, snapshot) + } + } else if (snapshotData && typeof snapshotData === 'object') { + // Legacy object format + this.#snapshots = new Map(Object.entries(snapshotData)) + } + } + + /** + * Starts the auto-flush timer + * @returns {void} + */ + #startAutoFlush () { + return this.#scheduleFlush() + } + + /** + * Stops the auto-flush timer + * @returns {void} + */ + #stopAutoFlush () { + if (this.#flushTimeout) { + clearTimeout(this.#flushTimeout) + // Ensure any pending flush is completed + this.saveSnapshots().catch(() => { + // Ignore flush errors + }) + this.#flushTimeout = null + } + } + + /** + * Schedules a flush (debounced to avoid excessive writes) + */ + #scheduleFlush () { + this.#flushTimeout = setTimeout(() => { + this.saveSnapshots().catch(() => { + // Ignore flush errors + }) + if (this.#autoFlush) { + this.#flushTimeout?.refresh() + } else { + this.#flushTimeout = null + } + }, 1000) // 1 second debounce + } + + /** + * Cleanup method to stop timers + * @returns {void} + */ + destroy () { + this.#stopAutoFlush() + if (this.#flushTimeout) { + clearTimeout(this.#flushTimeout) + this.#flushTimeout = null + } + } + + /** + * Async close method that saves all recordings and performs cleanup + * @returns {Promise} + */ + async close () { + // Save any pending recordings if we have a snapshot path + if (this.#snapshotPath && this.#snapshots.size !== 0) { + await this.saveSnapshots() + } + + // Perform cleanup + this.destroy() + } +} + +module.exports = { SnapshotRecorder, formatRequestKey, createRequestHash, filterHeadersForMatching, filterHeadersForStorage, createHeaderFilters } diff --git a/node_modules/undici/lib/mock/snapshot-utils.js b/node_modules/undici/lib/mock/snapshot-utils.js new file mode 100644 index 000000000..a14b69c15 --- /dev/null +++ b/node_modules/undici/lib/mock/snapshot-utils.js @@ -0,0 +1,158 @@ +'use strict' + +const { InvalidArgumentError } = require('../core/errors') +const { runtimeFeatures } = require('../util/runtime-features.js') + +/** + * @typedef {Object} HeaderFilters + * @property {Set} ignore - Set of headers to ignore for matching + * @property {Set} exclude - Set of headers to exclude from matching + * @property {Set} match - Set of headers to match (empty means match + */ + +/** + * Creates cached header sets for performance + * + * @param {import('./snapshot-recorder').SnapshotRecorderMatchOptions} matchOptions - Matching options for headers + * @returns {HeaderFilters} - Cached sets for ignore, exclude, and match headers + */ +function createHeaderFilters (matchOptions = {}) { + const { ignoreHeaders = [], excludeHeaders = [], matchHeaders = [], caseSensitive = false } = matchOptions + + return { + ignore: new Set(ignoreHeaders.map(header => caseSensitive ? header : header.toLowerCase())), + exclude: new Set(excludeHeaders.map(header => caseSensitive ? header : header.toLowerCase())), + match: new Set(matchHeaders.map(header => caseSensitive ? header : header.toLowerCase())) + } +} + +const crypto = runtimeFeatures.has('crypto') + ? require('node:crypto') + : null + +/** + * @callback HashIdFunction + * @param {string} value - The value to hash + * @returns {string} - The base64url encoded hash of the value + */ + +/** + * Generates a hash for a given value + * @type {HashIdFunction} + */ +const hashId = crypto?.hash + ? (value) => crypto.hash('sha256', value, 'base64url') + : (value) => Buffer.from(value).toString('base64url') + +/** + * @typedef {(url: string) => boolean} IsUrlExcluded Checks if a URL matches any of the exclude patterns + */ + +/** @typedef {{[key: Lowercase]: string}} NormalizedHeaders */ +/** @typedef {Array} UndiciHeaders */ +/** @typedef {Record} Headers */ + +/** + * @param {*} headers + * @returns {headers is UndiciHeaders} + */ +function isUndiciHeaders (headers) { + return Array.isArray(headers) && (headers.length & 1) === 0 +} + +/** + * Factory function to create a URL exclusion checker + * @param {Array} [excludePatterns=[]] - Array of patterns to exclude + * @returns {IsUrlExcluded} - A function that checks if a URL matches any of the exclude patterns + */ +function isUrlExcludedFactory (excludePatterns = []) { + if (excludePatterns.length === 0) { + return () => false + } + + return function isUrlExcluded (url) { + let urlLowerCased + + for (const pattern of excludePatterns) { + if (typeof pattern === 'string') { + if (!urlLowerCased) { + // Convert URL to lowercase only once + urlLowerCased = url.toLowerCase() + } + // Simple string match (case-insensitive) + if (urlLowerCased.includes(pattern.toLowerCase())) { + return true + } + } else if (pattern instanceof RegExp) { + // Regex pattern match + if (pattern.test(url)) { + return true + } + } + } + + return false + } +} + +/** + * Normalizes headers for consistent comparison + * + * @param {Object|UndiciHeaders} headers - Headers to normalize + * @returns {NormalizedHeaders} - Normalized headers as a lowercase object + */ +function normalizeHeaders (headers) { + /** @type {NormalizedHeaders} */ + const normalizedHeaders = {} + + if (!headers) return normalizedHeaders + + // Handle array format (undici internal format: [name, value, name, value, ...]) + if (isUndiciHeaders(headers)) { + for (let i = 0; i < headers.length; i += 2) { + const key = headers[i] + const value = headers[i + 1] + if (key && value !== undefined) { + // Convert Buffers to strings if needed + const keyStr = Buffer.isBuffer(key) ? key.toString() : key + const valueStr = Buffer.isBuffer(value) ? value.toString() : value + normalizedHeaders[keyStr.toLowerCase()] = valueStr + } + } + return normalizedHeaders + } + + // Handle object format + if (headers && typeof headers === 'object') { + for (const [key, value] of Object.entries(headers)) { + if (key && typeof key === 'string') { + normalizedHeaders[key.toLowerCase()] = Array.isArray(value) ? value.join(', ') : String(value) + } + } + } + + return normalizedHeaders +} + +const validSnapshotModes = /** @type {const} */ (['record', 'playback', 'update']) + +/** @typedef {typeof validSnapshotModes[number]} SnapshotMode */ + +/** + * @param {*} mode - The snapshot mode to validate + * @returns {asserts mode is SnapshotMode} + */ +function validateSnapshotMode (mode) { + if (!validSnapshotModes.includes(mode)) { + throw new InvalidArgumentError(`Invalid snapshot mode: ${mode}. Must be one of: ${validSnapshotModes.join(', ')}`) + } +} + +module.exports = { + createHeaderFilters, + hashId, + isUndiciHeaders, + normalizeHeaders, + isUrlExcludedFactory, + validateSnapshotMode +} diff --git a/node_modules/undici/lib/util/cache.js b/node_modules/undici/lib/util/cache.js new file mode 100644 index 000000000..b7627d05e --- /dev/null +++ b/node_modules/undici/lib/util/cache.js @@ -0,0 +1,405 @@ +'use strict' + +const { + safeHTTPMethods, + pathHasQueryOrFragment +} = require('../core/util') + +const { serializePathWithQuery } = require('../core/util') + +/** + * @param {import('../../types/dispatcher.d.ts').default.DispatchOptions} opts + */ +function makeCacheKey (opts) { + if (!opts.origin) { + throw new Error('opts.origin is undefined') + } + + let fullPath = opts.path || '/' + + if (opts.query && !pathHasQueryOrFragment(opts.path)) { + fullPath = serializePathWithQuery(fullPath, opts.query) + } + + return { + origin: opts.origin.toString(), + method: opts.method, + path: fullPath, + headers: opts.headers + } +} + +/** + * @param {Record} + * @returns {Record} + */ +function normalizeHeaders (opts) { + let headers + if (opts.headers == null) { + headers = {} + } else if (typeof opts.headers[Symbol.iterator] === 'function') { + headers = {} + for (const x of opts.headers) { + if (!Array.isArray(x)) { + throw new Error('opts.headers is not a valid header map') + } + const [key, val] = x + if (typeof key !== 'string' || typeof val !== 'string') { + throw new Error('opts.headers is not a valid header map') + } + headers[key.toLowerCase()] = val + } + } else if (typeof opts.headers === 'object') { + headers = {} + + for (const key of Object.keys(opts.headers)) { + headers[key.toLowerCase()] = opts.headers[key] + } + } else { + throw new Error('opts.headers is not an object') + } + + return headers +} + +/** + * @param {any} key + */ +function assertCacheKey (key) { + if (typeof key !== 'object') { + throw new TypeError(`expected key to be object, got ${typeof key}`) + } + + for (const property of ['origin', 'method', 'path']) { + if (typeof key[property] !== 'string') { + throw new TypeError(`expected key.${property} to be string, got ${typeof key[property]}`) + } + } + + if (key.headers !== undefined && typeof key.headers !== 'object') { + throw new TypeError(`expected headers to be object, got ${typeof key}`) + } +} + +/** + * @param {any} value + */ +function assertCacheValue (value) { + if (typeof value !== 'object') { + throw new TypeError(`expected value to be object, got ${typeof value}`) + } + + for (const property of ['statusCode', 'cachedAt', 'staleAt', 'deleteAt']) { + if (typeof value[property] !== 'number') { + throw new TypeError(`expected value.${property} to be number, got ${typeof value[property]}`) + } + } + + if (typeof value.statusMessage !== 'string') { + throw new TypeError(`expected value.statusMessage to be string, got ${typeof value.statusMessage}`) + } + + if (value.headers != null && typeof value.headers !== 'object') { + throw new TypeError(`expected value.rawHeaders to be object, got ${typeof value.headers}`) + } + + if (value.vary !== undefined && typeof value.vary !== 'object') { + throw new TypeError(`expected value.vary to be object, got ${typeof value.vary}`) + } + + if (value.etag !== undefined && typeof value.etag !== 'string') { + throw new TypeError(`expected value.etag to be string, got ${typeof value.etag}`) + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-cache-control + * @see https://www.iana.org/assignments/http-cache-directives/http-cache-directives.xhtml + + * @param {string | string[]} header + * @returns {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} + */ +function parseCacheControlHeader (header) { + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} + */ + const output = {} + + let directives + if (Array.isArray(header)) { + directives = [] + + for (const directive of header) { + directives.push(...directive.split(',')) + } + } else { + directives = header.split(',') + } + + for (let i = 0; i < directives.length; i++) { + const directive = directives[i].toLowerCase() + const keyValueDelimiter = directive.indexOf('=') + + let key + let value + if (keyValueDelimiter !== -1) { + key = directive.substring(0, keyValueDelimiter).trimStart() + value = directive.substring(keyValueDelimiter + 1) + } else { + key = directive.trim() + } + + switch (key) { + case 'min-fresh': + case 'max-stale': + case 'max-age': + case 's-maxage': + case 'stale-while-revalidate': + case 'stale-if-error': { + if (value === undefined || value[0] === ' ') { + continue + } + + if ( + value.length >= 2 && + value[0] === '"' && + value[value.length - 1] === '"' + ) { + value = value.substring(1, value.length - 1) + } + + const parsedValue = parseInt(value, 10) + // eslint-disable-next-line no-self-compare + if (parsedValue !== parsedValue) { + continue + } + + if (key === 'max-age' && key in output && output[key] >= parsedValue) { + continue + } + + output[key] = parsedValue + + break + } + case 'private': + case 'no-cache': { + if (value) { + // The private and no-cache directives can be unqualified (aka just + // `private` or `no-cache`) or qualified (w/ a value). When they're + // qualified, it's a list of headers like `no-cache=header1`, + // `no-cache="header1"`, or `no-cache="header1, header2"` + // If we're given multiple headers, the comma messes us up since + // we split the full header by commas. So, let's loop through the + // remaining parts in front of us until we find one that ends in a + // quote. We can then just splice all of the parts in between the + // starting quote and the ending quote out of the directives array + // and continue parsing like normal. + // https://www.rfc-editor.org/rfc/rfc9111.html#name-no-cache-2 + if (value[0] === '"') { + // Something like `no-cache="some-header"` OR `no-cache="some-header, another-header"`. + + // Add the first header on and cut off the leading quote + const headers = [value.substring(1)] + + let foundEndingQuote = value[value.length - 1] === '"' + if (!foundEndingQuote) { + // Something like `no-cache="some-header, another-header"` + // This can still be something invalid, e.g. `no-cache="some-header, ...` + for (let j = i + 1; j < directives.length; j++) { + const nextPart = directives[j] + const nextPartLength = nextPart.length + + headers.push(nextPart.trim()) + + if (nextPartLength !== 0 && nextPart[nextPartLength - 1] === '"') { + foundEndingQuote = true + break + } + } + } + + if (foundEndingQuote) { + let lastHeader = headers[headers.length - 1] + if (lastHeader[lastHeader.length - 1] === '"') { + lastHeader = lastHeader.substring(0, lastHeader.length - 1) + headers[headers.length - 1] = lastHeader + } + + if (key in output) { + output[key] = output[key].concat(headers) + } else { + output[key] = headers + } + } + } else { + // Something like `no-cache="some-header"` + if (key in output) { + output[key] = output[key].concat(value) + } else { + output[key] = [value] + } + } + + break + } + } + // eslint-disable-next-line no-fallthrough + case 'public': + case 'no-store': + case 'must-revalidate': + case 'proxy-revalidate': + case 'immutable': + case 'no-transform': + case 'must-understand': + case 'only-if-cached': + if (value) { + // These are qualified (something like `public=...`) when they aren't + // allowed to be, skip + continue + } + + output[key] = true + break + default: + // Ignore unknown directives as per https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.3-1 + continue + } + } + + return output +} + +/** + * @param {string | string[]} varyHeader Vary header from the server + * @param {Record} headers Request headers + * @returns {Record} + */ +function parseVaryHeader (varyHeader, headers) { + if (typeof varyHeader === 'string' && varyHeader.includes('*')) { + return headers + } + + const output = /** @type {Record} */ ({}) + + const varyingHeaders = typeof varyHeader === 'string' + ? varyHeader.split(',') + : varyHeader + + for (const header of varyingHeaders) { + const trimmedHeader = header.trim().toLowerCase() + + output[trimmedHeader] = headers[trimmedHeader] ?? null + } + + return output +} + +/** + * Note: this deviates from the spec a little. Empty etags ("", W/"") are valid, + * however, including them in cached resposnes serves little to no purpose. + * + * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-etag + * + * @param {string} etag + * @returns {boolean} + */ +function isEtagUsable (etag) { + if (etag.length <= 2) { + // Shortest an etag can be is two chars (just ""). This is where we deviate + // from the spec requiring a min of 3 chars however + return false + } + + if (etag[0] === '"' && etag[etag.length - 1] === '"') { + // ETag: ""asd123"" or ETag: "W/"asd123"", kinda undefined behavior in the + // spec. Some servers will accept these while others don't. + // ETag: "asd123" + return !(etag[1] === '"' || etag.startsWith('"W/')) + } + + if (etag.startsWith('W/"') && etag[etag.length - 1] === '"') { + // ETag: W/"", also where we deviate from the spec & require a min of 3 + // chars + // ETag: for W/"", W/"asd123" + return etag.length !== 4 + } + + // Anything else + return false +} + +/** + * @param {unknown} store + * @returns {asserts store is import('../../types/cache-interceptor.d.ts').default.CacheStore} + */ +function assertCacheStore (store, name = 'CacheStore') { + if (typeof store !== 'object' || store === null) { + throw new TypeError(`expected type of ${name} to be a CacheStore, got ${store === null ? 'null' : typeof store}`) + } + + for (const fn of ['get', 'createWriteStream', 'delete']) { + if (typeof store[fn] !== 'function') { + throw new TypeError(`${name} needs to have a \`${fn}()\` function`) + } + } +} +/** + * @param {unknown} methods + * @returns {asserts methods is import('../../types/cache-interceptor.d.ts').default.CacheMethods[]} + */ +function assertCacheMethods (methods, name = 'CacheMethods') { + if (!Array.isArray(methods)) { + throw new TypeError(`expected type of ${name} needs to be an array, got ${methods === null ? 'null' : typeof methods}`) + } + + if (methods.length === 0) { + throw new TypeError(`${name} needs to have at least one method`) + } + + for (const method of methods) { + if (!safeHTTPMethods.includes(method)) { + throw new TypeError(`element of ${name}-array needs to be one of following values: ${safeHTTPMethods.join(', ')}, got ${method}`) + } + } +} + +/** + * Creates a string key for request deduplication purposes. + * This key is used to identify in-flight requests that can be shared. + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey + * @param {Set} [excludeHeaders] Set of lowercase header names to exclude from the key + * @returns {string} + */ +function makeDeduplicationKey (cacheKey, excludeHeaders) { + // Create a deterministic string key from the cache key + // Include origin, method, path, and sorted headers + let key = `${cacheKey.origin}:${cacheKey.method}:${cacheKey.path}` + + if (cacheKey.headers) { + const sortedHeaders = Object.keys(cacheKey.headers).sort() + for (const header of sortedHeaders) { + // Skip excluded headers + if (excludeHeaders?.has(header.toLowerCase())) { + continue + } + const value = cacheKey.headers[header] + key += `:${header}=${Array.isArray(value) ? value.join(',') : value}` + } + } + + return key +} + +module.exports = { + makeCacheKey, + normalizeHeaders, + assertCacheKey, + assertCacheValue, + parseCacheControlHeader, + parseVaryHeader, + isEtagUsable, + assertCacheMethods, + assertCacheStore, + makeDeduplicationKey +} diff --git a/node_modules/undici/lib/util/date.js b/node_modules/undici/lib/util/date.js new file mode 100644 index 000000000..99dd150ab --- /dev/null +++ b/node_modules/undici/lib/util/date.js @@ -0,0 +1,653 @@ +'use strict' + +/** + * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-date-time-formats + * + * @param {string} date + * @returns {Date | undefined} + */ +function parseHttpDate (date) { + // Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate + // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format + // Sunday, 06-Nov-94 08:49:37 GMT ; obsolete RFC 850 format + + switch (date[3]) { + case ',': return parseImfDate(date) + case ' ': return parseAscTimeDate(date) + default: return parseRfc850Date(date) + } +} + +/** + * @see https://httpwg.org/specs/rfc9110.html#preferred.date.format + * + * @param {string} date + * @returns {Date | undefined} + */ +function parseImfDate (date) { + if ( + date.length !== 29 || + date[4] !== ' ' || + date[7] !== ' ' || + date[11] !== ' ' || + date[16] !== ' ' || + date[19] !== ':' || + date[22] !== ':' || + date[25] !== ' ' || + date[26] !== 'G' || + date[27] !== 'M' || + date[28] !== 'T' + ) { + return undefined + } + + let weekday = -1 + if (date[0] === 'S' && date[1] === 'u' && date[2] === 'n') { // Sunday + weekday = 0 + } else if (date[0] === 'M' && date[1] === 'o' && date[2] === 'n') { // Monday + weekday = 1 + } else if (date[0] === 'T' && date[1] === 'u' && date[2] === 'e') { // Tuesday + weekday = 2 + } else if (date[0] === 'W' && date[1] === 'e' && date[2] === 'd') { // Wednesday + weekday = 3 + } else if (date[0] === 'T' && date[1] === 'h' && date[2] === 'u') { // Thursday + weekday = 4 + } else if (date[0] === 'F' && date[1] === 'r' && date[2] === 'i') { // Friday + weekday = 5 + } else if (date[0] === 'S' && date[1] === 'a' && date[2] === 't') { // Saturday + weekday = 6 + } else { + return undefined // Not a valid day of the week + } + + let day = 0 + if (date[5] === '0') { + // Single digit day, e.g. "Sun Nov 6 08:49:37 1994" + const code = date.charCodeAt(6) + if (code < 49 || code > 57) { + return undefined // Not a digit + } + day = code - 48 // Convert ASCII code to number + } else { + const code1 = date.charCodeAt(5) + if (code1 < 49 || code1 > 51) { + return undefined // Not a digit between 1 and 3 + } + const code2 = date.charCodeAt(6) + if (code2 < 48 || code2 > 57) { + return undefined // Not a digit + } + day = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number + } + + let monthIdx = -1 + if ( + (date[8] === 'J' && date[9] === 'a' && date[10] === 'n') + ) { + monthIdx = 0 // Jan + } else if ( + (date[8] === 'F' && date[9] === 'e' && date[10] === 'b') + ) { + monthIdx = 1 // Feb + } else if ( + (date[8] === 'M' && date[9] === 'a') + ) { + if (date[10] === 'r') { + monthIdx = 2 // Mar + } else if (date[10] === 'y') { + monthIdx = 4 // May + } else { + return undefined // Invalid month + } + } else if ( + (date[8] === 'J') + ) { + if (date[9] === 'a' && date[10] === 'n') { + monthIdx = 0 // Jan + } else if (date[9] === 'u') { + if (date[10] === 'n') { + monthIdx = 5 // Jun + } else if (date[10] === 'l') { + monthIdx = 6 // Jul + } else { + return undefined // Invalid month + } + } else { + return undefined // Invalid month + } + } else if ( + (date[8] === 'A') + ) { + if (date[9] === 'p' && date[10] === 'r') { + monthIdx = 3 // Apr + } else if (date[9] === 'u' && date[10] === 'g') { + monthIdx = 7 // Aug + } else { + return undefined // Invalid month + } + } else if ( + (date[8] === 'S' && date[9] === 'e' && date[10] === 'p') + ) { + monthIdx = 8 // Sep + } else if ( + (date[8] === 'O' && date[9] === 'c' && date[10] === 't') + ) { + monthIdx = 9 // Oct + } else if ( + (date[8] === 'N' && date[9] === 'o' && date[10] === 'v') + ) { + monthIdx = 10 // Nov + } else if ( + (date[8] === 'D' && date[9] === 'e' && date[10] === 'c') + ) { + monthIdx = 11 // Dec + } else { + // Not a valid month + return undefined + } + + const yearDigit1 = date.charCodeAt(12) + if (yearDigit1 < 48 || yearDigit1 > 57) { + return undefined // Not a digit + } + const yearDigit2 = date.charCodeAt(13) + if (yearDigit2 < 48 || yearDigit2 > 57) { + return undefined // Not a digit + } + const yearDigit3 = date.charCodeAt(14) + if (yearDigit3 < 48 || yearDigit3 > 57) { + return undefined // Not a digit + } + const yearDigit4 = date.charCodeAt(15) + if (yearDigit4 < 48 || yearDigit4 > 57) { + return undefined // Not a digit + } + const year = (yearDigit1 - 48) * 1000 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48) + + let hour = 0 + if (date[17] === '0') { + const code = date.charCodeAt(18) + if (code < 48 || code > 57) { + return undefined // Not a digit + } + hour = code - 48 // Convert ASCII code to number + } else { + const code1 = date.charCodeAt(17) + if (code1 < 48 || code1 > 50) { + return undefined // Not a digit between 0 and 2 + } + const code2 = date.charCodeAt(18) + if (code2 < 48 || code2 > 57) { + return undefined // Not a digit + } + if (code1 === 50 && code2 > 51) { + return undefined // Hour cannot be greater than 23 + } + hour = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number + } + + let minute = 0 + if (date[20] === '0') { + const code = date.charCodeAt(21) + if (code < 48 || code > 57) { + return undefined // Not a digit + } + minute = code - 48 // Convert ASCII code to number + } else { + const code1 = date.charCodeAt(20) + if (code1 < 48 || code1 > 53) { + return undefined // Not a digit between 0 and 5 + } + const code2 = date.charCodeAt(21) + if (code2 < 48 || code2 > 57) { + return undefined // Not a digit + } + minute = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number + } + + let second = 0 + if (date[23] === '0') { + const code = date.charCodeAt(24) + if (code < 48 || code > 57) { + return undefined // Not a digit + } + second = code - 48 // Convert ASCII code to number + } else { + const code1 = date.charCodeAt(23) + if (code1 < 48 || code1 > 53) { + return undefined // Not a digit between 0 and 5 + } + const code2 = date.charCodeAt(24) + if (code2 < 48 || code2 > 57) { + return undefined // Not a digit + } + second = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number + } + + const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second)) + return result.getUTCDay() === weekday ? result : undefined +} + +/** + * @see https://httpwg.org/specs/rfc9110.html#obsolete.date.formats + * + * @param {string} date + * @returns {Date | undefined} + */ +function parseAscTimeDate (date) { + // This is assumed to be in UTC + + if ( + date.length !== 24 || + date[7] !== ' ' || + date[10] !== ' ' || + date[19] !== ' ' + ) { + return undefined + } + + let weekday = -1 + if (date[0] === 'S' && date[1] === 'u' && date[2] === 'n') { // Sunday + weekday = 0 + } else if (date[0] === 'M' && date[1] === 'o' && date[2] === 'n') { // Monday + weekday = 1 + } else if (date[0] === 'T' && date[1] === 'u' && date[2] === 'e') { // Tuesday + weekday = 2 + } else if (date[0] === 'W' && date[1] === 'e' && date[2] === 'd') { // Wednesday + weekday = 3 + } else if (date[0] === 'T' && date[1] === 'h' && date[2] === 'u') { // Thursday + weekday = 4 + } else if (date[0] === 'F' && date[1] === 'r' && date[2] === 'i') { // Friday + weekday = 5 + } else if (date[0] === 'S' && date[1] === 'a' && date[2] === 't') { // Saturday + weekday = 6 + } else { + return undefined // Not a valid day of the week + } + + let monthIdx = -1 + if ( + (date[4] === 'J' && date[5] === 'a' && date[6] === 'n') + ) { + monthIdx = 0 // Jan + } else if ( + (date[4] === 'F' && date[5] === 'e' && date[6] === 'b') + ) { + monthIdx = 1 // Feb + } else if ( + (date[4] === 'M' && date[5] === 'a') + ) { + if (date[6] === 'r') { + monthIdx = 2 // Mar + } else if (date[6] === 'y') { + monthIdx = 4 // May + } else { + return undefined // Invalid month + } + } else if ( + (date[4] === 'J') + ) { + if (date[5] === 'a' && date[6] === 'n') { + monthIdx = 0 // Jan + } else if (date[5] === 'u') { + if (date[6] === 'n') { + monthIdx = 5 // Jun + } else if (date[6] === 'l') { + monthIdx = 6 // Jul + } else { + return undefined // Invalid month + } + } else { + return undefined // Invalid month + } + } else if ( + (date[4] === 'A') + ) { + if (date[5] === 'p' && date[6] === 'r') { + monthIdx = 3 // Apr + } else if (date[5] === 'u' && date[6] === 'g') { + monthIdx = 7 // Aug + } else { + return undefined // Invalid month + } + } else if ( + (date[4] === 'S' && date[5] === 'e' && date[6] === 'p') + ) { + monthIdx = 8 // Sep + } else if ( + (date[4] === 'O' && date[5] === 'c' && date[6] === 't') + ) { + monthIdx = 9 // Oct + } else if ( + (date[4] === 'N' && date[5] === 'o' && date[6] === 'v') + ) { + monthIdx = 10 // Nov + } else if ( + (date[4] === 'D' && date[5] === 'e' && date[6] === 'c') + ) { + monthIdx = 11 // Dec + } else { + // Not a valid month + return undefined + } + + let day = 0 + if (date[8] === ' ') { + // Single digit day, e.g. "Sun Nov 6 08:49:37 1994" + const code = date.charCodeAt(9) + if (code < 49 || code > 57) { + return undefined // Not a digit + } + day = code - 48 // Convert ASCII code to number + } else { + const code1 = date.charCodeAt(8) + if (code1 < 49 || code1 > 51) { + return undefined // Not a digit between 1 and 3 + } + const code2 = date.charCodeAt(9) + if (code2 < 48 || code2 > 57) { + return undefined // Not a digit + } + day = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number + } + + let hour = 0 + if (date[11] === '0') { + const code = date.charCodeAt(12) + if (code < 48 || code > 57) { + return undefined // Not a digit + } + hour = code - 48 // Convert ASCII code to number + } else { + const code1 = date.charCodeAt(11) + if (code1 < 48 || code1 > 50) { + return undefined // Not a digit between 0 and 2 + } + const code2 = date.charCodeAt(12) + if (code2 < 48 || code2 > 57) { + return undefined // Not a digit + } + if (code1 === 50 && code2 > 51) { + return undefined // Hour cannot be greater than 23 + } + hour = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number + } + + let minute = 0 + if (date[14] === '0') { + const code = date.charCodeAt(15) + if (code < 48 || code > 57) { + return undefined // Not a digit + } + minute = code - 48 // Convert ASCII code to number + } else { + const code1 = date.charCodeAt(14) + if (code1 < 48 || code1 > 53) { + return undefined // Not a digit between 0 and 5 + } + const code2 = date.charCodeAt(15) + if (code2 < 48 || code2 > 57) { + return undefined // Not a digit + } + minute = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number + } + + let second = 0 + if (date[17] === '0') { + const code = date.charCodeAt(18) + if (code < 48 || code > 57) { + return undefined // Not a digit + } + second = code - 48 // Convert ASCII code to number + } else { + const code1 = date.charCodeAt(17) + if (code1 < 48 || code1 > 53) { + return undefined // Not a digit between 0 and 5 + } + const code2 = date.charCodeAt(18) + if (code2 < 48 || code2 > 57) { + return undefined // Not a digit + } + second = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number + } + + const yearDigit1 = date.charCodeAt(20) + if (yearDigit1 < 48 || yearDigit1 > 57) { + return undefined // Not a digit + } + const yearDigit2 = date.charCodeAt(21) + if (yearDigit2 < 48 || yearDigit2 > 57) { + return undefined // Not a digit + } + const yearDigit3 = date.charCodeAt(22) + if (yearDigit3 < 48 || yearDigit3 > 57) { + return undefined // Not a digit + } + const yearDigit4 = date.charCodeAt(23) + if (yearDigit4 < 48 || yearDigit4 > 57) { + return undefined // Not a digit + } + const year = (yearDigit1 - 48) * 1000 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48) + + const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second)) + return result.getUTCDay() === weekday ? result : undefined +} + +/** + * @see https://httpwg.org/specs/rfc9110.html#obsolete.date.formats + * + * @param {string} date + * @returns {Date | undefined} + */ +function parseRfc850Date (date) { + let commaIndex = -1 + + let weekday = -1 + if (date[0] === 'S') { + if (date[1] === 'u' && date[2] === 'n' && date[3] === 'd' && date[4] === 'a' && date[5] === 'y') { + weekday = 0 // Sunday + commaIndex = 6 + } else if (date[1] === 'a' && date[2] === 't' && date[3] === 'u' && date[4] === 'r' && date[5] === 'd' && date[6] === 'a' && date[7] === 'y') { + weekday = 6 // Saturday + commaIndex = 8 + } + } else if (date[0] === 'M' && date[1] === 'o' && date[2] === 'n' && date[3] === 'd' && date[4] === 'a' && date[5] === 'y') { + weekday = 1 // Monday + commaIndex = 6 + } else if (date[0] === 'T') { + if (date[1] === 'u' && date[2] === 'e' && date[3] === 's' && date[4] === 'd' && date[5] === 'a' && date[6] === 'y') { + weekday = 2 // Tuesday + commaIndex = 7 + } else if (date[1] === 'h' && date[2] === 'u' && date[3] === 'r' && date[4] === 's' && date[5] === 'd' && date[6] === 'a' && date[7] === 'y') { + weekday = 4 // Thursday + commaIndex = 8 + } + } else if (date[0] === 'W' && date[1] === 'e' && date[2] === 'd' && date[3] === 'n' && date[4] === 'e' && date[5] === 's' && date[6] === 'd' && date[7] === 'a' && date[8] === 'y') { + weekday = 3 // Wednesday + commaIndex = 9 + } else if (date[0] === 'F' && date[1] === 'r' && date[2] === 'i' && date[3] === 'd' && date[4] === 'a' && date[5] === 'y') { + weekday = 5 // Friday + commaIndex = 6 + } else { + // Not a valid day name + return undefined + } + + if ( + date[commaIndex] !== ',' || + (date.length - commaIndex - 1) !== 23 || + date[commaIndex + 1] !== ' ' || + date[commaIndex + 4] !== '-' || + date[commaIndex + 8] !== '-' || + date[commaIndex + 11] !== ' ' || + date[commaIndex + 14] !== ':' || + date[commaIndex + 17] !== ':' || + date[commaIndex + 20] !== ' ' || + date[commaIndex + 21] !== 'G' || + date[commaIndex + 22] !== 'M' || + date[commaIndex + 23] !== 'T' + ) { + return undefined + } + + let day = 0 + if (date[commaIndex + 2] === '0') { + // Single digit day, e.g. "Sun Nov 6 08:49:37 1994" + const code = date.charCodeAt(commaIndex + 3) + if (code < 49 || code > 57) { + return undefined // Not a digit + } + day = code - 48 // Convert ASCII code to number + } else { + const code1 = date.charCodeAt(commaIndex + 2) + if (code1 < 49 || code1 > 51) { + return undefined // Not a digit between 1 and 3 + } + const code2 = date.charCodeAt(commaIndex + 3) + if (code2 < 48 || code2 > 57) { + return undefined // Not a digit + } + day = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number + } + + let monthIdx = -1 + if ( + (date[commaIndex + 5] === 'J' && date[commaIndex + 6] === 'a' && date[commaIndex + 7] === 'n') + ) { + monthIdx = 0 // Jan + } else if ( + (date[commaIndex + 5] === 'F' && date[commaIndex + 6] === 'e' && date[commaIndex + 7] === 'b') + ) { + monthIdx = 1 // Feb + } else if ( + (date[commaIndex + 5] === 'M' && date[commaIndex + 6] === 'a' && date[commaIndex + 7] === 'r') + ) { + monthIdx = 2 // Mar + } else if ( + (date[commaIndex + 5] === 'A' && date[commaIndex + 6] === 'p' && date[commaIndex + 7] === 'r') + ) { + monthIdx = 3 // Apr + } else if ( + (date[commaIndex + 5] === 'M' && date[commaIndex + 6] === 'a' && date[commaIndex + 7] === 'y') + ) { + monthIdx = 4 // May + } else if ( + (date[commaIndex + 5] === 'J' && date[commaIndex + 6] === 'u' && date[commaIndex + 7] === 'n') + ) { + monthIdx = 5 // Jun + } else if ( + (date[commaIndex + 5] === 'J' && date[commaIndex + 6] === 'u' && date[commaIndex + 7] === 'l') + ) { + monthIdx = 6 // Jul + } else if ( + (date[commaIndex + 5] === 'A' && date[commaIndex + 6] === 'u' && date[commaIndex + 7] === 'g') + ) { + monthIdx = 7 // Aug + } else if ( + (date[commaIndex + 5] === 'S' && date[commaIndex + 6] === 'e' && date[commaIndex + 7] === 'p') + ) { + monthIdx = 8 // Sep + } else if ( + (date[commaIndex + 5] === 'O' && date[commaIndex + 6] === 'c' && date[commaIndex + 7] === 't') + ) { + monthIdx = 9 // Oct + } else if ( + (date[commaIndex + 5] === 'N' && date[commaIndex + 6] === 'o' && date[commaIndex + 7] === 'v') + ) { + monthIdx = 10 // Nov + } else if ( + (date[commaIndex + 5] === 'D' && date[commaIndex + 6] === 'e' && date[commaIndex + 7] === 'c') + ) { + monthIdx = 11 // Dec + } else { + // Not a valid month + return undefined + } + + const yearDigit1 = date.charCodeAt(commaIndex + 9) + if (yearDigit1 < 48 || yearDigit1 > 57) { + return undefined // Not a digit + } + const yearDigit2 = date.charCodeAt(commaIndex + 10) + if (yearDigit2 < 48 || yearDigit2 > 57) { + return undefined // Not a digit + } + + let year = (yearDigit1 - 48) * 10 + (yearDigit2 - 48) // Convert ASCII codes to number + + // RFC 6265 states that the year is in the range 1970-2069. + // @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.1 + // + // 3. If the year-value is greater than or equal to 70 and less than or + // equal to 99, increment the year-value by 1900. + // 4. If the year-value is greater than or equal to 0 and less than or + // equal to 69, increment the year-value by 2000. + year += year < 70 ? 2000 : 1900 + + let hour = 0 + if (date[commaIndex + 12] === '0') { + const code = date.charCodeAt(commaIndex + 13) + if (code < 48 || code > 57) { + return undefined // Not a digit + } + hour = code - 48 // Convert ASCII code to number + } else { + const code1 = date.charCodeAt(commaIndex + 12) + if (code1 < 48 || code1 > 50) { + return undefined // Not a digit between 0 and 2 + } + const code2 = date.charCodeAt(commaIndex + 13) + if (code2 < 48 || code2 > 57) { + return undefined // Not a digit + } + if (code1 === 50 && code2 > 51) { + return undefined // Hour cannot be greater than 23 + } + hour = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number + } + + let minute = 0 + if (date[commaIndex + 15] === '0') { + const code = date.charCodeAt(commaIndex + 16) + if (code < 48 || code > 57) { + return undefined // Not a digit + } + minute = code - 48 // Convert ASCII code to number + } else { + const code1 = date.charCodeAt(commaIndex + 15) + if (code1 < 48 || code1 > 53) { + return undefined // Not a digit between 0 and 5 + } + const code2 = date.charCodeAt(commaIndex + 16) + if (code2 < 48 || code2 > 57) { + return undefined // Not a digit + } + minute = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number + } + + let second = 0 + if (date[commaIndex + 18] === '0') { + const code = date.charCodeAt(commaIndex + 19) + if (code < 48 || code > 57) { + return undefined // Not a digit + } + second = code - 48 // Convert ASCII code to number + } else { + const code1 = date.charCodeAt(commaIndex + 18) + if (code1 < 48 || code1 > 53) { + return undefined // Not a digit between 0 and 5 + } + const code2 = date.charCodeAt(commaIndex + 19) + if (code2 < 48 || code2 > 57) { + return undefined // Not a digit + } + second = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number + } + + const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second)) + return result.getUTCDay() === weekday ? result : undefined +} + +module.exports = { + parseHttpDate +} diff --git a/node_modules/undici/lib/util/promise.js b/node_modules/undici/lib/util/promise.js new file mode 100644 index 000000000..048f86e34 --- /dev/null +++ b/node_modules/undici/lib/util/promise.js @@ -0,0 +1,28 @@ +'use strict' + +/** + * @template {*} T + * @typedef {Object} DeferredPromise + * @property {Promise} promise + * @property {(value?: T) => void} resolve + * @property {(reason?: any) => void} reject + */ + +/** + * @template {*} T + * @returns {DeferredPromise} An object containing a promise and its resolve/reject methods. + */ +function createDeferredPromise () { + let res + let rej + const promise = new Promise((resolve, reject) => { + res = resolve + rej = reject + }) + + return { promise, resolve: res, reject: rej } +} + +module.exports = { + createDeferredPromise +} diff --git a/node_modules/undici/lib/util/runtime-features.js b/node_modules/undici/lib/util/runtime-features.js new file mode 100644 index 000000000..3e62dc004 --- /dev/null +++ b/node_modules/undici/lib/util/runtime-features.js @@ -0,0 +1,124 @@ +'use strict' + +/** @typedef {`node:${string}`} NodeModuleName */ + +/** @type {Record any>} */ +const lazyLoaders = { + __proto__: null, + 'node:crypto': () => require('node:crypto'), + 'node:sqlite': () => require('node:sqlite'), + 'node:worker_threads': () => require('node:worker_threads'), + 'node:zlib': () => require('node:zlib') +} + +/** + * @param {NodeModuleName} moduleName + * @returns {boolean} + */ +function detectRuntimeFeatureByNodeModule (moduleName) { + try { + lazyLoaders[moduleName]() + return true + } catch (err) { + if (err.code !== 'ERR_UNKNOWN_BUILTIN_MODULE' && err.code !== 'ERR_NO_CRYPTO') { + throw err + } + return false + } +} + +/** + * @param {NodeModuleName} moduleName + * @param {string} property + * @returns {boolean} + */ +function detectRuntimeFeatureByExportedProperty (moduleName, property) { + const module = lazyLoaders[moduleName]() + return typeof module[property] !== 'undefined' +} + +const runtimeFeaturesByExportedProperty = /** @type {const} */ (['markAsUncloneable', 'zstd']) + +/** @type {Record} */ +const exportedPropertyLookup = { + markAsUncloneable: ['node:worker_threads', 'markAsUncloneable'], + zstd: ['node:zlib', 'createZstdDecompress'] +} + +/** @typedef {typeof runtimeFeaturesByExportedProperty[number]} RuntimeFeatureByExportedProperty */ + +const runtimeFeaturesAsNodeModule = /** @type {const} */ (['crypto', 'sqlite']) +/** @typedef {typeof runtimeFeaturesAsNodeModule[number]} RuntimeFeatureByNodeModule */ + +const features = /** @type {const} */ ([ + ...runtimeFeaturesAsNodeModule, + ...runtimeFeaturesByExportedProperty +]) + +/** @typedef {typeof features[number]} Feature */ + +/** + * @param {Feature} feature + * @returns {boolean} + */ +function detectRuntimeFeature (feature) { + if (runtimeFeaturesAsNodeModule.includes(/** @type {RuntimeFeatureByNodeModule} */ (feature))) { + return detectRuntimeFeatureByNodeModule(`node:${feature}`) + } else if (runtimeFeaturesByExportedProperty.includes(/** @type {RuntimeFeatureByExportedProperty} */ (feature))) { + const [moduleName, property] = exportedPropertyLookup[feature] + return detectRuntimeFeatureByExportedProperty(moduleName, property) + } + throw new TypeError(`unknown feature: ${feature}`) +} + +/** + * @class + * @name RuntimeFeatures + */ +class RuntimeFeatures { + /** @type {Map} */ + #map = new Map() + + /** + * Clears all cached feature detections. + */ + clear () { + this.#map.clear() + } + + /** + * @param {Feature} feature + * @returns {boolean} + */ + has (feature) { + return ( + this.#map.get(feature) ?? this.#detectRuntimeFeature(feature) + ) + } + + /** + * @param {Feature} feature + * @param {boolean} value + */ + set (feature, value) { + if (features.includes(feature) === false) { + throw new TypeError(`unknown feature: ${feature}`) + } + this.#map.set(feature, value) + } + + /** + * @param {Feature} feature + * @returns {boolean} + */ + #detectRuntimeFeature (feature) { + const result = detectRuntimeFeature(feature) + this.#map.set(feature, result) + return result + } +} + +const instance = new RuntimeFeatures() + +module.exports.runtimeFeatures = instance +module.exports.default = instance diff --git a/node_modules/undici/lib/util/stats.js b/node_modules/undici/lib/util/stats.js new file mode 100644 index 000000000..a13132e4e --- /dev/null +++ b/node_modules/undici/lib/util/stats.js @@ -0,0 +1,32 @@ +'use strict' + +const { + kConnected, + kPending, + kRunning, + kSize, + kFree, + kQueued +} = require('../core/symbols') + +class ClientStats { + constructor (client) { + this.connected = client[kConnected] + this.pending = client[kPending] + this.running = client[kRunning] + this.size = client[kSize] + } +} + +class PoolStats { + constructor (pool) { + this.connected = pool[kConnected] + this.free = pool[kFree] + this.pending = pool[kPending] + this.queued = pool[kQueued] + this.running = pool[kRunning] + this.size = pool[kSize] + } +} + +module.exports = { ClientStats, PoolStats } diff --git a/node_modules/undici/lib/util/timers.js b/node_modules/undici/lib/util/timers.js new file mode 100644 index 000000000..14984d42e --- /dev/null +++ b/node_modules/undici/lib/util/timers.js @@ -0,0 +1,425 @@ +'use strict' + +/** + * This module offers an optimized timer implementation designed for scenarios + * where high precision is not critical. + * + * The timer achieves faster performance by using a low-resolution approach, + * with an accuracy target of within 500ms. This makes it particularly useful + * for timers with delays of 1 second or more, where exact timing is less + * crucial. + * + * It's important to note that Node.js timers are inherently imprecise, as + * delays can occur due to the event loop being blocked by other operations. + * Consequently, timers may trigger later than their scheduled time. + */ + +/** + * The fastNow variable contains the internal fast timer clock value. + * + * @type {number} + */ +let fastNow = 0 + +/** + * RESOLUTION_MS represents the target resolution time in milliseconds. + * + * @type {number} + * @default 1000 + */ +const RESOLUTION_MS = 1e3 + +/** + * TICK_MS defines the desired interval in milliseconds between each tick. + * The target value is set to half the resolution time, minus 1 ms, to account + * for potential event loop overhead. + * + * @type {number} + * @default 499 + */ +const TICK_MS = (RESOLUTION_MS >> 1) - 1 + +/** + * fastNowTimeout is a Node.js timer used to manage and process + * the FastTimers stored in the `fastTimers` array. + * + * @type {NodeJS.Timeout} + */ +let fastNowTimeout + +/** + * The kFastTimer symbol is used to identify FastTimer instances. + * + * @type {Symbol} + */ +const kFastTimer = Symbol('kFastTimer') + +/** + * The fastTimers array contains all active FastTimers. + * + * @type {FastTimer[]} + */ +const fastTimers = [] + +/** + * These constants represent the various states of a FastTimer. + */ + +/** + * The `NOT_IN_LIST` constant indicates that the FastTimer is not included + * in the `fastTimers` array. Timers with this status will not be processed + * during the next tick by the `onTick` function. + * + * A FastTimer can be re-added to the `fastTimers` array by invoking the + * `refresh` method on the FastTimer instance. + * + * @type {-2} + */ +const NOT_IN_LIST = -2 + +/** + * The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled + * for removal from the `fastTimers` array. A FastTimer in this state will + * be removed in the next tick by the `onTick` function and will no longer + * be processed. + * + * This status is also set when the `clear` method is called on the FastTimer instance. + * + * @type {-1} + */ +const TO_BE_CLEARED = -1 + +/** + * The `PENDING` constant signifies that the FastTimer is awaiting processing + * in the next tick by the `onTick` function. Timers with this status will have + * their `_idleStart` value set and their status updated to `ACTIVE` in the next tick. + * + * @type {0} + */ +const PENDING = 0 + +/** + * The `ACTIVE` constant indicates that the FastTimer is active and waiting + * for its timer to expire. During the next tick, the `onTick` function will + * check if the timer has expired, and if so, it will execute the associated callback. + * + * @type {1} + */ +const ACTIVE = 1 + +/** + * The onTick function processes the fastTimers array. + * + * @returns {void} + */ +function onTick () { + /** + * Increment the fastNow value by the TICK_MS value, despite the actual time + * that has passed since the last tick. This approach ensures independence + * from the system clock and delays caused by a blocked event loop. + * + * @type {number} + */ + fastNow += TICK_MS + + /** + * The `idx` variable is used to iterate over the `fastTimers` array. + * Expired timers are removed by replacing them with the last element in the array. + * Consequently, `idx` is only incremented when the current element is not removed. + * + * @type {number} + */ + let idx = 0 + + /** + * The len variable will contain the length of the fastTimers array + * and will be decremented when a FastTimer should be removed from the + * fastTimers array. + * + * @type {number} + */ + let len = fastTimers.length + + while (idx < len) { + /** + * @type {FastTimer} + */ + const timer = fastTimers[idx] + + // If the timer is in the ACTIVE state and the timer has expired, it will + // be processed in the next tick. + if (timer._state === PENDING) { + // Set the _idleStart value to the fastNow value minus the TICK_MS value + // to account for the time the timer was in the PENDING state. + timer._idleStart = fastNow - TICK_MS + timer._state = ACTIVE + } else if ( + timer._state === ACTIVE && + fastNow >= timer._idleStart + timer._idleTimeout + ) { + timer._state = TO_BE_CLEARED + timer._idleStart = -1 + timer._onTimeout(timer._timerArg) + } + + if (timer._state === TO_BE_CLEARED) { + timer._state = NOT_IN_LIST + + // Move the last element to the current index and decrement len if it is + // not the only element in the array. + if (--len !== 0) { + fastTimers[idx] = fastTimers[len] + } + } else { + ++idx + } + } + + // Set the length of the fastTimers array to the new length and thus + // removing the excess FastTimers elements from the array. + fastTimers.length = len + + // If there are still active FastTimers in the array, refresh the Timer. + // If there are no active FastTimers, the timer will be refreshed again + // when a new FastTimer is instantiated. + if (fastTimers.length !== 0) { + refreshTimeout() + } +} + +function refreshTimeout () { + // If the fastNowTimeout is already set and the Timer has the refresh()- + // method available, call it to refresh the timer. + // Some timer objects returned by setTimeout may not have a .refresh() + // method (e.g. mocked timers in tests). + if (fastNowTimeout?.refresh) { + fastNowTimeout.refresh() + // fastNowTimeout is not instantiated yet or refresh is not availabe, + // create a new Timer. + } else { + clearTimeout(fastNowTimeout) + fastNowTimeout = setTimeout(onTick, TICK_MS) + // If the Timer has an unref method, call it to allow the process to exit, + // if there are no other active handles. When using fake timers or mocked + // environments (like Jest), .unref() may not be defined, + fastNowTimeout?.unref() + } +} + +/** + * The `FastTimer` class is a data structure designed to store and manage + * timer information. + */ +class FastTimer { + [kFastTimer] = true + + /** + * The state of the timer, which can be one of the following: + * - NOT_IN_LIST (-2) + * - TO_BE_CLEARED (-1) + * - PENDING (0) + * - ACTIVE (1) + * + * @type {-2|-1|0|1} + * @private + */ + _state = NOT_IN_LIST + + /** + * The number of milliseconds to wait before calling the callback. + * + * @type {number} + * @private + */ + _idleTimeout = -1 + + /** + * The time in milliseconds when the timer was started. This value is used to + * calculate when the timer should expire. + * + * @type {number} + * @default -1 + * @private + */ + _idleStart = -1 + + /** + * The function to be executed when the timer expires. + * @type {Function} + * @private + */ + _onTimeout + + /** + * The argument to be passed to the callback when the timer expires. + * + * @type {*} + * @private + */ + _timerArg + + /** + * @constructor + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should wait + * before the specified function or code is executed. + * @param {*} arg + */ + constructor (callback, delay, arg) { + this._onTimeout = callback + this._idleTimeout = delay + this._timerArg = arg + + this.refresh() + } + + /** + * 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. + * Using this on a timer that has already called its callback will reactivate + * the timer. + * + * @returns {void} + */ + refresh () { + // In the special case that the timer is not in the list of active timers, + // add it back to the array to be processed in the next tick by the onTick + // function. + if (this._state === NOT_IN_LIST) { + fastTimers.push(this) + } + + // If the timer is the only active timer, refresh the fastNowTimeout for + // better resolution. + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout() + } + + // Setting the state to PENDING will cause the timer to be reset in the + // next tick by the onTick function. + this._state = PENDING + } + + /** + * The `clear` method cancels the timer, preventing it from executing. + * + * @returns {void} + * @private + */ + clear () { + // Set the state to TO_BE_CLEARED to mark the timer for removal in the next + // tick by the onTick function. + this._state = TO_BE_CLEARED + + // Reset the _idleStart value to -1 to indicate that the timer is no longer + // active. + this._idleStart = -1 + } +} + +/** + * This module exports a setTimeout and clearTimeout function that can be + * used as a drop-in replacement for the native functions. + */ +module.exports = { + /** + * The setTimeout() method sets a timer which executes a function once the + * timer expires. + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should + * wait before the specified function or code is executed. + * @param {*} [arg] An optional argument to be passed to the callback function + * when the timer expires. + * @returns {NodeJS.Timeout|FastTimer} + */ + setTimeout (callback, delay, arg) { + // If the delay is less than or equal to the RESOLUTION_MS value return a + // native Node.js Timer instance. + return delay <= RESOLUTION_MS + ? setTimeout(callback, delay, arg) + : new FastTimer(callback, delay, arg) + }, + /** + * The clearTimeout method cancels an instantiated Timer previously created + * by calling setTimeout. + * + * @param {NodeJS.Timeout|FastTimer} timeout + */ + clearTimeout (timeout) { + // If the timeout is a FastTimer, call its own clear method. + if (timeout[kFastTimer]) { + /** + * @type {FastTimer} + */ + timeout.clear() + // Otherwise it is an instance of a native NodeJS.Timeout, so call the + // Node.js native clearTimeout function. + } else { + clearTimeout(timeout) + } + }, + /** + * The setFastTimeout() method sets a fastTimer which executes a function once + * the timer expires. + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should + * wait before the specified function or code is executed. + * @param {*} [arg] An optional argument to be passed to the callback function + * when the timer expires. + * @returns {FastTimer} + */ + setFastTimeout (callback, delay, arg) { + return new FastTimer(callback, delay, arg) + }, + /** + * The clearTimeout method cancels an instantiated FastTimer previously + * created by calling setFastTimeout. + * + * @param {FastTimer} timeout + */ + clearFastTimeout (timeout) { + timeout.clear() + }, + /** + * The now method returns the value of the internal fast timer clock. + * + * @returns {number} + */ + now () { + return fastNow + }, + /** + * Trigger the onTick function to process the fastTimers array. + * Exported for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + * @param {number} [delay=0] The delay in milliseconds to add to the now value. + */ + tick (delay = 0) { + fastNow += delay - RESOLUTION_MS + 1 + onTick() + onTick() + }, + /** + * Reset FastTimers. + * Exported for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + */ + reset () { + fastNow = 0 + fastTimers.length = 0 + clearTimeout(fastNowTimeout) + fastNowTimeout = null + }, + /** + * Exporting for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + */ + kFastTimer +} diff --git a/node_modules/undici/lib/web/cache/cache.js b/node_modules/undici/lib/web/cache/cache.js new file mode 100644 index 000000000..10decbede --- /dev/null +++ b/node_modules/undici/lib/web/cache/cache.js @@ -0,0 +1,864 @@ +'use strict' + +const assert = require('node:assert') + +const { kConstruct } = require('../../core/symbols') +const { urlEquals, getFieldValues } = require('./util') +const { kEnumerableProperty, isDisturbed } = require('../../core/util') +const { webidl } = require('../webidl') +const { cloneResponse, fromInnerResponse, getResponseState } = require('../fetch/response') +const { Request, fromInnerRequest, getRequestState } = require('../fetch/request') +const { fetching } = require('../fetch/index') +const { urlIsHttpHttpsScheme, readAllBytes } = require('../fetch/util') +const { createDeferredPromise } = require('../../util/promise') + +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation + * @typedef {Object} CacheBatchOperation + * @property {'delete' | 'put'} type + * @property {any} request + * @property {any} response + * @property {import('../../../types/cache').CacheQueryOptions} options + */ + +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ + +class Cache { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} + */ + #relevantRequestResponseList + + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor() + } + + webidl.util.markAsUncloneable(this) + this.#relevantRequestResponseList = arguments[1] + } + + async match (request, options = {}) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.match' + webidl.argumentLengthCheck(arguments, 1, prefix) + + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options, prefix, 'options') + + const p = this.#internalMatchAll(request, options, 1) + + if (p.length === 0) { + return + } + + return p[0] + } + + async matchAll (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.matchAll' + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options, prefix, 'options') + + return this.#internalMatchAll(request, options) + } + + async add (request) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.add' + webidl.argumentLengthCheck(arguments, 1, prefix) + + request = webidl.converters.RequestInfo(request) + + // 1. + const requests = [request] + + // 2. + const responseArrayPromise = this.addAll(requests) + + // 3. + return await responseArrayPromise + } + + async addAll (requests) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.addAll' + webidl.argumentLengthCheck(arguments, 1, prefix) + + // 1. + const responsePromises = [] + + // 2. + const requestList = [] + + // 3. + for (let request of requests) { + if (request === undefined) { + throw webidl.errors.conversionFailed({ + prefix, + argument: 'Argument 1', + types: ['undefined is not allowed'] + }) + } + + request = webidl.converters.RequestInfo(request) + + if (typeof request === 'string') { + continue + } + + // 3.1 + const r = getRequestState(request) + + // 3.2 + if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { + throw webidl.errors.exception({ + header: prefix, + message: 'Expected http/s scheme when method is not GET.' + }) + } + } + + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = [] + + // 5. + for (const request of requests) { + // 5.1 + const r = getRequestState(new Request(request)) + + // 5.2 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: prefix, + message: 'Expected http/s scheme.' + }) + } + + // 5.4 + r.initiator = 'fetch' + r.destination = 'subresource' + + // 5.5 + requestList.push(r) + + // 5.6 + const responsePromise = createDeferredPromise() + + // 5.7 + fetchControllers.push(fetching({ + request: r, + processResponse (response) { + // 1. + if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Received an invalid status code or the request failed.' + })) + } else if (response.headersList.contains('vary')) { // 2. + // 2.1 + const fieldValues = getFieldValues(response.headersList.get('vary')) + + // 2.2 + for (const fieldValue of fieldValues) { + // 2.2.1 + if (fieldValue === '*') { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'invalid vary field value' + })) + + for (const controller of fetchControllers) { + controller.abort() + } + + return + } + } + } + }, + processResponseEndOfBody (response) { + // 1. + if (response.aborted) { + responsePromise.reject(new DOMException('aborted', 'AbortError')) + return + } + + // 2. + responsePromise.resolve(response) + } + })) + + // 5.8 + responsePromises.push(responsePromise.promise) + } + + // 6. + const p = Promise.all(responsePromises) + + // 7. + const responses = await p + + // 7.1 + const operations = [] + + // 7.2 + let index = 0 + + // 7.3 + for (const response of responses) { + // 7.3.1 + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 7.3.2 + request: requestList[index], // 7.3.3 + response // 7.3.4 + } + + operations.push(operation) // 7.3.5 + + index++ // 7.3.6 + } + + // 7.5 + const cacheJobPromise = createDeferredPromise() + + // 7.6.1 + let errorData = null + + // 7.6.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 7.6.3 + queueMicrotask(() => { + // 7.6.3.1 + if (errorData === null) { + cacheJobPromise.resolve(undefined) + } else { + // 7.6.3.2 + cacheJobPromise.reject(errorData) + } + }) + + // 7.7 + return cacheJobPromise.promise + } + + async put (request, response) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.put' + webidl.argumentLengthCheck(arguments, 2, prefix) + + request = webidl.converters.RequestInfo(request) + response = webidl.converters.Response(response, prefix, 'response') + + // 1. + let innerRequest = null + + // 2. + if (webidl.is.Request(request)) { + innerRequest = getRequestState(request) + } else { // 3. + innerRequest = getRequestState(new Request(request)) + } + + // 4. + if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { + throw webidl.errors.exception({ + header: prefix, + message: 'Expected an http/s scheme when method is not GET' + }) + } + + // 5. + const innerResponse = getResponseState(response) + + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: prefix, + message: 'Got 206 status' + }) + } + + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) + + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: prefix, + message: 'Got * vary field value' + }) + } + } + } + + // 8. + if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { + throw webidl.errors.exception({ + header: prefix, + message: 'Response body is locked or disturbed' + }) + } + + // 9. + const clonedResponse = cloneResponse(innerResponse) + + // 10. + const bodyReadPromise = createDeferredPromise() + + // 11. + if (innerResponse.body != null) { + // 11.1 + const stream = innerResponse.body.stream + + // 11.2 + const reader = stream.getReader() + + // 11.3 + readAllBytes(reader, bodyReadPromise.resolve, bodyReadPromise.reject) + } else { + bodyReadPromise.resolve(undefined) + } + + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = [] + + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. + } + + // 17. + operations.push(operation) + + // 19. + const bytes = await bodyReadPromise.promise + + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes + } + + // 19.1 + const cacheJobPromise = createDeferredPromise() + + // 19.2.1 + let errorData = null + + // 19.2.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve() + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise + } + + async delete (request, options = {}) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.delete' + webidl.argumentLengthCheck(arguments, 1, prefix) + + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options, prefix, 'options') + + /** + * @type {Request} + */ + let r = null + + if (webidl.is.Request(request)) { + r = getRequestState(request) + + if (r.method !== 'GET' && !options.ignoreMethod) { + return false + } + } else { + assert(typeof request === 'string') + + r = getRequestState(new Request(request)) + } + + /** @type {CacheBatchOperation[]} */ + const operations = [] + + /** @type {CacheBatchOperation} */ + const operation = { + type: 'delete', + request: r, + options + } + + operations.push(operation) + + const cacheJobPromise = createDeferredPromise() + + let errorData = null + let requestResponses + + try { + requestResponses = this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length) + } else { + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys + * @param {any} request + * @param {import('../../../types/cache').CacheQueryOptions} options + * @returns {Promise} + */ + async keys (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.keys' + + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options, prefix, 'options') + + // 1. + let r = null + + // 2. + if (request !== undefined) { + // 2.1 + if (webidl.is.Request(request)) { + // 2.1.1 + r = getRequestState(request) + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = getRequestState(new Request(request)) + } + } + + // 4. + const promise = createDeferredPromise() + + // 5. + // 5.1 + const requests = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + // 5.2.1.1 + requests.push(requestResponse[0]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + // 5.3.2.1 + requests.push(requestResponse[0]) + } + } + + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = [] + + // 5.4.2 + for (const request of requests) { + const requestObject = fromInnerRequest( + request, + undefined, + new AbortController().signal, + 'immutable' + ) + // 5.4.2.1 + requestList.push(requestObject) + } + + // 5.4.3 + promise.resolve(Object.freeze(requestList)) + }) + + return promise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} + */ + #batchCacheOperations (operations) { + // 1. + const cache = this.#relevantRequestResponseList + + // 2. + const backupCache = [...cache] + + // 3. + const addedItems = [] + + // 4.1 + const resultList = [] + + try { + // 4.2 + for (const operation of operations) { + // 4.2.1 + if (operation.type !== 'delete' && operation.type !== 'put') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'operation type does not match "delete" or "put"' + }) + } + + // 4.2.2 + if (operation.type === 'delete' && operation.response != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'delete operation should not have an associated response' + }) + } + + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } + + // 4.2.4 + let requestResponses + + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options) + + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } + + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) + + // 4.2.5.2.1 + cache.splice(idx, 1) + } + } else if (operation.type === 'put') { // 4.2.6 + // 4.2.6.1 + if (operation.response == null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'put operation should have an associated response' + }) + } + + // 4.2.6.2 + const r = operation.request + + // 4.2.6.3 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'expected http or https scheme' + }) + } + + // 4.2.6.4 + if (r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'not get method' + }) + } + + // 4.2.6.5 + if (operation.options != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'options must not be defined' + }) + } + + // 4.2.6.6 + requestResponses = this.#queryCache(operation.request) + + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) + + // 4.2.6.7.1 + cache.splice(idx, 1) + } + + // 4.2.6.8 + cache.push([operation.request, operation.response]) + + // 4.2.6.10 + addedItems.push([operation.request, operation.response]) + } + + // 4.2.7 + resultList.push([operation.request, operation.response]) + } + + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0 + + // 5.2 + this.#relevantRequestResponseList = backupCache + + // 5.3 + throw e + } + } + + /** + * @see https://w3c.github.io/ServiceWorker/#query-cache + * @param {any} requestQuery + * @param {import('../../../types/cache').CacheQueryOptions} options + * @param {requestResponseList} targetStorage + * @returns {requestResponseList} + */ + #queryCache (requestQuery, options, targetStorage) { + /** @type {requestResponseList} */ + const resultList = [] + + const storage = targetStorage ?? this.#relevantRequestResponseList + + for (const requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse) + } + } + + return resultList + } + + /** + * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm + * @param {any} requestQuery + * @param {any} request + * @param {any | null} response + * @param {import('../../../types/cache').CacheQueryOptions | undefined} options + * @returns {boolean} + */ + #requestMatchesCachedItem (requestQuery, request, response = null, options) { + // if (options?.ignoreMethod === false && request.method === 'GET') { + // return false + // } + + const queryURL = new URL(requestQuery.url) + + const cachedURL = new URL(request.url) + + if (options?.ignoreSearch) { + cachedURL.search = '' + + queryURL.search = '' + } + + if (!urlEquals(queryURL, cachedURL, true)) { + return false + } + + if ( + response == null || + options?.ignoreVary || + !response.headersList.contains('vary') + ) { + return true + } + + const fieldValues = getFieldValues(response.headersList.get('vary')) + + for (const fieldValue of fieldValues) { + if (fieldValue === '*') { + return false + } + + const requestValue = request.headersList.get(fieldValue) + const queryValue = requestQuery.headersList.get(fieldValue) + + // If one has the header and the other doesn't, or one has + // a different value than the other, return false + if (requestValue !== queryValue) { + return false + } + } + + return true + } + + #internalMatchAll (request, options, maxResponses = Infinity) { + // 1. + let r = null + + // 2. + if (request !== undefined) { + if (webidl.is.Request(request)) { + // 2.1.1 + r = getRequestState(request) + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { + // 2.2.1 + r = getRequestState(new Request(request)) + } + } + + // 5. + // 5.1 + const responses = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + responses.push(requestResponse[1]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]) + } + } + + // 5.4 + // We don't implement CORs so we don't need to loop over the responses, yay! + + // 5.5.1 + const responseList = [] + + // 5.5.2 + for (const response of responses) { + // 5.5.2.1 + const responseObject = fromInnerResponse(cloneResponse(response), 'immutable') + + responseList.push(responseObject) + + if (responseList.length >= maxResponses) { + break + } + } + + // 6. + return Object.freeze(responseList) + } +} + +Object.defineProperties(Cache.prototype, { + [Symbol.toStringTag]: { + value: 'Cache', + configurable: true + }, + match: kEnumerableProperty, + matchAll: kEnumerableProperty, + add: kEnumerableProperty, + addAll: kEnumerableProperty, + put: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +const cacheQueryOptionConverters = [ + { + key: 'ignoreSearch', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'ignoreMethod', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'ignoreVary', + converter: webidl.converters.boolean, + defaultValue: () => false + } +] + +webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) + +webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: 'cacheName', + converter: webidl.converters.DOMString + } +]) + +webidl.converters.Response = webidl.interfaceConverter( + webidl.is.Response, + 'Response' +) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.RequestInfo +) + +module.exports = { + Cache +} diff --git a/node_modules/undici/lib/web/cache/cachestorage.js b/node_modules/undici/lib/web/cache/cachestorage.js new file mode 100644 index 000000000..c49b1e82e --- /dev/null +++ b/node_modules/undici/lib/web/cache/cachestorage.js @@ -0,0 +1,152 @@ +'use strict' + +const { Cache } = require('./cache') +const { webidl } = require('../webidl') +const { kEnumerableProperty } = require('../../core/util') +const { kConstruct } = require('../../core/symbols') + +class CacheStorage { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map} + */ + async has (cacheName) { + webidl.brandCheck(this, CacheStorage) + + const prefix = 'CacheStorage.has' + webidl.argumentLengthCheck(arguments, 1, prefix) + + cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') + + // 2.1.1 + // 2.2 + return this.#caches.has(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open + * @param {string} cacheName + * @returns {Promise} + */ + async open (cacheName) { + webidl.brandCheck(this, CacheStorage) + + const prefix = 'CacheStorage.open' + webidl.argumentLengthCheck(arguments, 1, prefix) + + cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') + + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') + + // 2.1.1 + const cache = this.#caches.get(cacheName) + + // 2.1.1.1 + return new Cache(kConstruct, cache) + } + + // 2.2 + const cache = [] + + // 2.3 + this.#caches.set(cacheName, cache) + + // 2.4 + return new Cache(kConstruct, cache) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete + * @param {string} cacheName + * @returns {Promise} + */ + async delete (cacheName) { + webidl.brandCheck(this, CacheStorage) + + const prefix = 'CacheStorage.delete' + webidl.argumentLengthCheck(arguments, 1, prefix) + + cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') + + return this.#caches.delete(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {Promise} + */ + async keys () { + webidl.brandCheck(this, CacheStorage) + + // 2.1 + const keys = this.#caches.keys() + + // 2.2 + return [...keys] + } +} + +Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: 'CacheStorage', + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +module.exports = { + CacheStorage +} diff --git a/node_modules/undici/lib/web/cache/util.js b/node_modules/undici/lib/web/cache/util.js new file mode 100644 index 000000000..5ac9d846d --- /dev/null +++ b/node_modules/undici/lib/web/cache/util.js @@ -0,0 +1,45 @@ +'use strict' + +const assert = require('node:assert') +const { URLSerializer } = require('../fetch/data-url') +const { isValidHeaderName } = require('../fetch/util') + +/** + * @see https://url.spec.whatwg.org/#concept-url-equals + * @param {URL} A + * @param {URL} B + * @param {boolean | undefined} excludeFragment + * @returns {boolean} + */ +function urlEquals (A, B, excludeFragment = false) { + const serializedA = URLSerializer(A, excludeFragment) + + const serializedB = URLSerializer(B, excludeFragment) + + return serializedA === serializedB +} + +/** + * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 + * @param {string} header + */ +function getFieldValues (header) { + assert(header !== null) + + const values = [] + + for (let value of header.split(',')) { + value = value.trim() + + if (isValidHeaderName(value)) { + values.push(value) + } + } + + return values +} + +module.exports = { + urlEquals, + getFieldValues +} diff --git a/node_modules/undici/lib/web/cookies/constants.js b/node_modules/undici/lib/web/cookies/constants.js new file mode 100644 index 000000000..85f1fec0e --- /dev/null +++ b/node_modules/undici/lib/web/cookies/constants.js @@ -0,0 +1,12 @@ +'use strict' + +// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size +const maxAttributeValueSize = 1024 + +// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size +const maxNameValuePairSize = 4096 + +module.exports = { + maxAttributeValueSize, + maxNameValuePairSize +} diff --git a/node_modules/undici/lib/web/cookies/index.js b/node_modules/undici/lib/web/cookies/index.js new file mode 100644 index 000000000..be99f6f3d --- /dev/null +++ b/node_modules/undici/lib/web/cookies/index.js @@ -0,0 +1,199 @@ +'use strict' + +const { parseSetCookie } = require('./parse') +const { stringify } = require('./util') +const { webidl } = require('../webidl') +const { Headers } = require('../fetch/headers') + +const brandChecks = webidl.brandCheckMultiple([Headers, globalThis.Headers].filter(Boolean)) + +/** + * @typedef {Object} Cookie + * @property {string} name + * @property {string} value + * @property {Date|number} [expires] + * @property {number} [maxAge] + * @property {string} [domain] + * @property {string} [path] + * @property {boolean} [secure] + * @property {boolean} [httpOnly] + * @property {'Strict'|'Lax'|'None'} [sameSite] + * @property {string[]} [unparsed] + */ + +/** + * @param {Headers} headers + * @returns {Record} + */ +function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, 'getCookies') + + brandChecks(headers) + + const cookie = headers.get('cookie') + + /** @type {Record} */ + const out = {} + + if (!cookie) { + return out + } + + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('=') + + out[name.trim()] = value.join('=') + } + + return out +} + +/** + * @param {Headers} headers + * @param {string} name + * @param {{ path?: string, domain?: string }|undefined} attributes + * @returns {void} + */ +function deleteCookie (headers, name, attributes) { + brandChecks(headers) + + const prefix = 'deleteCookie' + webidl.argumentLengthCheck(arguments, 2, prefix) + + name = webidl.converters.DOMString(name, prefix, 'name') + attributes = webidl.converters.DeleteCookieAttributes(attributes) + + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }) +} + +/** + * @param {Headers} headers + * @returns {Cookie[]} + */ +function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, 'getSetCookies') + + brandChecks(headers) + + const cookies = headers.getSetCookie() + + if (!cookies) { + return [] + } + + return cookies.map((pair) => parseSetCookie(pair)) +} + +/** + * Parses a cookie string + * @param {string} cookie + */ +function parseCookie (cookie) { + cookie = webidl.converters.DOMString(cookie) + + return parseSetCookie(cookie) +} + +/** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ +function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, 'setCookie') + + brandChecks(headers) + + cookie = webidl.converters.Cookie(cookie) + + const str = stringify(cookie) + + if (str) { + headers.append('set-cookie', str, true) + } +} + +webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: () => null + } +]) + +webidl.converters.Cookie = webidl.dictionaryConverter([ + { + converter: webidl.converters.DOMString, + key: 'name' + }, + { + converter: webidl.converters.DOMString, + key: 'value' + }, + { + converter: webidl.nullableConverter((value) => { + if (typeof value === 'number') { + return webidl.converters['unsigned long long'](value) + } + + return new Date(value) + }), + key: 'expires', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters['long long']), + key: 'maxAge', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'secure', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'httpOnly', + defaultValue: () => null + }, + { + converter: webidl.converters.USVString, + key: 'sameSite', + allowedValues: ['Strict', 'Lax', 'None'] + }, + { + converter: webidl.sequenceConverter(webidl.converters.DOMString), + key: 'unparsed', + defaultValue: () => [] + } +]) + +module.exports = { + getCookies, + deleteCookie, + getSetCookies, + setCookie, + parseCookie +} diff --git a/node_modules/undici/lib/web/cookies/parse.js b/node_modules/undici/lib/web/cookies/parse.js new file mode 100644 index 000000000..74edf7ec6 --- /dev/null +++ b/node_modules/undici/lib/web/cookies/parse.js @@ -0,0 +1,322 @@ +'use strict' + +const { collectASequenceOfCodePointsFast } = require('../infra') +const { maxNameValuePairSize, maxAttributeValueSize } = require('./constants') +const { isCTLExcludingHtab } = require('./util') +const assert = require('node:assert') +const { unescape: qsUnescape } = require('node:querystring') + +/** + * @description Parses the field-value attributes of a set-cookie header string. + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} header + * @returns {import('./index').Cookie|null} if the header is invalid, null will be returned + */ +function parseSetCookie (header) { + // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F + // character (CTL characters excluding HTAB): Abort these steps and + // ignore the set-cookie-string entirely. + if (isCTLExcludingHtab(header)) { + return null + } + + let nameValuePair = '' + let unparsedAttributes = '' + let name = '' + let value = '' + + // 2. If the set-cookie-string contains a %x3B (";") character: + if (header.includes(';')) { + // 1. The name-value-pair string consists of the characters up to, + // but not including, the first %x3B (";"), and the unparsed- + // attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question). + const position = { position: 0 } + + nameValuePair = collectASequenceOfCodePointsFast(';', header, position) + unparsedAttributes = header.slice(position.position) + } else { + // Otherwise: + + // 1. The name-value-pair string consists of all the characters + // contained in the set-cookie-string, and the unparsed- + // attributes is the empty string. + nameValuePair = header + } + + // 3. If the name-value-pair string lacks a %x3D ("=") character, then + // the name string is empty, and the value string is the value of + // name-value-pair. + if (!nameValuePair.includes('=')) { + value = nameValuePair + } else { + // Otherwise, the name string consists of the characters up to, but + // not including, the first %x3D ("=") character, and the (possibly + // empty) value string consists of the characters after the first + // %x3D ("=") character. + const position = { position: 0 } + name = collectASequenceOfCodePointsFast( + '=', + nameValuePair, + position + ) + value = nameValuePair.slice(position.position + 1) + } + + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim() + value = value.trim() + + // 5. If the sum of the lengths of the name string and the value string + // is more than 4096 octets, abort these steps and ignore the set- + // cookie-string entirely. + if (name.length + value.length > maxNameValuePairSize) { + return null + } + + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + // https://datatracker.ietf.org/doc/html/rfc6265 + // To maximize compatibility with user agents, servers that wish to + // store arbitrary data in a cookie-value SHOULD encode that data, for + // example, using Base64 [RFC4648]. + return { + name, value: qsUnescape(value), ...parseUnparsedAttributes(unparsedAttributes) + } +} + +/** + * Parses the remaining attributes of a set-cookie header + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} unparsedAttributes + * @param {Object.} [cookieAttributeList={}] + */ +function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { + // 1. If the unparsed-attributes string is empty, skip the rest of + // these steps. + if (unparsedAttributes.length === 0) { + return cookieAttributeList + } + + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';') + unparsedAttributes = unparsedAttributes.slice(1) + + let cookieAv = '' + + // 3. If the remaining unparsed-attributes contains a %x3B (";") + // character: + if (unparsedAttributes.includes(';')) { + // 1. Consume the characters of the unparsed-attributes up to, but + // not including, the first %x3B (";") character. + cookieAv = collectASequenceOfCodePointsFast( + ';', + unparsedAttributes, + { position: 0 } + ) + unparsedAttributes = unparsedAttributes.slice(cookieAv.length) + } else { + // Otherwise: + + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes + unparsedAttributes = '' + } + + // Let the cookie-av string be the characters consumed in this step. + + let attributeName = '' + let attributeValue = '' + + // 4. If the cookie-av string contains a %x3D ("=") character: + if (cookieAv.includes('=')) { + // 1. The (possibly empty) attribute-name string consists of the + // characters up to, but not including, the first %x3D ("=") + // character, and the (possibly empty) attribute-value string + // consists of the characters after the first %x3D ("=") + // character. + const position = { position: 0 } + + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ) + attributeValue = cookieAv.slice(position.position + 1) + } else { + // Otherwise: + + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv + } + + // 5. Remove any leading or trailing WSP characters from the attribute- + // name string and the attribute-value string. + attributeName = attributeName.trim() + attributeValue = attributeValue.trim() + + // 6. If the attribute-value is longer than 1024 octets, ignore the + // cookie-av string and return to Step 1 of this algorithm. + if (attributeValue.length > maxAttributeValueSize) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 7. Process the attribute-name and attribute-value according to the + // requirements in the following subsections. (Notice that + // attributes with unrecognized attribute-names are ignored.) + const attributeNameLowercase = attributeName.toLowerCase() + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 + // If the attribute-name case-insensitively matches the string + // "Expires", the user agent MUST process the cookie-av as follows. + if (attributeNameLowercase === 'expires') { + // 1. Let the expiry-time be the result of parsing the attribute-value + // as cookie-date (see Section 5.1.1). + const expiryTime = new Date(attributeValue) + + // 2. If the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. + + cookieAttributeList.expires = expiryTime + } else if (attributeNameLowercase === 'max-age') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 + // If the attribute-name case-insensitively matches the string "Max- + // Age", the user agent MUST process the cookie-av as follows. + + // 1. If the first character of the attribute-value is not a DIGIT or a + // "-" character, ignore the cookie-av. + const charCode = attributeValue.charCodeAt(0) + + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue) + + // 4. Let cookie-age-limit be the maximum age of the cookie (which + // SHOULD be 400 days or less, see Section 4.1.2.2). + + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + + // 6. If delta-seconds is less than or equal to zero (0), let expiry- + // time be the earliest representable date and time. Otherwise, let + // the expiry-time be the current date and time plus delta-seconds + // seconds. + // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds + + // 7. Append an attribute to the cookie-attribute-list with an + // attribute-name of Max-Age and an attribute-value of expiry-time. + cookieAttributeList.maxAge = deltaSeconds + } else if (attributeNameLowercase === 'domain') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 + // If the attribute-name case-insensitively matches the string "Domain", + // the user agent MUST process the cookie-av as follows. + + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue + + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1) + } + + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase() + + // 4. Append an attribute to the cookie-attribute-list with an + // attribute-name of Domain and an attribute-value of cookie-domain. + cookieAttributeList.domain = cookieDomain + } else if (attributeNameLowercase === 'path') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 + // If the attribute-name case-insensitively matches the string "Path", + // the user agent MUST process the cookie-av as follows. + + // 1. If the attribute-value is empty or if the first character of the + // attribute-value is not %x2F ("/"): + let cookiePath = '' + if (attributeValue.length === 0 || attributeValue[0] !== '/') { + // 1. Let cookie-path be the default-path. + cookiePath = '/' + } else { + // Otherwise: + + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue + } + + // 2. Append an attribute to the cookie-attribute-list with an + // attribute-name of Path and an attribute-value of cookie-path. + cookieAttributeList.path = cookiePath + } else if (attributeNameLowercase === 'secure') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 + // If the attribute-name case-insensitively matches the string "Secure", + // the user agent MUST append an attribute to the cookie-attribute-list + // with an attribute-name of Secure and an empty attribute-value. + + cookieAttributeList.secure = true + } else if (attributeNameLowercase === 'httponly') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 + // If the attribute-name case-insensitively matches the string + // "HttpOnly", the user agent MUST append an attribute to the cookie- + // attribute-list with an attribute-name of HttpOnly and an empty + // attribute-value. + + cookieAttributeList.httpOnly = true + } else if (attributeNameLowercase === 'samesite') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 + // If the attribute-name case-insensitively matches the string + // "SameSite", the user agent MUST process the cookie-av as follows: + + // 1. Let enforcement be "Default". + let enforcement = 'Default' + + const attributeValueLowercase = attributeValue.toLowerCase() + // 2. If cookie-av's attribute-value is a case-insensitive match for + // "None", set enforcement to "None". + if (attributeValueLowercase.includes('none')) { + enforcement = 'None' + } + + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict' + } + + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax' + } + + // 5. Append an attribute to the cookie-attribute-list with an + // attribute-name of "SameSite" and an attribute-value of + // enforcement. + cookieAttributeList.sameSite = enforcement + } else { + cookieAttributeList.unparsed ??= [] + + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) + } + + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) +} + +module.exports = { + parseSetCookie, + parseUnparsedAttributes +} diff --git a/node_modules/undici/lib/web/cookies/util.js b/node_modules/undici/lib/web/cookies/util.js new file mode 100644 index 000000000..254f5419e --- /dev/null +++ b/node_modules/undici/lib/web/cookies/util.js @@ -0,0 +1,282 @@ +'use strict' + +/** + * @param {string} value + * @returns {boolean} + */ +function isCTLExcludingHtab (value) { + for (let i = 0; i < value.length; ++i) { + const code = value.charCodeAt(i) + + if ( + (code >= 0x00 && code <= 0x08) || + (code >= 0x0A && code <= 0x1F) || + code === 0x7F + ) { + return true + } + } + return false +} + +/** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ +function validateCookieName (name) { + for (let i = 0; i < name.length; ++i) { + const code = name.charCodeAt(i) + + if ( + code < 0x21 || // exclude CTLs (0-31), SP and HT + code > 0x7E || // exclude non-ascii and DEL + code === 0x22 || // " + code === 0x28 || // ( + code === 0x29 || // ) + code === 0x3C || // < + code === 0x3E || // > + code === 0x40 || // @ + code === 0x2C || // , + code === 0x3B || // ; + code === 0x3A || // : + code === 0x5C || // \ + code === 0x2F || // / + code === 0x5B || // [ + code === 0x5D || // ] + code === 0x3F || // ? + code === 0x3D || // = + code === 0x7B || // { + code === 0x7D // } + ) { + throw new Error('Invalid cookie name') + } + } +} + +/** + cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + ; US-ASCII characters excluding CTLs, + ; whitespace DQUOTE, comma, semicolon, + ; and backslash + * @param {string} value + */ +function validateCookieValue (value) { + let len = value.length + let i = 0 + + // if the value is wrapped in DQUOTE + if (value[0] === '"') { + if (len === 1 || value[len - 1] !== '"') { + throw new Error('Invalid cookie value') + } + --len + ++i + } + + while (i < len) { + const code = value.charCodeAt(i++) + + if ( + code < 0x21 || // exclude CTLs (0-31) + code > 0x7E || // non-ascii and DEL (127) + code === 0x22 || // " + code === 0x2C || // , + code === 0x3B || // ; + code === 0x5C // \ + ) { + throw new Error('Invalid cookie value') + } + } +} + +/** + * path-value = + * @param {string} path + */ +function validateCookiePath (path) { + for (let i = 0; i < path.length; ++i) { + const code = path.charCodeAt(i) + + if ( + code < 0x20 || // exclude CTLs (0-31) + code === 0x7F || // DEL + code === 0x3B // ; + ) { + throw new Error('Invalid cookie path') + } + } +} + +/** + * I have no idea why these values aren't allowed to be honest, + * but Deno tests these. - Khafra + * @param {string} domain + */ +function validateCookieDomain (domain) { + if ( + domain.startsWith('-') || + domain.endsWith('.') || + domain.endsWith('-') + ) { + throw new Error('Invalid cookie domain') + } +} + +const IMFDays = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' +] + +const IMFMonths = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' +] + +const IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, '0')) + +/** + * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 + * @param {number|Date} date + IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + ; fixed length/zone/capitalization subset of the format + ; see Section 3.3 of [RFC5322] + + day-name = %x4D.6F.6E ; "Mon", case-sensitive + / %x54.75.65 ; "Tue", case-sensitive + / %x57.65.64 ; "Wed", case-sensitive + / %x54.68.75 ; "Thu", case-sensitive + / %x46.72.69 ; "Fri", case-sensitive + / %x53.61.74 ; "Sat", case-sensitive + / %x53.75.6E ; "Sun", case-sensitive + date1 = day SP month SP year + ; e.g., 02 Jun 1982 + + day = 2DIGIT + month = %x4A.61.6E ; "Jan", case-sensitive + / %x46.65.62 ; "Feb", case-sensitive + / %x4D.61.72 ; "Mar", case-sensitive + / %x41.70.72 ; "Apr", case-sensitive + / %x4D.61.79 ; "May", case-sensitive + / %x4A.75.6E ; "Jun", case-sensitive + / %x4A.75.6C ; "Jul", case-sensitive + / %x41.75.67 ; "Aug", case-sensitive + / %x53.65.70 ; "Sep", case-sensitive + / %x4F.63.74 ; "Oct", case-sensitive + / %x4E.6F.76 ; "Nov", case-sensitive + / %x44.65.63 ; "Dec", case-sensitive + year = 4DIGIT + + GMT = %x47.4D.54 ; "GMT", case-sensitive + + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) + + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ +function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date) + } + + return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT` +} + +/** + max-age-av = "Max-Age=" non-zero-digit *DIGIT + ; In practice, both expires-av and max-age-av + ; are limited to dates representable by the + ; user agent. + * @param {number} maxAge + */ +function validateCookieMaxAge (maxAge) { + if (maxAge < 0) { + throw new Error('Invalid cookie max-age') + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 + * @param {import('./index').Cookie} cookie + */ +function stringify (cookie) { + if (cookie.name.length === 0) { + return null + } + + validateCookieName(cookie.name) + validateCookieValue(cookie.value) + + const out = [`${cookie.name}=${cookie.value}`] + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 + if (cookie.name.startsWith('__Secure-')) { + cookie.secure = true + } + + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true + cookie.domain = null + cookie.path = '/' + } + + if (cookie.secure) { + out.push('Secure') + } + + if (cookie.httpOnly) { + out.push('HttpOnly') + } + + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge) + out.push(`Max-Age=${cookie.maxAge}`) + } + + if (cookie.domain) { + validateCookieDomain(cookie.domain) + out.push(`Domain=${cookie.domain}`) + } + + if (cookie.path) { + validateCookiePath(cookie.path) + out.push(`Path=${cookie.path}`) + } + + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`) + } + + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`) + } + + for (const part of cookie.unparsed) { + if (!part.includes('=')) { + throw new Error('Invalid unparsed') + } + + const [key, ...value] = part.split('=') + + out.push(`${key.trim()}=${value.join('=')}`) + } + + return out.join('; ') +} + +module.exports = { + isCTLExcludingHtab, + validateCookieName, + validateCookiePath, + validateCookieValue, + toIMFDate, + stringify +} diff --git a/node_modules/undici/lib/web/eventsource/eventsource-stream.js b/node_modules/undici/lib/web/eventsource/eventsource-stream.js new file mode 100644 index 000000000..d24e8f6a1 --- /dev/null +++ b/node_modules/undici/lib/web/eventsource/eventsource-stream.js @@ -0,0 +1,399 @@ +'use strict' +const { Transform } = require('node:stream') +const { isASCIINumber, isValidLastEventId } = require('./util') + +/** + * @type {number[]} BOM + */ +const BOM = [0xEF, 0xBB, 0xBF] +/** + * @type {10} LF + */ +const LF = 0x0A +/** + * @type {13} CR + */ +const CR = 0x0D +/** + * @type {58} COLON + */ +const COLON = 0x3A +/** + * @type {32} SPACE + */ +const SPACE = 0x20 + +/** + * @typedef {object} EventSourceStreamEvent + * @type {object} + * @property {string} [event] The event type. + * @property {string} [data] The data of the message. + * @property {string} [id] A unique ID for the event. + * @property {string} [retry] The reconnection time, in milliseconds. + */ + +/** + * @typedef eventSourceSettings + * @type {object} + * @property {string} [lastEventId] The last event ID received from the server. + * @property {string} [origin] The origin of the event source. + * @property {number} [reconnectionTime] The reconnection time, in milliseconds. + */ + +class EventSourceStream extends Transform { + /** + * @type {eventSourceSettings} + */ + state + + /** + * Leading byte-order-mark check. + * @type {boolean} + */ + checkBOM = true + + /** + * @type {boolean} + */ + crlfCheck = false + + /** + * @type {boolean} + */ + eventEndCheck = false + + /** + * @type {Buffer|null} + */ + buffer = null + + pos = 0 + + event = { + data: undefined, + event: undefined, + id: undefined, + retry: undefined + } + + /** + * @param {object} options + * @param {boolean} [options.readableObjectMode] + * @param {eventSourceSettings} [options.eventSourceSettings] + * @param {(chunk: any, encoding?: BufferEncoding | undefined) => boolean} [options.push] + */ + constructor (options = {}) { + // Enable object mode as EventSourceStream emits objects of shape + // EventSourceStreamEvent + options.readableObjectMode = true + + super(options) + + this.state = options.eventSourceSettings || {} + if (options.push) { + this.push = options.push + } + } + + /** + * @param {Buffer} chunk + * @param {string} _encoding + * @param {Function} callback + * @returns {void} + */ + _transform (chunk, _encoding, callback) { + if (chunk.length === 0) { + callback() + return + } + + // Cache the chunk in the buffer, as the data might not be complete while + // processing it + // TODO: Investigate if there is a more performant way to handle + // incoming chunks + // see: https://github.com/nodejs/undici/issues/2630 + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]) + } else { + this.buffer = chunk + } + + // Strip leading byte-order-mark if we opened the stream and started + // the processing of the incoming data + if (this.checkBOM) { + switch (this.buffer.length) { + case 1: + // Check if the first byte is the same as the first byte of the BOM + if (this.buffer[0] === BOM[0]) { + // If it is, we need to wait for more data + callback() + return + } + // Set the checkBOM flag to false as we don't need to check for the + // BOM anymore + this.checkBOM = false + + // The buffer only contains one byte so we need to wait for more data + callback() + return + case 2: + // Check if the first two bytes are the same as the first two bytes + // of the BOM + if ( + this.buffer[0] === BOM[0] && + this.buffer[1] === BOM[1] + ) { + // If it is, we need to wait for more data, because the third byte + // is needed to determine if it is the BOM or not + callback() + return + } + + // Set the checkBOM flag to false as we don't need to check for the + // BOM anymore + this.checkBOM = false + break + case 3: + // Check if the first three bytes are the same as the first three + // bytes of the BOM + if ( + this.buffer[0] === BOM[0] && + this.buffer[1] === BOM[1] && + this.buffer[2] === BOM[2] + ) { + // If it is, we can drop the buffered data, as it is only the BOM + this.buffer = Buffer.alloc(0) + // Set the checkBOM flag to false as we don't need to check for the + // BOM anymore + this.checkBOM = false + + // Await more data + callback() + return + } + // If it is not the BOM, we can start processing the data + this.checkBOM = false + break + default: + // The buffer is longer than 3 bytes, so we can drop the BOM if it is + // present + if ( + this.buffer[0] === BOM[0] && + this.buffer[1] === BOM[1] && + this.buffer[2] === BOM[2] + ) { + // Remove the BOM from the buffer + this.buffer = this.buffer.subarray(3) + } + + // Set the checkBOM flag to false as we don't need to check for the + this.checkBOM = false + break + } + } + + while (this.pos < this.buffer.length) { + // If the previous line ended with an end-of-line, we need to check + // if the next character is also an end-of-line. + if (this.eventEndCheck) { + // If the the current character is an end-of-line, then the event + // is finished and we can process it + + // If the previous line ended with a carriage return, we need to + // check if the current character is a line feed and remove it + // from the buffer. + if (this.crlfCheck) { + // If the current character is a line feed, we can remove it + // from the buffer and reset the crlfCheck flag + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1) + this.pos = 0 + this.crlfCheck = false + + // It is possible that the line feed is not the end of the + // event. We need to check if the next character is an + // end-of-line character to determine if the event is + // finished. We simply continue the loop to check the next + // character. + + // As we removed the line feed from the buffer and set the + // crlfCheck flag to false, we basically don't make any + // distinction between a line feed and a carriage return. + continue + } + this.crlfCheck = false + } + + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + // If the current character is a carriage return, we need to + // set the crlfCheck flag to true, as we need to check if the + // next character is a line feed so we can remove it from the + // buffer + if (this.buffer[this.pos] === CR) { + this.crlfCheck = true + } + + this.buffer = this.buffer.subarray(this.pos + 1) + this.pos = 0 + if ( + this.event.data !== undefined || this.event.event || this.event.id !== undefined || this.event.retry) { + this.processEvent(this.event) + } + this.clearEvent() + continue + } + // If the current character is not an end-of-line, then the event + // is not finished and we have to reset the eventEndCheck flag + this.eventEndCheck = false + continue + } + + // If the current character is an end-of-line, we can process the + // line + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + // If the current character is a carriage return, we need to + // set the crlfCheck flag to true, as we need to check if the + // next character is a line feed + if (this.buffer[this.pos] === CR) { + this.crlfCheck = true + } + + // In any case, we can process the line as we reached an + // end-of-line character + this.parseLine(this.buffer.subarray(0, this.pos), this.event) + + // Remove the processed line from the buffer + this.buffer = this.buffer.subarray(this.pos + 1) + // Reset the position as we removed the processed line from the buffer + this.pos = 0 + // A line was processed and this could be the end of the event. We need + // to check if the next line is empty to determine if the event is + // finished. + this.eventEndCheck = true + continue + } + + this.pos++ + } + + callback() + } + + /** + * @param {Buffer} line + * @param {EventSourceStreamEvent} event + */ + parseLine (line, event) { + // If the line is empty (a blank line) + // Dispatch the event, as defined below. + // This will be handled in the _transform method + if (line.length === 0) { + return + } + + // If the line starts with a U+003A COLON character (:) + // Ignore the line. + const colonPosition = line.indexOf(COLON) + if (colonPosition === 0) { + return + } + + let field = '' + let value = '' + + // If the line contains a U+003A COLON character (:) + if (colonPosition !== -1) { + // Collect the characters on the line before the first U+003A COLON + // character (:), and let field be that string. + // TODO: Investigate if there is a more performant way to extract the + // field + // see: https://github.com/nodejs/undici/issues/2630 + field = line.subarray(0, colonPosition).toString('utf8') + + // Collect the characters on the line after the first U+003A COLON + // character (:), and let value be that string. + // If value starts with a U+0020 SPACE character, remove it from value. + let valueStart = colonPosition + 1 + if (line[valueStart] === SPACE) { + ++valueStart + } + // TODO: Investigate if there is a more performant way to extract the + // value + // see: https://github.com/nodejs/undici/issues/2630 + value = line.subarray(valueStart).toString('utf8') + + // Otherwise, the string is not empty but does not contain a U+003A COLON + // character (:) + } else { + // Process the field using the steps described below, using the whole + // line as the field name, and the empty string as the field value. + field = line.toString('utf8') + value = '' + } + + // Modify the event with the field name and value. The value is also + // decoded as UTF-8 + switch (field) { + case 'data': + if (event[field] === undefined) { + event[field] = value + } else { + event[field] += `\n${value}` + } + break + case 'retry': + if (isASCIINumber(value)) { + event[field] = value + } + break + case 'id': + if (isValidLastEventId(value)) { + event[field] = value + } + break + case 'event': + if (value.length > 0) { + event[field] = value + } + break + } + } + + /** + * @param {EventSourceStreamEvent} event + */ + processEvent (event) { + if (event.retry && isASCIINumber(event.retry)) { + this.state.reconnectionTime = parseInt(event.retry, 10) + } + + if (event.id !== undefined && isValidLastEventId(event.id)) { + this.state.lastEventId = event.id + } + + // only dispatch event, when data is provided + if (event.data !== undefined) { + this.push({ + type: event.event || 'message', + options: { + data: event.data, + lastEventId: this.state.lastEventId, + origin: this.state.origin + } + }) + } + } + + clearEvent () { + this.event = { + data: undefined, + event: undefined, + id: undefined, + retry: undefined + } + } +} + +module.exports = { + EventSourceStream +} diff --git a/node_modules/undici/lib/web/eventsource/eventsource.js b/node_modules/undici/lib/web/eventsource/eventsource.js new file mode 100644 index 000000000..32dcf0e42 --- /dev/null +++ b/node_modules/undici/lib/web/eventsource/eventsource.js @@ -0,0 +1,501 @@ +'use strict' + +const { pipeline } = require('node:stream') +const { fetching } = require('../fetch') +const { makeRequest } = require('../fetch/request') +const { webidl } = require('../webidl') +const { EventSourceStream } = require('./eventsource-stream') +const { parseMIMEType } = require('../fetch/data-url') +const { createFastMessageEvent } = require('../websocket/events') +const { isNetworkError } = require('../fetch/response') +const { kEnumerableProperty } = require('../../core/util') +const { environmentSettingsObject } = require('../fetch/util') + +let experimentalWarned = false + +/** + * A reconnection time, in milliseconds. This must initially be an implementation-defined value, + * probably in the region of a few seconds. + * + * In Comparison: + * - Chrome uses 3000ms. + * - Deno uses 5000ms. + * + * @type {3000} + */ +const defaultReconnectionTime = 3000 + +/** + * The readyState attribute represents the state of the connection. + * @typedef ReadyState + * @type {0|1|2} + * @readonly + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev + */ + +/** + * The connection has not yet been established, or it was closed and the user + * agent is reconnecting. + * @type {0} + */ +const CONNECTING = 0 + +/** + * The user agent has an open connection and is dispatching events as it + * receives them. + * @type {1} + */ +const OPEN = 1 + +/** + * The connection is not open, and the user agent is not trying to reconnect. + * @type {2} + */ +const CLOSED = 2 + +/** + * Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin". + * @type {'anonymous'} + */ +const ANONYMOUS = 'anonymous' + +/** + * Requests for the element will have their mode set to "cors" and their credentials mode set to "include". + * @type {'use-credentials'} + */ +const USE_CREDENTIALS = 'use-credentials' + +/** + * The EventSource interface is used to receive server-sent events. It + * connects to a server over HTTP and receives events in text/event-stream + * format without closing the connection. + * @extends {EventTarget} + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events + * @api public + */ +class EventSource extends EventTarget { + #events = { + open: null, + error: null, + message: null + } + + #url + #withCredentials = false + + /** + * @type {ReadyState} + */ + #readyState = CONNECTING + + #request = null + #controller = null + + #dispatcher + + /** + * @type {import('./eventsource-stream').eventSourceSettings} + */ + #state + + /** + * Creates a new EventSource object. + * @param {string} url + * @param {EventSourceInit} [eventSourceInitDict={}] + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface + */ + constructor (url, eventSourceInitDict = {}) { + // 1. Let ev be a new EventSource object. + super() + + webidl.util.markAsUncloneable(this) + + const prefix = 'EventSource constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + if (!experimentalWarned) { + experimentalWarned = true + process.emitWarning('EventSource is experimental, expect them to change at any time.', { + code: 'UNDICI-ES' + }) + } + + url = webidl.converters.USVString(url) + eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, 'eventSourceInitDict') + + this.#dispatcher = eventSourceInitDict.node.dispatcher || eventSourceInitDict.dispatcher + this.#state = { + lastEventId: '', + reconnectionTime: eventSourceInitDict.node.reconnectionTime + } + + // 2. Let settings be ev's relevant settings object. + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + const settings = environmentSettingsObject + + let urlRecord + + try { + // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings. + urlRecord = new URL(url, settings.settingsObject.baseUrl) + this.#state.origin = urlRecord.origin + } catch (e) { + // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 5. Set ev's url to urlRecord. + this.#url = urlRecord.href + + // 6. Let corsAttributeState be Anonymous. + let corsAttributeState = ANONYMOUS + + // 7. If the value of eventSourceInitDict's withCredentials member is true, + // then set corsAttributeState to Use Credentials and set ev's + // withCredentials attribute to true. + if (eventSourceInitDict.withCredentials === true) { + corsAttributeState = USE_CREDENTIALS + this.#withCredentials = true + } + + // 8. Let request be the result of creating a potential-CORS request given + // urlRecord, the empty string, and corsAttributeState. + const initRequest = { + redirect: 'follow', + keepalive: true, + // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes + mode: 'cors', + credentials: corsAttributeState === 'anonymous' + ? 'same-origin' + : 'omit', + referrer: 'no-referrer' + } + + // 9. Set request's client to settings. + initRequest.client = environmentSettingsObject.settingsObject + + // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list. + initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]] + + // 11. Set request's cache mode to "no-store". + initRequest.cache = 'no-store' + + // 12. Set request's initiator type to "other". + initRequest.initiator = 'other' + + initRequest.urlList = [new URL(this.#url)] + + // 13. Set ev's request to request. + this.#request = makeRequest(initRequest) + + this.#connect() + } + + /** + * Returns the state of this EventSource object's connection. It can have the + * values described below. + * @returns {ReadyState} + * @readonly + */ + get readyState () { + return this.#readyState + } + + /** + * Returns the URL providing the event stream. + * @readonly + * @returns {string} + */ + get url () { + return this.#url + } + + /** + * Returns a boolean indicating whether the EventSource object was + * instantiated with CORS credentials set (true), or not (false, the default). + */ + get withCredentials () { + return this.#withCredentials + } + + #connect () { + if (this.#readyState === CLOSED) return + + this.#readyState = CONNECTING + + const fetchParams = { + request: this.#request, + dispatcher: this.#dispatcher + } + + // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection. + const processEventSourceEndOfBody = (response) => { + if (!isNetworkError(response)) { + return this.#reconnect() + } + } + + // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody... + fetchParams.processResponseEndOfBody = processEventSourceEndOfBody + + // and processResponse set to the following steps given response res: + fetchParams.processResponse = (response) => { + // 1. If res is an aborted network error, then fail the connection. + + if (isNetworkError(response)) { + // 1. When a user agent is to fail the connection, the user agent + // must queue a task which, if the readyState attribute is set to a + // value other than CLOSED, sets the readyState attribute to CLOSED + // and fires an event named error at the EventSource object. Once the + // user agent has failed the connection, it does not attempt to + // reconnect. + if (response.aborted) { + this.close() + this.dispatchEvent(new Event('error')) + return + // 2. Otherwise, if res is a network error, then reestablish the + // connection, unless the user agent knows that to be futile, in + // which case the user agent may fail the connection. + } else { + this.#reconnect() + return + } + } + + // 3. Otherwise, if res's status is not 200, or if res's `Content-Type` + // is not `text/event-stream`, then fail the connection. + const contentType = response.headersList.get('content-type', true) + const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure' + const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream' + if ( + response.status !== 200 || + contentTypeValid === false + ) { + this.close() + this.dispatchEvent(new Event('error')) + return + } + + // 4. Otherwise, announce the connection and interpret res's body + // line by line. + + // When a user agent is to announce the connection, the user agent + // must queue a task which, if the readyState attribute is set to a + // value other than CLOSED, sets the readyState attribute to OPEN + // and fires an event named open at the EventSource object. + // @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model + this.#readyState = OPEN + this.dispatchEvent(new Event('open')) + + // If redirected to a different origin, set the origin to the new origin. + this.#state.origin = response.urlList[response.urlList.length - 1].origin + + const eventSourceStream = new EventSourceStream({ + eventSourceSettings: this.#state, + push: (event) => { + this.dispatchEvent(createFastMessageEvent( + event.type, + event.options + )) + } + }) + + pipeline(response.body.stream, + eventSourceStream, + (error) => { + if ( + error?.aborted === false + ) { + this.close() + this.dispatchEvent(new Event('error')) + } + }) + } + + this.#controller = fetching(fetchParams) + } + + /** + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model + * @returns {void} + */ + #reconnect () { + // When a user agent is to reestablish the connection, the user agent must + // run the following steps. These steps are run in parallel, not as part of + // a task. (The tasks that it queues, of course, are run like normal tasks + // and not themselves in parallel.) + + // 1. Queue a task to run the following steps: + + // 1. If the readyState attribute is set to CLOSED, abort the task. + if (this.#readyState === CLOSED) return + + // 2. Set the readyState attribute to CONNECTING. + this.#readyState = CONNECTING + + // 3. Fire an event named error at the EventSource object. + this.dispatchEvent(new Event('error')) + + // 2. Wait a delay equal to the reconnection time of the event source. + setTimeout(() => { + // 5. Queue a task to run the following steps: + + // 1. If the EventSource object's readyState attribute is not set to + // CONNECTING, then return. + if (this.#readyState !== CONNECTING) return + + // 2. Let request be the EventSource object's request. + // 3. If the EventSource object's last event ID string is not the empty + // string, then: + // 1. Let lastEventIDValue be the EventSource object's last event ID + // string, encoded as UTF-8. + // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header + // list. + if (this.#state.lastEventId.length) { + this.#request.headersList.set('last-event-id', this.#state.lastEventId, true) + } + + // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section. + this.#connect() + }, this.#state.reconnectionTime)?.unref() + } + + /** + * Closes the connection, if any, and sets the readyState attribute to + * CLOSED. + */ + close () { + webidl.brandCheck(this, EventSource) + + if (this.#readyState === CLOSED) return + this.#readyState = CLOSED + this.#controller.abort() + this.#request = null + } + + get onopen () { + return this.#events.open + } + + set onopen (fn) { + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) + } + + const listener = webidl.converters.EventHandlerNonNull(fn) + + if (listener !== null) { + this.addEventListener('open', listener) + this.#events.open = fn + } else { + this.#events.open = null + } + } + + get onmessage () { + return this.#events.message + } + + set onmessage (fn) { + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } + + const listener = webidl.converters.EventHandlerNonNull(fn) + + if (listener !== null) { + this.addEventListener('message', listener) + this.#events.message = fn + } else { + this.#events.message = null + } + } + + get onerror () { + return this.#events.error + } + + set onerror (fn) { + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) + } + + const listener = webidl.converters.EventHandlerNonNull(fn) + + if (listener !== null) { + this.addEventListener('error', listener) + this.#events.error = fn + } else { + this.#events.error = null + } + } +} + +const constantsPropertyDescriptors = { + CONNECTING: { + __proto__: null, + configurable: false, + enumerable: true, + value: CONNECTING, + writable: false + }, + OPEN: { + __proto__: null, + configurable: false, + enumerable: true, + value: OPEN, + writable: false + }, + CLOSED: { + __proto__: null, + configurable: false, + enumerable: true, + value: CLOSED, + writable: false + } +} + +Object.defineProperties(EventSource, constantsPropertyDescriptors) +Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors) + +Object.defineProperties(EventSource.prototype, { + close: kEnumerableProperty, + onerror: kEnumerableProperty, + onmessage: kEnumerableProperty, + onopen: kEnumerableProperty, + readyState: kEnumerableProperty, + url: kEnumerableProperty, + withCredentials: kEnumerableProperty +}) + +webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([ + { + key: 'withCredentials', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'dispatcher', // undici only + converter: webidl.converters.any + }, + { + key: 'node', // undici only + converter: webidl.dictionaryConverter([ + { + key: 'reconnectionTime', + converter: webidl.converters['unsigned long'], + defaultValue: () => defaultReconnectionTime + }, + { + key: 'dispatcher', + converter: webidl.converters.any + } + ]), + defaultValue: () => ({}) + } +]) + +module.exports = { + EventSource, + defaultReconnectionTime +} diff --git a/node_modules/undici/lib/web/eventsource/util.js b/node_modules/undici/lib/web/eventsource/util.js new file mode 100644 index 000000000..a87cc834e --- /dev/null +++ b/node_modules/undici/lib/web/eventsource/util.js @@ -0,0 +1,29 @@ +'use strict' + +/** + * Checks if the given value is a valid LastEventId. + * @param {string} value + * @returns {boolean} + */ +function isValidLastEventId (value) { + // LastEventId should not contain U+0000 NULL + return value.indexOf('\u0000') === -1 +} + +/** + * Checks if the given value is a base 10 digit. + * @param {string} value + * @returns {boolean} + */ +function isASCIINumber (value) { + if (value.length === 0) return false + for (let i = 0; i < value.length; i++) { + if (value.charCodeAt(i) < 0x30 || value.charCodeAt(i) > 0x39) return false + } + return true +} + +module.exports = { + isValidLastEventId, + isASCIINumber +} diff --git a/node_modules/undici/lib/web/fetch/LICENSE b/node_modules/undici/lib/web/fetch/LICENSE new file mode 100644 index 000000000..294350045 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Ethan Arrowood + +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/undici/lib/web/fetch/body.js b/node_modules/undici/lib/web/fetch/body.js new file mode 100644 index 000000000..619bc783a --- /dev/null +++ b/node_modules/undici/lib/web/fetch/body.js @@ -0,0 +1,527 @@ +'use strict' + +const util = require('../../core/util') +const { + ReadableStreamFrom, + readableStreamClose, + fullyReadBody, + extractMimeType +} = require('./util') +const { FormData, setFormDataState } = require('./formdata') +const { webidl } = require('../webidl') +const assert = require('node:assert') +const { isErrored, isDisturbed } = require('node:stream') +const { isArrayBuffer } = require('node:util/types') +const { serializeAMimeType } = require('./data-url') +const { multipartFormDataParser } = require('./formdata-parser') +const { createDeferredPromise } = require('../../util/promise') +const { parseJSONFromBytes } = require('../infra') +const { utf8DecodeBytes } = require('../../encoding') +const { runtimeFeatures } = require('../../util/runtime-features.js') + +const random = runtimeFeatures.has('crypto') + ? require('node:crypto').randomInt + : (max) => Math.floor(Math.random() * max) + +const textEncoder = new TextEncoder() +function noop () {} + +const streamRegistry = new FinalizationRegistry((weakRef) => { + const stream = weakRef.deref() + if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) { + stream.cancel('Response object has been garbage collected').catch(noop) + } +}) + +/** + * Extract a body with type from a byte sequence or BodyInit object + * + * @param {import('../../../types').BodyInit} object - The BodyInit object to extract from + * @param {boolean} [keepalive=false] - If true, indicates that the body + * @returns {[{stream: ReadableStream, source: any, length: number | null}, string | null]} - Returns a tuple containing the body and its type + * + * @see https://fetch.spec.whatwg.org/#concept-bodyinit-extract + */ +function extractBody (object, keepalive = false) { + // 1. Let stream be null. + let stream = null + + // 2. If object is a ReadableStream object, then set stream to object. + if (webidl.is.ReadableStream(object)) { + stream = object + } else if (webidl.is.Blob(object)) { + // 3. Otherwise, if object is a Blob object, set stream to the + // result of running object’s get stream. + stream = object.stream() + } else { + // 4. Otherwise, set stream to a new ReadableStream object, and set + // up stream with byte reading support. + stream = new ReadableStream({ + pull (controller) { + const buffer = typeof source === 'string' ? textEncoder.encode(source) : source + + if (buffer.byteLength) { + controller.enqueue(buffer) + } + + queueMicrotask(() => readableStreamClose(controller)) + }, + start () {}, + type: 'bytes' + }) + } + + // 5. Assert: stream is a ReadableStream object. + assert(webidl.is.ReadableStream(stream)) + + // 6. Let action be null. + let action = null + + // 7. Let source be null. + let source = null + + // 8. Let length be null. + let length = null + + // 9. Let type be null. + let type = null + + // 10. Switch on object: + if (typeof object === 'string') { + // Set source to the UTF-8 encoding of object. + // Note: setting source to a Uint8Array here breaks some mocking assumptions. + source = object + + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8' + } else if (webidl.is.URLSearchParams(object)) { + // URLSearchParams + + // spec says to run application/x-www-form-urlencoded on body.list + // this is implemented in Node.js as apart of an URLSearchParams instance toString method + // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 + // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 + + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString() + + // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. + type = 'application/x-www-form-urlencoded;charset=UTF-8' + } else if (webidl.is.BufferSource(object)) { + source = isArrayBuffer(object) + ? new Uint8Array(object.slice()) + : new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) + } else if (webidl.is.FormData(object)) { + const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` + const prefix = `--${boundary}\r\nContent-Disposition: form-data` + + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + const formdataEscape = (str) => + str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') + const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') + + // Set action to this step: run the multipart/form-data + // encoding algorithm, with object’s entry list and UTF-8. + // - This ensures that the body is immutable and can't be changed afterwords + // - That the content-length is calculated in advance. + // - And that all parts are pre-encoded and ready to be sent. + + const blobParts = [] + const rn = new Uint8Array([13, 10]) // '\r\n' + length = 0 + let hasUnknownSizeValue = false + + for (const [name, value] of object) { + if (typeof value === 'string') { + const chunk = textEncoder.encode(prefix + + `; name="${formdataEscape(normalizeLinefeeds(name))}"` + + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) + blobParts.push(chunk) + length += chunk.byteLength + } else { + const chunk = textEncoder.encode(`${prefix}; name="${formdataEscape(normalizeLinefeeds(name))}"` + + (value.name ? `; filename="${formdataEscape(value.name)}"` : '') + '\r\n' + + `Content-Type: ${ + value.type || 'application/octet-stream' + }\r\n\r\n`) + blobParts.push(chunk, value, rn) + if (typeof value.size === 'number') { + length += chunk.byteLength + value.size + rn.byteLength + } else { + hasUnknownSizeValue = true + } + } + } + + // CRLF is appended to the body to function with legacy servers and match other implementations. + // https://github.com/curl/curl/blob/3434c6b46e682452973972e8313613dfa58cd690/lib/mime.c#L1029-L1030 + // https://github.com/form-data/form-data/issues/63 + const chunk = textEncoder.encode(`--${boundary}--\r\n`) + blobParts.push(chunk) + length += chunk.byteLength + if (hasUnknownSizeValue) { + length = null + } + + // Set source to object. + source = object + + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream() + } else { + yield part + } + } + } + + // Set type to `multipart/form-data; boundary=`, + // followed by the multipart/form-data boundary string generated + // by the multipart/form-data encoding algorithm. + type = `multipart/form-data; boundary=${boundary}` + } else if (webidl.is.Blob(object)) { + // Blob + + // Set source to object. + source = object + + // Set length to object’s size. + length = object.size + + // If object’s type attribute is not the empty byte sequence, set + // type to its value. + if (object.type) { + type = object.type + } + } else if (typeof object[Symbol.asyncIterator] === 'function') { + // If keepalive is true, then throw a TypeError. + if (keepalive) { + throw new TypeError('keepalive') + } + + // If object is disturbed or locked, then throw a TypeError. + if (util.isDisturbed(object) || object.locked) { + throw new TypeError( + 'Response body object should not be disturbed or locked' + ) + } + + stream = + webidl.is.ReadableStream(object) ? object : ReadableStreamFrom(object) + } + + // 11. If source is a byte sequence, then set action to a + // step that returns source and length to source’s length. + if (typeof source === 'string' || util.isBuffer(source)) { + length = Buffer.byteLength(source) + } + + // 12. If action is non-null, then run these steps in in parallel: + if (action != null) { + // Run action. + let iterator + stream = new ReadableStream({ + start () { + iterator = action(object)[Symbol.asyncIterator]() + }, + pull (controller) { + return iterator.next().then(({ value, done }) => { + if (done) { + // When running action is done, close stream. + queueMicrotask(() => { + controller.close() + controller.byobRequest?.respond(0) + }) + } else { + // Whenever one or more bytes are available and stream is not errored, + // enqueue a Uint8Array wrapping an ArrayBuffer containing the available + // bytes into stream. + if (!isErrored(stream)) { + const buffer = new Uint8Array(value) + if (buffer.byteLength) { + controller.enqueue(buffer) + } + } + } + return controller.desiredSize > 0 + }) + }, + cancel (reason) { + return iterator.return() + }, + type: 'bytes' + }) + } + + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length } + + // 14. Return (body, type). + return [body, type] +} + +/** + * @typedef {object} ExtractBodyResult + * @property {ReadableStream>} stream - The ReadableStream containing the body data + * @property {any} source - The original source of the body data + * @property {number | null} length - The length of the body data, or null + */ + +/** + * Safely extract a body with type from a byte sequence or BodyInit object. + * + * @param {import('../../../types').BodyInit} object - The BodyInit object to extract from + * @param {boolean} [keepalive=false] - If true, indicates that the body + * @returns {[ExtractBodyResult, string | null]} - Returns a tuple containing the body and its type + * + * @see https://fetch.spec.whatwg.org/#bodyinit-safely-extract + */ +function safelyExtractBody (object, keepalive = false) { + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: + + // 1. If object is a ReadableStream object, then: + if (webidl.is.ReadableStream(object)) { + // Assert: object is neither disturbed nor locked. + assert(!util.isDisturbed(object), 'The body has already been consumed.') + assert(!object.locked, 'The stream is locked.') + } + + // 2. Return the results of extracting object. + return extractBody(object, keepalive) +} + +function cloneBody (body) { + // To clone a body body, run these steps: + + // https://fetch.spec.whatwg.org/#concept-body-clone + + // 1. Let « out1, out2 » be the result of teeing body’s stream. + const { 0: out1, 1: out2 } = body.stream.tee() + + // 2. Set body’s stream to out1. + body.stream = out1 + + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: out2, + length: body.length, + source: body.source + } +} + +function bodyMixinMethods (instance, getInternalState) { + const methods = { + blob () { + // The blob() method steps are to return the result of + // running consume body with this and the following step + // given a byte sequence bytes: return a Blob whose + // contents are bytes and whose type attribute is this’s + // MIME type. + return consumeBody(this, (bytes) => { + let mimeType = bodyMimeType(getInternalState(this)) + + if (mimeType === null) { + mimeType = '' + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType) + } + + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance, getInternalState) + }, + + arrayBuffer () { + // The arrayBuffer() method steps are to return the result + // of running consume body with this and the following step + // given a byte sequence bytes: return a new ArrayBuffer + // whose contents are bytes. + return consumeBody(this, (bytes) => { + return new Uint8Array(bytes).buffer + }, instance, getInternalState) + }, + + text () { + // The text() method steps are to return the result of running + // consume body with this and UTF-8 decode. + return consumeBody(this, utf8DecodeBytes, instance, getInternalState) + }, + + json () { + // The json() method steps are to return the result of running + // consume body with this and parse JSON from bytes. + return consumeBody(this, parseJSONFromBytes, instance, getInternalState) + }, + + formData () { + // The formData() method steps are to return the result of running + // consume body with this and the following step given a byte sequence bytes: + return consumeBody(this, (value) => { + // 1. Let mimeType be the result of get the MIME type with this. + const mimeType = bodyMimeType(getInternalState(this)) + + // 2. If mimeType is non-null, then switch on mimeType’s essence and run + // the corresponding steps: + if (mimeType !== null) { + switch (mimeType.essence) { + case 'multipart/form-data': { + // 1. ... [long step] + // 2. If that fails for some reason, then throw a TypeError. + const parsed = multipartFormDataParser(value, mimeType) + + // 3. Return a new FormData object, appending each entry, + // resulting from the parsing operation, to its entry list. + const fd = new FormData() + setFormDataState(fd, parsed) + + return fd + } + case 'application/x-www-form-urlencoded': { + // 1. Let entries be the result of parsing bytes. + const entries = new URLSearchParams(value.toString()) + + // 2. If entries is failure, then throw a TypeError. + + // 3. Return a new FormData object whose entry list is entries. + const fd = new FormData() + + for (const [name, value] of entries) { + fd.append(name, value) + } + + return fd + } + } + } + + // 3. Throw a TypeError. + throw new TypeError( + 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".' + ) + }, instance, getInternalState) + }, + + bytes () { + // The bytes() method steps are to return the result of running consume body + // with this and the following step given a byte sequence bytes: return the + // result of creating a Uint8Array from bytes in this’s relevant realm. + return consumeBody(this, (bytes) => { + return new Uint8Array(bytes) + }, instance, getInternalState) + } + } + + return methods +} + +function mixinBody (prototype, getInternalState) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype, getInternalState)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param {any} object internal state + * @param {(value: unknown) => unknown} convertBytesToJSValue + * @param {any} instance + * @param {(target: any) => any} getInternalState + */ +function consumeBody (object, convertBytesToJSValue, instance, getInternalState) { + try { + webidl.brandCheck(object, instance) + } catch (e) { + return Promise.reject(e) + } + + const state = getInternalState(object) + + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(state)) { + return Promise.reject(new TypeError('Body is unusable: Body has already been read')) + } + + if (state.aborted) { + return Promise.reject(new DOMException('The operation was aborted.', 'AbortError')) + } + + // 2. Let promise be a new promise. + const promise = createDeferredPromise() + + // 3. Let errorSteps given error be to reject promise with error. + const errorSteps = promise.reject + + // 4. Let successSteps given a byte sequence data be to resolve + // promise with the result of running convertBytesToJSValue + // with data. If that threw an exception, then run errorSteps + // with that exception. + const successSteps = (data) => { + try { + promise.resolve(convertBytesToJSValue(data)) + } catch (e) { + errorSteps(e) + } + } + + // 5. If object’s body is null, then run successSteps with an + // empty byte sequence. + if (state.body == null) { + successSteps(Buffer.allocUnsafe(0)) + return promise.promise + } + + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + fullyReadBody(state.body, successSteps, errorSteps) + + // 7. Return promise. + return promise.promise +} + +/** + * @see https://fetch.spec.whatwg.org/#body-unusable + * @param {any} object internal state + */ +function bodyUnusable (object) { + const body = object.body + + // An object including the Body interface mixin is + // said to be unusable if its body is non-null and + // its body’s stream is disturbed or locked. + return body != null && (body.stream.locked || util.isDisturbed(body.stream)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-mime-type + * @param {any} requestOrResponse internal state + */ +function bodyMimeType (requestOrResponse) { + // 1. Let headers be null. + // 2. If requestOrResponse is a Request object, then set headers to requestOrResponse’s request’s header list. + // 3. Otherwise, set headers to requestOrResponse’s response’s header list. + /** @type {import('./headers').HeadersList} */ + const headers = requestOrResponse.headersList + + // 4. Let mimeType be the result of extracting a MIME type from headers. + const mimeType = extractMimeType(headers) + + // 5. If mimeType is failure, then return null. + if (mimeType === 'failure') { + return null + } + + // 6. Return mimeType. + return mimeType +} + +module.exports = { + extractBody, + safelyExtractBody, + cloneBody, + mixinBody, + streamRegistry, + bodyUnusable +} diff --git a/node_modules/undici/lib/web/fetch/constants.js b/node_modules/undici/lib/web/fetch/constants.js new file mode 100644 index 000000000..ef63b0c8e --- /dev/null +++ b/node_modules/undici/lib/web/fetch/constants.js @@ -0,0 +1,131 @@ +'use strict' + +const corsSafeListedMethods = /** @type {const} */ (['GET', 'HEAD', 'POST']) +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) + +const nullBodyStatus = /** @type {const} */ ([101, 204, 205, 304]) + +const redirectStatus = /** @type {const} */ ([301, 302, 303, 307, 308]) +const redirectStatusSet = new Set(redirectStatus) + +/** + * @see https://fetch.spec.whatwg.org/#block-bad-port + */ +const badPorts = /** @type {const} */ ([ + '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', + '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', + '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', + '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', + '2049', '3659', '4045', '4190', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6679', + '6697', '10080' +]) +const badPortsSet = new Set(badPorts) + +/** + * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-header + */ +const referrerPolicyTokens = /** @type {const} */ ([ + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' +]) + +/** + * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policies + */ +const referrerPolicy = /** @type {const} */ ([ + '', + ...referrerPolicyTokens +]) +const referrerPolicyTokensSet = new Set(referrerPolicyTokens) + +const requestRedirect = /** @type {const} */ (['follow', 'manual', 'error']) + +const safeMethods = /** @type {const} */ (['GET', 'HEAD', 'OPTIONS', 'TRACE']) +const safeMethodsSet = new Set(safeMethods) + +const requestMode = /** @type {const} */ (['navigate', 'same-origin', 'no-cors', 'cors']) + +const requestCredentials = /** @type {const} */ (['omit', 'same-origin', 'include']) + +const requestCache = /** @type {const} */ ([ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' +]) + +/** + * @see https://fetch.spec.whatwg.org/#request-body-header-name + */ +const requestBodyHeader = /** @type {const} */ ([ + 'content-encoding', + 'content-language', + 'content-location', + 'content-type', + // See https://github.com/nodejs/undici/issues/2021 + // 'Content-Length' is a forbidden header name, which is typically + // removed in the Headers implementation. However, undici doesn't + // filter out headers, so we add it here. + 'content-length' +]) + +/** + * @see https://fetch.spec.whatwg.org/#enumdef-requestduplex + */ +const requestDuplex = /** @type {const} */ ([ + 'half' +]) + +/** + * @see http://fetch.spec.whatwg.org/#forbidden-method + */ +const forbiddenMethods = /** @type {const} */ (['CONNECT', 'TRACE', 'TRACK']) +const forbiddenMethodsSet = new Set(forbiddenMethods) + +const subresource = /** @type {const} */ ([ + 'audio', + 'audioworklet', + 'font', + 'image', + 'manifest', + 'paintworklet', + 'script', + 'style', + 'track', + 'video', + 'xslt', + '' +]) +const subresourceSet = new Set(subresource) + +module.exports = { + subresource, + forbiddenMethods, + requestBodyHeader, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + redirectStatus, + corsSafeListedMethods, + nullBodyStatus, + safeMethods, + badPorts, + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicyTokens: referrerPolicyTokensSet +} diff --git a/node_modules/undici/lib/web/fetch/data-url.js b/node_modules/undici/lib/web/fetch/data-url.js new file mode 100644 index 000000000..27ad7ae59 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/data-url.js @@ -0,0 +1,596 @@ +'use strict' + +const assert = require('node:assert') +const { forgivingBase64, collectASequenceOfCodePoints, collectASequenceOfCodePointsFast, isomorphicDecode, removeASCIIWhitespace, removeChars } = require('../infra') + +const encoder = new TextEncoder() + +/** + * @see https://mimesniff.spec.whatwg.org/#http-token-code-point + */ +const HTTP_TOKEN_CODEPOINTS = /^[-!#$%&'*+.^_|~A-Za-z0-9]+$/u +const HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/u // eslint-disable-line + +/** + * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point + */ +const HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/u // eslint-disable-line + +// https://fetch.spec.whatwg.org/#data-url-processor +/** @param {URL} dataURL */ +function dataURLProcessor (dataURL) { + // 1. Assert: dataURL’s scheme is "data". + assert(dataURL.protocol === 'data:') + + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true) + + // 3. Remove the leading "data:" string from input. + input = input.slice(5) + + // 4. Let position point at the start of input. + const position = { position: 0 } + + // 5. Let mimeType be the result of collecting a + // sequence of code points that are not equal + // to U+002C (,), given position. + let mimeType = collectASequenceOfCodePointsFast( + ',', + input, + position + ) + + // 6. Strip leading and trailing ASCII whitespace + // from mimeType. + // Undici implementation note: we need to store the + // length because if the mimetype has spaces removed, + // the wrong amount will be sliced from the input in + // step #9 + const mimeTypeLength = mimeType.length + mimeType = removeASCIIWhitespace(mimeType, true, true) + + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' + } + + // 8. Advance position by 1. + position.position++ + + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1) + + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody) + + // 11. If mimeType ends with U+003B (;), followed by + // zero or more U+0020 SPACE, followed by an ASCII + // case-insensitive match for "base64", then: + if (/;(?:\u0020*)base64$/ui.test(mimeType)) { + // 1. Let stringBody be the isomorphic decode of body. + const stringBody = isomorphicDecode(body) + + // 2. Set body to the forgiving-base64 decode of + // stringBody. + body = forgivingBase64(stringBody) + + // 3. If body is failure, then return failure. + if (body === 'failure') { + return 'failure' + } + + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6) + + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020+)$/u, '') + + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1) + } + + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType + } + + // 13. Let mimeTypeRecord be the result of parsing + // mimeType. + let mimeTypeRecord = parseMIMEType(mimeType) + + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + } + + // 15. Return a new data: URL struct whose MIME + // type is mimeTypeRecord and body is body. + // https://fetch.spec.whatwg.org/#data-url-struct + return { mimeType: mimeTypeRecord, body } +} + +// https://url.spec.whatwg.org/#concept-url-serializer +/** + * @param {URL} url + * @param {boolean} excludeFragment + */ +function URLSerializer (url, excludeFragment = false) { + if (!excludeFragment) { + return url.href + } + + const href = url.href + const hashLength = url.hash.length + + const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength) + + if (!hashLength && href.endsWith('#')) { + return serialized.slice(0, -1) + } + + return serialized +} + +// https://url.spec.whatwg.org/#string-percent-decode +/** @param {string} input */ +function stringPercentDecode (input) { + // 1. Let bytes be the UTF-8 encoding of input. + const bytes = encoder.encode(input) + + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) +} + +/** + * @param {number} byte + */ +function isHexCharByte (byte) { + // 0-9 A-F a-f + return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66) +} + +/** + * @param {number} byte + */ +function hexByteToNumber (byte) { + return ( + // 0-9 + byte >= 0x30 && byte <= 0x39 + ? (byte - 48) + // Convert to uppercase + // ((byte & 0xDF) - 65) + 10 + : ((byte & 0xDF) - 55) + ) +} + +// https://url.spec.whatwg.org/#percent-decode +/** @param {Uint8Array} input */ +function percentDecode (input) { + const length = input.length + // 1. Let output be an empty byte sequence. + /** @type {Uint8Array} */ + const output = new Uint8Array(length) + let j = 0 + let i = 0 + // 2. For each byte byte in input: + while (i < length) { + const byte = input[i] + + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output[j++] = byte + + // 2. Otherwise, if byte is 0x25 (%) and the next two bytes + // after byte in input are not in the ranges + // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), + // and 0x61 (a) to 0x66 (f), all inclusive, append byte + // to output. + } else if ( + byte === 0x25 && + !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2])) + ) { + output[j++] = 0x25 + + // 3. Otherwise: + } else { + // 1. Let bytePoint be the two bytes after byte in input, + // decoded, and then interpreted as hexadecimal number. + // 2. Append a byte whose value is bytePoint to output. + output[j++] = (hexByteToNumber(input[i + 1]) << 4) | hexByteToNumber(input[i + 2]) + + // 3. Skip the next two bytes in input. + i += 2 + } + ++i + } + + // 3. Return output. + return length === j ? output : output.subarray(0, j) +} + +// https://mimesniff.spec.whatwg.org/#parse-a-mime-type +/** @param {string} input */ +function parseMIMEType (input) { + // 1. Remove any leading and trailing HTTP whitespace + // from input. + input = removeHTTPWhitespace(input, true, true) + + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 } + + // 3. Let type be the result of collecting a sequence + // of code points that are not U+002F (/) from + // input, given position. + const type = collectASequenceOfCodePointsFast( + '/', + input, + position + ) + + // 4. If type is the empty string or does not solely + // contain HTTP token code points, then return failure. + // https://mimesniff.spec.whatwg.org/#http-token-code-point + if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { + return 'failure' + } + + // 5. If position is past the end of input, then return + // failure + if (position.position >= input.length) { + return 'failure' + } + + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++ + + // 7. Let subtype be the result of collecting a sequence of + // code points that are not U+003B (;) from input, given + // position. + let subtype = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true) + + // 9. If subtype is the empty string or does not solely + // contain HTTP token code points, then return failure. + if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { + return 'failure' + } + + const typeLowercase = type.toLowerCase() + const subtypeLowercase = subtype.toLowerCase() + + // 10. Let mimeType be a new MIME type record whose type + // is type, in ASCII lowercase, and subtype is subtype, + // in ASCII lowercase. + // https://mimesniff.spec.whatwg.org/#mime-type + const mimeType = { + type: typeLowercase, + subtype: subtypeLowercase, + /** @type {Map} */ + parameters: new Map(), + // https://mimesniff.spec.whatwg.org/#mime-type-essence + essence: `${typeLowercase}/${subtypeLowercase}` + } + + // 11. While position is not past the end of input: + while (position.position < input.length) { + // 1. Advance position by 1. (This skips past U+003B (;).) + position.position++ + + // 2. Collect a sequence of code points that are HTTP + // whitespace from input given position. + collectASequenceOfCodePoints( + // https://fetch.spec.whatwg.org/#http-whitespace + char => HTTP_WHITESPACE_REGEX.test(char), + input, + position + ) + + // 3. Let parameterName be the result of collecting a + // sequence of code points that are not U+003B (;) + // or U+003D (=) from input, given position. + let parameterName = collectASequenceOfCodePoints( + (char) => char !== ';' && char !== '=', + input, + position + ) + + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase() + + // 5. If position is not past the end of input, then: + if (position.position < input.length) { + // 1. If the code point at position within input is + // U+003B (;), then continue. + if (input[position.position] === ';') { + continue + } + + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++ + } + + // 6. If position is past the end of input, then break. + if (position.position >= input.length) { + break + } + + // 7. Let parameterValue be null. + let parameterValue = null + + // 8. If the code point at position within input is + // U+0022 ("), then: + if (input[position.position] === '"') { + // 1. Set parameterValue to the result of collecting + // an HTTP quoted string from input, given position + // and the extract-value flag. + parameterValue = collectAnHTTPQuotedString(input, position, true) + + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 9. Otherwise: + } else { + // 1. Set parameterValue to the result of collecting + // a sequence of code points that are not U+003B (;) + // from input, given position. + parameterValue = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 2. Remove any trailing HTTP whitespace from parameterValue. + parameterValue = removeHTTPWhitespace(parameterValue, false, true) + + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue + } + } + + // 10. If all of the following are true + // - parameterName is not the empty string + // - parameterName solely contains HTTP token code points + // - parameterValue solely contains HTTP quoted-string token code points + // - mimeType’s parameters[parameterName] does not exist + // then set mimeType’s parameters[parameterName] to parameterValue. + if ( + parameterName.length !== 0 && + HTTP_TOKEN_CODEPOINTS.test(parameterName) && + (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && + !mimeType.parameters.has(parameterName) + ) { + mimeType.parameters.set(parameterName, parameterValue) + } + } + + // 12. Return mimeType. + return mimeType +} + +// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string +// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string +/** + * @param {string} input + * @param {{ position: number }} position + * @param {boolean} [extractValue=false] + */ +function collectAnHTTPQuotedString (input, position, extractValue = false) { + // 1. Let positionStart be position. + const positionStart = position.position + + // 2. Let value be the empty string. + let value = '' + + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"') + + // 4. Advance position by 1. + position.position++ + + // 5. While true: + while (true) { + // 1. Append the result of collecting a sequence of code points + // that are not U+0022 (") or U+005C (\) from input, given + // position, to value. + value += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== '\\', + input, + position + ) + + // 2. If position is past the end of input, then break. + if (position.position >= input.length) { + break + } + + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position] + + // 4. Advance position by 1. + position.position++ + + // 5. If quoteOrBackslash is U+005C (\), then: + if (quoteOrBackslash === '\\') { + // 1. If position is past the end of input, then append + // U+005C (\) to value and break. + if (position.position >= input.length) { + value += '\\' + break + } + + // 2. Append the code point at position within input to value. + value += input[position.position] + + // 3. Advance position by 1. + position.position++ + + // 6. Otherwise: + } else { + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"') + + // 2. Break. + break + } + } + + // 6. If the extract-value flag is set, then return value. + if (extractValue) { + return value + } + + // 7. Return the code points from positionStart to position, + // inclusive, within input. + return input.slice(positionStart, position.position) +} + +/** + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +function serializeAMimeType (mimeType) { + assert(mimeType !== 'failure') + const { parameters, essence } = mimeType + + // 1. Let serialization be the concatenation of mimeType’s + // type, U+002F (/), and mimeType’s subtype. + let serialization = essence + + // 2. For each name → value of mimeType’s parameters: + for (let [name, value] of parameters.entries()) { + // 1. Append U+003B (;) to serialization. + serialization += ';' + + // 2. Append name to serialization. + serialization += name + + // 3. Append U+003D (=) to serialization. + serialization += '=' + + // 4. If value does not solely contain HTTP token code + // points or value is the empty string, then: + if (!HTTP_TOKEN_CODEPOINTS.test(value)) { + // 1. Precede each occurrence of U+0022 (") or + // U+005C (\) in value with U+005C (\). + value = value.replace(/[\\"]/ug, '\\$&') + + // 2. Prepend U+0022 (") to value. + value = '"' + value + + // 3. Append U+0022 (") to value. + value += '"' + } + + // 5. Append value to serialization. + serialization += value + } + + // 3. Return serialization. + return serialization +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {number} char + */ +function isHTTPWhiteSpace (char) { + // "\r\n\t " + return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x020 +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} str + * @param {boolean} [leading=true] + * @param {boolean} [trailing=true] + */ +function removeHTTPWhitespace (str, leading = true, trailing = true) { + return removeChars(str, leading, trailing, isHTTPWhiteSpace) +} + +/** + * @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type + * @param {Exclude, 'failure'>} mimeType + */ +function minimizeSupportedMimeType (mimeType) { + switch (mimeType.essence) { + case 'application/ecmascript': + case 'application/javascript': + case 'application/x-ecmascript': + case 'application/x-javascript': + case 'text/ecmascript': + case 'text/javascript': + case 'text/javascript1.0': + case 'text/javascript1.1': + case 'text/javascript1.2': + case 'text/javascript1.3': + case 'text/javascript1.4': + case 'text/javascript1.5': + case 'text/jscript': + case 'text/livescript': + case 'text/x-ecmascript': + case 'text/x-javascript': + // 1. If mimeType is a JavaScript MIME type, then return "text/javascript". + return 'text/javascript' + case 'application/json': + case 'text/json': + // 2. If mimeType is a JSON MIME type, then return "application/json". + return 'application/json' + case 'image/svg+xml': + // 3. If mimeType’s essence is "image/svg+xml", then return "image/svg+xml". + return 'image/svg+xml' + case 'text/xml': + case 'application/xml': + // 4. If mimeType is an XML MIME type, then return "application/xml". + return 'application/xml' + } + + // 2. If mimeType is a JSON MIME type, then return "application/json". + if (mimeType.subtype.endsWith('+json')) { + return 'application/json' + } + + // 4. If mimeType is an XML MIME type, then return "application/xml". + if (mimeType.subtype.endsWith('+xml')) { + return 'application/xml' + } + + // 5. If mimeType is supported by the user agent, then return mimeType’s essence. + // Technically, node doesn't support any mimetypes. + + // 6. Return the empty string. + return '' +} + +module.exports = { + dataURLProcessor, + URLSerializer, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType, + removeHTTPWhitespace, + minimizeSupportedMimeType, + HTTP_TOKEN_CODEPOINTS +} diff --git a/node_modules/undici/lib/web/fetch/formdata-parser.js b/node_modules/undici/lib/web/fetch/formdata-parser.js new file mode 100644 index 000000000..4ba204cfa --- /dev/null +++ b/node_modules/undici/lib/web/fetch/formdata-parser.js @@ -0,0 +1,575 @@ +'use strict' + +const { bufferToLowerCasedHeaderName } = require('../../core/util') +const { HTTP_TOKEN_CODEPOINTS } = require('./data-url') +const { makeEntry } = require('./formdata') +const { webidl } = require('../webidl') +const assert = require('node:assert') +const { isomorphicDecode } = require('../infra') +const { utf8DecodeBytes } = require('../../encoding') + +const dd = Buffer.from('--') +const decoder = new TextDecoder() + +/** + * @param {string} chars + */ +function isAsciiString (chars) { + for (let i = 0; i < chars.length; ++i) { + if ((chars.charCodeAt(i) & ~0x7F) !== 0) { + return false + } + } + return true +} + +/** + * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-boundary + * @param {string} boundary + */ +function validateBoundary (boundary) { + const length = boundary.length + + // - its length is greater or equal to 27 and lesser or equal to 70, and + if (length < 27 || length > 70) { + return false + } + + // - it is composed by bytes in the ranges 0x30 to 0x39, 0x41 to 0x5A, or + // 0x61 to 0x7A, inclusive (ASCII alphanumeric), or which are 0x27 ('), + // 0x2D (-) or 0x5F (_). + for (let i = 0; i < length; ++i) { + const cp = boundary.charCodeAt(i) + + if (!( + (cp >= 0x30 && cp <= 0x39) || + (cp >= 0x41 && cp <= 0x5a) || + (cp >= 0x61 && cp <= 0x7a) || + cp === 0x27 || + cp === 0x2d || + cp === 0x5f + )) { + return false + } + } + + return true +} + +/** + * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-parser + * @param {Buffer} input + * @param {ReturnType} mimeType + */ +function multipartFormDataParser (input, mimeType) { + // 1. Assert: mimeType’s essence is "multipart/form-data". + assert(mimeType !== 'failure' && mimeType.essence === 'multipart/form-data') + + const boundaryString = mimeType.parameters.get('boundary') + + // 2. If mimeType’s parameters["boundary"] does not exist, return failure. + // Otherwise, let boundary be the result of UTF-8 decoding mimeType’s + // parameters["boundary"]. + if (boundaryString === undefined) { + throw parsingError('missing boundary in content-type header') + } + + const boundary = Buffer.from(`--${boundaryString}`, 'utf8') + + // 3. Let entry list be an empty entry list. + const entryList = [] + + // 4. Let position be a pointer to a byte in input, initially pointing at + // the first byte. + const position = { position: 0 } + + // Note: Per RFC 2046 Section 5.1.1, we must ignore anything before the + // first boundary delimiter line (preamble). Search for the first boundary. + const firstBoundaryIndex = input.indexOf(boundary) + + if (firstBoundaryIndex === -1) { + throw parsingError('no boundary found in multipart body') + } + + // Start parsing from the first boundary, ignoring any preamble + position.position = firstBoundaryIndex + + // 5. While true: + while (true) { + // 5.1. If position points to a sequence of bytes starting with 0x2D 0x2D + // (`--`) followed by boundary, advance position by 2 + the length of + // boundary. Otherwise, return failure. + // Note: boundary is padded with 2 dashes already, no need to add 2. + if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) { + position.position += boundary.length + } else { + throw parsingError('expected a value starting with -- and the boundary') + } + + // 5.2. If position points to the sequence of bytes 0x2D 0x2D 0x0D 0x0A + // (`--` followed by CR LF) followed by the end of input, return entry list. + // Note: Per RFC 2046 Section 5.1.1, we must ignore anything after the + // final boundary delimiter (epilogue). Check for -- or --CRLF and return + // regardless of what follows. + if (bufferStartsWith(input, dd, position)) { + // Found closing boundary delimiter (--), ignore any epilogue + return entryList + } + + // 5.3. If position does not point to a sequence of bytes starting with 0x0D + // 0x0A (CR LF), return failure. + if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { + throw parsingError('expected CRLF') + } + + // 5.4. Advance position by 2. (This skips past the newline.) + position.position += 2 + + // 5.5. Let name, filename and contentType be the result of parsing + // multipart/form-data headers on input and position, if the result + // is not failure. Otherwise, return failure. + const result = parseMultipartFormDataHeaders(input, position) + + let { name, filename, contentType, encoding } = result + + // 5.6. Advance position by 2. (This skips past the empty line that marks + // the end of the headers.) + position.position += 2 + + // 5.7. Let body be the empty byte sequence. + let body + + // 5.8. Body loop: While position is not past the end of input: + // TODO: the steps here are completely wrong + { + const boundaryIndex = input.indexOf(boundary.subarray(2), position.position) + + if (boundaryIndex === -1) { + throw parsingError('expected boundary after body') + } + + body = input.subarray(position.position, boundaryIndex - 4) + + position.position += body.length + + // Note: position must be advanced by the body's length before being + // decoded, otherwise the parsing will fail. + if (encoding === 'base64') { + body = Buffer.from(body.toString(), 'base64') + } + } + + // 5.9. If position does not point to a sequence of bytes starting with + // 0x0D 0x0A (CR LF), return failure. Otherwise, advance position by 2. + if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { + throw parsingError('expected CRLF') + } else { + position.position += 2 + } + + // 5.10. If filename is not null: + let value + + if (filename !== null) { + // 5.10.1. If contentType is null, set contentType to "text/plain". + contentType ??= 'text/plain' + + // 5.10.2. If contentType is not an ASCII string, set contentType to the empty string. + + // Note: `buffer.isAscii` can be used at zero-cost, but converting a string to a buffer is a high overhead. + // Content-Type is a relatively small string, so it is faster to use `String#charCodeAt`. + if (!isAsciiString(contentType)) { + contentType = '' + } + + // 5.10.3. Let value be a new File object with name filename, type contentType, and body body. + value = new File([body], filename, { type: contentType }) + } else { + // 5.11. Otherwise: + + // 5.11.1. Let value be the UTF-8 decoding without BOM of body. + value = utf8DecodeBytes(Buffer.from(body)) + } + + // 5.12. Assert: name is a scalar value string and value is either a scalar value string or a File object. + assert(webidl.is.USVString(name)) + assert((typeof value === 'string' && webidl.is.USVString(value)) || webidl.is.File(value)) + + // 5.13. Create an entry with name and value, and append it to entry list. + entryList.push(makeEntry(name, value, filename)) + } +} + +/** + * Parses content-disposition attributes (e.g., name="value" or filename*=utf-8''encoded) + * @param {Buffer} input + * @param {{ position: number }} position + * @returns {{ name: string, value: string }} + */ +function parseContentDispositionAttribute (input, position) { + // Skip leading semicolon and whitespace + if (input[position.position] === 0x3b /* ; */) { + position.position++ + } + + // Skip whitespace + collectASequenceOfBytes( + (char) => char === 0x20 || char === 0x09, + input, + position + ) + + // Collect attribute name (token characters) + const attributeName = collectASequenceOfBytes( + (char) => isToken(char) && char !== 0x3d && char !== 0x2a, // not = or * + input, + position + ) + + if (attributeName.length === 0) { + return null + } + + const attrNameStr = attributeName.toString('ascii').toLowerCase() + + // Check for extended notation (attribute*) + const isExtended = input[position.position] === 0x2a /* * */ + if (isExtended) { + position.position++ // skip * + } + + // Expect = sign + if (input[position.position] !== 0x3d /* = */) { + return null + } + position.position++ // skip = + + // Skip whitespace + collectASequenceOfBytes( + (char) => char === 0x20 || char === 0x09, + input, + position + ) + + let value + + if (isExtended) { + // Extended attribute format: charset'language'encoded-value + const headerValue = collectASequenceOfBytes( + (char) => char !== 0x20 && char !== 0x0d && char !== 0x0a && char !== 0x3b, // not space, CRLF, or ; + input, + position + ) + + // Check for utf-8'' prefix (case insensitive) + if ( + (headerValue[0] !== 0x75 && headerValue[0] !== 0x55) || // u or U + (headerValue[1] !== 0x74 && headerValue[1] !== 0x54) || // t or T + (headerValue[2] !== 0x66 && headerValue[2] !== 0x46) || // f or F + headerValue[3] !== 0x2d || // - + headerValue[4] !== 0x38 // 8 + ) { + throw parsingError('unknown encoding, expected utf-8\'\'') + } + + // Skip utf-8'' and decode the rest + value = decodeURIComponent(decoder.decode(headerValue.subarray(7))) + } else if (input[position.position] === 0x22 /* " */) { + // Quoted string + position.position++ // skip opening quote + + const quotedValue = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d && char !== 0x22, // not LF, CR, or " + input, + position + ) + + if (input[position.position] !== 0x22) { + throw parsingError('Closing quote not found') + } + position.position++ // skip closing quote + + value = decoder.decode(quotedValue) + .replace(/%0A/ig, '\n') + .replace(/%0D/ig, '\r') + .replace(/%22/g, '"') + } else { + // Token value (no quotes) + const tokenValue = collectASequenceOfBytes( + (char) => isToken(char) && char !== 0x3b, // not ; + input, + position + ) + + value = decoder.decode(tokenValue) + } + + return { name: attrNameStr, value } +} + +/** + * @see https://andreubotella.github.io/multipart-form-data/#parse-multipart-form-data-headers + * @param {Buffer} input + * @param {{ position: number }} position + */ +function parseMultipartFormDataHeaders (input, position) { + // 1. Let name, filename and contentType be null. + let name = null + let filename = null + let contentType = null + let encoding = null + + // 2. While true: + while (true) { + // 2.1. If position points to a sequence of bytes starting with 0x0D 0x0A (CR LF): + if (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { + // 2.1.1. If name is null, return failure. + if (name === null) { + throw parsingError('header name is null') + } + + // 2.1.2. Return name, filename and contentType. + return { name, filename, contentType, encoding } + } + + // 2.2. Let header name be the result of collecting a sequence of bytes that are + // not 0x0A (LF), 0x0D (CR) or 0x3A (:), given position. + let headerName = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d && char !== 0x3a, + input, + position + ) + + // 2.3. Remove any HTTP tab or space bytes from the start or end of header name. + headerName = removeChars(headerName, true, true, (char) => char === 0x9 || char === 0x20) + + // 2.4. If header name does not match the field-name token production, return failure. + if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) { + throw parsingError('header name does not match the field-name token production') + } + + // 2.5. If the byte at position is not 0x3A (:), return failure. + if (input[position.position] !== 0x3a) { + throw parsingError('expected :') + } + + // 2.6. Advance position by 1. + position.position++ + + // 2.7. Collect a sequence of bytes that are HTTP tab or space bytes given position. + // (Do nothing with those bytes.) + collectASequenceOfBytes( + (char) => char === 0x20 || char === 0x09, + input, + position + ) + + // 2.8. Byte-lowercase header name and switch on the result: + switch (bufferToLowerCasedHeaderName(headerName)) { + case 'content-disposition': { + name = filename = null + + // Collect the disposition type (should be "form-data") + const dispositionType = collectASequenceOfBytes( + (char) => isToken(char), + input, + position + ) + + if (dispositionType.toString('ascii').toLowerCase() !== 'form-data') { + throw parsingError('expected form-data for content-disposition header') + } + + // Parse attributes recursively until CRLF + while ( + position.position < input.length && + input[position.position] !== 0x0d && + input[position.position + 1] !== 0x0a + ) { + const attribute = parseContentDispositionAttribute(input, position) + + if (!attribute) { + break + } + + if (attribute.name === 'name') { + name = attribute.value + } else if (attribute.name === 'filename') { + filename = attribute.value + } + } + + if (name === null) { + throw parsingError('name attribute is required in content-disposition header') + } + + break + } + case 'content-type': { + // 1. Let header value be the result of collecting a sequence of bytes that are + // not 0x0A (LF) or 0x0D (CR), given position. + let headerValue = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d, + input, + position + ) + + // 2. Remove any HTTP tab or space bytes from the end of header value. + headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20) + + // 3. Set contentType to the isomorphic decoding of header value. + contentType = isomorphicDecode(headerValue) + + break + } + case 'content-transfer-encoding': { + let headerValue = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d, + input, + position + ) + + headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20) + + encoding = isomorphicDecode(headerValue) + + break + } + default: { + // Collect a sequence of bytes that are not 0x0A (LF) or 0x0D (CR), given position. + // (Do nothing with those bytes.) + collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d, + input, + position + ) + } + } + + // 2.9. If position does not point to a sequence of bytes starting with 0x0D 0x0A + // (CR LF), return failure. Otherwise, advance position by 2 (past the newline). + if (input[position.position] !== 0x0d && input[position.position + 1] !== 0x0a) { + throw parsingError('expected CRLF') + } else { + position.position += 2 + } + } +} + +/** + * @param {(char: number) => boolean} condition + * @param {Buffer} input + * @param {{ position: number }} position + */ +function collectASequenceOfBytes (condition, input, position) { + let start = position.position + + while (start < input.length && condition(input[start])) { + ++start + } + + return input.subarray(position.position, (position.position = start)) +} + +/** + * @param {Buffer} buf + * @param {boolean} leading + * @param {boolean} trailing + * @param {(charCode: number) => boolean} predicate + * @returns {Buffer} + */ +function removeChars (buf, leading, trailing, predicate) { + let lead = 0 + let trail = buf.length - 1 + + if (leading) { + while (lead < buf.length && predicate(buf[lead])) lead++ + } + + if (trailing) { + while (trail > 0 && predicate(buf[trail])) trail-- + } + + return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1) +} + +/** + * Checks if {@param buffer} starts with {@param start} + * @param {Buffer} buffer + * @param {Buffer} start + * @param {{ position: number }} position + */ +function bufferStartsWith (buffer, start, position) { + if (buffer.length < start.length) { + return false + } + + for (let i = 0; i < start.length; i++) { + if (start[i] !== buffer[position.position + i]) { + return false + } + } + + return true +} + +function parsingError (cause) { + return new TypeError('Failed to parse body as FormData.', { cause: new TypeError(cause) }) +} + +/** + * CTL = + * @param {number} char + */ +function isCTL (char) { + return char <= 0x1f || char === 0x7f +} + +/** + * tspecials := "(" / ")" / "<" / ">" / "@" / + * "," / ";" / ":" / "\" / <"> + * "/" / "[" / "]" / "?" / "=" + * ; Must be in quoted-string, + * ; to use within parameter values + * @param {number} char + */ +function isTSpecial (char) { + return ( + char === 0x28 || // ( + char === 0x29 || // ) + char === 0x3c || // < + char === 0x3e || // > + char === 0x40 || // @ + char === 0x2c || // , + char === 0x3b || // ; + char === 0x3a || // : + char === 0x5c || // \ + char === 0x22 || // " + char === 0x2f || // / + char === 0x5b || // [ + char === 0x5d || // ] + char === 0x3f || // ? + char === 0x3d // + + ) +} + +/** + * token := 1* + * @param {number} char + */ +function isToken (char) { + return ( + char <= 0x7f && // ascii + char !== 0x20 && // space + char !== 0x09 && + !isCTL(char) && + !isTSpecial(char) + ) +} + +module.exports = { + multipartFormDataParser, + validateBoundary +} diff --git a/node_modules/undici/lib/web/fetch/formdata.js b/node_modules/undici/lib/web/fetch/formdata.js new file mode 100644 index 000000000..c21fb06a3 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/formdata.js @@ -0,0 +1,259 @@ +'use strict' + +const { iteratorMixin } = require('./util') +const { kEnumerableProperty } = require('../../core/util') +const { webidl } = require('../webidl') +const nodeUtil = require('node:util') + +// https://xhr.spec.whatwg.org/#formdata +class FormData { + #state = [] + + constructor (form = undefined) { + webidl.util.markAsUncloneable(this) + + if (form !== undefined) { + throw webidl.errors.conversionFailed({ + prefix: 'FormData constructor', + argument: 'Argument 1', + types: ['undefined'] + }) + } + } + + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.append' + webidl.argumentLengthCheck(arguments, 2, prefix) + + name = webidl.converters.USVString(name) + + if (arguments.length === 3 || webidl.is.Blob(value)) { + value = webidl.converters.Blob(value, prefix, 'value') + + if (filename !== undefined) { + filename = webidl.converters.USVString(filename) + } + } else { + value = webidl.converters.USVString(value) + } + + // 1. Let value be value if given; otherwise blobValue. + + // 2. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename) + + // 3. Append entry to this’s entry list. + this.#state.push(entry) + } + + delete (name) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.delete' + webidl.argumentLengthCheck(arguments, 1, prefix) + + name = webidl.converters.USVString(name) + + // The delete(name) method steps are to remove all entries whose name + // is name from this’s entry list. + this.#state = this.#state.filter(entry => entry.name !== name) + } + + get (name) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.get' + webidl.argumentLengthCheck(arguments, 1, prefix) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return null. + const idx = this.#state.findIndex((entry) => entry.name === name) + if (idx === -1) { + return null + } + + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this.#state[idx].value + } + + getAll (name) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.getAll' + webidl.argumentLengthCheck(arguments, 1, prefix) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return the empty list. + // 2. Return the values of all entries whose name is name, in order, + // from this’s entry list. + return this.#state + .filter((entry) => entry.name === name) + .map((entry) => entry.value) + } + + has (name) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.has' + webidl.argumentLengthCheck(arguments, 1, prefix) + + name = webidl.converters.USVString(name) + + // The has(name) method steps are to return true if there is an entry + // whose name is name in this’s entry list; otherwise false. + return this.#state.findIndex((entry) => entry.name === name) !== -1 + } + + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.set' + webidl.argumentLengthCheck(arguments, 2, prefix) + + name = webidl.converters.USVString(name) + + if (arguments.length === 3 || webidl.is.Blob(value)) { + value = webidl.converters.Blob(value, prefix, 'value') + + if (filename !== undefined) { + filename = webidl.converters.USVString(filename) + } + } else { + value = webidl.converters.USVString(value) + } + + // The set(name, value) and set(name, blobValue, filename) method steps + // are: + + // 1. Let value be value if given; otherwise blobValue. + + // 2. Let entry be the result of creating an entry with name, value, and + // filename if given. + const entry = makeEntry(name, value, filename) + + // 3. If there are entries in this’s entry list whose name is name, then + // replace the first such entry with entry and remove the others. + const idx = this.#state.findIndex((entry) => entry.name === name) + if (idx !== -1) { + this.#state = [ + ...this.#state.slice(0, idx), + entry, + ...this.#state.slice(idx + 1).filter((entry) => entry.name !== name) + ] + } else { + // 4. Otherwise, append entry to this’s entry list. + this.#state.push(entry) + } + } + + [nodeUtil.inspect.custom] (depth, options) { + const state = this.#state.reduce((a, b) => { + if (a[b.name]) { + if (Array.isArray(a[b.name])) { + a[b.name].push(b.value) + } else { + a[b.name] = [a[b.name], b.value] + } + } else { + a[b.name] = b.value + } + + return a + }, { __proto__: null }) + + options.depth ??= depth + options.colors ??= true + + const output = nodeUtil.formatWithOptions(options, state) + + // remove [Object null prototype] + return `FormData ${output.slice(output.indexOf(']') + 2)}` + } + + /** + * @param {FormData} formData + */ + static getFormDataState (formData) { + return formData.#state + } + + /** + * @param {FormData} formData + * @param {any[]} newState + */ + static setFormDataState (formData, newState) { + formData.#state = newState + } +} + +const { getFormDataState, setFormDataState } = FormData +Reflect.deleteProperty(FormData, 'getFormDataState') +Reflect.deleteProperty(FormData, 'setFormDataState') + +iteratorMixin('FormData', FormData, getFormDataState, 'name', 'value') + +Object.defineProperties(FormData.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + getAll: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FormData', + configurable: true + } +}) + +/** + * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry + * @param {string} name + * @param {string|Blob} value + * @param {?string} filename + * @returns + */ +function makeEntry (name, value, filename) { + // 1. Set name to the result of converting name into a scalar value string. + // Note: This operation was done by the webidl converter USVString. + + // 2. If value is a string, then set value to the result of converting + // value into a scalar value string. + if (typeof value === 'string') { + // Note: This operation was done by the webidl converter USVString. + } else { + // 3. Otherwise: + + // 1. If value is not a File object, then set value to a new File object, + // representing the same bytes, whose name attribute value is "blob" + if (!webidl.is.File(value)) { + value = new File([value], 'blob', { type: value.type }) + } + + // 2. If filename is given, then set value to a new File object, + // representing the same bytes, whose name attribute is filename. + if (filename !== undefined) { + /** @type {FilePropertyBag} */ + const options = { + type: value.type, + lastModified: value.lastModified + } + + value = new File([value], filename, options) + } + } + + // 4. Return an entry whose name is name and whose value is value. + return { name, value } +} + +webidl.is.FormData = webidl.util.MakeTypeAssertion(FormData) + +module.exports = { FormData, makeEntry, setFormDataState } diff --git a/node_modules/undici/lib/web/fetch/global.js b/node_modules/undici/lib/web/fetch/global.js new file mode 100644 index 000000000..1df6f1227 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/global.js @@ -0,0 +1,40 @@ +'use strict' + +// In case of breaking changes, increase the version +// number to avoid conflicts. +const globalOrigin = Symbol.for('undici.globalOrigin.1') + +function getGlobalOrigin () { + return globalThis[globalOrigin] +} + +function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }) + + return + } + + const parsedURL = new URL(newOrigin) + + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + } + + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }) +} + +module.exports = { + getGlobalOrigin, + setGlobalOrigin +} diff --git a/node_modules/undici/lib/web/fetch/headers.js b/node_modules/undici/lib/web/fetch/headers.js new file mode 100644 index 000000000..024d19895 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/headers.js @@ -0,0 +1,719 @@ +// https://github.com/Ethan-Arrowood/undici-fetch + +'use strict' + +const { kConstruct } = require('../../core/symbols') +const { kEnumerableProperty } = require('../../core/util') +const { + iteratorMixin, + isValidHeaderName, + isValidHeaderValue +} = require('./util') +const { webidl } = require('../webidl') +const assert = require('node:assert') +const util = require('node:util') + +/** + * @param {number} code + * @returns {code is (0x0a | 0x0d | 0x09 | 0x20)} + */ +function isHTTPWhiteSpaceCharCode (code) { + return code === 0x0a || code === 0x0d || code === 0x09 || code === 0x20 +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue + * @returns {string} + */ +function headerValueNormalize (potentialValue) { + // To normalize a byte sequence potentialValue, remove + // any leading and trailing HTTP whitespace bytes from + // potentialValue. + let i = 0; let j = potentialValue.length + + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i + + return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) +} + +/** + * @param {Headers} headers + * @param {Array|Object} object + */ +function fill (headers, object) { + // To fill a Headers object headers with a given object object, run these steps: + + // 1. If object is a sequence, then for each header in object: + // Note: webidl conversion to array has already been done. + if (Array.isArray(object)) { + for (let i = 0; i < object.length; ++i) { + const header = object[i] + // 1. If header does not contain exactly two items, then throw a TypeError. + if (header.length !== 2) { + throw webidl.errors.exception({ + header: 'Headers constructor', + message: `expected name/value pair to be length 2, found ${header.length}.` + }) + } + + // 2. Append (header’s first item, header’s second item) to headers. + appendHeader(headers, header[0], header[1]) + } + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw + + // 2. Otherwise, object is a record, then for each key → value in object, + // append (key, value) to headers + const keys = Object.keys(object) + for (let i = 0; i < keys.length; ++i) { + appendHeader(headers, keys[i], object[keys[i]]) + } + } else { + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) + } +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-headers-append + * @param {Headers} headers + * @param {string} name + * @param {string} value + */ +function appendHeader (headers, name, value) { + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value, + type: 'header value' + }) + } + + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if headers’s guard is "request-no-cors": + // TODO + // Note: undici does not implement forbidden header names + if (getHeadersGuard(headers) === 'immutable') { + throw new TypeError('immutable') + } + + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. + + // 7. Append (name, value) to headers’s header list. + return getHeadersList(headers).append(name, value, false) + + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers +} + +// https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine +/** + * @param {Headers} target + */ +function headersListSortAndCombine (target) { + const headersList = getHeadersList(target) + + if (!headersList) { + return [] + } + + if (headersList.sortedMap) { + return headersList.sortedMap + } + + // 1. Let headers be an empty list of headers with the key being the name + // and value the value. + const headers = [] + + // 2. Let names be the result of convert header names to a sorted-lowercase + // set with all the names of the headers in list. + const names = headersList.toSortedArray() + + const cookies = headersList.cookies + + // fast-path + if (cookies === null || cookies.length === 1) { + // Note: The non-null assertion of value has already been done by `HeadersList#toSortedArray` + return (headersList.sortedMap = names) + } + + // 3. For each name of names: + for (let i = 0; i < names.length; ++i) { + const { 0: name, 1: value } = names[i] + // 1. If name is `set-cookie`, then: + if (name === 'set-cookie') { + // 1. Let values be a list of all values of headers in list whose name + // is a byte-case-insensitive match for name, in order. + + // 2. For each value of values: + // 1. Append (name, value) to headers. + for (let j = 0; j < cookies.length; ++j) { + headers.push([name, cookies[j]]) + } + } else { + // 2. Otherwise: + + // 1. Let value be the result of getting name from list. + + // 2. Assert: value is non-null. + // Note: This operation was done by `HeadersList#toSortedArray`. + + // 3. Append (name, value) to headers. + headers.push([name, value]) + } + } + + // 4. Return headers. + return (headersList.sortedMap = headers) +} + +function compareHeaderName (a, b) { + return a[0] < b[0] ? -1 : 1 +} + +class HeadersList { + /** @type {[string, string][]|null} */ + cookies = null + + sortedMap + headersMap + + constructor (init) { + if (init instanceof HeadersList) { + this.headersMap = new Map(init.headersMap) + this.sortedMap = init.sortedMap + this.cookies = init.cookies === null ? null : [...init.cookies] + } else { + this.headersMap = new Map(init) + this.sortedMap = null + } + } + + /** + * @see https://fetch.spec.whatwg.org/#header-list-contains + * @param {string} name + * @param {boolean} isLowerCase + */ + contains (name, isLowerCase) { + // A header list list contains a header name name if list + // contains a header whose name is a byte-case-insensitive + // match for name. + + return this.headersMap.has(isLowerCase ? name : name.toLowerCase()) + } + + clear () { + this.headersMap.clear() + this.sortedMap = null + this.cookies = null + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-append + * @param {string} name + * @param {string} value + * @param {boolean} isLowerCase + */ + append (name, value, isLowerCase) { + this.sortedMap = null + + // 1. If list contains name, then set name to the first such + // header’s name. + const lowercaseName = isLowerCase ? name : name.toLowerCase() + const exists = this.headersMap.get(lowercaseName) + + // 2. Append (name, value) to list. + if (exists) { + const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' + this.headersMap.set(lowercaseName, { + name: exists.name, + value: `${exists.value}${delimiter}${value}` + }) + } else { + this.headersMap.set(lowercaseName, { name, value }) + } + + if (lowercaseName === 'set-cookie') { + (this.cookies ??= []).push(value) + } + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-set + * @param {string} name + * @param {string} value + * @param {boolean} isLowerCase + */ + set (name, value, isLowerCase) { + this.sortedMap = null + const lowercaseName = isLowerCase ? name : name.toLowerCase() + + if (lowercaseName === 'set-cookie') { + this.cookies = [value] + } + + // 1. If list contains name, then set the value of + // the first such header to value and remove the + // others. + // 2. Otherwise, append header (name, value) to list. + this.headersMap.set(lowercaseName, { name, value }) + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-delete + * @param {string} name + * @param {boolean} isLowerCase + */ + delete (name, isLowerCase) { + this.sortedMap = null + if (!isLowerCase) name = name.toLowerCase() + + if (name === 'set-cookie') { + this.cookies = null + } + + this.headersMap.delete(name) + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-get + * @param {string} name + * @param {boolean} isLowerCase + * @returns {string | null} + */ + get (name, isLowerCase) { + // 1. If list does not contain name, then return null. + // 2. Return the values of all headers in list whose name + // is a byte-case-insensitive match for name, + // separated from each other by 0x2C 0x20, in order. + return this.headersMap.get(isLowerCase ? name : name.toLowerCase())?.value ?? null + } + + * [Symbol.iterator] () { + // use the lowercased name + for (const { 0: name, 1: { value } } of this.headersMap) { + yield [name, value] + } + } + + get entries () { + const headers = {} + + if (this.headersMap.size !== 0) { + for (const { name, value } of this.headersMap.values()) { + headers[name] = value + } + } + + return headers + } + + rawValues () { + return this.headersMap.values() + } + + get entriesList () { + const headers = [] + + if (this.headersMap.size !== 0) { + for (const { 0: lowerName, 1: { name, value } } of this.headersMap) { + if (lowerName === 'set-cookie') { + for (const cookie of this.cookies) { + headers.push([name, cookie]) + } + } else { + headers.push([name, value]) + } + } + } + + return headers + } + + // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set + toSortedArray () { + const size = this.headersMap.size + const array = new Array(size) + // In most cases, you will use the fast-path. + // fast-path: Use binary insertion sort for small arrays. + if (size <= 32) { + if (size === 0) { + // If empty, it is an empty array. To avoid the first index assignment. + return array + } + // Improve performance by unrolling loop and avoiding double-loop. + // Double-loop-less version of the binary insertion sort. + const iterator = this.headersMap[Symbol.iterator]() + const firstValue = iterator.next().value + // set [name, value] to first index. + array[0] = [firstValue[0], firstValue[1].value] + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + // 3.2.2. Assert: value is non-null. + assert(firstValue[1].value !== null) + for ( + let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value; + i < size; + ++i + ) { + // get next value + value = iterator.next().value + // set [name, value] to current index. + x = array[i] = [value[0], value[1].value] + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + // 3.2.2. Assert: value is non-null. + assert(x[1] !== null) + left = 0 + right = i + // binary search + while (left < right) { + // middle index + pivot = left + ((right - left) >> 1) + // compare header name + if (array[pivot][0] <= x[0]) { + left = pivot + 1 + } else { + right = pivot + } + } + if (i !== pivot) { + j = i + while (j > left) { + array[j] = array[--j] + } + array[left] = x + } + } + /* c8 ignore next 4 */ + if (!iterator.next().done) { + // This is for debugging and will never be called. + throw new TypeError('Unreachable') + } + return array + } else { + // This case would be a rare occurrence. + // slow-path: fallback + let i = 0 + for (const { 0: name, 1: { value } } of this.headersMap) { + array[i++] = [name, value] + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + // 3.2.2. Assert: value is non-null. + assert(value !== null) + } + return array.sort(compareHeaderName) + } + } +} + +// https://fetch.spec.whatwg.org/#headers-class +class Headers { + #guard + /** + * @type {HeadersList} + */ + #headersList + + /** + * @param {HeadersInit|Symbol} [init] + * @returns + */ + constructor (init = undefined) { + webidl.util.markAsUncloneable(this) + + if (init === kConstruct) { + return + } + + this.#headersList = new HeadersList() + + // The new Headers(init) constructor steps are: + + // 1. Set this’s guard to "none". + this.#guard = 'none' + + // 2. If init is given, then fill this with init. + if (init !== undefined) { + init = webidl.converters.HeadersInit(init, 'Headers constructor', 'init') + fill(this, init) + } + } + + // https://fetch.spec.whatwg.org/#dom-headers-append + append (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, 'Headers.append') + + const prefix = 'Headers.append' + name = webidl.converters.ByteString(name, prefix, 'name') + value = webidl.converters.ByteString(value, prefix, 'value') + + return appendHeader(this, name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, 'Headers.delete') + + const prefix = 'Headers.delete' + name = webidl.converters.ByteString(name, prefix, 'name') + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.delete', + value: name, + type: 'header name' + }) + } + + // 2. If this’s guard is "immutable", then throw a TypeError. + // 3. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 4. Otherwise, if this’s guard is "request-no-cors", name + // is not a no-CORS-safelisted request-header name, and + // name is not a privileged no-CORS request-header name, + // return. + // 5. Otherwise, if this’s guard is "response" and name is + // a forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this.#guard === 'immutable') { + throw new TypeError('immutable') + } + + // 6. If this’s header list does not contain name, then + // return. + if (!this.#headersList.contains(name, false)) { + return + } + + // 7. Delete name from this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this. + this.#headersList.delete(name, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, 'Headers.get') + + const prefix = 'Headers.get' + name = webidl.converters.ByteString(name, prefix, 'name') + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: 'header name' + }) + } + + // 2. Return the result of getting name from this’s header + // list. + return this.#headersList.get(name, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-has + has (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, 'Headers.has') + + const prefix = 'Headers.has' + name = webidl.converters.ByteString(name, prefix, 'name') + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: 'header name' + }) + } + + // 2. Return true if this’s header list contains name; + // otherwise false. + return this.#headersList.contains(name, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, 'Headers.set') + + const prefix = 'Headers.set' + name = webidl.converters.ByteString(name, prefix, 'name') + value = webidl.converters.ByteString(value, prefix, 'value') + + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix, + value, + type: 'header value' + }) + } + + // 3. If this’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if this’s guard is "request-no-cors" and + // name/value is not a no-CORS-safelisted request-header, + // return. + // 6. Otherwise, if this’s guard is "response" and name is a + // forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this.#guard === 'immutable') { + throw new TypeError('immutable') + } + + // 7. Set (name, value) in this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this + this.#headersList.set(name, value, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers) + + // 1. If this’s header list does not contain `Set-Cookie`, then return « ». + // 2. Return the values of all headers in this’s header list whose name is + // a byte-case-insensitive match for `Set-Cookie`, in order. + + const list = this.#headersList.cookies + + if (list) { + return [...list] + } + + return [] + } + + [util.inspect.custom] (depth, options) { + options.depth ??= depth + + return `Headers ${util.formatWithOptions(options, this.#headersList.entries)}` + } + + static getHeadersGuard (o) { + return o.#guard + } + + static setHeadersGuard (o, guard) { + o.#guard = guard + } + + /** + * @param {Headers} o + */ + static getHeadersList (o) { + return o.#headersList + } + + /** + * @param {Headers} target + * @param {HeadersList} list + */ + static setHeadersList (target, list) { + target.#headersList = list + } +} + +const { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers +Reflect.deleteProperty(Headers, 'getHeadersGuard') +Reflect.deleteProperty(Headers, 'setHeadersGuard') +Reflect.deleteProperty(Headers, 'getHeadersList') +Reflect.deleteProperty(Headers, 'setHeadersList') + +iteratorMixin('Headers', Headers, headersListSortAndCombine, 0, 1) + +Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + getSetCookie: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Headers', + configurable: true + }, + [util.inspect.custom]: { + enumerable: false + } +}) + +webidl.converters.HeadersInit = function (V, prefix, argument) { + if (webidl.util.Type(V) === webidl.util.Types.OBJECT) { + const iterator = Reflect.get(V, Symbol.iterator) + + // A work-around to ensure we send the properly-cased Headers when V is a Headers object. + // Read https://github.com/nodejs/undici/pull/3159#issuecomment-2075537226 before touching, please. + if (!util.types.isProxy(V) && iterator === Headers.prototype.entries) { // Headers object + try { + return getHeadersList(V).entriesList + } catch { + // fall-through + } + } + + if (typeof iterator === 'function') { + return webidl.converters['sequence>'](V, prefix, argument, iterator.bind(V)) + } + + return webidl.converters['record'](V, prefix, argument) + } + + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) +} + +module.exports = { + fill, + // for test. + compareHeaderName, + Headers, + HeadersList, + getHeadersGuard, + setHeadersGuard, + setHeadersList, + getHeadersList +} diff --git a/node_modules/undici/lib/web/fetch/index.js b/node_modules/undici/lib/web/fetch/index.js new file mode 100644 index 000000000..24d724c22 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/index.js @@ -0,0 +1,2343 @@ +// https://github.com/Ethan-Arrowood/undici-fetch + +'use strict' + +const { + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse, + fromInnerResponse, + getResponseState +} = require('./response') +const { HeadersList } = require('./headers') +const { Request, cloneRequest, getRequestDispatcher, getRequestState } = require('./request') +const zlib = require('node:zlib') +const { + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + urlIsLocal, + urlIsHttpHttpsScheme, + urlHasHttpsScheme, + clampAndCoarsenConnectionTimingInfo, + simpleRangeHeaderValue, + buildContentRange, + createInflate, + extractMimeType, + hasAuthenticationEntry, + includesCredentials, + isTraversableNavigable +} = require('./util') +const assert = require('node:assert') +const { safelyExtractBody, extractBody } = require('./body') +const { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet +} = require('./constants') +const EE = require('node:events') +const { Readable, pipeline, finished, isErrored, isReadable } = require('node:stream') +const { addAbortListener, bufferToLowerCasedHeaderName } = require('../../core/util') +const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require('./data-url') +const { getGlobalDispatcher } = require('../../global') +const { webidl } = require('../webidl') +const { STATUS_CODES } = require('node:http') +const { bytesMatch } = require('../subresource-integrity/subresource-integrity') +const { createDeferredPromise } = require('../../util/promise') +const { isomorphicEncode } = require('../infra') +const { runtimeFeatures } = require('../../util/runtime-features') + +// Node.js v23.8.0+ and v22.15.0+ supports Zstandard +const hasZstd = runtimeFeatures.has('zstd') + +const GET_OR_HEAD = ['GET', 'HEAD'] + +const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined' + ? 'node' + : 'undici' + +/** @type {import('buffer').resolveObjectURL} */ +let resolveObjectURL + +class Fetch extends EE { + constructor (dispatcher) { + super() + + this.dispatcher = dispatcher + this.connection = null + this.dump = false + this.state = 'ongoing' + } + + terminate (reason) { + if (this.state !== 'ongoing') { + return + } + + this.state = 'terminated' + this.connection?.destroy(reason) + this.emit('terminated', reason) + } + + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return + } + + // 1. Set controller’s state to "aborted". + this.state = 'aborted' + + // 2. Let fallbackError be an "AbortError" DOMException. + // 3. Set error to fallbackError if it is not given. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). + + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error + + this.connection?.destroy(error) + this.emit('terminated', error) + } +} + +function handleFetchDone (response) { + finalizeAndReportTiming(response, 'fetch') +} + +// https://fetch.spec.whatwg.org/#fetch-method +function fetch (input, init = undefined) { + webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch') + + // 1. Let p be a new promise. + let p = createDeferredPromise() + + // 2. Let requestObject be the result of invoking the initial value of + // Request as constructor with input and init as arguments. If this throws + // an exception, reject p with it and return p. + let requestObject + + try { + requestObject = new Request(input, init) + } catch (e) { + p.reject(e) + return p.promise + } + + // 3. Let request be requestObject’s request. + const request = getRequestState(requestObject) + + // 4. If requestObject’s signal’s aborted flag is set, then: + if (requestObject.signal.aborted) { + // 1. Abort the fetch() call with p, request, null, and + // requestObject’s signal’s abort reason. + abortFetch(p, request, null, requestObject.signal.reason) + + // 2. Return p. + return p.promise + } + + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject + + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none' + } + + // 7. Let responseObject be null. + let responseObject = null + + // 8. Let relevantRealm be this’s relevant Realm. + + // 9. Let locallyAborted be false. + let locallyAborted = false + + // 10. Let controller be null. + let controller = null + + // 11. Add the following abort steps to requestObject’s signal: + addAbortListener( + requestObject.signal, + () => { + // 1. Set locallyAborted to true. + locallyAborted = true + + // 2. Assert: controller is non-null. + assert(controller != null) + + // 3. Abort controller with requestObject’s signal’s abort reason. + controller.abort(requestObject.signal.reason) + + const realResponse = responseObject?.deref() + + // 4. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, realResponse, requestObject.signal.reason) + } + ) + + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + // see function handleFetchDone + + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: + + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return + } + + // 2. If response’s aborted flag is set, then: + if (response.aborted) { + // 1. Let deserializedError be the result of deserialize a serialized + // abort reason given controller’s serialized abort reason and + // relevantRealm. + + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. + + abortFetch(p, request, responseObject, controller.serializedAbortReason) + return + } + + // 3. If response is a network error, then reject p with a TypeError + // and terminate these substeps. + if (response.type === 'error') { + p.reject(new TypeError('fetch failed', { cause: response.error })) + return + } + + // 4. Set responseObject to the result of creating a Response object, + // given response, "immutable", and relevantRealm. + responseObject = new WeakRef(fromInnerResponse(response, 'immutable')) + + // 5. Resolve p with responseObject. + p.resolve(responseObject.deref()) + p = null + } + + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: getRequestDispatcher(requestObject) // undici + }) + + // 14. Return p. + return p.promise +} + +// https://fetch.spec.whatwg.org/#finalize-and-report-timing +function finalizeAndReportTiming (response, initiatorType = 'other') { + // 1. If response is an aborted network error, then return. + if (response.type === 'error' && response.aborted) { + return + } + + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return + } + + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0] + + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo + + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState + + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return + } + + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } + + // 8. If response’s timing allow passed flag is not set, then: + if (!response.timingAllowPassed) { + // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }) + + // 2. Set cacheState to the empty string. + cacheState = '' + } + + // 9. Set timingInfo’s end time to the coarsened shared current time + // given global’s relevant settings object’s cross-origin isolated + // capability. + // TODO: given global’s relevant settings object’s cross-origin isolated + // capability? + timingInfo.endTime = coarsenedSharedCurrentTime() + + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL.href, + initiatorType, + globalThis, + cacheState, + '', // bodyType + response.status + ) +} + +// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing +const markResourceTiming = performance.markResourceTiming + +// https://fetch.spec.whatwg.org/#abort-fetch +function abortFetch (p, request, responseObject, error) { + // 1. Reject promise with error. + if (p) { + // We might have already resolved the promise at this stage + p.reject(error) + } + + // 2. If request’s body is not null and is readable, then cancel request’s + // body with error. + if (request.body?.stream != null && isReadable(request.body.stream)) { + request.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } + + // 3. If responseObject is null, then return. + if (responseObject == null) { + return + } + + // 4. Let response be responseObject’s response. + const response = getResponseState(responseObject) + + // 5. If response’s body is not null and is readable, then error response’s + // body with error. + if (response.body?.stream != null && isReadable(response.body.stream)) { + response.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } +} + +// https://fetch.spec.whatwg.org/#fetching +function fetching ({ + request, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseEndOfBody, + processResponseConsumeBody, + useParallelQueue = false, + dispatcher = getGlobalDispatcher() // undici +}) { + // Ensure that the dispatcher is set accordingly + assert(dispatcher) + + // 1. Let taskDestination be null. + let taskDestination = null + + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false + + // 3. If request’s client is non-null, then: + if (request.client != null) { + // 1. Set taskDestination to request’s client’s global object. + taskDestination = request.client.globalObject + + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability + } + + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO + + // 5. Let timingInfo be a new fetch timing info whose start time and + // post-redirect start time are the coarsened shared current time given + // crossOriginIsolatedCapability. + const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) + const timingInfo = createOpaqueTimingInfo({ + startTime: currentTime + }) + + // 6. Let fetchParams be a new fetch params whose + // request is request, + // timing info is timingInfo, + // process request body chunk length is processRequestBodyChunkLength, + // process request end-of-body is processRequestEndOfBody, + // process response is processResponse, + // process response consume body is processResponseConsumeBody, + // process response end-of-body is processResponseEndOfBody, + // task destination is taskDestination, + // and cross-origin isolated capability is crossOriginIsolatedCapability. + const fetchParams = { + controller: new Fetch(dispatcher), + request, + timingInfo, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseConsumeBody, + processResponseEndOfBody, + taskDestination, + crossOriginIsolatedCapability + } + + // 7. If request’s body is a byte sequence, then set request’s body to + // request’s body as a body. + // NOTE: Since fetching is only called from fetch, body should already be + // extracted. + assert(!request.body || request.body.stream) + + // 8. If request’s window is "client", then set request’s window to request’s + // client, if request’s client’s global object is a Window object; otherwise + // "no-window". + if (request.window === 'client') { + // TODO: What if request.client is null? + request.window = + request.client?.globalObject?.constructor?.name === 'Window' + ? request.client + : 'no-window' + } + + // 9. If request’s origin is "client", then set request’s origin to request’s + // client’s origin. + if (request.origin === 'client') { + request.origin = request.client.origin + } + + // 10. If all of the following conditions are true: + // TODO + + // 11. If request’s policy container is "client", then: + if (request.policyContainer === 'client') { + // 1. If request’s client is non-null, then set request’s policy + // container to a clone of request’s client’s policy container. [HTML] + if (request.client != null) { + request.policyContainer = clonePolicyContainer( + request.client.policyContainer + ) + } else { + // 2. Otherwise, set request’s policy container to a new policy + // container. + request.policyContainer = makePolicyContainer() + } + } + + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept', true)) { + // 1. Let value be `*/*`. + const value = '*/*' + + // 2. A user agent should set value to the first matching statement, if + // any, switching on request’s destination: + // "document" + // "frame" + // "iframe" + // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` + // "image" + // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` + // "style" + // `text/css,*/*;q=0.1` + // TODO + + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value, true) + } + + // 13. If request’s header list does not contain `Accept-Language`, then + // user agents should append `Accept-Language`/an appropriate value to + // request’s header list. + if (!request.headersList.contains('accept-language', true)) { + request.headersList.append('accept-language', '*', true) + } + + // 14. If request’s priority is null, then use request’s initiator and + // destination appropriately in setting request’s priority to a + // user-agent-defined object. + if (request.priority === null) { + // TODO + } + + // 15. If request is a subresource request, then: + if (subresourceSet.has(request.destination)) { + // TODO + } + + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams, false) + + // 17. Return fetchParam's controller + return fetchParams.controller +} + +// https://fetch.spec.whatwg.org/#concept-main-fetch +async function mainFetch (fetchParams, recursive) { + try { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. If request’s local-URLs-only flag is set and request’s current URL is + // not local, then set response to a network error. + if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { + response = makeNetworkError('local URLs only') + } + + // 4. Run report Content Security Policy violations for request. + // TODO + + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request) + + // 6. If should request be blocked due to a bad port, should fetching request + // be blocked as mixed content, or should request be blocked by Content + // Security Policy returns blocked, then set response to a network error. + if (requestBadPort(request) === 'blocked') { + response = makeNetworkError('bad port') + } + // TODO: should fetching request be blocked as mixed content? + // TODO: should request be blocked by Content Security Policy? + + // 7. If request’s referrer policy is the empty string, then set request’s + // referrer policy to request’s policy container’s referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = request.policyContainer.referrerPolicy + } + + // 8. If request’s referrer is not "no-referrer", then set request’s + // referrer to the result of invoking determine request’s referrer. + if (request.referrer !== 'no-referrer') { + request.referrer = determineRequestsReferrer(request) + } + + // 9. Set request’s current URL’s scheme to "https" if all of the following + // conditions are true: + // - request’s current URL’s scheme is "http" + // - request’s current URL’s host is a domain + // - Matching request’s current URL’s host per Known HSTS Host Domain Name + // Matching results in either a superdomain match with an asserted + // includeSubDomains directive or a congruent match (with or without an + // asserted includeSubDomains directive). [HSTS] + // TODO + + // 10. If recursive is false, then run the remaining steps in parallel. + // TODO + + // 11. If response is null, then set response to the result of running + // the steps corresponding to the first matching statement: + if (response === null) { + const currentURL = requestCurrentURL(request) + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || + // request’s current URL’s scheme is "data" + (currentURL.protocol === 'data:') || + // - request’s mode is "navigate" or "websocket" + (request.mode === 'navigate' || request.mode === 'websocket') + ) { + // 1. Set request’s response tainting to "basic". + request.responseTainting = 'basic' + + // 2. Return the result of running scheme fetch given fetchParams. + response = await schemeFetch(fetchParams) + + // request’s mode is "same-origin" + } else if (request.mode === 'same-origin') { + // 1. Return a network error. + response = makeNetworkError('request mode cannot be "same-origin"') + + // request’s mode is "no-cors" + } else if (request.mode === 'no-cors') { + // 1. If request’s redirect mode is not "follow", then return a network + // error. + if (request.redirect !== 'follow') { + response = makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ) + } else { + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque' + + // 3. Return the result of running scheme fetch given fetchParams. + response = await schemeFetch(fetchParams) + } + // request’s current URL’s scheme is not an HTTP(S) scheme + } else if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { + // Return a network error. + response = makeNetworkError('URL scheme must be a HTTP(S) scheme') + + // - request’s use-CORS-preflight flag is set + // - request’s unsafe-request flag is set and either request’s method is + // not a CORS-safelisted method or CORS-unsafe request-header names with + // request’s header list is not empty + // 1. Set request’s response tainting to "cors". + // 2. Let corsWithPreflightResponse be the result of running HTTP fetch + // given fetchParams and true. + // 3. If corsWithPreflightResponse is a network error, then clear cache + // entries using request. + // 4. Return corsWithPreflightResponse. + // TODO + + // Otherwise + } else { + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors' + + // 2. Return the result of running HTTP fetch given fetchParams. + response = await httpFetch(fetchParams) + } + } + + // 12. If recursive is true, then return response. + if (recursive) { + return response + } + + // 13. If response is not a network error and response is not a filtered + // response, then: + if (response.status !== 0 && !response.internalResponse) { + // If request’s response tainting is "cors", then: + if (request.responseTainting === 'cors') { + // 1. Let headerNames be the result of extracting header list values + // given `Access-Control-Expose-Headers` and response’s header list. + // TODO + // 2. If request’s credentials mode is not "include" and headerNames + // contains `*`, then set response’s CORS-exposed header-name list to + // all unique header names in response’s header list. + // TODO + // 3. Otherwise, if headerNames is not null or failure, then set + // response’s CORS-exposed header-name list to headerNames. + // TODO + } + + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (request.responseTainting === 'basic') { + response = filterResponse(response, 'basic') + } else if (request.responseTainting === 'cors') { + response = filterResponse(response, 'cors') + } else if (request.responseTainting === 'opaque') { + response = filterResponse(response, 'opaque') + } else { + assert(false) + } + } + + // 14. Let internalResponse be response, if response is a network error, + // and response’s internal response otherwise. + let internalResponse = + response.status === 0 ? response : response.internalResponse + + // 15. If internalResponse’s URL list is empty, then set it to a clone of + // request’s URL list. + if (internalResponse.urlList.length === 0) { + internalResponse.urlList.push(...request.urlList) + } + + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true + } + + // 17. If response is not a network error and any of the following returns + // blocked + // - should internalResponse to request be blocked as mixed content + // - should internalResponse to request be blocked by Content Security Policy + // - should internalResponse to request be blocked due to its MIME type + // - should internalResponse to request be blocked due to nosniff + // TODO + + // 18. If response’s type is "opaque", internalResponse’s status is 206, + // internalResponse’s range-requested flag is set, and request’s header + // list does not contain `Range`, then set response and internalResponse + // to a network error. + if ( + response.type === 'opaque' && + internalResponse.status === 206 && + internalResponse.rangeRequested && + !request.headers.contains('range', true) + ) { + response = internalResponse = makeNetworkError() + } + + // 19. If response is not a network error and either request’s method is + // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, + // set internalResponse’s body to null and disregard any enqueuing toward + // it (if any). + if ( + response.status !== 0 && + (request.method === 'HEAD' || + request.method === 'CONNECT' || + nullBodyStatus.includes(internalResponse.status)) + ) { + internalResponse.body = null + fetchParams.controller.dump = true + } + + // 20. If request’s integrity metadata is not the empty string, then: + if (request.integrity) { + // 1. Let processBodyError be this step: run fetch finale given fetchParams + // and a network error. + const processBodyError = (reason) => + fetchFinale(fetchParams, makeNetworkError(reason)) + + // 2. If request’s response tainting is "opaque", or response’s body is null, + // then run processBodyError and abort these steps. + if (request.responseTainting === 'opaque' || response.body == null) { + processBodyError(response.error) + return + } + + // 3. Let processBody given bytes be these steps: + const processBody = (bytes) => { + // 1. If bytes do not match request’s integrity metadata, + // then run processBodyError and abort these steps. [SRI] + if (!bytesMatch(bytes, request.integrity)) { + processBodyError('integrity mismatch') + return + } + + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0] + + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } + + // 4. Fully read response’s body given processBody and processBodyError. + fullyReadBody(response.body, processBody, processBodyError) + } else { + // 21. Otherwise, run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } + } catch (err) { + fetchParams.controller.terminate(err) + } +} + +// https://fetch.spec.whatwg.org/#concept-scheme-fetch +// given a fetch params fetchParams +function schemeFetch (fetchParams) { + // Note: since the connection is destroyed on redirect, which sets fetchParams to a + // cancelled state, we do not want this condition to trigger *unless* there have been + // no redirects. See https://github.com/nodejs/undici/issues/1776 + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) + } + + // 2. Let request be fetchParams’s request. + const { request } = fetchParams + + const { protocol: scheme } = requestCurrentURL(request) + + // 3. Switch on request’s current URL’s scheme and run the associated steps: + switch (scheme) { + case 'about:': { + // If request’s current URL’s path is the string "blank", then return a new response + // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », + // and body is the empty byte sequence as a body. + + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) + } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = require('node:buffer').resolveObjectURL + } + + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request) + + // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 + // Buffer.resolveObjectURL does not ignore URL queries. + if (blobURLEntry.search.length !== 0) { + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) + } + + const blob = resolveObjectURL(blobURLEntry.toString()) + + // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s + // object is not a Blob object, then return a network error. + if (request.method !== 'GET' || !webidl.is.Blob(blob)) { + return Promise.resolve(makeNetworkError('invalid method')) + } + + // 3. Let blob be blobURLEntry’s object. + // Note: done above + + // 4. Let response be a new response. + const response = makeResponse() + + // 5. Let fullLength be blob’s size. + const fullLength = blob.size + + // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded. + const serializedFullLength = isomorphicEncode(`${fullLength}`) + + // 7. Let type be blob’s type. + const type = blob.type + + // 8. If request’s header list does not contain `Range`: + // 9. Otherwise: + if (!request.headersList.contains('range', true)) { + // 1. Let bodyWithType be the result of safely extracting blob. + // Note: in the FileAPI a blob "object" is a Blob *or* a MediaSource. + // In node, this can only ever be a Blob. Therefore we can safely + // use extractBody directly. + const bodyWithType = extractBody(blob) + + // 2. Set response’s status message to `OK`. + response.statusText = 'OK' + + // 3. Set response’s body to bodyWithType’s body. + response.body = bodyWithType[0] + + // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ». + response.headersList.set('content-length', serializedFullLength, true) + response.headersList.set('content-type', type, true) + } else { + // 1. Set response’s range-requested flag. + response.rangeRequested = true + + // 2. Let rangeHeader be the result of getting `Range` from request’s header list. + const rangeHeader = request.headersList.get('range', true) + + // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true. + const rangeValue = simpleRangeHeaderValue(rangeHeader, true) + + // 4. If rangeValue is failure, then return a network error. + if (rangeValue === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } + + // 5. Let (rangeStart, rangeEnd) be rangeValue. + let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue + + // 6. If rangeStart is null: + // 7. Otherwise: + if (rangeStart === null) { + // 1. Set rangeStart to fullLength − rangeEnd. + rangeStart = fullLength - rangeEnd + + // 2. Set rangeEnd to rangeStart + rangeEnd − 1. + rangeEnd = rangeStart + rangeEnd - 1 + } else { + // 1. If rangeStart is greater than or equal to fullLength, then return a network error. + if (rangeStart >= fullLength) { + return Promise.resolve(makeNetworkError('Range start is greater than the blob\'s size.')) + } + + // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set + // rangeEnd to fullLength − 1. + if (rangeEnd === null || rangeEnd >= fullLength) { + rangeEnd = fullLength - 1 + } + } + + // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart, + // rangeEnd + 1, and type. + const slicedBlob = blob.slice(rangeStart, rangeEnd + 1, type) + + // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob. + // Note: same reason as mentioned above as to why we use extractBody + const slicedBodyWithType = extractBody(slicedBlob) + + // 10. Set response’s body to slicedBodyWithType’s body. + response.body = slicedBodyWithType[0] + + // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded. + const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`) + + // 12. Let contentRange be the result of invoking build a content range given rangeStart, + // rangeEnd, and fullLength. + const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength) + + // 13. Set response’s status to 206. + response.status = 206 + + // 14. Set response’s status message to `Partial Content`. + response.statusText = 'Partial Content' + + // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength), + // (`Content-Type`, type), (`Content-Range`, contentRange) ». + response.headersList.set('content-length', serializedSlicedLength, true) + response.headersList.set('content-type', type, true) + response.headersList.set('content-range', contentRange, true) + } + + // 10. Return response. + return Promise.resolve(response) + } + case 'data:': { + // 1. Let dataURLStruct be the result of running the + // data: URL processor on request’s current URL. + const currentURL = requestCurrentURL(request) + const dataURLStruct = dataURLProcessor(currentURL) + + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } + + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType) + + // 4. Return a response whose status message is `OK`, + // header list is « (`Content-Type`, mimeType) », + // and body is dataURLStruct’s body as a body. + return Promise.resolve(makeResponse({ + statusText: 'OK', + headersList: [ + ['content-type', { name: 'Content-Type', value: mimeType }] + ], + body: safelyExtractBody(dataURLStruct.body)[0] + })) + } + case 'file:': { + // For now, unfortunate as it is, file URLs are left as an exercise for the reader. + // When in doubt, return a network error. + return Promise.resolve(makeNetworkError('not implemented... yet...')) + } + case 'http:': + case 'https:': { + // Return the result of running HTTP fetch given fetchParams. + + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) + } + } +} + +// https://fetch.spec.whatwg.org/#finalize-response +function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // 2, If fetchParams’s process response done is not null, then queue a fetch + // task to run fetchParams’s process response done given response, with + // fetchParams’s task destination. + if (fetchParams.processResponseDone != null) { + queueMicrotask(() => fetchParams.processResponseDone(response)) + } +} + +// https://fetch.spec.whatwg.org/#fetch-finale +function fetchFinale (fetchParams, response) { + // 1. Let timingInfo be fetchParams’s timing info. + let timingInfo = fetchParams.timingInfo + + // 2. If response is not a network error and fetchParams’s request’s client is a secure context, + // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting + // `Server-Timing` from response’s internal response’s header list. + // TODO + + // 3. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Let unsafeEndTime be the unsafe shared current time. + const unsafeEndTime = Date.now() // ? + + // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s + // full timing info to fetchParams’s timing info. + if (fetchParams.request.destination === 'document') { + fetchParams.controller.fullTimingInfo = timingInfo + } + + // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global: + fetchParams.controller.reportTimingSteps = () => { + // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(fetchParams.request.url)) { + return + } + + // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global. + timingInfo.endTime = unsafeEndTime + + // 3. Let cacheState be response’s cache state. + let cacheState = response.cacheState + + // 4. Let bodyInfo be response’s body info. + const bodyInfo = response.bodyInfo + + // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an + // opaque timing info for timingInfo and set cacheState to the empty string. + if (!response.timingAllowPassed) { + timingInfo = createOpaqueTimingInfo(timingInfo) + + cacheState = '' + } + + // 6. Let responseStatus be 0. + let responseStatus = 0 + + // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false: + if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) { + // 1. Set responseStatus to response’s status. + responseStatus = response.status + + // 2. Let mimeType be the result of extracting a MIME type from response’s header list. + const mimeType = extractMimeType(response.headersList) + + // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType. + if (mimeType !== 'failure') { + bodyInfo.contentType = minimizeSupportedMimeType(mimeType) + } + } + + // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo, + // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo, + // and responseStatus. + if (fetchParams.request.initiatorType != null) { + markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus) + } + } + + // 4. Let processResponseEndOfBodyTask be the following steps: + const processResponseEndOfBodyTask = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process + // response end-of-body given response. + if (fetchParams.processResponseEndOfBody != null) { + queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) + } + + // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s + // global object is fetchParams’s task destination, then run fetchParams’s controller’s report + // timing steps given fetchParams’s request’s client’s global object. + if (fetchParams.request.initiatorType != null) { + fetchParams.controller.reportTimingSteps() + } + } + + // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination + queueMicrotask(() => processResponseEndOfBodyTask()) + } + + // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s + // process response given response, with fetchParams’s task destination. + if (fetchParams.processResponse != null) { + queueMicrotask(() => { + fetchParams.processResponse(response) + fetchParams.processResponse = null + }) + } + + // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response. + const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response) + + // 6. If internalResponse’s body is null, then run processResponseEndOfBody. + // 7. Otherwise: + if (internalResponse.body == null) { + processResponseEndOfBody() + } else { + // mcollina: all the following steps of the specs are skipped. + // The internal transform stream is not needed. + // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541 + + // 1. Let transformStream be a new TransformStream. + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream. + // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm + // set to processResponseEndOfBody. + // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream. + + finished(internalResponse.body.stream, () => { + processResponseEndOfBody() + }) + } +} + +// https://fetch.spec.whatwg.org/#http-fetch +async function httpFetch (fetchParams) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let actualResponse be null. + let actualResponse = null + + // 4. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 5. If request’s service-workers mode is "all", then: + if (request.serviceWorkers === 'all') { + // TODO + } + + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO + + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none' + } + + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) + + // 4. If request’s response tainting is "cors" and a CORS check + // for request and response returns failure, then return a network error. + if ( + request.responseTainting === 'cors' && + corsCheck(request, response) === 'failure' + ) { + return makeNetworkError('cors failure') + } + + // 5. If the TAO check for request and response returns failure, then set + // request’s timing allow failed flag. + if (TAOCheck(request, response) === 'failure') { + request.timingAllowFailed = true + } + } + + // 7. If either request’s response tainting or response’s type + // is "opaque", and the cross-origin resource policy check with + // request’s origin, request’s client, request’s destination, + // and actualResponse returns blocked, then return a network error. + if ( + (request.responseTainting === 'opaque' || response.type === 'opaque') && + crossOriginResourcePolicyCheck( + request.origin, + request.client, + request.destination, + actualResponse + ) === 'blocked' + ) { + return makeNetworkError('blocked') + } + + // 8. If actualResponse’s status is a redirect status, then: + if (redirectStatusSet.has(actualResponse.status)) { + // 1. If actualResponse’s status is not 303, request’s body is not null, + // and the connection uses HTTP/2, then user agents may, and are even + // encouraged to, transmit an RST_STREAM frame. + // See, https://github.com/whatwg/fetch/issues/1288 + if (request.redirect !== 'manual') { + fetchParams.controller.connection.destroy(undefined, false) + } + + // 2. Switch on request’s redirect mode: + if (request.redirect === 'error') { + // Set response to a network error. + response = makeNetworkError('unexpected redirect') + } else if (request.redirect === 'manual') { + // Set response to an opaque-redirect filtered response whose internal + // response is actualResponse. + // NOTE(spec): On the web this would return an `opaqueredirect` response, + // but that doesn't make sense server side. + // See https://github.com/nodejs/undici/issues/1193. + response = actualResponse + } else if (request.redirect === 'follow') { + // Set response to the result of running HTTP-redirect fetch given + // fetchParams and response. + response = await httpRedirectFetch(fetchParams, response) + } else { + assert(false) + } + } + + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 10. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-redirect-fetch +function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let actualResponse be response, if response is not a filtered response, + // and response’s internal response otherwise. + const actualResponse = response.internalResponse + ? response.internalResponse + : response + + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL + + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ) + + // 4. If locationURL is null, then return response. + if (locationURL == null) { + return response + } + } catch (err) { + // 5. If locationURL is failure, then return a network error. + return Promise.resolve(makeNetworkError(err)) + } + + // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network + // error. + if (!urlIsHttpHttpsScheme(locationURL)) { + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) + } + + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return Promise.resolve(makeNetworkError('redirect count exceeded')) + } + + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1 + + // 9. If request’s mode is "cors", locationURL includes credentials, and + // request’s origin is not same origin with locationURL’s origin, then return + // a network error. + if ( + request.mode === 'cors' && + (locationURL.username || locationURL.password) && + !sameOrigin(request, locationURL) + ) { + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) + } + + // 10. If request’s response tainting is "cors" and locationURL includes + // credentials, then return a network error. + if ( + request.responseTainting === 'cors' && + (locationURL.username || locationURL.password) + ) { + return Promise.resolve(makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + )) + } + + // 11. If actualResponse’s status is not 303, request’s body is non-null, + // and request’s body’s source is null, then return a network error. + if ( + actualResponse.status !== 303 && + request.body != null && + request.body.source == null + ) { + return Promise.resolve(makeNetworkError()) + } + + // 12. If one of the following is true + // - actualResponse’s status is 301 or 302 and request’s method is `POST` + // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` + if ( + ([301, 302].includes(actualResponse.status) && request.method === 'POST') || + (actualResponse.status === 303 && + !GET_OR_HEAD.includes(request.method)) + ) { + // then: + // 1. Set request’s method to `GET` and request’s body to null. + request.method = 'GET' + request.body = null + + // 2. For each headerName of request-body-header name, delete headerName from + // request’s header list. + for (const headerName of requestBodyHeader) { + request.headersList.delete(headerName) + } + } + + // 13. If request’s current URL’s origin is not same origin with locationURL’s + // origin, then for each headerName of CORS non-wildcard request-header name, + // delete headerName from request’s header list. + if (!sameOrigin(requestCurrentURL(request), locationURL)) { + // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name + request.headersList.delete('authorization', true) + + // https://fetch.spec.whatwg.org/#authentication-entries + request.headersList.delete('proxy-authorization', true) + + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie', true) + request.headersList.delete('host', true) + } + + // 14. If request’s body is non-null, then set request’s body to the first return + // value of safely extracting request’s body’s source. + if (request.body != null) { + assert(request.body.source != null) + request.body = safelyExtractBody(request.body.source)[0] + } + + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 16. Set timingInfo’s redirect end time and post-redirect start time to the + // coarsened shared current time given fetchParams’s cross-origin isolated + // capability. + timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = + coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + + // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s + // redirect start time to timingInfo’s start time. + if (timingInfo.redirectStartTime === 0) { + timingInfo.redirectStartTime = timingInfo.startTime + } + + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL) + + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse) + + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) +} + +// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch +async function httpNetworkOrCacheFetch ( + fetchParams, + isAuthenticationFetch = false, + isNewConnectionFetch = false +) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let httpFetchParams be null. + let httpFetchParams = null + + // 3. Let httpRequest be null. + let httpRequest = null + + // 4. Let response be null. + let response = null + + // 5. Let storedResponse be null. + // TODO: cache + + // 6. Let httpCache be null. + const httpCache = null + + // 7. Let the revalidatingFlag be unset. + const revalidatingFlag = false + + // 8. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If request’s window is "no-window" and request’s redirect mode is + // "error", then set httpFetchParams to fetchParams and httpRequest to + // request. + if (request.window === 'no-window' && request.redirect === 'error') { + httpFetchParams = fetchParams + httpRequest = request + } else { + // Otherwise: + + // 1. Set httpRequest to a clone of request. + httpRequest = cloneRequest(request) + + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams } + + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest + } + + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic') + + // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s + // body is non-null; otherwise null. + const contentLength = httpRequest.body ? httpRequest.body.length : null + + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null + + // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or + // `PUT`, then set contentLengthHeaderValue to `0`. + if ( + httpRequest.body == null && + ['POST', 'PUT'].includes(httpRequest.method) + ) { + contentLengthHeaderValue = '0' + } + + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) + } + + // 8. If contentLengthHeaderValue is non-null, then append + // `Content-Length`/contentLengthHeaderValue to httpRequest’s header + // list. + if (contentLengthHeaderValue != null) { + httpRequest.headersList.append('content-length', contentLengthHeaderValue, true) + } + + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. + + // 10. If contentLength is non-null and httpRequest’s keepalive is true, + // then: + if (contentLength != null && httpRequest.keepalive) { + // NOTE: keepalive is a noop outside of browser context. + } + + // 11. If httpRequest’s referrer is a URL, then append + // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, + // to httpRequest’s header list. + if (webidl.is.URL(httpRequest.referrer)) { + httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true) + } + + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest) + + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest) + + // 14. If httpRequest’s header list does not contain `User-Agent`, then + // user agents should append `User-Agent`/default `User-Agent` value to + // httpRequest’s header list. + if (!httpRequest.headersList.contains('user-agent', true)) { + httpRequest.headersList.append('user-agent', defaultUserAgent, true) + } + + // 15. If httpRequest’s cache mode is "default" and httpRequest’s header + // list contains `If-Modified-Since`, `If-None-Match`, + // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set + // httpRequest’s cache mode to "no-store". + if ( + httpRequest.cache === 'default' && + (httpRequest.headersList.contains('if-modified-since', true) || + httpRequest.headersList.contains('if-none-match', true) || + httpRequest.headersList.contains('if-unmodified-since', true) || + httpRequest.headersList.contains('if-match', true) || + httpRequest.headersList.contains('if-range', true)) + ) { + httpRequest.cache = 'no-store' + } + + // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent + // no-cache cache-control header modification flag is unset, and + // httpRequest’s header list does not contain `Cache-Control`, then append + // `Cache-Control`/`max-age=0` to httpRequest’s header list. + if ( + httpRequest.cache === 'no-cache' && + !httpRequest.preventNoCacheCacheControlHeaderModification && + !httpRequest.headersList.contains('cache-control', true) + ) { + httpRequest.headersList.append('cache-control', 'max-age=0', true) + } + + // 17. If httpRequest’s cache mode is "no-store" or "reload", then: + if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { + // 1. If httpRequest’s header list does not contain `Pragma`, then append + // `Pragma`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('pragma', true)) { + httpRequest.headersList.append('pragma', 'no-cache', true) + } + + // 2. If httpRequest’s header list does not contain `Cache-Control`, + // then append `Cache-Control`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('cache-control', true)) { + httpRequest.headersList.append('cache-control', 'no-cache', true) + } + } + + // 18. If httpRequest’s header list contains `Range`, then append + // `Accept-Encoding`/`identity` to httpRequest’s header list. + if (httpRequest.headersList.contains('range', true)) { + httpRequest.headersList.append('accept-encoding', 'identity', true) + } + + // 19. Modify httpRequest’s header list per HTTP. Do not append a given + // header if httpRequest’s header list contains that header’s name. + // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 + if (!httpRequest.headersList.contains('accept-encoding', true)) { + if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { + httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true) + } else { + httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true) + } + } + + httpRequest.headersList.delete('host', true) + + // 21. If includeCredentials is true, then: + if (includeCredentials) { + // 1. If the user agent is not configured to block cookies for httpRequest + // (see section 7 of [COOKIES]), then: + // TODO: credentials + + // 2. If httpRequest’s header list does not contain `Authorization`, then: + if (!httpRequest.headersList.contains('authorization', true)) { + // 1. Let authorizationValue be null. + let authorizationValue = null + + // 2. If there’s an authentication entry for httpRequest and either + // httpRequest’s use-URL-credentials flag is unset or httpRequest’s + // current URL does not include credentials, then set + // authorizationValue to authentication entry. + if (hasAuthenticationEntry(httpRequest) && ( + httpRequest.useURLCredentials === undefined || !includesCredentials(requestCurrentURL(httpRequest)) + )) { + // TODO + } else if (includesCredentials(requestCurrentURL(httpRequest)) && isAuthenticationFetch) { + // 3. Otherwise, if httpRequest’s current URL does include credentials + // and isAuthenticationFetch is true, set authorizationValue to + // httpRequest’s current URL, converted to an `Authorization` value + const { username, password } = requestCurrentURL(httpRequest) + authorizationValue = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}` + } + + // 4. If authorizationValue is non-null, then append (`Authorization`, + // authorizationValue) to httpRequest’s header list. + if (authorizationValue !== null) { + httpRequest.headersList.append('Authorization', authorizationValue, false) + } + } + } + + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication + + // 22. Set httpCache to the result of determining the HTTP cache + // partition, given httpRequest. + // TODO: cache + + // 23. If httpCache is null, then set httpRequest’s cache mode to + // "no-store". + if (httpCache == null) { + httpRequest.cache = 'no-store' + } + + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') { + // TODO: cache + } + + // 9. If aborted, then return the appropriate network error for fetchParams. + // TODO + + // 10. If response is null, then: + if (response == null) { + // 1. If httpRequest’s cache mode is "only-if-cached", then return a + // network error. + if (httpRequest.cache === 'only-if-cached') { + return makeNetworkError('only if cached') + } + + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ) + + // 3. If httpRequest’s method is unsafe and forwardResponse’s status is + // in the range 200 to 399, inclusive, invalidate appropriate stored + // responses in httpCache, as per the "Invalidation" chapter of HTTP + // Caching, and set storedResponse to null. [HTTP-CACHING] + if ( + !safeMethodsSet.has(httpRequest.method) && + forwardResponse.status >= 200 && + forwardResponse.status <= 399 + ) { + // TODO: cache + } + + // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, + // then: + if (revalidatingFlag && forwardResponse.status === 304) { + // TODO: cache + } + + // 5. If response is null, then: + if (response == null) { + // 1. Set response to forwardResponse. + response = forwardResponse + + // 2. Store httpRequest and forwardResponse in httpCache, as per the + // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] + // TODO: cache + } + } + + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList] + + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range', true)) { + response.rangeRequested = true + } + + // 13. Set response’s request-includes-credentials to includeCredentials. + response.requestIncludesCredentials = includeCredentials + + // 14. If response’s status is 401, httpRequest’s response tainting is not "cors", + // includeCredentials is true, and request’s traversable for user prompts is + // a traversable navigable: + if (response.status === 401 && httpRequest.responseTainting !== 'cors' && includeCredentials && isTraversableNavigable(request.traversableForUserPrompts)) { + // 2. If request’s body is non-null, then: + if (request.body != null) { + // 1. If request’s body’s source is null, then return a network error. + if (request.body.source == null) { + return makeNetworkError('expected non-null body source') + } + + // 2. Set request’s body to the body of the result of safely extracting + // request’s body’s source. + request.body = safelyExtractBody(request.body.source)[0] + } + + // 3. If request’s use-URL-credentials flag is unset or isAuthenticationFetch is + // true, then: + if (request.useURLCredentials === undefined || isAuthenticationFetch) { + // 1. If fetchParams is canceled, then return the appropriate network error + // for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Let username and password be the result of prompting the end user for a + // username and password, respectively, in request’s traversable for user prompts. + // TODO + + // 3. Set the username given request’s current URL and username. + // requestCurrentURL(request).username = TODO + + // 4. Set the password given request’s current URL and password. + // requestCurrentURL(request).password = TODO + + // In browsers, the user will be prompted to enter a username/password before the request + // is re-sent. To prevent an infinite 401 loop, return a network error for now. + // https://github.com/nodejs/undici/pull/4756 + return makeNetworkError() + } + + // 4. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams and true. + fetchParams.controller.connection.destroy() + + response = await httpNetworkOrCacheFetch(fetchParams, true) + } + + // 15. If response’s status is 407, then: + if (response.status === 407) { + // 1. If request’s window is "no-window", then return a network error. + if (request.window === 'no-window') { + return makeNetworkError() + } + + // 2. ??? + + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 4. Prompt the end user as appropriate in request’s window and store + // the result as a proxy-authentication entry. [HTTP-AUTH] + // TODO: Invoke some kind of callback? + + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') + } + + // 16. If all of the following are true + if ( + // response’s status is 421 + response.status === 421 && + // isNewConnectionFetch is false + !isNewConnectionFetch && + // request’s body is null, or request’s body is non-null and request’s body’s source is non-null + (request.body == null || request.body.source != null) + ) { + // then: + + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. + + // TODO (spec): The spec doesn't specify this but we need to cancel + // the active response before we can start a new one. + // https://github.com/whatwg/fetch/issues/1293 + fetchParams.controller.connection.destroy() + + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ) + } + + // 17. If isAuthenticationFetch is true, then create an authentication entry + if (isAuthenticationFetch) { + // TODO + } + + // 18. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-network-fetch +async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false +) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) + + fetchParams.controller.connection = { + abort: null, + destroyed: false, + destroy (err, abort = true) { + if (!this.destroyed) { + this.destroyed = true + if (abort) { + this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) + } + } + } + } + + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 4. Let httpCache be the result of determining the HTTP cache partition, + // given request. + // TODO: cache + const httpCache = null + + // 5. If httpCache is null, then set request’s cache mode to "no-store". + if (httpCache == null) { + request.cache = 'no-store' + } + + // 6. Let networkPartitionKey be the result of determining the network + // partition key given request. + // TODO + + // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise + // "no". + const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars + + // 8. Switch on request’s mode: + if (request.mode === 'websocket') { + // Let connection be the result of obtaining a WebSocket connection, + // given request’s current URL. + // TODO + } else { + // Let connection be the result of obtaining a connection, given + // networkPartitionKey, request’s current URL’s origin, + // includeCredentials, and forceNewConnection. + // TODO + } + + // 9. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If connection is failure, then return a network error. + + // 2. Set timingInfo’s final connection timing info to the result of + // calling clamp and coarsen connection timing info with connection’s + // timing info, timingInfo’s post-redirect start time, and fetchParams’s + // cross-origin isolated capability. + + // 3. If connection is not an HTTP/2 connection, request’s body is non-null, + // and request’s body’s source is null, then append (`Transfer-Encoding`, + // `chunked`) to request’s header list. + + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. + + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: + + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] + + // - If request’s body is non-null, and request’s body’s source is null, + // then the user agent may have a buffer of up to 64 kibibytes and store + // a part of request’s body in that buffer. If the user agent reads from + // request’s body beyond that buffer’s size and the user agent needs to + // resend request, then instead return a network error. + + // - Set timingInfo’s final network-response start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated capability, + // immediately after the user agent’s HTTP parser receives the first byte + // of the response (e.g., frame header bytes for HTTP/2 or response status + // line for HTTP/1.x). + + // - Wait until all the headers are transmitted. + + // - Any responses whose status is in the range 100 to 199, inclusive, + // and is not 101, are to be ignored, except for the purposes of setting + // timingInfo’s final network-response start time above. + + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. + + // - If the HTTP request results in a TLS client certificate dialog, then: + + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. + + // 2. Otherwise, return a network error. + + // To transmit request’s body body, run these steps: + let requestBody = null + // 1. If body is null and fetchParams’s process request end-of-body is + // non-null, then queue a fetch task given fetchParams’s process request + // end-of-body and fetchParams’s task destination. + if (request.body == null && fetchParams.processRequestEndOfBody) { + queueMicrotask(() => fetchParams.processRequestEndOfBody()) + } else if (request.body != null) { + // 2. Otherwise, if body is non-null: + + // 1. Let processBodyChunk given bytes be these steps: + const processBodyChunk = async function * (bytes) { + // 1. If the ongoing fetch is terminated, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. Run this step in parallel: transmit bytes. + yield bytes + + // 3. If fetchParams’s process request body is non-null, then run + // fetchParams’s process request body given bytes’s length. + fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) + } + + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If fetchParams’s process request end-of-body is non-null, + // then run fetchParams’s process request end-of-body. + if (fetchParams.processRequestEndOfBody) { + fetchParams.processRequestEndOfBody() + } + } + + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort() + } else { + fetchParams.controller.terminate(e) + } + } + + // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, + // processBodyError, and fetchParams’s task destination. + requestBody = (async function * () { + try { + for await (const bytes of request.body.stream) { + yield * processBodyChunk(bytes) + } + processEndOfBody() + } catch (err) { + processBodyError(err) + } + })() + } + + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) + + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }) + } else { + const iterator = body[Symbol.asyncIterator]() + fetchParams.controller.next = () => iterator.next() + + response = makeResponse({ status, statusText, headersList }) + } + } catch (err) { + // 10. If aborted, then: + if (err.name === 'AbortError') { + // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. + fetchParams.controller.connection.destroy() + + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) + } + + return makeNetworkError(err) + } + + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = () => { + return fetchParams.controller.resume() + } + + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + // If the aborted fetch was already terminated, then we do not + // need to do anything. + if (!isCancelled(fetchParams)) { + fetchParams.controller.abort(reason) + } + } + + // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by + // the user agent. + // TODO + + // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object + // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. + // TODO + + // 15. Let stream be a new ReadableStream. + // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm, + // cancelAlgorithm set to cancelAlgorithm. + const stream = new ReadableStream( + { + start (controller) { + fetchParams.controller.controller = controller + }, + pull: pullAlgorithm, + cancel: cancelAlgorithm, + type: 'bytes' + } + ) + + // 17. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. Set response’s body to a new body whose stream is stream. + response.body = { stream, source: null, length: null } + + // 2. If response is not a network error and request’s cache mode is + // not "no-store", then update response in httpCache for request. + // TODO + + // 3. If includeCredentials is true and the user agent is not configured + // to block cookies for request (see section 7 of [COOKIES]), then run the + // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on + // the value of each header whose name is a byte-case-insensitive match for + // `Set-Cookie` in response’s header list, if any, and request’s current URL. + // TODO + + // 18. If aborted, then: + // TODO + + // 19. Run these steps in parallel: + + // 1. Run these steps, but abort when fetchParams is canceled: + if (!fetchParams.controller.resume) { + fetchParams.controller.on('terminated', onAborted) + } + + fetchParams.controller.resume = async () => { + // 1. While true + while (true) { + // 1-3. See onData... + + // 4. Set bytes to the result of handling content codings given + // codings and bytes. + let bytes + let isFailure + try { + const { done, value } = await fetchParams.controller.next() + + if (isAborted(fetchParams)) { + break + } + + bytes = done ? undefined : value + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined + } else { + bytes = err + + // err may be propagated from the result of calling readablestream.cancel, + // which might not be an error. https://github.com/nodejs/undici/issues/2009 + isFailure = true + } + } + + if (bytes === undefined) { + // 2. Otherwise, if the bytes transmission for response’s message + // body is done normally and stream is readable, then close + // stream, finalize response for fetchParams and response, and + // abort these in-parallel steps. + readableStreamClose(fetchParams.controller.controller) + + finalizeResponse(fetchParams, response) + + return + } + + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0 + + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes) + return + } + + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + const buffer = new Uint8Array(bytes) + if (buffer.byteLength) { + fetchParams.controller.controller.enqueue(buffer) + } + + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate() + return + } + + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (fetchParams.controller.controller.desiredSize <= 0) { + return + } + } + } + + // 2. If aborted, then: + function onAborted (reason) { + // 2. If fetchParams is aborted, then: + if (isAborted(fetchParams)) { + // 1. Set response’s aborted flag. + response.aborted = true + + // 2. If stream is readable, then error stream with the result of + // deserialize a serialized abort reason given fetchParams’s + // controller’s serialized abort reason and an + // implementation-defined realm. + if (isReadable(stream)) { + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ) + } + } else { + // 3. Otherwise, if stream is readable, error stream with a TypeError. + if (isReadable(stream)) { + fetchParams.controller.controller.error(new TypeError('terminated', { + cause: isErrorLike(reason) ? reason : undefined + })) + } + } + + // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. + // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. + fetchParams.controller.connection.destroy() + } + + // 20. Return response. + return response + + function dispatch ({ body }) { + const url = requestCurrentURL(request) + /** @type {import('../../..').Agent} */ + const agent = fetchParams.controller.dispatcher + + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body, + headers: request.headersList.entries, + maxRedirections: 0, + upgrade: request.mode === 'websocket' ? 'websocket' : undefined + }, + { + body: null, + abort: null, + + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller + + // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen + // connection timing info with connection’s timing info, timingInfo’s post-redirect start + // time, and fetchParams’s cross-origin isolated capability. + // TODO: implement connection timing + timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability) + + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')) + } else { + fetchParams.controller.on('terminated', abort) + this.abort = connection.abort = abort + } + + // Set timingInfo’s final network-request start time to the coarsened shared current time given + // fetchParams’s cross-origin isolated capability. + timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + }, + + onResponseStarted () { + // Set timingInfo’s final network-response start time to the coarsened shared current + // time given fetchParams’s cross-origin isolated capability, immediately after the + // user agent’s HTTP parser receives the first byte of the response (e.g., frame header + // bytes for HTTP/2 or response status line for HTTP/1.x). + timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + }, + + onHeaders (status, rawHeaders, resume, statusText) { + if (status < 200) { + return false + } + + const headersList = new HeadersList() + + for (let i = 0; i < rawHeaders.length; i += 2) { + headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true) + } + const location = headersList.get('location', true) + + this.body = new Readable({ read: resume }) + + const willFollow = location && request.redirect === 'follow' && + redirectStatusSet.has(status) + + const decoders = [] + + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + const contentEncoding = headersList.get('content-encoding', true) + // "All content-coding values are case-insensitive..." + /** @type {string[]} */ + const codings = contentEncoding ? contentEncoding.toLowerCase().split(',') : [] + + // Limit the number of content-encodings to prevent resource exhaustion. + // CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206). + const maxContentEncodings = 5 + if (codings.length > maxContentEncodings) { + reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`)) + return true + } + + for (let i = codings.length - 1; i >= 0; --i) { + const coding = codings[i].trim() + // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 + if (coding === 'x-gzip' || coding === 'gzip') { + decoders.push(zlib.createGunzip({ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })) + } else if (coding === 'deflate') { + decoders.push(createInflate({ + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })) + } else if (coding === 'br') { + decoders.push(zlib.createBrotliDecompress({ + flush: zlib.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH + })) + } else if (coding === 'zstd' && hasZstd) { + decoders.push(zlib.createZstdDecompress({ + flush: zlib.constants.ZSTD_e_continue, + finishFlush: zlib.constants.ZSTD_e_end + })) + } else { + decoders.length = 0 + break + } + } + } + + const onError = this.onError.bind(this) + + resolve({ + status, + statusText, + headersList, + body: decoders.length + ? pipeline(this.body, ...decoders, (err) => { + if (err) { + this.onError(err) + } + }).on('error', onError) + : this.body.on('error', onError) + }) + + return true + }, + + onData (chunk) { + if (fetchParams.controller.dump) { + return + } + + // 1. If one or more bytes have been transmitted from response’s + // message body, then: + + // 1. Let bytes be the transmitted bytes. + const bytes = chunk + + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. + + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength + + // 4. See pullAlgorithm... + + return this.body.push(bytes) + }, + + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + fetchParams.controller.ended = true + + this.body.push(null) + }, + + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + this.body?.destroy(error) + + fetchParams.controller.terminate(error) + + reject(error) + }, + + onUpgrade (status, rawHeaders, socket) { + // We need to support 200 for websocket over h2 as per RFC-8441 + // Absence of session means H1 + if ((socket.session != null && status !== 200) || (socket.session == null && status !== 101)) { + return false + } + + const headersList = new HeadersList() + + for (let i = 0; i < rawHeaders.length; i += 2) { + headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true) + } + + resolve({ + status, + statusText: STATUS_CODES[status], + headersList, + socket + }) + + return true + } + } + )) + } +} + +module.exports = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming +} diff --git a/node_modules/undici/lib/web/fetch/request.js b/node_modules/undici/lib/web/fetch/request.js new file mode 100644 index 000000000..6ef40f999 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/request.js @@ -0,0 +1,1115 @@ +/* globals AbortController */ + +'use strict' + +const { extractBody, mixinBody, cloneBody, bodyUnusable } = require('./body') +const { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require('./headers') +const util = require('../../core/util') +const nodeUtil = require('node:util') +const { + isValidHTTPToken, + sameOrigin, + environmentSettingsObject +} = require('./util') +const { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex +} = require('./constants') +const { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util +const { webidl } = require('../webidl') +const { URLSerializer } = require('./data-url') +const { kConstruct } = require('../../core/symbols') +const assert = require('node:assert') +const { getMaxListeners, setMaxListeners, defaultMaxListeners } = require('node:events') + +const kAbortController = Symbol('abortController') + +const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort) +}) + +const dependentControllerMap = new WeakMap() + +let abortSignalHasEventHandlerLeakWarning + +try { + abortSignalHasEventHandlerLeakWarning = getMaxListeners(new AbortController().signal) > 0 +} catch { + abortSignalHasEventHandlerLeakWarning = false +} + +function buildAbort (acRef) { + return abort + + function abort () { + const ac = acRef.deref() + if (ac !== undefined) { + // Currently, there is a problem with FinalizationRegistry. + // https://github.com/nodejs/node/issues/49344 + // https://github.com/nodejs/node/issues/47748 + // In the case of abort, the first step is to unregister from it. + // If the controller can refer to it, it is still registered. + // It will be removed in the future. + requestFinalizer.unregister(abort) + + // Unsubscribe a listener. + // FinalizationRegistry will no longer be called, so this must be done. + this.removeEventListener('abort', abort) + + ac.abort(this.reason) + + const controllerList = dependentControllerMap.get(ac.signal) + + if (controllerList !== undefined) { + if (controllerList.size !== 0) { + for (const ref of controllerList) { + const ctrl = ref.deref() + if (ctrl !== undefined) { + ctrl.abort(this.reason) + } + } + controllerList.clear() + } + dependentControllerMap.delete(ac.signal) + } + } + } +} + +let patchMethodWarning = false + +// https://fetch.spec.whatwg.org/#request-class +class Request { + /** @type {AbortSignal} */ + #signal + + /** @type {import('../../dispatcher/dispatcher')} */ + #dispatcher + + /** @type {Headers} */ + #headers + + #state + + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = undefined) { + webidl.util.markAsUncloneable(this) + + if (input === kConstruct) { + return + } + + const prefix = 'Request constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + input = webidl.converters.RequestInfo(input) + init = webidl.converters.RequestInit(init) + + // 1. Let request be null. + let request = null + + // 2. Let fallbackMode be null. + let fallbackMode = null + + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = environmentSettingsObject.settingsObject.baseUrl + + // 4. Let signal be null. + let signal = null + + // 5. If input is a string, then: + if (typeof input === 'string') { + this.#dispatcher = init.dispatcher + + // 1. Let parsedURL be the result of parsing input with baseURL. + // 2. If parsedURL is failure, then throw a TypeError. + let parsedURL + try { + parsedURL = new URL(input, baseUrl) + } catch (err) { + throw new TypeError('Failed to parse URL from ' + input, { cause: err }) + } + + // 3. If parsedURL includes credentials, then throw a TypeError. + if (parsedURL.username || parsedURL.password) { + throw new TypeError( + 'Request cannot be constructed from a URL that includes credentials: ' + + input + ) + } + + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }) + + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors' + } else { + // 6. Otherwise: + + // 7. Assert: input is a Request object. + assert(webidl.is.Request(input)) + + // 8. Set request to input’s request. + request = input.#state + + // 9. Set signal to input’s signal. + signal = input.#signal + + this.#dispatcher = init.dispatcher || input.#dispatcher + } + + // 7. Let origin be this’s relevant settings object’s origin. + const origin = environmentSettingsObject.settingsObject.origin + + // 8. Let window be "client". + let window = 'client' + + // 9. If request’s window is an environment settings object and its origin + // is same origin with origin, then set window to request’s window. + if ( + request.window?.constructor?.name === 'EnvironmentSettingsObject' && + sameOrigin(request.window, origin) + ) { + window = request.window + } + + // 10. If init["window"] exists and is non-null, then throw a TypeError. + if (init.window != null) { + throw new TypeError(`'window' option '${window}' must be null`) + } + + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window' + } + + // 12. Set request to a new request with the following properties: + request = makeRequest({ + // URL request’s URL. + // undici implementation note: this is set as the first item in request's urlList in makeRequest + // method request’s method. + method: request.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest + headersList: request.headersList, + // unsafe-request flag Set. + unsafeRequest: request.unsafeRequest, + // client This’s relevant settings object. + client: environmentSettingsObject.settingsObject, + // window window. + window, + // priority request’s priority. + priority: request.priority, + // origin request’s origin. The propagation of the origin is only significant for navigation requests + // being handled by a service worker. In this scenario a request can have an origin that is different + // from the current client. + origin: request.origin, + // referrer request’s referrer. + referrer: request.referrer, + // referrer policy request’s referrer policy. + referrerPolicy: request.referrerPolicy, + // mode request’s mode. + mode: request.mode, + // credentials mode request’s credentials mode. + credentials: request.credentials, + // cache mode request’s cache mode. + cache: request.cache, + // redirect mode request’s redirect mode. + redirect: request.redirect, + // integrity metadata request’s integrity metadata. + integrity: request.integrity, + // keepalive request’s keepalive. + keepalive: request.keepalive, + // reload-navigation flag request’s reload-navigation flag. + reloadNavigation: request.reloadNavigation, + // history-navigation flag request’s history-navigation flag. + historyNavigation: request.historyNavigation, + // URL list A clone of request’s URL list. + urlList: [...request.urlList] + }) + + const initHasKey = Object.keys(init).length !== 0 + + // 13. If init is not empty, then: + if (initHasKey) { + // 1. If request’s mode is "navigate", then set it to "same-origin". + if (request.mode === 'navigate') { + request.mode = 'same-origin' + } + + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false + + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false + + // 4. Set request’s origin to "client". + request.origin = 'client' + + // 5. Set request’s referrer to "client" + request.referrer = 'client' + + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = '' + + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1] + + // 8. Set request’s URL list to « request’s URL ». + request.urlList = [request.url] + } + + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer + + // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". + if (referrer === '') { + request.referrer = 'no-referrer' + } else { + // 1. Let parsedReferrer be the result of parsing referrer with + // baseURL. + // 2. If parsedReferrer is failure, then throw a TypeError. + let parsedReferrer + try { + parsedReferrer = new URL(referrer, baseUrl) + } catch (err) { + throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) + } + + // 3. If one of the following is true + // - parsedReferrer’s scheme is "about" and path is the string "client" + // - parsedReferrer’s origin is not same origin with origin + // then set request’s referrer to "client". + if ( + (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || + (origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) + ) { + request.referrer = 'client' + } else { + // 4. Otherwise, set request’s referrer to parsedReferrer. + request.referrer = parsedReferrer + } + } + } + + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy + } + + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode + if (init.mode !== undefined) { + mode = init.mode + } else { + mode = fallbackMode + } + + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) + } + + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode + } + + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials + } + + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache + } + + // 21. If request’s cache mode is "only-if-cached" and request’s mode is + // not "same-origin", then throw a TypeError. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ) + } + + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect + } + + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity != null) { + request.integrity = String(init.integrity) + } + + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive) + } + + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method + + const mayBeNormalized = normalizedMethodRecords[method] + + if (mayBeNormalized !== undefined) { + // Note: Bypass validation DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH and these lowercase ones + request.method = mayBeNormalized + } else { + // 2. If method is not a method or method is a forbidden method, then + // throw a TypeError. + if (!isValidHTTPToken(method)) { + throw new TypeError(`'${method}' is not a valid HTTP method.`) + } + + const upperCase = method.toUpperCase() + + if (forbiddenMethodsSet.has(upperCase)) { + throw new TypeError(`'${method}' HTTP method is unsupported.`) + } + + // 3. Normalize method. + // https://fetch.spec.whatwg.org/#concept-method-normalize + // Note: must be in uppercase + method = normalizedMethodRecordsBase[upperCase] ?? method + + // 4. Set request’s method to method. + request.method = method + } + + if (!patchMethodWarning && request.method === 'patch') { + process.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', { + code: 'UNDICI-FETCH-patch' + }) + + patchMethodWarning = true + } + } + + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal + } + + // 27. Set this’s request to request. + this.#state = request + + // 28. Set this’s signal to a new AbortSignal object with this’s relevant + // Realm. + // TODO: could this be simplified with AbortSignal.any + // (https://dom.spec.whatwg.org/#dom-abortsignal-any) + const ac = new AbortController() + this.#signal = ac.signal + + // 29. If signal is not null, then make this’s signal follow signal. + if (signal != null) { + if (signal.aborted) { + ac.abort(signal.reason) + } else { + // Keep a strong ref to ac while request object + // is alive. This is needed to prevent AbortController + // from being prematurely garbage collected. + // See, https://github.com/nodejs/undici/issues/1926. + this[kAbortController] = ac + + const acRef = new WeakRef(ac) + const abort = buildAbort(acRef) + + // If the max amount of listeners is equal to the default, increase it + if (abortSignalHasEventHandlerLeakWarning && getMaxListeners(signal) === defaultMaxListeners) { + setMaxListeners(1500, signal) + } + + util.addAbortListener(signal, abort) + // The third argument must be a registry key to be unregistered. + // Without it, you cannot unregister. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + // abort is used as the unregister key. (because it is unique) + requestFinalizer.register(ac, { signal, abort }, abort) + } + } + + // 30. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is request’s header list and guard is + // "request". + this.#headers = new Headers(kConstruct) + setHeadersList(this.#headers, request.headersList) + setHeadersGuard(this.#headers, 'request') + + // 31. If this’s request’s mode is "no-cors", then: + if (mode === 'no-cors') { + // 1. If this’s request’s method is not a CORS-safelisted method, + // then throw a TypeError. + if (!corsSafeListedMethodsSet.has(request.method)) { + throw new TypeError( + `'${request.method} is unsupported in no-cors mode.` + ) + } + + // 2. Set this’s headers’s guard to "request-no-cors". + setHeadersGuard(this.#headers, 'request-no-cors') + } + + // 32. If init is not empty, then: + if (initHasKey) { + /** @type {HeadersList} */ + const headersList = getHeadersList(this.#headers) + // 1. Let headers be a copy of this’s headers and its associated header + // list. + // 2. If init["headers"] exists, then set headers to init["headers"]. + const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) + + // 3. Empty this’s headers’s header list. + headersList.clear() + + // 4. If headers is a Headers object, then for each header in its header + // list, append header’s name/header’s value to this’s headers. + if (headers instanceof HeadersList) { + for (const { name, value } of headers.rawValues()) { + headersList.append(name, value, false) + } + // Note: Copy the `set-cookie` meta-data. + headersList.cookies = headers.cookies + } else { + // 5. Otherwise, fill this’s headers with headers. + fillHeaders(this.#headers, headers) + } + } + + // 33. Let inputBody be input’s request’s body if input is a Request + // object; otherwise null. + const inputBody = webidl.is.Request(input) ? input.#state.body : null + + // 34. If either init["body"] exists and is non-null or inputBody is + // non-null, and request’s method is `GET` or `HEAD`, then throw a + // TypeError. + if ( + (init.body != null || inputBody != null) && + (request.method === 'GET' || request.method === 'HEAD') + ) { + throw new TypeError('Request with GET/HEAD method cannot have body.') + } + + // 35. Let initBody be null. + let initBody = null + + // 36. If init["body"] exists and is non-null, then: + if (init.body != null) { + // 1. Let Content-Type be null. + // 2. Set initBody and Content-Type to the result of extracting + // init["body"], with keepalive set to request’s keepalive. + const [extractedBody, contentType] = extractBody( + init.body, + request.keepalive + ) + initBody = extractedBody + + // 3, If Content-Type is non-null and this’s headers’s header list does + // not contain `Content-Type`, then append `Content-Type`/Content-Type to + // this’s headers. + if (contentType && !getHeadersList(this.#headers).contains('content-type', true)) { + this.#headers.append('content-type', contentType, true) + } + } + + // 37. Let inputOrInitBody be initBody if it is non-null; otherwise + // inputBody. + const inputOrInitBody = initBody ?? inputBody + + // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is + // null, then: + if (inputOrInitBody != null && inputOrInitBody.source == null) { + // 1. If initBody is non-null and init["duplex"] does not exist, + // then throw a TypeError. + if (initBody != null && init.duplex == null) { + throw new TypeError('RequestInit: duplex option is required when sending a body.') + } + + // 2. If this’s request’s mode is neither "same-origin" nor "cors", + // then throw a TypeError. + if (request.mode !== 'same-origin' && request.mode !== 'cors') { + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ) + } + + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true + } + + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody + + // 40. If initBody is null and inputBody is non-null, then: + if (initBody == null && inputBody != null) { + // 1. If input is unusable, then throw a TypeError. + if (bodyUnusable(input.#state)) { + throw new TypeError( + 'Cannot construct a Request with a Request object that has already been used.' + ) + } + + // 2. Set finalBody to the result of creating a proxy for inputBody. + // https://streams.spec.whatwg.org/#readablestream-create-a-proxy + const identityTransform = new TransformStream() + inputBody.stream.pipeThrough(identityTransform) + finalBody = { + source: inputBody.source, + length: inputBody.length, + stream: identityTransform.readable + } + } + + // 41. Set this’s request’s body to finalBody. + this.#state.body = finalBody + } + + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request) + + // The method getter steps are to return this’s request’s method. + return this.#state.method + } + + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request) + + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this.#state.url) + } + + // Returns a Headers object consisting of the headers associated with request. + // Note that headers added in the network layer by the user agent will not + // be accounted for in this object, e.g., the "Host" header. + get headers () { + webidl.brandCheck(this, Request) + + // The headers getter steps are to return this’s headers. + return this.#headers + } + + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request) + + // The destination getter are to return this’s request’s destination. + return this.#state.destination + } + + // Returns the referrer of request. Its value can be a same-origin URL if + // explicitly set in init, the empty string to indicate no referrer, and + // "about:client" when defaulting to the global’s default. This is used + // during fetching to determine the value of the `Referer` header of the + // request being made. + get referrer () { + webidl.brandCheck(this, Request) + + // 1. If this’s request’s referrer is "no-referrer", then return the + // empty string. + if (this.#state.referrer === 'no-referrer') { + return '' + } + + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this.#state.referrer === 'client') { + return 'about:client' + } + + // Return this’s request’s referrer, serialized. + return this.#state.referrer.toString() + } + + // Returns the referrer policy associated with request. + // This is used during fetching to compute the value of the request’s + // referrer. + get referrerPolicy () { + webidl.brandCheck(this, Request) + + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this.#state.referrerPolicy + } + + // Returns the mode associated with request, which is a string indicating + // whether the request will use CORS, or will be restricted to same-origin + // URLs. + get mode () { + webidl.brandCheck(this, Request) + + // The mode getter steps are to return this’s request’s mode. + return this.#state.mode + } + + // Returns the credentials mode associated with request, + // which is a string indicating whether credentials will be sent with the + // request always, never, or only when sent to a same-origin URL. + get credentials () { + webidl.brandCheck(this, Request) + + // The credentials getter steps are to return this’s request’s credentials mode. + return this.#state.credentials + } + + // Returns the cache mode associated with request, + // which is a string indicating how the request will + // interact with the browser’s cache when fetching. + get cache () { + webidl.brandCheck(this, Request) + + // The cache getter steps are to return this’s request’s cache mode. + return this.#state.cache + } + + // Returns the redirect mode associated with request, + // which is a string indicating how redirects for the + // request will be handled during fetching. A request + // will follow redirects by default. + get redirect () { + webidl.brandCheck(this, Request) + + // The redirect getter steps are to return this’s request’s redirect mode. + return this.#state.redirect + } + + // Returns request’s subresource integrity metadata, which is a + // cryptographic hash of the resource being fetched. Its value + // consists of multiple hashes separated by whitespace. [SRI] + get integrity () { + webidl.brandCheck(this, Request) + + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this.#state.integrity + } + + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request) + + // The keepalive getter steps are to return this’s request’s keepalive. + return this.#state.keepalive + } + + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request) + + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this.#state.reloadNavigation + } + + // Returns a boolean indicating whether or not request is for a history + // navigation (a.k.a. back-forward navigation). + get isHistoryNavigation () { + webidl.brandCheck(this, Request) + + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this.#state.historyNavigation + } + + // Returns the signal associated with request, which is an AbortSignal + // object indicating whether or not request has been aborted, and its + // abort event handler. + get signal () { + webidl.brandCheck(this, Request) + + // The signal getter steps are to return this’s signal. + return this.#signal + } + + get body () { + webidl.brandCheck(this, Request) + + return this.#state.body ? this.#state.body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Request) + + return !!this.#state.body && util.isDisturbed(this.#state.body.stream) + } + + get duplex () { + webidl.brandCheck(this, Request) + + return 'half' + } + + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request) + + // 1. If this is unusable, then throw a TypeError. + if (bodyUnusable(this.#state)) { + throw new TypeError('unusable') + } + + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this.#state) + + // 3. Let clonedRequestObject be the result of creating a Request object, + // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. + // 4. Make clonedRequestObject’s signal follow this’s signal. + const ac = new AbortController() + if (this.signal.aborted) { + ac.abort(this.signal.reason) + } else { + let list = dependentControllerMap.get(this.signal) + if (list === undefined) { + list = new Set() + dependentControllerMap.set(this.signal, list) + } + const acRef = new WeakRef(ac) + list.add(acRef) + util.addAbortListener( + ac.signal, + buildAbort(acRef) + ) + } + + // 4. Return clonedRequestObject. + return fromInnerRequest(clonedRequest, this.#dispatcher, ac.signal, getHeadersGuard(this.#headers)) + } + + [nodeUtil.inspect.custom] (depth, options) { + if (options.depth === null) { + options.depth = 2 + } + + options.colors ??= true + + const properties = { + method: this.method, + url: this.url, + headers: this.headers, + destination: this.destination, + referrer: this.referrer, + referrerPolicy: this.referrerPolicy, + mode: this.mode, + credentials: this.credentials, + cache: this.cache, + redirect: this.redirect, + integrity: this.integrity, + keepalive: this.keepalive, + isReloadNavigation: this.isReloadNavigation, + isHistoryNavigation: this.isHistoryNavigation, + signal: this.signal + } + + return `Request ${nodeUtil.formatWithOptions(options, properties)}` + } + + /** + * @param {Request} request + * @param {AbortSignal} newSignal + */ + static setRequestSignal (request, newSignal) { + request.#signal = newSignal + return request + } + + /** + * @param {Request} request + */ + static getRequestDispatcher (request) { + return request.#dispatcher + } + + /** + * @param {Request} request + * @param {import('../../dispatcher/dispatcher')} newDispatcher + */ + static setRequestDispatcher (request, newDispatcher) { + request.#dispatcher = newDispatcher + } + + /** + * @param {Request} request + * @param {Headers} newHeaders + */ + static setRequestHeaders (request, newHeaders) { + request.#headers = newHeaders + } + + /** + * @param {Request} request + */ + static getRequestState (request) { + return request.#state + } + + /** + * @param {Request} request + * @param {any} newState + */ + static setRequestState (request, newState) { + request.#state = newState + } +} + +const { setRequestSignal, getRequestDispatcher, setRequestDispatcher, setRequestHeaders, getRequestState, setRequestState } = Request +Reflect.deleteProperty(Request, 'setRequestSignal') +Reflect.deleteProperty(Request, 'getRequestDispatcher') +Reflect.deleteProperty(Request, 'setRequestDispatcher') +Reflect.deleteProperty(Request, 'setRequestHeaders') +Reflect.deleteProperty(Request, 'getRequestState') +Reflect.deleteProperty(Request, 'setRequestState') + +mixinBody(Request, getRequestState) + +// https://fetch.spec.whatwg.org/#requests +function makeRequest (init) { + return { + method: init.method ?? 'GET', + localURLsOnly: init.localURLsOnly ?? false, + unsafeRequest: init.unsafeRequest ?? false, + body: init.body ?? null, + client: init.client ?? null, + reservedClient: init.reservedClient ?? null, + replacesClientId: init.replacesClientId ?? '', + window: init.window ?? 'client', + keepalive: init.keepalive ?? false, + serviceWorkers: init.serviceWorkers ?? 'all', + initiator: init.initiator ?? '', + destination: init.destination ?? '', + priority: init.priority ?? null, + origin: init.origin ?? 'client', + policyContainer: init.policyContainer ?? 'client', + referrer: init.referrer ?? 'client', + referrerPolicy: init.referrerPolicy ?? '', + mode: init.mode ?? 'no-cors', + useCORSPreflightFlag: init.useCORSPreflightFlag ?? false, + credentials: init.credentials ?? 'same-origin', + useCredentials: init.useCredentials ?? false, + cache: init.cache ?? 'default', + redirect: init.redirect ?? 'follow', + integrity: init.integrity ?? '', + cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? '', + parserMetadata: init.parserMetadata ?? '', + reloadNavigation: init.reloadNavigation ?? false, + historyNavigation: init.historyNavigation ?? false, + userActivation: init.userActivation ?? false, + taintedOrigin: init.taintedOrigin ?? false, + redirectCount: init.redirectCount ?? 0, + responseTainting: init.responseTainting ?? 'basic', + preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false, + done: init.done ?? false, + timingAllowFailed: init.timingAllowFailed ?? false, + useURLCredentials: init.useURLCredentials ?? undefined, + traversableForUserPrompts: init.traversableForUserPrompts ?? 'client', + urlList: init.urlList, + url: init.urlList[0], + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList() + } +} + +// https://fetch.spec.whatwg.org/#concept-request-clone +function cloneRequest (request) { + // To clone a request request, run these steps: + + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }) + + // 2. If request’s body is non-null, set newRequest’s body to the + // result of cloning request’s body. + if (request.body != null) { + newRequest.body = cloneBody(request.body) + } + + // 3. Return newRequest. + return newRequest +} + +/** + * @see https://fetch.spec.whatwg.org/#request-create + * @param {any} innerRequest + * @param {import('../../dispatcher/agent')} dispatcher + * @param {AbortSignal} signal + * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard + * @returns {Request} + */ +function fromInnerRequest (innerRequest, dispatcher, signal, guard) { + const request = new Request(kConstruct) + setRequestState(request, innerRequest) + setRequestDispatcher(request, dispatcher) + setRequestSignal(request, signal) + const headers = new Headers(kConstruct) + setRequestHeaders(request, headers) + setHeadersList(headers, innerRequest.headersList) + setHeadersGuard(headers, guard) + return request +} + +Object.defineProperties(Request.prototype, { + method: kEnumerableProperty, + url: kEnumerableProperty, + headers: kEnumerableProperty, + redirect: kEnumerableProperty, + clone: kEnumerableProperty, + signal: kEnumerableProperty, + duplex: kEnumerableProperty, + destination: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + isHistoryNavigation: kEnumerableProperty, + isReloadNavigation: kEnumerableProperty, + keepalive: kEnumerableProperty, + integrity: kEnumerableProperty, + cache: kEnumerableProperty, + credentials: kEnumerableProperty, + attribute: kEnumerableProperty, + referrerPolicy: kEnumerableProperty, + referrer: kEnumerableProperty, + mode: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Request', + configurable: true + } +}) + +webidl.is.Request = webidl.util.MakeTypeAssertion(Request) + +/** + * @param {*} V + * @returns {import('../../../types/fetch').Request|string} + * + * @see https://fetch.spec.whatwg.org/#requestinfo + */ +webidl.converters.RequestInfo = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (webidl.is.Request(V)) { + return V + } + + return webidl.converters.USVString(V) +} + +/** + * @param {*} V + * @returns {import('../../../types/fetch').RequestInit} + * @see https://fetch.spec.whatwg.org/#requestinit + */ +webidl.converters.RequestInit = webidl.dictionaryConverter([ + { + key: 'method', + converter: webidl.converters.ByteString + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + }, + { + key: 'body', + converter: webidl.nullableConverter( + webidl.converters.BodyInit + ) + }, + { + key: 'referrer', + converter: webidl.converters.USVString + }, + { + key: 'referrerPolicy', + converter: webidl.converters.DOMString, + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy + allowedValues: referrerPolicy + }, + { + key: 'mode', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#concept-request-mode + allowedValues: requestMode + }, + { + key: 'credentials', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcredentials + allowedValues: requestCredentials + }, + { + key: 'cache', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcache + allowedValues: requestCache + }, + { + key: 'redirect', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestredirect + allowedValues: requestRedirect + }, + { + key: 'integrity', + converter: webidl.converters.DOMString + }, + { + key: 'keepalive', + converter: webidl.converters.boolean + }, + { + key: 'signal', + converter: webidl.nullableConverter( + (signal) => webidl.converters.AbortSignal( + signal, + 'RequestInit', + 'signal' + ) + ) + }, + { + key: 'window', + converter: webidl.converters.any + }, + { + key: 'duplex', + converter: webidl.converters.DOMString, + allowedValues: requestDuplex + }, + { + key: 'dispatcher', // undici specific option + converter: webidl.converters.any + }, + { + key: 'priority', + converter: webidl.converters.DOMString, + allowedValues: ['high', 'low', 'auto'], + defaultValue: () => 'auto' + } +]) + +module.exports = { + Request, + makeRequest, + fromInnerRequest, + cloneRequest, + getRequestDispatcher, + getRequestState +} diff --git a/node_modules/undici/lib/web/fetch/response.js b/node_modules/undici/lib/web/fetch/response.js new file mode 100644 index 000000000..6b954afaa --- /dev/null +++ b/node_modules/undici/lib/web/fetch/response.js @@ -0,0 +1,640 @@ +'use strict' + +const { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require('./headers') +const { extractBody, cloneBody, mixinBody, streamRegistry, bodyUnusable } = require('./body') +const util = require('../../core/util') +const nodeUtil = require('node:util') +const { kEnumerableProperty } = util +const { + isValidReasonPhrase, + isCancelled, + isAborted, + isErrorLike, + environmentSettingsObject: relevantRealm +} = require('./util') +const { + redirectStatusSet, + nullBodyStatus +} = require('./constants') +const { webidl } = require('../webidl') +const { URLSerializer } = require('./data-url') +const { kConstruct } = require('../../core/symbols') +const assert = require('node:assert') +const { isomorphicEncode, serializeJavascriptValueToJSONString } = require('../infra') + +const textEncoder = new TextEncoder('utf-8') + +// https://fetch.spec.whatwg.org/#response-class +class Response { + /** @type {Headers} */ + #headers + + #state + + // Creates network error Response. + static error () { + // The static error() method steps are to return the result of creating a + // Response object, given a new network error, "immutable", and this’s + // relevant Realm. + const responseObject = fromInnerResponse(makeNetworkError(), 'immutable') + + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response-json + static json (data, init = undefined) { + webidl.argumentLengthCheck(arguments, 1, 'Response.json') + + if (init !== null) { + init = webidl.converters.ResponseInit(init) + } + + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ) + + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes) + + // 3. Let responseObject be the result of creating a Response object, given a new response, + // "response", and this’s relevant Realm. + const responseObject = fromInnerResponse(makeResponse({}), 'response') + + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) + + // 5. Return responseObject. + return responseObject + } + + // Creates a redirect Response that redirects to url with status status. + static redirect (url, status = 302) { + webidl.argumentLengthCheck(arguments, 1, 'Response.redirect') + + url = webidl.converters.USVString(url) + status = webidl.converters['unsigned short'](status) + + // 1. Let parsedURL be the result of parsing url with current settings + // object’s API base URL. + // 2. If parsedURL is failure, then throw a TypeError. + // TODO: base-URL? + let parsedURL + try { + parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl) + } catch (err) { + throw new TypeError(`Failed to parse URL from ${url}`, { cause: err }) + } + + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatusSet.has(status)) { + throw new RangeError(`Invalid status code ${status}`) + } + + // 4. Let responseObject be the result of creating a Response object, + // given a new response, "immutable", and this’s relevant Realm. + const responseObject = fromInnerResponse(makeResponse({}), 'immutable') + + // 5. Set responseObject’s response’s status to status. + responseObject.#state.status = status + + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)) + + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject.#state.headersList.append('location', value, true) + + // 8. Return responseObject. + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = undefined) { + webidl.util.markAsUncloneable(this) + + if (body === kConstruct) { + return + } + + if (body !== null) { + body = webidl.converters.BodyInit(body, 'Response', 'body') + } + + init = webidl.converters.ResponseInit(init) + + // 1. Set this’s response to a new response. + this.#state = makeResponse({}) + + // 2. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is this’s response’s header list and guard + // is "response". + this.#headers = new Headers(kConstruct) + setHeadersGuard(this.#headers, 'response') + setHeadersList(this.#headers, this.#state.headersList) + + // 3. Let bodyWithType be null. + let bodyWithType = null + + // 4. If body is non-null, then set bodyWithType to the result of extracting body. + if (body != null) { + const [extractedBody, type] = extractBody(body) + bodyWithType = { body: extractedBody, type } + } + + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType) + } + + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response) + + // The type getter steps are to return this’s response’s type. + return this.#state.type + } + + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response) + + const urlList = this.#state.urlList + + // The url getter steps are to return the empty string if this’s + // response’s URL is null; otherwise this’s response’s URL, + // serialized with exclude fragment set to true. + const url = urlList[urlList.length - 1] ?? null + + if (url === null) { + return '' + } + + return URLSerializer(url, true) + } + + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response) + + // The redirected getter steps are to return true if this’s response’s URL + // list has more than one item; otherwise false. + return this.#state.urlList.length > 1 + } + + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response) + + // The status getter steps are to return this’s response’s status. + return this.#state.status + } + + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response) + + // The ok getter steps are to return true if this’s response’s status is an + // ok status; otherwise false. + return this.#state.status >= 200 && this.#state.status <= 299 + } + + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response) + + // The statusText getter steps are to return this’s response’s status + // message. + return this.#state.statusText + } + + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response) + + // The headers getter steps are to return this’s headers. + return this.#headers + } + + get body () { + webidl.brandCheck(this, Response) + + return this.#state.body ? this.#state.body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Response) + + return !!this.#state.body && util.isDisturbed(this.#state.body.stream) + } + + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response) + + // 1. If this is unusable, then throw a TypeError. + if (bodyUnusable(this.#state)) { + throw webidl.errors.exception({ + header: 'Response.clone', + message: 'Body has already been consumed.' + }) + } + + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this.#state) + + // Note: To re-register because of a new stream. + if (this.#state.body?.stream) { + streamRegistry.register(this, new WeakRef(this.#state.body.stream)) + } + + // 3. Return the result of creating a Response object, given + // clonedResponse, this’s headers’s guard, and this’s relevant Realm. + return fromInnerResponse(clonedResponse, getHeadersGuard(this.#headers)) + } + + [nodeUtil.inspect.custom] (depth, options) { + if (options.depth === null) { + options.depth = 2 + } + + options.colors ??= true + + const properties = { + status: this.status, + statusText: this.statusText, + headers: this.headers, + body: this.body, + bodyUsed: this.bodyUsed, + ok: this.ok, + redirected: this.redirected, + type: this.type, + url: this.url + } + + return `Response ${nodeUtil.formatWithOptions(options, properties)}` + } + + /** + * @param {Response} response + */ + static getResponseHeaders (response) { + return response.#headers + } + + /** + * @param {Response} response + * @param {Headers} newHeaders + */ + static setResponseHeaders (response, newHeaders) { + response.#headers = newHeaders + } + + /** + * @param {Response} response + */ + static getResponseState (response) { + return response.#state + } + + /** + * @param {Response} response + * @param {any} newState + */ + static setResponseState (response, newState) { + response.#state = newState + } +} + +const { getResponseHeaders, setResponseHeaders, getResponseState, setResponseState } = Response +Reflect.deleteProperty(Response, 'getResponseHeaders') +Reflect.deleteProperty(Response, 'setResponseHeaders') +Reflect.deleteProperty(Response, 'getResponseState') +Reflect.deleteProperty(Response, 'setResponseState') + +mixinBody(Response, getResponseState) + +Object.defineProperties(Response.prototype, { + type: kEnumerableProperty, + url: kEnumerableProperty, + status: kEnumerableProperty, + ok: kEnumerableProperty, + redirected: kEnumerableProperty, + statusText: kEnumerableProperty, + headers: kEnumerableProperty, + clone: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Response', + configurable: true + } +}) + +Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty +}) + +// https://fetch.spec.whatwg.org/#concept-response-clone +function cloneResponse (response) { + // To clone a response response, run these steps: + + // 1. If response is a filtered response, then return a new identical + // filtered response whose internal response is a clone of response’s + // internal response. + if (response.internalResponse) { + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ) + } + + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, body: null }) + + // 3. If response’s body is non-null, then set newResponse’s body to the + // result of cloning response’s body. + if (response.body != null) { + newResponse.body = cloneBody(response.body) + } + + // 4. Return newResponse. + return newResponse +} + +function makeResponse (init) { + return { + aborted: false, + rangeRequested: false, + timingAllowPassed: false, + requestIncludesCredentials: false, + type: 'default', + status: 200, + timingInfo: null, + cacheState: '', + statusText: '', + ...init, + headersList: init?.headersList + ? new HeadersList(init?.headersList) + : new HeadersList(), + urlList: init?.urlList ? [...init.urlList] : [] + } +} + +function makeNetworkError (reason) { + const isError = isErrorLike(reason) + return makeResponse({ + type: 'error', + status: 0, + error: isError + ? reason + : new Error(reason ? String(reason) : reason), + aborted: reason && reason.name === 'AbortError' + }) +} + +// @see https://fetch.spec.whatwg.org/#concept-network-error +function isNetworkError (response) { + return ( + // A network error is a response whose type is "error", + response.type === 'error' && + // status is 0 + response.status === 0 + ) +} + +function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state + } + + return new Proxy(response, { + get (target, p) { + return p in state ? state[p] : target[p] + }, + set (target, p, value) { + assert(!(p in state)) + target[p] = value + return true + } + }) +} + +// https://fetch.spec.whatwg.org/#concept-filtered-response +function filterResponse (response, type) { + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (type === 'basic') { + // A basic filtered response is a filtered response whose type is "basic" + // and header list excludes any headers in internal response’s header list + // whose name is a forbidden response-header name. + + // Note: undici does not implement forbidden response-header names + return makeFilteredResponse(response, { + type: 'basic', + headersList: response.headersList + }) + } else if (type === 'cors') { + // A CORS filtered response is a filtered response whose type is "cors" + // and header list excludes any headers in internal response’s header + // list whose name is not a CORS-safelisted response-header name, given + // internal response’s CORS-exposed header-name list. + + // Note: undici does not implement CORS-safelisted response-header names + return makeFilteredResponse(response, { + type: 'cors', + headersList: response.headersList + }) + } else if (type === 'opaque') { + // An opaque filtered response is a filtered response whose type is + // "opaque", URL list is the empty list, status is 0, status message + // is the empty byte sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaque', + urlList: [], + status: 0, + statusText: '', + body: null + }) + } else if (type === 'opaqueredirect') { + // An opaque-redirect filtered response is a filtered response whose type + // is "opaqueredirect", status is 0, status message is the empty byte + // sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false) + } +} + +// https://fetch.spec.whatwg.org/#appropriate-network-error +function makeAppropriateNetworkError (fetchParams, err = null) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)) + + // 2. Return an aborted network error if fetchParams is aborted; + // otherwise return a network error. + return isAborted(fetchParams) + ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) + : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) +} + +// https://whatpr.org/fetch/1392.html#initialize-a-response +function initializeResponse (response, init, body) { + // 1. If init["status"] is not in the range 200 to 599, inclusive, then + // throw a RangeError. + if (init.status !== null && (init.status < 200 || init.status > 599)) { + throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') + } + + // 2. If init["statusText"] does not match the reason-phrase token production, + // then throw a TypeError. + if ('statusText' in init && init.statusText != null) { + // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: + // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) + if (!isValidReasonPhrase(String(init.statusText))) { + throw new TypeError('Invalid statusText') + } + } + + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + getResponseState(response).status = init.status + } + + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + getResponseState(response).statusText = init.statusText + } + + // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. + if ('headers' in init && init.headers != null) { + fill(getResponseHeaders(response), init.headers) + } + + // 6. If body was given, then: + if (body) { + // 1. If response's status is a null body status, then throw a TypeError. + if (nullBodyStatus.includes(response.status)) { + throw webidl.errors.exception({ + header: 'Response constructor', + message: `Invalid response status code ${response.status}` + }) + } + + // 2. Set response's body to body's body. + getResponseState(response).body = body.body + + // 3. If body's type is non-null and response's header list does not contain + // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. + if (body.type != null && !getResponseState(response).headersList.contains('content-type', true)) { + getResponseState(response).headersList.append('content-type', body.type, true) + } + } +} + +/** + * @see https://fetch.spec.whatwg.org/#response-create + * @param {any} innerResponse + * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard + * @returns {Response} + */ +function fromInnerResponse (innerResponse, guard) { + const response = new Response(kConstruct) + setResponseState(response, innerResponse) + const headers = new Headers(kConstruct) + setResponseHeaders(response, headers) + setHeadersList(headers, innerResponse.headersList) + setHeadersGuard(headers, guard) + + // Note: If innerResponse's urlList contains a URL, it is a fetch response. + if (innerResponse.urlList.length !== 0 && innerResponse.body?.stream) { + // If the target (response) is reclaimed, the cleanup callback may be called at some point with + // the held value provided for it (innerResponse.body.stream). The held value can be any value: + // a primitive or an object, even undefined. If the held value is an object, the registry keeps + // a strong reference to it (so it can pass it to the cleanup callback later). Reworded from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + streamRegistry.register(response, new WeakRef(innerResponse.body.stream)) + } + + return response +} + +// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit +webidl.converters.XMLHttpRequestBodyInit = function (V, prefix, name) { + if (typeof V === 'string') { + return webidl.converters.USVString(V, prefix, name) + } + + if (webidl.is.Blob(V)) { + return V + } + + if (webidl.is.BufferSource(V)) { + return V + } + + if (webidl.is.FormData(V)) { + return V + } + + if (webidl.is.URLSearchParams(V)) { + return V + } + + return webidl.converters.DOMString(V, prefix, name) +} + +// https://fetch.spec.whatwg.org/#bodyinit +webidl.converters.BodyInit = function (V, prefix, argument) { + if (webidl.is.ReadableStream(V)) { + return V + } + + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V + } + + return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument) +} + +webidl.converters.ResponseInit = webidl.dictionaryConverter([ + { + key: 'status', + converter: webidl.converters['unsigned short'], + defaultValue: () => 200 + }, + { + key: 'statusText', + converter: webidl.converters.ByteString, + defaultValue: () => '' + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + } +]) + +webidl.is.Response = webidl.util.MakeTypeAssertion(Response) + +module.exports = { + isNetworkError, + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response, + cloneResponse, + fromInnerResponse, + getResponseState +} diff --git a/node_modules/undici/lib/web/fetch/util.js b/node_modules/undici/lib/web/fetch/util.js new file mode 100644 index 000000000..5e51bdd35 --- /dev/null +++ b/node_modules/undici/lib/web/fetch/util.js @@ -0,0 +1,1520 @@ +'use strict' + +const { Transform } = require('node:stream') +const zlib = require('node:zlib') +const { redirectStatusSet, referrerPolicyTokens, badPortsSet } = require('./constants') +const { getGlobalOrigin } = require('./global') +const { collectAnHTTPQuotedString, parseMIMEType } = require('./data-url') +const { performance } = require('node:perf_hooks') +const { ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = require('../../core/util') +const assert = require('node:assert') +const { isUint8Array } = require('node:util/types') +const { webidl } = require('../webidl') +const { isomorphicEncode, collectASequenceOfCodePoints, removeChars } = require('../infra') + +function responseURL (response) { + // https://fetch.spec.whatwg.org/#responses + // A response has an associated URL. It is a pointer to the last URL + // in response’s URL list and null if response’s URL list is empty. + const urlList = response.urlList + const length = urlList.length + return length === 0 ? null : urlList[length - 1].toString() +} + +// https://fetch.spec.whatwg.org/#concept-response-location-url +function responseLocationURL (response, requestFragment) { + // 1. If response’s status is not a redirect status, then return null. + if (!redirectStatusSet.has(response.status)) { + return null + } + + // 2. Let location be the result of extracting header list values given + // `Location` and response’s header list. + let location = response.headersList.get('location', true) + + // 3. If location is a header value, then set location to the result of + // parsing location with response’s URL. + if (location !== null && isValidHeaderValue(location)) { + if (!isValidEncodedURL(location)) { + // Some websites respond location header in UTF-8 form without encoding them as ASCII + // and major browsers redirect them to correctly UTF-8 encoded addresses. + // Here, we handle that behavior in the same way. + location = normalizeBinaryStringToUtf8(location) + } + location = new URL(location, responseURL(response)) + } + + // 4. If location is a URL whose fragment is null, then set location’s + // fragment to requestFragment. + if (location && !location.hash) { + location.hash = requestFragment + } + + // 5. Return location. + return location +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc1738#section-2.2 + * @param {string} url + * @returns {boolean} + */ +function isValidEncodedURL (url) { + for (let i = 0; i < url.length; ++i) { + const code = url.charCodeAt(i) + + if ( + code > 0x7E || // Non-US-ASCII + DEL + code < 0x20 // Control characters NUL - US + ) { + return false + } + } + return true +} + +/** + * If string contains non-ASCII characters, assumes it's UTF-8 encoded and decodes it. + * Since UTF-8 is a superset of ASCII, this will work for ASCII strings as well. + * @param {string} value + * @returns {string} + */ +function normalizeBinaryStringToUtf8 (value) { + return Buffer.from(value, 'binary').toString('utf8') +} + +/** @returns {URL} */ +function requestCurrentURL (request) { + return request.urlList[request.urlList.length - 1] +} + +function requestBadPort (request) { + // 1. Let url be request’s current URL. + const url = requestCurrentURL(request) + + // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, + // then return blocked. + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { + return 'blocked' + } + + // 3. Return allowed. + return 'allowed' +} + +function isErrorLike (object) { + return object instanceof Error || ( + object?.constructor?.name === 'Error' || + object?.constructor?.name === 'DOMException' + ) +} + +// Check whether |statusText| is a ByteString and +// matches the Reason-Phrase token production. +// RFC 2616: https://tools.ietf.org/html/rfc2616 +// RFC 7230: https://tools.ietf.org/html/rfc7230 +// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" +// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 +function isValidReasonPhrase (statusText) { + for (let i = 0; i < statusText.length; ++i) { + const c = statusText.charCodeAt(i) + if ( + !( + ( + c === 0x09 || // HTAB + (c >= 0x20 && c <= 0x7e) || // SP / VCHAR + (c >= 0x80 && c <= 0xff) + ) // obs-text + ) + ) { + return false + } + } + return true +} + +/** + * @see https://fetch.spec.whatwg.org/#header-name + * @param {string} potentialValue + */ +const isValidHeaderName = isValidHTTPToken + +/** + * @see https://fetch.spec.whatwg.org/#header-value + * @param {string} potentialValue + */ +function isValidHeaderValue (potentialValue) { + // - Has no leading or trailing HTTP tab or space bytes. + // - Contains no 0x00 (NUL) or HTTP newline bytes. + return ( + potentialValue[0] === '\t' || + potentialValue[0] === ' ' || + potentialValue[potentialValue.length - 1] === '\t' || + potentialValue[potentialValue.length - 1] === ' ' || + potentialValue.includes('\n') || + potentialValue.includes('\r') || + potentialValue.includes('\0') + ) === false +} + +/** + * Parse a referrer policy from a Referrer-Policy header + * @see https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header + */ +function parseReferrerPolicy (actualResponse) { + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. + const policyHeader = (actualResponse.headersList.get('referrer-policy', true) ?? '').split(',') + + // 2. Let policy be the empty string. + let policy = '' + + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. + + // Note: As the referrer-policy can contain multiple policies + // separated by comma, we need to loop through all of them + // and pick the first valid one. + // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy + if (policyHeader.length) { + // The right-most policy takes precedence. + // The left-most policy is the fallback. + for (let i = policyHeader.length; i !== 0; i--) { + const token = policyHeader[i - 1].trim() + if (referrerPolicyTokens.has(token)) { + policy = token + break + } + } + } + + // 4. Return policy. + return policy +} + +/** + * Given a request request and a response actualResponse, this algorithm + * updates request’s referrer policy according to the Referrer-Policy + * header (if any) in actualResponse. + * @see https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect + * @param {import('./request').Request} request + * @param {import('./response').Response} actualResponse + */ +function setRequestReferrerPolicyOnRedirect (request, actualResponse) { + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. + const policy = parseReferrerPolicy(actualResponse) + + // 2. If policy is not the empty string, then set request’s referrer policy to policy. + if (policy !== '') { + request.referrerPolicy = policy + } +} + +// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check +function crossOriginResourcePolicyCheck () { + // TODO + return 'allowed' +} + +// https://fetch.spec.whatwg.org/#concept-cors-check +function corsCheck () { + // TODO + return 'success' +} + +// https://fetch.spec.whatwg.org/#concept-tao-check +function TAOCheck () { + // TODO + return 'success' +} + +function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header + + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO + + // 2. Let header be a Structured Header whose value is a token. + let header = null + + // 3. Set header’s value to r’s mode. + header = httpRequest.mode + + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header, true) + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO +} + +// https://fetch.spec.whatwg.org/#append-a-request-origin-header +function appendRequestOriginHeader (request) { + // 1. Let serializedOrigin be the result of byte-serializing a request origin + // with request. + // TODO: implement "byte-serializing a request origin" + let serializedOrigin = request.origin + + // - "'client' is changed to an origin during fetching." + // This doesn't happen in undici (in most cases) because undici, by default, + // has no concept of origin. + // - request.origin can also be set to request.client.origin (client being + // an environment settings object), which is undefined without using + // setGlobalOrigin. + if (serializedOrigin === 'client' || serializedOrigin === undefined) { + return + } + + // 2. If request’s response tainting is "cors" or request’s mode is "websocket", + // then append (`Origin`, serializedOrigin) to request’s header list. + // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: + if (request.responseTainting === 'cors' || request.mode === 'websocket') { + request.headersList.append('origin', serializedOrigin, true) + } else if (request.method !== 'GET' && request.method !== 'HEAD') { + // 1. Switch on request’s referrer policy: + switch (request.referrerPolicy) { + case 'no-referrer': + // Set serializedOrigin to `null`. + serializedOrigin = null + break + case 'no-referrer-when-downgrade': + case 'strict-origin': + case 'strict-origin-when-cross-origin': + // If request’s origin is a tuple origin, its scheme is "https", and + // request’s current URL’s scheme is not "https", then set + // serializedOrigin to `null`. + if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { + serializedOrigin = null + } + break + case 'same-origin': + // If request’s origin is not same origin with request’s current URL’s + // origin, then set serializedOrigin to `null`. + if (!sameOrigin(request, requestCurrentURL(request))) { + serializedOrigin = null + } + break + default: + // Do nothing. + } + + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin, true) + } +} + +// https://w3c.github.io/hr-time/#dfn-coarsen-time +function coarsenTime (timestamp, crossOriginIsolatedCapability) { + // TODO + return timestamp +} + +// https://fetch.spec.whatwg.org/#clamp-and-coarsen-connection-timing-info +function clampAndCoarsenConnectionTimingInfo (connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) { + if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) { + return { + domainLookupStartTime: defaultStartTime, + domainLookupEndTime: defaultStartTime, + connectionStartTime: defaultStartTime, + connectionEndTime: defaultStartTime, + secureConnectionStartTime: defaultStartTime, + ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol + } + } + + return { + domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability), + domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability), + connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability), + connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability), + secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability), + ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol + } +} + +// https://w3c.github.io/hr-time/#dfn-coarsened-shared-current-time +function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + return coarsenTime(performance.now(), crossOriginIsolatedCapability) +} + +// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info +function createOpaqueTimingInfo (timingInfo) { + return { + startTime: timingInfo.startTime ?? 0, + redirectStartTime: 0, + redirectEndTime: 0, + postRedirectStartTime: timingInfo.startTime ?? 0, + finalServiceWorkerStartTime: 0, + finalNetworkResponseStartTime: 0, + finalNetworkRequestStartTime: 0, + endTime: 0, + encodedBodySize: 0, + decodedBodySize: 0, + finalConnectionTimingInfo: null + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#policy-container +function makePolicyContainer () { + // Note: the fetch spec doesn't make use of embedder policy or CSP list + return { + referrerPolicy: 'strict-origin-when-cross-origin' + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container +function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } +} + +/** + * Determine request’s Referrer + * + * @see https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer + */ +function determineRequestsReferrer (request) { + // Given a request request, we can determine the correct referrer information + // to send by examining its referrer policy as detailed in the following + // steps, which return either no referrer or a URL: + + // 1. Let policy be request's referrer policy. + const policy = request.referrerPolicy + + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy) + + // 2. Let environment be request’s client. + + let referrerSource = null + + // 3. Switch on request’s referrer: + + // "client" + if (request.referrer === 'client') { + // Note: node isn't a browser and doesn't implement document/iframes, + // so we bypass this step and replace it with our own. + + const globalOrigin = getGlobalOrigin() + + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' + } + + // Note: we need to clone it as it's mutated + referrerSource = new URL(globalOrigin) + // a URL + } else if (webidl.is.URL(request.referrer)) { + // Let referrerSource be request’s referrer. + referrerSource = request.referrer + } + + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource) + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as + // a referrer, with the origin-only flag set to true. + const referrerOrigin = stripURLForReferrer(referrerSource, true) + + // 6. If the result of serializing referrerURL is a string whose length is + // greater than 4096, set referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin + } + + // 7. The user agent MAY alter referrerURL or referrerOrigin at this point + // to enforce arbitrary policy considerations in the interests of minimizing + // data leakage. For example, the user agent could strip the URL down to an + // origin, modify its host, replace it with an empty string, etc. + + // 8. Execute the switch statements corresponding to the value of policy: + switch (policy) { + case 'no-referrer': + // Return no referrer + return 'no-referrer' + case 'origin': + // Return referrerOrigin + if (referrerOrigin != null) { + return referrerOrigin + } + return stripURLForReferrer(referrerSource, true) + case 'unsafe-url': + // Return referrerURL. + return referrerURL + case 'strict-origin': { + const currentURL = requestCurrentURL(request) + + // 1. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + // 2. Return referrerOrigin + return referrerOrigin + } + case 'strict-origin-when-cross-origin': { + const currentURL = requestCurrentURL(request) + + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(referrerURL, currentURL)) { + return referrerURL + } + + // 2. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + + // 3. Return referrerOrigin. + return referrerOrigin + } + case 'same-origin': + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(request, referrerURL)) { + return referrerURL + } + // 2. Return no referrer. + return 'no-referrer' + case 'origin-when-cross-origin': + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(request, referrerURL)) { + return referrerURL + } + // 2. Return referrerOrigin. + return referrerOrigin + case 'no-referrer-when-downgrade': { + const currentURL = requestCurrentURL(request) + + // 1. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + // 2. Return referrerURL. + return referrerURL + } + } +} + +/** + * Certain portions of URLs must not be included when sending a URL as the + * value of a `Referer` header: a URLs fragment, username, and password + * components must be stripped from the URL before it’s sent out. This + * algorithm accepts a origin-only flag, which defaults to false. If set to + * true, the algorithm will additionally remove the URL’s path and query + * components, leaving only the scheme, host, and port. + * + * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url + * @param {URL} url + * @param {boolean} [originOnly=false] + */ +function stripURLForReferrer (url, originOnly = false) { + // 1. Assert: url is a URL. + assert(webidl.is.URL(url)) + + // Note: Create a new URL instance to avoid mutating the original URL. + url = new URL(url) + + // 2. If url’s scheme is a local scheme, then return no referrer. + if (urlIsLocal(url)) { + return 'no-referrer' + } + + // 3. Set url’s username to the empty string. + url.username = '' + + // 4. Set url’s password to the empty string. + url.password = '' + + // 5. Set url’s fragment to null. + url.hash = '' + + // 6. If the origin-only flag is true, then: + if (originOnly === true) { + // 1. Set url’s path to « the empty string ». + url.pathname = '' + + // 2. Set url’s query to null. + url.search = '' + } + + // 7. Return url. + return url +} + +const isPotentialleTrustworthyIPv4 = RegExp.prototype.test + .bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/) + +const isPotentiallyTrustworthyIPv6 = RegExp.prototype.test + .bind(/^(?:(?:0{1,4}:){7}|(?:0{1,4}:){1,6}:|::)0{0,3}1$/) + +/** + * Check if host matches one of the CIDR notations 127.0.0.0/8 or ::1/128. + * + * @param {string} origin + * @returns {boolean} + */ +function isOriginIPPotentiallyTrustworthy (origin) { + // IPv6 + if (origin.includes(':')) { + // Remove brackets from IPv6 addresses + if (origin[0] === '[' && origin[origin.length - 1] === ']') { + origin = origin.slice(1, -1) + } + return isPotentiallyTrustworthyIPv6(origin) + } + + // IPv4 + return isPotentialleTrustworthyIPv4(origin) +} + +/** + * A potentially trustworthy origin is one which a user agent can generally + * trust as delivering data securely. + * + * Return value `true` means `Potentially Trustworthy`. + * Return value `false` means `Not Trustworthy`. + * + * @see https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy + * @param {string} origin + * @returns {boolean} + */ +function isOriginPotentiallyTrustworthy (origin) { + // 1. If origin is an opaque origin, return "Not Trustworthy". + if (origin == null || origin === 'null') { + return false + } + + // 2. Assert: origin is a tuple origin. + origin = new URL(origin) + + // 3. If origin’s scheme is either "https" or "wss", + // return "Potentially Trustworthy". + if (origin.protocol === 'https:' || origin.protocol === 'wss:') { + return true + } + + // 4. If origin’s host matches one of the CIDR notations 127.0.0.0/8 or + // ::1/128 [RFC4632], return "Potentially Trustworthy". + if (isOriginIPPotentiallyTrustworthy(origin.hostname)) { + return true + } + + // 5. If the user agent conforms to the name resolution rules in + // [let-localhost-be-localhost] and one of the following is true: + + // origin’s host is "localhost" or "localhost." + if (origin.hostname === 'localhost' || origin.hostname === 'localhost.') { + return true + } + + // origin’s host ends with ".localhost" or ".localhost." + if (origin.hostname.endsWith('.localhost') || origin.hostname.endsWith('.localhost.')) { + return true + } + + // 6. If origin’s scheme is "file", return "Potentially Trustworthy". + if (origin.protocol === 'file:') { + return true + } + + // 7. If origin’s scheme component is one which the user agent considers to + // be authenticated, return "Potentially Trustworthy". + + // 8. If origin has been configured as a trustworthy origin, return + // "Potentially Trustworthy". + + // 9. Return "Not Trustworthy". + return false +} + +/** + * A potentially trustworthy URL is one which either inherits context from its + * creator (about:blank, about:srcdoc, data) or one whose origin is a + * potentially trustworthy origin. + * + * Return value `true` means `Potentially Trustworthy`. + * Return value `false` means `Not Trustworthy`. + * + * @see https://www.w3.org/TR/secure-contexts/#is-url-trustworthy + * @param {URL} url + * @returns {boolean} + */ +function isURLPotentiallyTrustworthy (url) { + // Given a URL record (url), the following algorithm returns "Potentially + // Trustworthy" or "Not Trustworthy" as appropriate: + if (!webidl.is.URL(url)) { + return false + } + + // 1. If url is "about:blank" or "about:srcdoc", + // return "Potentially Trustworthy". + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true + } + + // 2. If url’s scheme is "data", return "Potentially Trustworthy". + if (url.protocol === 'data:') return true + + // Note: The origin of blob: URLs is the origin of the context in which they + // were created. Therefore, blobs created in a trustworthy origin will + // themselves be potentially trustworthy. + if (url.protocol === 'blob:') return true + + // 3. Return the result of executing § 3.1 Is origin potentially trustworthy? + // on url’s origin. + return isOriginPotentiallyTrustworthy(url.origin) +} + +// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request +function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO +} + +/** + * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} + * @param {URL} A + * @param {URL} B + */ +function sameOrigin (A, B) { + // 1. If A and B are the same opaque origin, then return true. + if (A.origin === B.origin && A.origin === 'null') { + return true + } + + // 2. If A and B are both tuple origins and their schemes, + // hosts, and port are identical, then return true. + if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { + return true + } + + // 3. Return false. + return false +} + +function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' +} + +function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-method-normalize + * @param {string} method + */ +function normalizeMethod (method) { + return normalizedMethodRecordsBase[method.toLowerCase()] ?? method +} + +// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object +const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) + +/** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {string} name name of the instance + * @param {((target: any) => any)} kInternalIterator + * @param {string | number} [keyIndex] + * @param {string | number} [valueIndex] + */ +function createIterator (name, kInternalIterator, keyIndex = 0, valueIndex = 1) { + class FastIterableIterator { + /** @type {any} */ + #target + /** @type {'key' | 'value' | 'key+value'} */ + #kind + /** @type {number} */ + #index + + /** + * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object + * @param {unknown} target + * @param {'key' | 'value' | 'key+value'} kind + */ + constructor (target, kind) { + this.#target = target + this.#kind = kind + this.#index = 0 + } + + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. + // 2. Let thisValue be the this value. + // 3. Let object be ? ToObject(thisValue). + // 4. If object is a platform object, then perform a security + // check, passing: + // 5. If object is not a default iterator object for interface, + // then throw a TypeError. + if (typeof this !== 'object' || this === null || !(#target in this)) { + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ) + } + + // 6. Let index be object’s index. + // 7. Let kind be object’s kind. + // 8. Let values be object’s target's value pairs to iterate over. + const index = this.#index + const values = kInternalIterator(this.#target) + + // 9. Let len be the length of values. + const len = values.length + + // 10. If index is greater than or equal to len, then return + // CreateIterResultObject(undefined, true). + if (index >= len) { + return { + value: undefined, + done: true + } + } + + // 11. Let pair be the entry in values at index index. + const { [keyIndex]: key, [valueIndex]: value } = values[index] + + // 12. Set object’s index to index + 1. + this.#index = index + 1 + + // 13. Return the iterator result for pair and kind. + + // https://webidl.spec.whatwg.org/#iterator-result + + // 1. Let result be a value determined by the value of kind: + let result + switch (this.#kind) { + case 'key': + // 1. Let idlKey be pair’s key. + // 2. Let key be the result of converting idlKey to an + // ECMAScript value. + // 3. result is key. + result = key + break + case 'value': + // 1. Let idlValue be pair’s value. + // 2. Let value be the result of converting idlValue to + // an ECMAScript value. + // 3. result is value. + result = value + break + case 'key+value': + // 1. Let idlKey be pair’s key. + // 2. Let idlValue be pair’s value. + // 3. Let key be the result of converting idlKey to an + // ECMAScript value. + // 4. Let value be the result of converting idlValue to + // an ECMAScript value. + // 5. Let array be ! ArrayCreate(2). + // 6. Call ! CreateDataProperty(array, "0", key). + // 7. Call ! CreateDataProperty(array, "1", value). + // 8. result is array. + result = [key, value] + break + } + + // 2. Return CreateIterResultObject(result, false). + return { + value: result, + done: false + } + } + } + + // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + // @ts-ignore + delete FastIterableIterator.prototype.constructor + + Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype) + + Object.defineProperties(FastIterableIterator.prototype, { + [Symbol.toStringTag]: { + writable: false, + enumerable: false, + configurable: true, + value: `${name} Iterator` + }, + next: { writable: true, enumerable: true, configurable: true } + }) + + /** + * @param {unknown} target + * @param {'key' | 'value' | 'key+value'} kind + * @returns {IterableIterator} + */ + return function (target, kind) { + return new FastIterableIterator(target, kind) + } +} + +/** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {string} name name of the instance + * @param {any} object class + * @param {(target: any) => any} kInternalIterator + * @param {string | number} [keyIndex] + * @param {string | number} [valueIndex] + */ +function iteratorMixin (name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) { + const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex) + + const properties = { + keys: { + writable: true, + enumerable: true, + configurable: true, + value: function keys () { + webidl.brandCheck(this, object) + return makeIterator(this, 'key') + } + }, + values: { + writable: true, + enumerable: true, + configurable: true, + value: function values () { + webidl.brandCheck(this, object) + return makeIterator(this, 'value') + } + }, + entries: { + writable: true, + enumerable: true, + configurable: true, + value: function entries () { + webidl.brandCheck(this, object) + return makeIterator(this, 'key+value') + } + }, + forEach: { + writable: true, + enumerable: true, + configurable: true, + value: function forEach (callbackfn, thisArg = globalThis) { + webidl.brandCheck(this, object) + webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`) + if (typeof callbackfn !== 'function') { + throw new TypeError( + `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.` + ) + } + for (const { 0: key, 1: value } of makeIterator(this, 'key+value')) { + callbackfn.call(thisArg, value, key, this) + } + } + } + } + + return Object.defineProperties(object.prototype, { + ...properties, + [Symbol.iterator]: { + writable: true, + enumerable: false, + configurable: true, + value: properties.entries.value + } + }) +} + +/** + * @param {import('./body').ExtractBodyResult} body + * @param {(bytes: Uint8Array) => void} processBody + * @param {(error: Error) => void} processBodyError + * @returns {void} + * + * @see https://fetch.spec.whatwg.org/#body-fully-read + */ +function fullyReadBody (body, processBody, processBodyError) { + // 1. If taskDestination is null, then set taskDestination to + // the result of starting a new parallel queue. + + // 2. Let successSteps given a byte sequence bytes be to queue a + // fetch task to run processBody given bytes, with taskDestination. + const successSteps = processBody + + // 3. Let errorSteps be to queue a fetch task to run processBodyError, + // with taskDestination. + const errorSteps = processBodyError + + try { + // 4. Let reader be the result of getting a reader for body’s stream. + // If that threw an exception, then run errorSteps with that + // exception and return. + const reader = body.stream.getReader() + + // 5. Read all bytes from reader, given successSteps and errorSteps. + readAllBytes(reader, successSteps, errorSteps) + } catch (e) { + errorSteps(e) + } +} + +/** + * @param {ReadableStreamController} controller + */ +function readableStreamClose (controller) { + try { + controller.close() + controller.byobRequest?.respond(0) + } catch (err) { + // TODO: add comment explaining why this error occurs. + if (!err.message.includes('Controller is already closed') && !err.message.includes('ReadableStream is already closed')) { + throw err + } + } +} + +/** + * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes + * @see https://streams.spec.whatwg.org/#read-loop + * @param {ReadableStream>} reader + * @param {(bytes: Uint8Array) => void} successSteps + * @param {(error: Error) => void} failureSteps + * @returns {Promise} + */ +async function readAllBytes (reader, successSteps, failureSteps) { + try { + const bytes = [] + let byteLength = 0 + + do { + const { done, value: chunk } = await reader.read() + + if (done) { + // 1. Call successSteps with bytes. + successSteps(Buffer.concat(bytes, byteLength)) + return + } + + // 1. If chunk is not a Uint8Array object, call failureSteps + // with a TypeError and abort these steps. + if (!isUint8Array(chunk)) { + failureSteps(new TypeError('Received non-Uint8Array chunk')) + return + } + + // 2. Append the bytes represented by chunk to bytes. + bytes.push(chunk) + byteLength += chunk.length + + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. + } while (true) + } catch (e) { + // 1. Call failureSteps with e. + failureSteps(e) + } +} + +/** + * @see https://fetch.spec.whatwg.org/#is-local + * @param {URL} url + * @returns {boolean} + */ +function urlIsLocal (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + // A URL is local if its scheme is a local scheme. + // A local scheme is "about", "blob", or "data". + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' +} + +/** + * @param {string|URL} url + * @returns {boolean} + */ +function urlHasHttpsScheme (url) { + return ( + ( + typeof url === 'string' && + url[5] === ':' && + url[0] === 'h' && + url[1] === 't' && + url[2] === 't' && + url[3] === 'p' && + url[4] === 's' + ) || + url.protocol === 'https:' + ) +} + +/** + * @see https://fetch.spec.whatwg.org/#http-scheme + * @param {URL} url + */ +function urlIsHttpHttpsScheme (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + return protocol === 'http:' || protocol === 'https:' +} + +/** + * @typedef {Object} RangeHeaderValue + * @property {number|null} rangeStartValue + * @property {number|null} rangeEndValue + */ + +/** + * @see https://fetch.spec.whatwg.org/#simple-range-header-value + * @param {string} value + * @param {boolean} allowWhitespace + * @return {RangeHeaderValue|'failure'} + */ +function simpleRangeHeaderValue (value, allowWhitespace) { + // 1. Let data be the isomorphic decoding of value. + // Note: isomorphic decoding takes a sequence of bytes (ie. a Uint8Array) and turns it into a string, + // nothing more. We obviously don't need to do that if value is a string already. + const data = value + + // 2. If data does not start with "bytes", then return failure. + if (!data.startsWith('bytes')) { + return 'failure' + } + + // 3. Let position be a position variable for data, initially pointing at the 5th code point of data. + const position = { position: 5 } + + // 4. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, + // from data given position. + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ) + } + + // 5. If the code point at position within data is not U+003D (=), then return failure. + if (data.charCodeAt(position.position) !== 0x3D) { + return 'failure' + } + + // 6. Advance position by 1. + position.position++ + + // 7. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, from + // data given position. + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ) + } + + // 8. Let rangeStart be the result of collecting a sequence of code points that are ASCII digits, + // from data given position. + const rangeStart = collectASequenceOfCodePoints( + (char) => { + const code = char.charCodeAt(0) + + return code >= 0x30 && code <= 0x39 + }, + data, + position + ) + + // 9. Let rangeStartValue be rangeStart, interpreted as decimal number, if rangeStart is not the + // empty string; otherwise null. + const rangeStartValue = rangeStart.length ? Number(rangeStart) : null + + // 10. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, + // from data given position. + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ) + } + + // 11. If the code point at position within data is not U+002D (-), then return failure. + if (data.charCodeAt(position.position) !== 0x2D) { + return 'failure' + } + + // 12. Advance position by 1. + position.position++ + + // 13. If allowWhitespace is true, collect a sequence of code points that are HTTP tab + // or space, from data given position. + // Note from Khafra: its the same step as in #8 again lol + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ) + } + + // 14. Let rangeEnd be the result of collecting a sequence of code points that are + // ASCII digits, from data given position. + // Note from Khafra: you wouldn't guess it, but this is also the same step as #8 + const rangeEnd = collectASequenceOfCodePoints( + (char) => { + const code = char.charCodeAt(0) + + return code >= 0x30 && code <= 0x39 + }, + data, + position + ) + + // 15. Let rangeEndValue be rangeEnd, interpreted as decimal number, if rangeEnd + // is not the empty string; otherwise null. + // Note from Khafra: THE SAME STEP, AGAIN!!! + // Note: why interpret as a decimal if we only collect ascii digits? + const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null + + // 16. If position is not past the end of data, then return failure. + if (position.position < data.length) { + return 'failure' + } + + // 17. If rangeEndValue and rangeStartValue are null, then return failure. + if (rangeEndValue === null && rangeStartValue === null) { + return 'failure' + } + + // 18. If rangeStartValue and rangeEndValue are numbers, and rangeStartValue is + // greater than rangeEndValue, then return failure. + // Note: ... when can they not be numbers? + if (rangeStartValue > rangeEndValue) { + return 'failure' + } + + // 19. Return (rangeStartValue, rangeEndValue). + return { rangeStartValue, rangeEndValue } +} + +/** + * @see https://fetch.spec.whatwg.org/#build-a-content-range + * @param {number} rangeStart + * @param {number} rangeEnd + * @param {number} fullLength + */ +function buildContentRange (rangeStart, rangeEnd, fullLength) { + // 1. Let contentRange be `bytes `. + let contentRange = 'bytes ' + + // 2. Append rangeStart, serialized and isomorphic encoded, to contentRange. + contentRange += isomorphicEncode(`${rangeStart}`) + + // 3. Append 0x2D (-) to contentRange. + contentRange += '-' + + // 4. Append rangeEnd, serialized and isomorphic encoded to contentRange. + contentRange += isomorphicEncode(`${rangeEnd}`) + + // 5. Append 0x2F (/) to contentRange. + contentRange += '/' + + // 6. Append fullLength, serialized and isomorphic encoded to contentRange. + contentRange += isomorphicEncode(`${fullLength}`) + + // 7. Return contentRange. + return contentRange +} + +// A Stream, which pipes the response to zlib.createInflate() or +// zlib.createInflateRaw() depending on the first byte of the Buffer. +// If the lower byte of the first byte is 0x08, then the stream is +// interpreted as a zlib stream, otherwise it's interpreted as a +// raw deflate stream. +class InflateStream extends Transform { + #zlibOptions + + /** @param {zlib.ZlibOptions} [zlibOptions] */ + constructor (zlibOptions) { + super() + this.#zlibOptions = zlibOptions + } + + _transform (chunk, encoding, callback) { + if (!this._inflateStream) { + if (chunk.length === 0) { + callback() + return + } + this._inflateStream = (chunk[0] & 0x0F) === 0x08 + ? zlib.createInflate(this.#zlibOptions) + : zlib.createInflateRaw(this.#zlibOptions) + + this._inflateStream.on('data', this.push.bind(this)) + this._inflateStream.on('end', () => this.push(null)) + this._inflateStream.on('error', (err) => this.destroy(err)) + } + + this._inflateStream.write(chunk, encoding, callback) + } + + _final (callback) { + if (this._inflateStream) { + this._inflateStream.end() + this._inflateStream = null + } + callback() + } +} + +/** + * @param {zlib.ZlibOptions} [zlibOptions] + * @returns {InflateStream} + */ +function createInflate (zlibOptions) { + return new InflateStream(zlibOptions) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-extract-mime-type + * @param {import('./headers').HeadersList} headers + */ +function extractMimeType (headers) { + // 1. Let charset be null. + let charset = null + + // 2. Let essence be null. + let essence = null + + // 3. Let mimeType be null. + let mimeType = null + + // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers. + const values = getDecodeSplit('content-type', headers) + + // 5. If values is null, then return failure. + if (values === null) { + return 'failure' + } + + // 6. For each value of values: + for (const value of values) { + // 6.1. Let temporaryMimeType be the result of parsing value. + const temporaryMimeType = parseMIMEType(value) + + // 6.2. If temporaryMimeType is failure or its essence is "*/*", then continue. + if (temporaryMimeType === 'failure' || temporaryMimeType.essence === '*/*') { + continue + } + + // 6.3. Set mimeType to temporaryMimeType. + mimeType = temporaryMimeType + + // 6.4. If mimeType’s essence is not essence, then: + if (mimeType.essence !== essence) { + // 6.4.1. Set charset to null. + charset = null + + // 6.4.2. If mimeType’s parameters["charset"] exists, then set charset to + // mimeType’s parameters["charset"]. + if (mimeType.parameters.has('charset')) { + charset = mimeType.parameters.get('charset') + } + + // 6.4.3. Set essence to mimeType’s essence. + essence = mimeType.essence + } else if (!mimeType.parameters.has('charset') && charset !== null) { + // 6.5. Otherwise, if mimeType’s parameters["charset"] does not exist, and + // charset is non-null, set mimeType’s parameters["charset"] to charset. + mimeType.parameters.set('charset', charset) + } + } + + // 7. If mimeType is null, then return failure. + if (mimeType == null) { + return 'failure' + } + + // 8. Return mimeType. + return mimeType +} + +/** + * @see https://fetch.spec.whatwg.org/#header-value-get-decode-and-split + * @param {string|null} value + */ +function gettingDecodingSplitting (value) { + // 1. Let input be the result of isomorphic decoding value. + const input = value + + // 2. Let position be a position variable for input, initially pointing at the start of input. + const position = { position: 0 } + + // 3. Let values be a list of strings, initially empty. + const values = [] + + // 4. Let temporaryValue be the empty string. + let temporaryValue = '' + + // 5. While position is not past the end of input: + while (position.position < input.length) { + // 5.1. Append the result of collecting a sequence of code points that are not U+0022 (") + // or U+002C (,) from input, given position, to temporaryValue. + temporaryValue += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== ',', + input, + position + ) + + // 5.2. If position is not past the end of input, then: + if (position.position < input.length) { + // 5.2.1. If the code point at position within input is U+0022 ("), then: + if (input.charCodeAt(position.position) === 0x22) { + // 5.2.1.1. Append the result of collecting an HTTP quoted string from input, given position, to temporaryValue. + temporaryValue += collectAnHTTPQuotedString( + input, + position + ) + + // 5.2.1.2. If position is not past the end of input, then continue. + if (position.position < input.length) { + continue + } + } else { + // 5.2.2. Otherwise: + + // 5.2.2.1. Assert: the code point at position within input is U+002C (,). + assert(input.charCodeAt(position.position) === 0x2C) + + // 5.2.2.2. Advance position by 1. + position.position++ + } + } + + // 5.3. Remove all HTTP tab or space from the start and end of temporaryValue. + temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 0x9 || char === 0x20) + + // 5.4. Append temporaryValue to values. + values.push(temporaryValue) + + // 5.6. Set temporaryValue to the empty string. + temporaryValue = '' + } + + // 6. Return values. + return values +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split + * @param {string} name lowercase header name + * @param {import('./headers').HeadersList} list + */ +function getDecodeSplit (name, list) { + // 1. Let value be the result of getting name from list. + const value = list.get(name, true) + + // 2. If value is null, then return null. + if (value === null) { + return null + } + + // 3. Return the result of getting, decoding, and splitting value. + return gettingDecodingSplitting(value) +} + +function hasAuthenticationEntry (request) { + return false +} + +/** + * @see https://url.spec.whatwg.org/#include-credentials + * @param {URL} url + */ +function includesCredentials (url) { + // A URL includes credentials if its username or password is not the empty string. + return !!(url.username && url.password) +} + +/** + * @see https://html.spec.whatwg.org/multipage/document-sequences.html#traversable-navigable + * @param {object|string} navigable + */ +function isTraversableNavigable (navigable) { + // TODO + return true +} + +class EnvironmentSettingsObjectBase { + get baseUrl () { + return getGlobalOrigin() + } + + get origin () { + return this.baseUrl?.origin + } + + policyContainer = makePolicyContainer() +} + +class EnvironmentSettingsObject { + settingsObject = new EnvironmentSettingsObjectBase() +} + +const environmentSettingsObject = new EnvironmentSettingsObject() + +module.exports = { + isAborted, + isCancelled, + isValidEncodedURL, + ReadableStreamFrom, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + clampAndCoarsenConnectionTimingInfo, + coarsenedSharedCurrentTime, + determineRequestsReferrer, + makePolicyContainer, + clonePolicyContainer, + appendFetchMetadata, + appendRequestOriginHeader, + TAOCheck, + corsCheck, + crossOriginResourcePolicyCheck, + createOpaqueTimingInfo, + setRequestReferrerPolicyOnRedirect, + isValidHTTPToken, + requestBadPort, + requestCurrentURL, + responseURL, + responseLocationURL, + isURLPotentiallyTrustworthy, + isValidReasonPhrase, + sameOrigin, + normalizeMethod, + iteratorMixin, + createIterator, + isValidHeaderName, + isValidHeaderValue, + isErrorLike, + fullyReadBody, + readableStreamClose, + urlIsLocal, + urlHasHttpsScheme, + urlIsHttpHttpsScheme, + readAllBytes, + simpleRangeHeaderValue, + buildContentRange, + createInflate, + extractMimeType, + getDecodeSplit, + environmentSettingsObject, + isOriginIPPotentiallyTrustworthy, + hasAuthenticationEntry, + includesCredentials, + isTraversableNavigable +} diff --git a/node_modules/undici/lib/web/infra/index.js b/node_modules/undici/lib/web/infra/index.js new file mode 100644 index 000000000..391bb2e3d --- /dev/null +++ b/node_modules/undici/lib/web/infra/index.js @@ -0,0 +1,229 @@ +'use strict' + +const assert = require('node:assert') +const { utf8DecodeBytes } = require('../../encoding') + +/** + * @param {(char: string) => boolean} condition + * @param {string} input + * @param {{ position: number }} position + * @returns {string} + * + * @see https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points + */ +function collectASequenceOfCodePoints (condition, input, position) { + // 1. Let result be the empty string. + let result = '' + + // 2. While position doesn’t point past the end of input and the + // code point at position within input meets the condition condition: + while (position.position < input.length && condition(input[position.position])) { + // 1. Append that code point to the end of result. + result += input[position.position] + + // 2. Advance position by 1. + position.position++ + } + + // 3. Return result. + return result +} + +/** + * A faster collectASequenceOfCodePoints that only works when comparing a single character. + * @param {string} char + * @param {string} input + * @param {{ position: number }} position + * @returns {string} + * + * @see https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points + */ +function collectASequenceOfCodePointsFast (char, input, position) { + const idx = input.indexOf(char, position.position) + const start = position.position + + if (idx === -1) { + position.position = input.length + return input.slice(start) + } + + position.position = idx + return input.slice(start, position.position) +} + +const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line no-control-regex + +/** + * @param {string} data + * @returns {Uint8Array | 'failure'} + * + * @see https://infra.spec.whatwg.org/#forgiving-base64-decode + */ +function forgivingBase64 (data) { + // 1. Remove all ASCII whitespace from data. + data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') + + let dataLength = data.length + // 2. If data’s code point length divides by 4 leaving + // no remainder, then: + if (dataLength % 4 === 0) { + // 1. If data ends with one or two U+003D (=) code points, + // then remove them from data. + if (data.charCodeAt(dataLength - 1) === 0x003D) { + --dataLength + if (data.charCodeAt(dataLength - 1) === 0x003D) { + --dataLength + } + } + } + + // 3. If data’s code point length divides by 4 leaving + // a remainder of 1, then return failure. + if (dataLength % 4 === 1) { + return 'failure' + } + + // 4. If data contains a code point that is not one of + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // then return failure. + if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) { + return 'failure' + } + + const buffer = Buffer.from(data, 'base64') + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) +} + +/** + * @param {number} char + * @returns {boolean} + * + * @see https://infra.spec.whatwg.org/#ascii-whitespace + */ +function isASCIIWhitespace (char) { + return ( + char === 0x09 || // \t + char === 0x0a || // \n + char === 0x0c || // \f + char === 0x0d || // \r + char === 0x20 // space + ) +} + +/** + * @param {Uint8Array} input + * @returns {string} + * + * @see https://infra.spec.whatwg.org/#isomorphic-decode + */ +function isomorphicDecode (input) { + // 1. To isomorphic decode a byte sequence input, return a string whose code point + // length is equal to input’s length and whose code points have the same values + // as the values of input’s bytes, in the same order. + const length = input.length + if ((2 << 15) - 1 > length) { + return String.fromCharCode.apply(null, input) + } + let result = '' + let i = 0 + let addition = (2 << 15) - 1 + while (i < length) { + if (i + addition > length) { + addition = length - i + } + result += String.fromCharCode.apply(null, input.subarray(i, i += addition)) + } + return result +} + +const invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/ // eslint-disable-line no-control-regex + +/** + * @param {string} input + * @returns {string} + * + * @see https://infra.spec.whatwg.org/#isomorphic-encode + */ +function isomorphicEncode (input) { + // 1. Assert: input contains no code points greater than U+00FF. + assert(!invalidIsomorphicEncodeValueRegex.test(input)) + + // 2. Return a byte sequence whose length is equal to input’s code + // point length and whose bytes have the same values as the + // values of input’s code points, in the same order + return input +} + +/** + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes + */ +function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) +} + +/** + * @param {string} str + * @param {boolean} [leading=true] + * @param {boolean} [trailing=true] + * @returns {string} + * + * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace + */ +function removeASCIIWhitespace (str, leading = true, trailing = true) { + return removeChars(str, leading, trailing, isASCIIWhitespace) +} + +/** + * @param {string} str + * @param {boolean} leading + * @param {boolean} trailing + * @param {(charCode: number) => boolean} predicate + * @returns {string} + */ +function removeChars (str, leading, trailing, predicate) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + while (lead < str.length && predicate(str.charCodeAt(lead))) lead++ + } + + if (trailing) { + while (trail > 0 && predicate(str.charCodeAt(trail))) trail-- + } + + return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1) +} + +// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string +function serializeJavascriptValueToJSONString (value) { + // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). + const result = JSON.stringify(value) + + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') + } + + // 3. Assert: result is a string. + assert(typeof result === 'string') + + // 4. Return result. + return result +} + +module.exports = { + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + forgivingBase64, + isASCIIWhitespace, + isomorphicDecode, + isomorphicEncode, + parseJSONFromBytes, + removeASCIIWhitespace, + removeChars, + serializeJavascriptValueToJSONString +} diff --git a/node_modules/undici/lib/web/subresource-integrity/Readme.md b/node_modules/undici/lib/web/subresource-integrity/Readme.md new file mode 100644 index 000000000..289a2b84d --- /dev/null +++ b/node_modules/undici/lib/web/subresource-integrity/Readme.md @@ -0,0 +1,9 @@ +# Subresource Integrity + +based on Editor’s Draft, 12 June 2025 + +This module provides support for Subresource Integrity (SRI) in the context of web fetch operations. SRI is a security feature that allows clients to verify that fetched resources are delivered without unexpected manipulation. + +## Links + +- [Subresource Integrity](https://w3c.github.io/webappsec-subresource-integrity/) \ No newline at end of file diff --git a/node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js b/node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js new file mode 100644 index 000000000..8c8f6c4d8 --- /dev/null +++ b/node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js @@ -0,0 +1,307 @@ +'use strict' + +const assert = require('node:assert') +const { runtimeFeatures } = require('../../util/runtime-features.js') + +/** + * @typedef {object} Metadata + * @property {SRIHashAlgorithm} alg - The algorithm used for the hash. + * @property {string} val - The base64-encoded hash value. + */ + +/** + * @typedef {Metadata[]} MetadataList + */ + +/** + * @typedef {('sha256' | 'sha384' | 'sha512')} SRIHashAlgorithm + */ + +/** + * @type {Map} + * + * The valid SRI hash algorithm token set is the ordered set « "sha256", + * "sha384", "sha512" » (corresponding to SHA-256, SHA-384, and SHA-512 + * respectively). The ordering of this set is meaningful, with stronger + * algorithms appearing later in the set. + * + * @see https://w3c.github.io/webappsec-subresource-integrity/#valid-sri-hash-algorithm-token-set + */ +const validSRIHashAlgorithmTokenSet = new Map([['sha256', 0], ['sha384', 1], ['sha512', 2]]) + +// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable +/** @type {import('node:crypto')} */ +let crypto + +if (runtimeFeatures.has('crypto')) { + crypto = require('node:crypto') + const cryptoHashes = crypto.getHashes() + + // If no hashes are available, we cannot support SRI. + if (cryptoHashes.length === 0) { + validSRIHashAlgorithmTokenSet.clear() + } + + for (const algorithm of validSRIHashAlgorithmTokenSet.keys()) { + // If the algorithm is not supported, remove it from the list. + if (cryptoHashes.includes(algorithm) === false) { + validSRIHashAlgorithmTokenSet.delete(algorithm) + } + } +} else { + // If crypto is not available, we cannot support SRI. + validSRIHashAlgorithmTokenSet.clear() +} + +/** + * @typedef GetSRIHashAlgorithmIndex + * @type {(algorithm: SRIHashAlgorithm) => number} + * @param {SRIHashAlgorithm} algorithm + * @returns {number} The index of the algorithm in the valid SRI hash algorithm + * token set. + */ + +const getSRIHashAlgorithmIndex = /** @type {GetSRIHashAlgorithmIndex} */ (Map.prototype.get.bind( + validSRIHashAlgorithmTokenSet)) + +/** + * @typedef IsValidSRIHashAlgorithm + * @type {(algorithm: string) => algorithm is SRIHashAlgorithm} + * @param {*} algorithm + * @returns {algorithm is SRIHashAlgorithm} + */ + +const isValidSRIHashAlgorithm = /** @type {IsValidSRIHashAlgorithm} */ ( + Map.prototype.has.bind(validSRIHashAlgorithmTokenSet) +) + +/** + * @param {Uint8Array} bytes + * @param {string} metadataList + * @returns {boolean} + * + * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist + */ +const bytesMatch = runtimeFeatures.has('crypto') === false || validSRIHashAlgorithmTokenSet.size === 0 + // If node is not built with OpenSSL support, we cannot check + // a request's integrity, so allow it by default (the spec will + // allow requests if an invalid hash is given, as precedence). + ? () => true + : (bytes, metadataList) => { + // 1. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList) + + // 2. If parsedMetadata is empty set, return true. + if (parsedMetadata.length === 0) { + return true + } + + // 3. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const metadata = getStrongestMetadata(parsedMetadata) + + // 4. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the item["alg"]. + const algorithm = item.alg + + // 2. Let expectedValue be the item["val"]. + const expectedValue = item.val + + // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e + // "be liberal with padding". This is annoying, and it's not even in the spec. + + // 3. Let actualValue be the result of applying algorithm to bytes . + const actualValue = applyAlgorithmToBytes(algorithm, bytes) + + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (caseSensitiveMatch(actualValue, expectedValue)) { + return true + } + } + + // 5. Return false. + return false + } + +/** + * @param {MetadataList} metadataList + * @returns {MetadataList} The strongest hash algorithm from the metadata list. + */ +function getStrongestMetadata (metadataList) { + // 1. Let result be the empty set and strongest be the empty string. + const result = [] + /** @type {Metadata|null} */ + let strongest = null + + // 2. For each item in set: + for (const item of metadataList) { + // 1. Assert: item["alg"] is a valid SRI hash algorithm token. + assert(isValidSRIHashAlgorithm(item.alg), 'Invalid SRI hash algorithm token') + + // 2. If result is the empty set, then: + if (result.length === 0) { + // 1. Append item to result. + result.push(item) + + // 2. Set strongest to item. + strongest = item + + // 3. Continue. + continue + } + + // 3. Let currentAlgorithm be strongest["alg"], and currentAlgorithmIndex be + // the index of currentAlgorithm in the valid SRI hash algorithm token set. + const currentAlgorithm = /** @type {Metadata} */ (strongest).alg + const currentAlgorithmIndex = getSRIHashAlgorithmIndex(currentAlgorithm) + + // 4. Let newAlgorithm be the item["alg"], and newAlgorithmIndex be the + // index of newAlgorithm in the valid SRI hash algorithm token set. + const newAlgorithm = item.alg + const newAlgorithmIndex = getSRIHashAlgorithmIndex(newAlgorithm) + + // 5. If newAlgorithmIndex is less than currentAlgorithmIndex, then continue. + if (newAlgorithmIndex < currentAlgorithmIndex) { + continue + + // 6. Otherwise, if newAlgorithmIndex is greater than + // currentAlgorithmIndex: + } else if (newAlgorithmIndex > currentAlgorithmIndex) { + // 1. Set strongest to item. + strongest = item + + // 2. Set result to « item ». + result[0] = item + result.length = 1 + + // 7. Otherwise, newAlgorithmIndex and currentAlgorithmIndex are the same + // value. Append item to result. + } else { + result.push(item) + } + } + + // 3. Return result. + return result +} + +/** + * @param {string} metadata + * @returns {MetadataList} + * + * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata + */ +function parseMetadata (metadata) { + // 1. Let result be the empty set. + /** @type {MetadataList} */ + const result = [] + + // 2. For each item returned by splitting metadata on spaces: + for (const item of metadata.split(' ')) { + // 1. Let expression-and-options be the result of splitting item on U+003F (?). + const expressionAndOptions = item.split('?', 1) + + // 2. Let algorithm-expression be expression-and-options[0]. + const algorithmExpression = expressionAndOptions[0] + + // 3. Let base64-value be the empty string. + let base64Value = '' + + // 4. Let algorithm-and-value be the result of splitting algorithm-expression on U+002D (-). + const algorithmAndValue = [algorithmExpression.slice(0, 6), algorithmExpression.slice(7)] + + // 5. Let algorithm be algorithm-and-value[0]. + const algorithm = algorithmAndValue[0] + + // 6. If algorithm is not a valid SRI hash algorithm token, then continue. + if (!isValidSRIHashAlgorithm(algorithm)) { + continue + } + + // 7. If algorithm-and-value[1] exists, set base64-value to + // algorithm-and-value[1]. + if (algorithmAndValue[1]) { + base64Value = algorithmAndValue[1] + } + + // 8. Let metadata be the ordered map + // «["alg" → algorithm, "val" → base64-value]». + const metadata = { + alg: algorithm, + val: base64Value + } + + // 9. Append metadata to result. + result.push(metadata) + } + + // 3. Return result. + return result +} + +/** + * Applies the specified hash algorithm to the given bytes + * + * @typedef {(algorithm: SRIHashAlgorithm, bytes: Uint8Array) => string} ApplyAlgorithmToBytes + * @param {SRIHashAlgorithm} algorithm + * @param {Uint8Array} bytes + * @returns {string} + */ +const applyAlgorithmToBytes = (algorithm, bytes) => { + return crypto.hash(algorithm, bytes, 'base64') +} + +/** + * Compares two base64 strings, allowing for base64url + * in the second string. + * + * @param {string} actualValue base64 encoded string + * @param {string} expectedValue base64 or base64url encoded string + * @returns {boolean} + */ +function caseSensitiveMatch (actualValue, expectedValue) { + // Ignore padding characters from the end of the strings by + // decreasing the length by 1 or 2 if the last characters are `=`. + let actualValueLength = actualValue.length + if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === '=') { + actualValueLength -= 1 + } + if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === '=') { + actualValueLength -= 1 + } + let expectedValueLength = expectedValue.length + if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === '=') { + expectedValueLength -= 1 + } + if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === '=') { + expectedValueLength -= 1 + } + + if (actualValueLength !== expectedValueLength) { + return false + } + + for (let i = 0; i < actualValueLength; ++i) { + if ( + actualValue[i] === expectedValue[i] || + (actualValue[i] === '+' && expectedValue[i] === '-') || + (actualValue[i] === '/' && expectedValue[i] === '_') + ) { + continue + } + return false + } + + return true +} + +module.exports = { + applyAlgorithmToBytes, + bytesMatch, + caseSensitiveMatch, + isValidSRIHashAlgorithm, + getStrongestMetadata, + parseMetadata +} diff --git a/node_modules/undici/lib/web/webidl/index.js b/node_modules/undici/lib/web/webidl/index.js new file mode 100644 index 000000000..542571559 --- /dev/null +++ b/node_modules/undici/lib/web/webidl/index.js @@ -0,0 +1,951 @@ +'use strict' + +const { types, inspect } = require('node:util') +const { runtimeFeatures } = require('../../util/runtime-features') + +const UNDEFINED = 1 +const BOOLEAN = 2 +const STRING = 3 +const SYMBOL = 4 +const NUMBER = 5 +const BIGINT = 6 +const NULL = 7 +const OBJECT = 8 // function and object + +const FunctionPrototypeSymbolHasInstance = Function.call.bind(Function.prototype[Symbol.hasInstance]) + +/** @type {import('../../../types/webidl').Webidl} */ +const webidl = { + converters: {}, + util: {}, + errors: {}, + is: {} +} + +/** + * @description Instantiate an error. + * + * @param {Object} opts + * @param {string} opts.header + * @param {string} opts.message + * @returns {TypeError} + */ +webidl.errors.exception = function (message) { + return new TypeError(`${message.header}: ${message.message}`) +} + +/** + * @description Instantiate an error when conversion from one type to another has failed. + * + * @param {Object} opts + * @param {string} opts.prefix + * @param {string} opts.argument + * @param {string[]} opts.types + * @returns {TypeError} + */ +webidl.errors.conversionFailed = function (opts) { + const plural = opts.types.length === 1 ? '' : ' one of' + const message = + `${opts.argument} could not be converted to` + + `${plural}: ${opts.types.join(', ')}.` + + return webidl.errors.exception({ + header: opts.prefix, + message + }) +} + +/** + * @description Instantiate an error when an invalid argument is provided + * + * @param {Object} context + * @param {string} context.prefix + * @param {string} context.value + * @param {string} context.type + * @returns {TypeError} + */ +webidl.errors.invalidArgument = function (context) { + return webidl.errors.exception({ + header: context.prefix, + message: `"${context.value}" is an invalid ${context.type}.` + }) +} + +// https://webidl.spec.whatwg.org/#implements +webidl.brandCheck = function (V, I) { + if (!FunctionPrototypeSymbolHasInstance(I, V)) { + const err = new TypeError('Illegal invocation') + err.code = 'ERR_INVALID_THIS' // node compat. + throw err + } +} + +webidl.brandCheckMultiple = function (List) { + const prototypes = List.map((c) => webidl.util.MakeTypeAssertion(c)) + + return (V) => { + if (prototypes.every(typeCheck => !typeCheck(V))) { + const err = new TypeError('Illegal invocation') + err.code = 'ERR_INVALID_THIS' // node compat. + throw err + } + } +} + +webidl.argumentLengthCheck = function ({ length }, min, ctx) { + if (length < min) { + throw webidl.errors.exception({ + message: `${min} argument${min !== 1 ? 's' : ''} required, ` + + `but${length ? ' only' : ''} ${length} found.`, + header: ctx + }) + } +} + +webidl.illegalConstructor = function () { + throw webidl.errors.exception({ + header: 'TypeError', + message: 'Illegal constructor' + }) +} + +webidl.util.MakeTypeAssertion = function (I) { + return (O) => FunctionPrototypeSymbolHasInstance(I, O) +} + +// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values +webidl.util.Type = function (V) { + switch (typeof V) { + case 'undefined': return UNDEFINED + case 'boolean': return BOOLEAN + case 'string': return STRING + case 'symbol': return SYMBOL + case 'number': return NUMBER + case 'bigint': return BIGINT + case 'function': + case 'object': { + if (V === null) { + return NULL + } + + return OBJECT + } + } +} + +webidl.util.Types = { + UNDEFINED, + BOOLEAN, + STRING, + SYMBOL, + NUMBER, + BIGINT, + NULL, + OBJECT +} + +webidl.util.TypeValueToString = function (o) { + switch (webidl.util.Type(o)) { + case UNDEFINED: return 'Undefined' + case BOOLEAN: return 'Boolean' + case STRING: return 'String' + case SYMBOL: return 'Symbol' + case NUMBER: return 'Number' + case BIGINT: return 'BigInt' + case NULL: return 'Null' + case OBJECT: return 'Object' + } +} + +webidl.util.markAsUncloneable = runtimeFeatures.has('markAsUncloneable') + ? require('node:worker_threads').markAsUncloneable + : () => {} + +// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint +webidl.util.ConvertToInt = function (V, bitLength, signedness, flags) { + let upperBound + let lowerBound + + // 1. If bitLength is 64, then: + if (bitLength === 64) { + // 1. Let upperBound be 2^53 − 1. + upperBound = Math.pow(2, 53) - 1 + + // 2. If signedness is "unsigned", then let lowerBound be 0. + if (signedness === 'unsigned') { + lowerBound = 0 + } else { + // 3. Otherwise let lowerBound be −2^53 + 1. + lowerBound = Math.pow(-2, 53) + 1 + } + } else if (signedness === 'unsigned') { + // 2. Otherwise, if signedness is "unsigned", then: + + // 1. Let lowerBound be 0. + lowerBound = 0 + + // 2. Let upperBound be 2^bitLength − 1. + upperBound = Math.pow(2, bitLength) - 1 + } else { + // 3. Otherwise: + + // 1. Let lowerBound be -2^bitLength − 1. + lowerBound = Math.pow(-2, bitLength) - 1 + + // 2. Let upperBound be 2^bitLength − 1 − 1. + upperBound = Math.pow(2, bitLength - 1) - 1 + } + + // 4. Let x be ? ToNumber(V). + let x = Number(V) + + // 5. If x is −0, then set x to +0. + if (x === 0) { + x = 0 + } + + // 6. If the conversion is to an IDL type associated + // with the [EnforceRange] extended attribute, then: + if (webidl.util.HasFlag(flags, webidl.attributes.EnforceRange)) { + // 1. If x is NaN, +∞, or −∞, then throw a TypeError. + if ( + Number.isNaN(x) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Could not convert ${webidl.util.Stringify(V)} to an integer.` + }) + } + + // 2. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 3. If x < lowerBound or x > upperBound, then + // throw a TypeError. + if (x < lowerBound || x > upperBound) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` + }) + } + + // 4. Return x. + return x + } + + // 7. If x is not NaN and the conversion is to an IDL + // type associated with the [Clamp] extended + // attribute, then: + if (!Number.isNaN(x) && webidl.util.HasFlag(flags, webidl.attributes.Clamp)) { + // 1. Set x to min(max(x, lowerBound), upperBound). + x = Math.min(Math.max(x, lowerBound), upperBound) + + // 2. Round x to the nearest integer, choosing the + // even integer if it lies halfway between two, + // and choosing +0 rather than −0. + if (Math.floor(x) % 2 === 0) { + x = Math.floor(x) + } else { + x = Math.ceil(x) + } + + // 3. Return x. + return x + } + + // 8. If x is NaN, +0, +∞, or −∞, then return +0. + if ( + Number.isNaN(x) || + (x === 0 && Object.is(0, x)) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + return 0 + } + + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength) + + // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, + // then return x − 2^bitLength. + if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { + return x - Math.pow(2, bitLength) + } + + // 12. Otherwise, return x. + return x +} + +// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart +webidl.util.IntegerPart = function (n) { + // 1. Let r be floor(abs(n)). + const r = Math.floor(Math.abs(n)) + + // 2. If n < 0, then return -1 × r. + if (n < 0) { + return -1 * r + } + + // 3. Otherwise, return r. + return r +} + +webidl.util.Stringify = function (V) { + const type = webidl.util.Type(V) + + switch (type) { + case SYMBOL: + return `Symbol(${V.description})` + case OBJECT: + return inspect(V) + case STRING: + return `"${V}"` + case BIGINT: + return `${V}n` + default: + return `${V}` + } +} + +webidl.util.IsResizableArrayBuffer = function (V) { + if (types.isArrayBuffer(V)) { + return V.resizable + } + + if (types.isSharedArrayBuffer(V)) { + return V.growable + } + + throw webidl.errors.exception({ + header: 'IsResizableArrayBuffer', + message: `"${webidl.util.Stringify(V)}" is not an array buffer.` + }) +} + +webidl.util.HasFlag = function (flags, attributes) { + return typeof flags === 'number' && (flags & attributes) === attributes +} + +// https://webidl.spec.whatwg.org/#es-sequence +webidl.sequenceConverter = function (converter) { + return (V, prefix, argument, Iterable) => { + // 1. If Type(V) is not Object, throw a TypeError. + if (webidl.util.Type(V) !== OBJECT) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.` + }) + } + + // 2. Let method be ? GetMethod(V, @@iterator). + /** @type {Generator} */ + const method = typeof Iterable === 'function' ? Iterable() : V?.[Symbol.iterator]?.() + const seq = [] + let index = 0 + + // 3. If method is undefined, throw a TypeError. + if ( + method === undefined || + typeof method.next !== 'function' + ) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} is not iterable.` + }) + } + + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next() + + if (done) { + break + } + + seq.push(converter(value, prefix, `${argument}[${index++}]`)) + } + + return seq + } +} + +// https://webidl.spec.whatwg.org/#es-to-record +webidl.recordConverter = function (keyConverter, valueConverter) { + return (O, prefix, argument) => { + // 1. If Type(O) is not Object, throw a TypeError. + if (webidl.util.Type(O) !== OBJECT) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} ("${webidl.util.TypeValueToString(O)}") is not an Object.` + }) + } + + // 2. Let result be a new empty instance of record. + const result = {} + + if (!types.isProxy(O)) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const keys = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)] + + for (const key of keys) { + const keyName = webidl.util.Stringify(key) + + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key, prefix, `Key ${keyName} in ${argument}`) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key], prefix, `${argument}[${keyName}]`) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + + // 5. Return result. + return result + } + + // 3. Let keys be ? O.[[OwnPropertyKeys]](). + const keys = Reflect.ownKeys(O) + + // 4. For each key of keys. + for (const key of keys) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const desc = Reflect.getOwnPropertyDescriptor(O, key) + + // 2. If desc is not undefined and desc.[[Enumerable]] is true: + if (desc?.enumerable) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key, prefix, argument) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key], prefix, argument) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + } + + // 5. Return result. + return result + } +} + +webidl.interfaceConverter = function (TypeCheck, name) { + return (V, prefix, argument) => { + if (!TypeCheck(V)) { + throw webidl.errors.exception({ + header: prefix, + message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${name}.` + }) + } + + return V + } +} + +webidl.dictionaryConverter = function (converters) { + return (dictionary, prefix, argument) => { + const dict = {} + + if (dictionary != null && webidl.util.Type(dictionary) !== OBJECT) { + throw webidl.errors.exception({ + header: prefix, + message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` + }) + } + + for (const options of converters) { + const { key, defaultValue, required, converter } = options + + if (required === true) { + if (dictionary == null || !Object.hasOwn(dictionary, key)) { + throw webidl.errors.exception({ + header: prefix, + message: `Missing required key "${key}".` + }) + } + } + + let value = dictionary?.[key] + const hasDefault = defaultValue !== undefined + + // Only use defaultValue if value is undefined and + // a defaultValue options was provided. + if (hasDefault && value === undefined) { + value = defaultValue() + } + + // A key can be optional and have no default value. + // When this happens, do not perform a conversion, + // and do not assign the key a value. + if (required || hasDefault || value !== undefined) { + value = converter(value, prefix, `${argument}.${key}`) + + if ( + options.allowedValues && + !options.allowedValues.includes(value) + ) { + throw webidl.errors.exception({ + header: prefix, + message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` + }) + } + + dict[key] = value + } + } + + return dict + } +} + +webidl.nullableConverter = function (converter) { + return (V, prefix, argument) => { + if (V === null) { + return V + } + + return converter(V, prefix, argument) + } +} + +/** + * @param {*} value + * @returns {boolean} + */ +webidl.is.USVString = function (value) { + return ( + typeof value === 'string' && + value.isWellFormed() + ) +} + +webidl.is.ReadableStream = webidl.util.MakeTypeAssertion(ReadableStream) +webidl.is.Blob = webidl.util.MakeTypeAssertion(Blob) +webidl.is.URLSearchParams = webidl.util.MakeTypeAssertion(URLSearchParams) +webidl.is.File = webidl.util.MakeTypeAssertion(File) +webidl.is.URL = webidl.util.MakeTypeAssertion(URL) +webidl.is.AbortSignal = webidl.util.MakeTypeAssertion(AbortSignal) +webidl.is.MessagePort = webidl.util.MakeTypeAssertion(MessagePort) + +webidl.is.BufferSource = function (V) { + return types.isArrayBuffer(V) || ( + ArrayBuffer.isView(V) && + types.isArrayBuffer(V.buffer) + ) +} + +// https://webidl.spec.whatwg.org/#es-DOMString +webidl.converters.DOMString = function (V, prefix, argument, flags) { + // 1. If V is null and the conversion is to an IDL type + // associated with the [LegacyNullToEmptyString] + // extended attribute, then return the DOMString value + // that represents the empty string. + if (V === null && webidl.util.HasFlag(flags, webidl.attributes.LegacyNullToEmptyString)) { + return '' + } + + // 2. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} is a symbol, which cannot be converted to a DOMString.` + }) + } + + // 3. Return the IDL DOMString value that represents the + // same sequence of code units as the one the + // ECMAScript String value x represents. + return String(V) +} + +// https://webidl.spec.whatwg.org/#es-ByteString +webidl.converters.ByteString = function (V, prefix, argument) { + // 1. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} is a symbol, which cannot be converted to a ByteString.` + }) + } + + const x = String(V) + + // 2. If the value of any element of x is greater than + // 255, then throw a TypeError. + for (let index = 0; index < x.length; index++) { + if (x.charCodeAt(index) > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` + ) + } + } + + // 3. Return an IDL ByteString value whose length is the + // length of x, and where the value of each element is + // the value of the corresponding element of x. + return x +} + +/** + * @param {unknown} value + * @returns {string} + * @see https://webidl.spec.whatwg.org/#es-USVString + */ +webidl.converters.USVString = function (value) { + // TODO: rewrite this so we can control the errors thrown + if (typeof value === 'string') { + return value.toWellFormed() + } + return `${value}`.toWellFormed() +} + +// https://webidl.spec.whatwg.org/#es-boolean +webidl.converters.boolean = function (V) { + // 1. Let x be the result of computing ToBoolean(V). + // https://262.ecma-international.org/10.0/index.html#table-10 + const x = Boolean(V) + + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x +} + +// https://webidl.spec.whatwg.org/#es-any +webidl.converters.any = function (V) { + return V +} + +// https://webidl.spec.whatwg.org/#es-long-long +webidl.converters['long long'] = function (V, prefix, argument) { + // 1. Let x be ? ConvertToInt(V, 64, "signed"). + const x = webidl.util.ConvertToInt(V, 64, 'signed', 0, prefix, argument) + + // 2. Return the IDL long long value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long-long +webidl.converters['unsigned long long'] = function (V, prefix, argument) { + // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). + const x = webidl.util.ConvertToInt(V, 64, 'unsigned', 0, prefix, argument) + + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long +webidl.converters['unsigned long'] = function (V, prefix, argument) { + // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). + const x = webidl.util.ConvertToInt(V, 32, 'unsigned', 0, prefix, argument) + + // 2. Return the IDL unsigned long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-short +webidl.converters['unsigned short'] = function (V, prefix, argument, flags) { + // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). + const x = webidl.util.ConvertToInt(V, 16, 'unsigned', flags, prefix, argument) + + // 2. Return the IDL unsigned short value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#idl-ArrayBuffer +webidl.converters.ArrayBuffer = function (V, prefix, argument, flags) { + // 1. If V is not an Object, or V does not have an + // [[ArrayBufferData]] internal slot, then throw a + // TypeError. + // 2. If IsSharedArrayBuffer(V) is true, then throw a + // TypeError. + // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances + if ( + webidl.util.Type(V) !== OBJECT || + !types.isArrayBuffer(V) + ) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ['ArrayBuffer'] + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V) is true, then throw a + // TypeError. + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V)) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} cannot be a resizable ArrayBuffer.` + }) + } + + // 4. Return the IDL ArrayBuffer value that is a + // reference to the same object as V. + return V +} + +// https://webidl.spec.whatwg.org/#idl-SharedArrayBuffer +webidl.converters.SharedArrayBuffer = function (V, prefix, argument, flags) { + // 1. If V is not an Object, or V does not have an + // [[ArrayBufferData]] internal slot, then throw a + // TypeError. + // 2. If IsSharedArrayBuffer(V) is false, then throw a + // TypeError. + // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances + if ( + webidl.util.Type(V) !== OBJECT || + !types.isSharedArrayBuffer(V) + ) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ['SharedArrayBuffer'] + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V) is true, then throw a + // TypeError. + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V)) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} cannot be a resizable SharedArrayBuffer.` + }) + } + + // 4. Return the IDL SharedArrayBuffer value that is a + // reference to the same object as V. + return V +} + +// https://webidl.spec.whatwg.org/#dfn-typed-array-type +webidl.converters.TypedArray = function (V, T, prefix, argument, flags) { + // 1. Let T be the IDL type V is being converted to. + + // 2. If Type(V) is not Object, or V does not have a + // [[TypedArrayName]] internal slot with a value + // equal to T’s name, then throw a TypeError. + if ( + webidl.util.Type(V) !== OBJECT || + !types.isTypedArray(V) || + V.constructor.name !== T.name + ) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: [T.name] + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} cannot be a view on a shared array buffer.` + }) + } + + // 4. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} cannot be a view on a resizable array buffer.` + }) + } + + // 5. Return the IDL value of type T that is a reference + // to the same object as V. + return V +} + +// https://webidl.spec.whatwg.org/#idl-DataView +webidl.converters.DataView = function (V, prefix, argument, flags) { + // 1. If Type(V) is not Object, or V does not have a + // [[DataView]] internal slot, then throw a TypeError. + if (webidl.util.Type(V) !== OBJECT || !types.isDataView(V)) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ['DataView'] + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, + // then throw a TypeError. + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} cannot be a view on a shared array buffer.` + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} cannot be a view on a resizable array buffer.` + }) + } + + // 4. Return the IDL DataView value that is a reference + // to the same object as V. + return V +} + +// https://webidl.spec.whatwg.org/#ArrayBufferView +webidl.converters.ArrayBufferView = function (V, prefix, argument, flags) { + if ( + webidl.util.Type(V) !== OBJECT || + !types.isArrayBufferView(V) + ) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ['ArrayBufferView'] + }) + } + + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} cannot be a view on a shared array buffer.` + }) + } + + if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} cannot be a view on a resizable array buffer.` + }) + } + + return V +} + +// https://webidl.spec.whatwg.org/#BufferSource +webidl.converters.BufferSource = function (V, prefix, argument, flags) { + if (types.isArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, prefix, argument, flags) + } + + if (types.isArrayBufferView(V)) { + flags &= ~webidl.attributes.AllowShared + + return webidl.converters.ArrayBufferView(V, prefix, argument, flags) + } + + // Make this explicit for easier debugging + if (types.isSharedArrayBuffer(V)) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} cannot be a SharedArrayBuffer.` + }) + } + + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ['ArrayBuffer', 'ArrayBufferView'] + }) +} + +// https://webidl.spec.whatwg.org/#AllowSharedBufferSource +webidl.converters.AllowSharedBufferSource = function (V, prefix, argument, flags) { + if (types.isArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, prefix, argument, flags) + } + + if (types.isSharedArrayBuffer(V)) { + return webidl.converters.SharedArrayBuffer(V, prefix, argument, flags) + } + + if (types.isArrayBufferView(V)) { + flags |= webidl.attributes.AllowShared + return webidl.converters.ArrayBufferView(V, prefix, argument, flags) + } + + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ['ArrayBuffer', 'SharedArrayBuffer', 'ArrayBufferView'] + }) +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.ByteString +) + +webidl.converters['sequence>'] = webidl.sequenceConverter( + webidl.converters['sequence'] +) + +webidl.converters['record'] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString +) + +webidl.converters.Blob = webidl.interfaceConverter(webidl.is.Blob, 'Blob') + +webidl.converters.AbortSignal = webidl.interfaceConverter( + webidl.is.AbortSignal, + 'AbortSignal' +) + +/** + * [LegacyTreatNonObjectAsNull] + * callback EventHandlerNonNull = any (Event event); + * typedef EventHandlerNonNull? EventHandler; + * @param {*} V + */ +webidl.converters.EventHandlerNonNull = function (V) { + if (webidl.util.Type(V) !== OBJECT) { + return null + } + + // [I]f the value is not an object, it will be converted to null, and if the value is not callable, + // it will be converted to a callback function value that does nothing when called. + if (typeof V === 'function') { + return V + } + + return () => {} +} + +webidl.attributes = { + Clamp: 1 << 0, + EnforceRange: 1 << 1, + AllowShared: 1 << 2, + AllowResizable: 1 << 3, + LegacyNullToEmptyString: 1 << 4 +} + +module.exports = { + webidl +} diff --git a/node_modules/undici/lib/web/websocket/connection.js b/node_modules/undici/lib/web/websocket/connection.js new file mode 100644 index 000000000..4ecc8a195 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/connection.js @@ -0,0 +1,329 @@ +'use strict' + +const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require('./constants') +const { parseExtensions, isClosed, isClosing, isEstablished, isConnecting, validateCloseCodeAndReason } = require('./util') +const { makeRequest } = require('../fetch/request') +const { fetching } = require('../fetch/index') +const { Headers, getHeadersList } = require('../fetch/headers') +const { getDecodeSplit } = require('../fetch/util') +const { WebsocketFrameSend } = require('./frame') +const assert = require('node:assert') +const { runtimeFeatures } = require('../../util/runtime-features') + +const crypto = runtimeFeatures.has('crypto') + ? require('node:crypto') + : null + +let warningEmitted = false + +/** + * @see https://websockets.spec.whatwg.org/#concept-websocket-establish + * @param {URL} url + * @param {string|string[]} protocols + * @param {import('./websocket').Handler} handler + * @param {Partial} options + */ +function establishWebSocketConnection (url, protocols, client, handler, options) { + // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s + // scheme is "ws", and to "https" otherwise. + const requestURL = url + + requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' + + // 2. Let request be a new request, whose URL is requestURL, client is client, + // service-workers mode is "none", referrer is "no-referrer", mode is + // "websocket", credentials mode is "include", cache mode is "no-store" , + // redirect mode is "error", and use-URL-credentials flag is set. + const request = makeRequest({ + urlList: [requestURL], + client, + serviceWorkers: 'none', + referrer: 'no-referrer', + mode: 'websocket', + credentials: 'include', + cache: 'no-store', + redirect: 'error', + useURLCredentials: true + }) + + // Note: undici extension, allow setting custom headers. + if (options.headers) { + const headersList = getHeadersList(new Headers(options.headers)) + + request.headersList = headersList + } + + // 3. Append (`Upgrade`, `websocket`) to request’s header list. + // 4. Append (`Connection`, `Upgrade`) to request’s header list. + // Note: both of these are handled by undici currently. + // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 + + // 5. Let keyValue be a nonce consisting of a randomly selected + // 16-byte value that has been forgiving-base64-encoded and + // isomorphic encoded. + const keyValue = crypto.randomBytes(16).toString('base64') + + // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s + // header list. + request.headersList.append('sec-websocket-key', keyValue, true) + + // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s + // header list. + request.headersList.append('sec-websocket-version', '13', true) + + // 8. For each protocol in protocols, combine + // (`Sec-WebSocket-Protocol`, protocol) in request’s header + // list. + for (const protocol of protocols) { + request.headersList.append('sec-websocket-protocol', protocol, true) + } + + // 9. Let permessageDeflate be a user-agent defined + // "permessage-deflate" extension header value. + // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 + const permessageDeflate = 'permessage-deflate; client_max_window_bits' + + // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to + // request’s header list. + request.headersList.append('sec-websocket-extensions', permessageDeflate, true) + + // 11. Fetch request with useParallelQueue set to true, and + // processResponse given response being these steps: + const controller = fetching({ + request, + useParallelQueue: true, + dispatcher: options.dispatcher, + processResponse (response) { + // 1. If response is a network error or its status is not 101, + // fail the WebSocket connection. + // if (response.type === 'error' || ((response.socket?.session != null && response.status !== 200) && response.status !== 101)) { + if (response.type === 'error' || response.status !== 101) { + // The presence of a session property on the socket indicates HTTP2 + // HTTP1 + if (response.socket?.session == null) { + failWebsocketConnection(handler, 1002, 'Received network error or non-101 status code.', response.error) + return + } + + // HTTP2 + if (response.status !== 200) { + failWebsocketConnection(handler, 1002, 'Received network error or non-200 status code.', response.error) + return + } + } + + if (warningEmitted === false && response.socket?.session != null) { + process.emitWarning('WebSocket over HTTP2 is experimental, and subject to change.', 'ExperimentalWarning') + warningEmitted = true + } + + // 2. If protocols is not the empty list and extracting header + // list values given `Sec-WebSocket-Protocol` and response’s + // header list results in null, failure, or the empty byte + // sequence, then fail the WebSocket connection. + if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(handler, 1002, 'Server did not respond with sent protocols.') + return + } + + // 3. Follow the requirements stated step 2 to step 6, inclusive, + // of the last set of steps in section 4.1 of The WebSocket + // Protocol to validate response. This either results in fail + // the WebSocket connection or the WebSocket connection is + // established. + + // 2. If the response lacks an |Upgrade| header field or the |Upgrade| + // header field contains a value that is not an ASCII case- + // insensitive match for the value "websocket", the client MUST + // _Fail the WebSocket Connection_. + // For H2, no upgrade header is expected. + if (response.socket.session == null && response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { + failWebsocketConnection(handler, 1002, 'Server did not set Upgrade header to "websocket".') + return + } + + // 3. If the response lacks a |Connection| header field or the + // |Connection| header field doesn't contain a token that is an + // ASCII case-insensitive match for the value "Upgrade", the client + // MUST _Fail the WebSocket Connection_. + // For H2, no connection header is expected. + if (response.socket.session == null && response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { + failWebsocketConnection(handler, 1002, 'Server did not set Connection header to "upgrade".') + return + } + + // 4. If the response lacks a |Sec-WebSocket-Accept| header field or + // the |Sec-WebSocket-Accept| contains a value other than the + // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- + // Key| (as a string, not base64-decoded) with the string "258EAFA5- + // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and + // trailing whitespace, the client MUST _Fail the WebSocket + // Connection_. + const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') + const digest = crypto.hash('sha1', keyValue + uid, 'base64') + if (secWSAccept !== digest) { + failWebsocketConnection(handler, 1002, 'Incorrect hash received in Sec-WebSocket-Accept header.') + return + } + + // 5. If the response includes a |Sec-WebSocket-Extensions| header + // field and this header field indicates the use of an extension + // that was not present in the client's handshake (the server has + // indicated an extension not requested by the client), the client + // MUST _Fail the WebSocket Connection_. (The parsing of this + // header field to determine which extensions are requested is + // discussed in Section 9.1.) + const secExtension = response.headersList.get('Sec-WebSocket-Extensions') + let extensions + + if (secExtension !== null) { + extensions = parseExtensions(secExtension) + + if (!extensions.has('permessage-deflate')) { + failWebsocketConnection(handler, 1002, 'Sec-WebSocket-Extensions header does not match.') + return + } + } + + // 6. If the response includes a |Sec-WebSocket-Protocol| header field + // and this header field indicates the use of a subprotocol that was + // not present in the client's handshake (the server has indicated a + // subprotocol not requested by the client), the client MUST _Fail + // the WebSocket Connection_. + const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') + + if (secProtocol !== null) { + const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList) + + // The client can request that the server use a specific subprotocol by + // including the |Sec-WebSocket-Protocol| field in its handshake. If it + // is specified, the server needs to include the same field and one of + // the selected subprotocol values in its response for the connection to + // be established. + if (!requestProtocols.includes(secProtocol)) { + failWebsocketConnection(handler, 1002, 'Protocol was not set in the opening handshake.') + return + } + } + + response.socket.on('data', handler.onSocketData) + response.socket.on('close', handler.onSocketClose) + response.socket.on('error', handler.onSocketError) + + handler.wasEverConnected = true + handler.onConnectionEstablished(response, extensions) + } + }) + + return controller +} + +/** + * @see https://whatpr.org/websockets/48.html#close-the-websocket + * @param {import('./websocket').Handler} object + * @param {number} [code=null] + * @param {string} [reason=''] + */ +function closeWebSocketConnection (object, code, reason, validate = false) { + // 1. If code was not supplied, let code be null. + code ??= null + + // 2. If reason was not supplied, let reason be the empty string. + reason ??= '' + + // 3. Validate close code and reason with code and reason. + if (validate) validateCloseCodeAndReason(code, reason) + + // 4. Run the first matching steps from the following list: + // - If object’s ready state is CLOSING (2) or CLOSED (3) + // - If the WebSocket connection is not yet established [WSP] + // - If the WebSocket closing handshake has not yet been started [WSP] + // - Otherwise + if (isClosed(object.readyState) || isClosing(object.readyState)) { + // Do nothing. + } else if (!isEstablished(object.readyState)) { + // Fail the WebSocket connection and set object’s ready state to CLOSING (2). [WSP] + failWebsocketConnection(object) + object.readyState = states.CLOSING + } else if (!object.closeState.has(sentCloseFrameState.SENT) && !object.closeState.has(sentCloseFrameState.RECEIVED)) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + + const frame = new WebsocketFrameSend() + + // If neither code nor reason is present, the WebSocket Close + // message must not have a body. + + // If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + // If code is null and reason is the empty string, the WebSocket Close frame must not have a body. + // If reason is non-empty but code is null, then set code to 1000 ("Normal Closure"). + if (reason.length !== 0 && code === null) { + code = 1000 + } + + // If code is set, then the status code to use in the WebSocket Close frame must be the integer given by code. + assert(code === null || Number.isInteger(code)) + + if (code === null && reason.length === 0) { + frame.frameData = emptyBuffer + } else if (code !== null && reason === null) { + frame.frameData = Buffer.allocUnsafe(2) + frame.frameData.writeUInt16BE(code, 0) + } else if (code !== null && reason !== null) { + // If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason)) + frame.frameData.writeUInt16BE(code, 0) + // the body MAY contain UTF-8-encoded data with value /reason/ + frame.frameData.write(reason, 2, 'utf-8') + } else { + frame.frameData = emptyBuffer + } + + object.socket.write(frame.createFrame(opcodes.CLOSE)) + + object.closeState.add(sentCloseFrameState.SENT) + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + object.readyState = states.CLOSING + } else { + // Set object’s ready state to CLOSING (2). + object.readyState = states.CLOSING + } +} + +/** + * @param {import('./websocket').Handler} handler + * @param {number} code + * @param {string|undefined} reason + * @param {unknown} cause + * @returns {void} + */ +function failWebsocketConnection (handler, code, reason, cause) { + // If _The WebSocket Connection is Established_ prior to the point where + // the endpoint is required to _Fail the WebSocket Connection_, the + // endpoint SHOULD send a Close frame with an appropriate status code + // (Section 7.4) before proceeding to _Close the WebSocket Connection_. + if (isEstablished(handler.readyState)) { + closeWebSocketConnection(handler, code, reason, false) + } + + handler.controller.abort() + + if (isConnecting(handler.readyState)) { + // If the connection was not established, we must still emit an 'error' and 'close' events + handler.onSocketClose() + } else if (handler.socket?.destroyed === false) { + handler.socket.destroy() + } +} + +module.exports = { + establishWebSocketConnection, + failWebsocketConnection, + closeWebSocketConnection +} diff --git a/node_modules/undici/lib/web/websocket/constants.js b/node_modules/undici/lib/web/websocket/constants.js new file mode 100644 index 000000000..e4e69901c --- /dev/null +++ b/node_modules/undici/lib/web/websocket/constants.js @@ -0,0 +1,126 @@ +'use strict' + +/** + * This is a Globally Unique Identifier unique used to validate that the + * endpoint accepts websocket connections. + * @see https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 + * @type {'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'} + */ +const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' + +/** + * @type {PropertyDescriptor} + */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +/** + * The states of the WebSocket connection. + * + * @readonly + * @enum + * @property {0} CONNECTING + * @property {1} OPEN + * @property {2} CLOSING + * @property {3} CLOSED + */ +const states = { + CONNECTING: 0, + OPEN: 1, + CLOSING: 2, + CLOSED: 3 +} + +/** + * @readonly + * @enum + * @property {0} NOT_SENT + * @property {1} PROCESSING + * @property {2} SENT + */ +const sentCloseFrameState = { + SENT: 1, + RECEIVED: 2 +} + +/** + * The WebSocket opcodes. + * + * @readonly + * @enum + * @property {0x0} CONTINUATION + * @property {0x1} TEXT + * @property {0x2} BINARY + * @property {0x8} CLOSE + * @property {0x9} PING + * @property {0xA} PONG + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + */ +const opcodes = { + CONTINUATION: 0x0, + TEXT: 0x1, + BINARY: 0x2, + CLOSE: 0x8, + PING: 0x9, + PONG: 0xA +} + +/** + * The maximum value for an unsigned 16-bit integer. + * + * @type {65535} 2 ** 16 - 1 + */ +const maxUnsigned16Bit = 65535 + +/** + * The states of the parser. + * + * @readonly + * @enum + * @property {0} INFO + * @property {2} PAYLOADLENGTH_16 + * @property {3} PAYLOADLENGTH_64 + * @property {4} READ_DATA + */ +const parserStates = { + INFO: 0, + PAYLOADLENGTH_16: 2, + PAYLOADLENGTH_64: 3, + READ_DATA: 4 +} + +/** + * An empty buffer. + * + * @type {Buffer} + */ +const emptyBuffer = Buffer.allocUnsafe(0) + +/** + * @readonly + * @property {1} text + * @property {2} typedArray + * @property {3} arrayBuffer + * @property {4} blob + */ +const sendHints = { + text: 1, + typedArray: 2, + arrayBuffer: 3, + blob: 4 +} + +module.exports = { + uid, + sentCloseFrameState, + staticPropertyDescriptors, + states, + opcodes, + maxUnsigned16Bit, + parserStates, + emptyBuffer, + sendHints +} diff --git a/node_modules/undici/lib/web/websocket/events.js b/node_modules/undici/lib/web/websocket/events.js new file mode 100644 index 000000000..7ac9566be --- /dev/null +++ b/node_modules/undici/lib/web/websocket/events.js @@ -0,0 +1,331 @@ +'use strict' + +const { webidl } = require('../webidl') +const { kEnumerableProperty } = require('../../core/util') +const { kConstruct } = require('../../core/symbols') + +/** + * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent + */ +class MessageEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + if (type === kConstruct) { + super(arguments[1], arguments[2]) + webidl.util.markAsUncloneable(this) + return + } + + const prefix = 'MessageEvent constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + type = webidl.converters.DOMString(type, prefix, 'type') + eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, 'eventInitDict') + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + webidl.util.markAsUncloneable(this) + } + + get data () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.data + } + + get origin () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.origin + } + + get lastEventId () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.lastEventId + } + + get source () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.source + } + + get ports () { + webidl.brandCheck(this, MessageEvent) + + if (!Object.isFrozen(this.#eventInit.ports)) { + Object.freeze(this.#eventInit.ports) + } + + return this.#eventInit.ports + } + + initMessageEvent ( + type, + bubbles = false, + cancelable = false, + data = null, + origin = '', + lastEventId = '', + source = null, + ports = [] + ) { + webidl.brandCheck(this, MessageEvent) + + webidl.argumentLengthCheck(arguments, 1, 'MessageEvent.initMessageEvent') + + return new MessageEvent(type, { + bubbles, cancelable, data, origin, lastEventId, source, ports + }) + } + + static createFastMessageEvent (type, init) { + const messageEvent = new MessageEvent(kConstruct, type, init) + messageEvent.#eventInit = init + messageEvent.#eventInit.data ??= null + messageEvent.#eventInit.origin ??= '' + messageEvent.#eventInit.lastEventId ??= '' + messageEvent.#eventInit.source ??= null + messageEvent.#eventInit.ports ??= [] + return messageEvent + } +} + +const { createFastMessageEvent } = MessageEvent +delete MessageEvent.createFastMessageEvent + +/** + * @see https://websockets.spec.whatwg.org/#the-closeevent-interface + */ +class CloseEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + const prefix = 'CloseEvent constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + type = webidl.converters.DOMString(type, prefix, 'type') + eventInitDict = webidl.converters.CloseEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + webidl.util.markAsUncloneable(this) + } + + get wasClean () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.wasClean + } + + get code () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.code + } + + get reason () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.reason + } +} + +// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface +class ErrorEvent extends Event { + #eventInit + + constructor (type, eventInitDict) { + const prefix = 'ErrorEvent constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + super(type, eventInitDict) + webidl.util.markAsUncloneable(this) + + type = webidl.converters.DOMString(type, prefix, 'type') + eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) + + this.#eventInit = eventInitDict + } + + get message () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.message + } + + get filename () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.filename + } + + get lineno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.lineno + } + + get colno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.colno + } + + get error () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.error + } +} + +Object.defineProperties(MessageEvent.prototype, { + [Symbol.toStringTag]: { + value: 'MessageEvent', + configurable: true + }, + data: kEnumerableProperty, + origin: kEnumerableProperty, + lastEventId: kEnumerableProperty, + source: kEnumerableProperty, + ports: kEnumerableProperty, + initMessageEvent: kEnumerableProperty +}) + +Object.defineProperties(CloseEvent.prototype, { + [Symbol.toStringTag]: { + value: 'CloseEvent', + configurable: true + }, + reason: kEnumerableProperty, + code: kEnumerableProperty, + wasClean: kEnumerableProperty +}) + +Object.defineProperties(ErrorEvent.prototype, { + [Symbol.toStringTag]: { + value: 'ErrorEvent', + configurable: true + }, + message: kEnumerableProperty, + filename: kEnumerableProperty, + lineno: kEnumerableProperty, + colno: kEnumerableProperty, + error: kEnumerableProperty +}) + +webidl.converters.MessagePort = webidl.interfaceConverter( + webidl.is.MessagePort, + 'MessagePort' +) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.MessagePort +) + +const eventInit = [ + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: () => false + } +] + +webidl.converters.MessageEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'data', + converter: webidl.converters.any, + defaultValue: () => null + }, + { + key: 'origin', + converter: webidl.converters.USVString, + defaultValue: () => '' + }, + { + key: 'lastEventId', + converter: webidl.converters.DOMString, + defaultValue: () => '' + }, + { + key: 'source', + // Node doesn't implement WindowProxy or ServiceWorker, so the only + // valid value for source is a MessagePort. + converter: webidl.nullableConverter(webidl.converters.MessagePort), + defaultValue: () => null + }, + { + key: 'ports', + converter: webidl.converters['sequence'], + defaultValue: () => [] + } +]) + +webidl.converters.CloseEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'wasClean', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'code', + converter: webidl.converters['unsigned short'], + defaultValue: () => 0 + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: () => '' + } +]) + +webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'message', + converter: webidl.converters.DOMString, + defaultValue: () => '' + }, + { + key: 'filename', + converter: webidl.converters.USVString, + defaultValue: () => '' + }, + { + key: 'lineno', + converter: webidl.converters['unsigned long'], + defaultValue: () => 0 + }, + { + key: 'colno', + converter: webidl.converters['unsigned long'], + defaultValue: () => 0 + }, + { + key: 'error', + converter: webidl.converters.any + } +]) + +module.exports = { + MessageEvent, + CloseEvent, + ErrorEvent, + createFastMessageEvent +} diff --git a/node_modules/undici/lib/web/websocket/frame.js b/node_modules/undici/lib/web/websocket/frame.js new file mode 100644 index 000000000..e397c878a --- /dev/null +++ b/node_modules/undici/lib/web/websocket/frame.js @@ -0,0 +1,133 @@ +'use strict' + +const { runtimeFeatures } = require('../../util/runtime-features') +const { maxUnsigned16Bit, opcodes } = require('./constants') + +const BUFFER_SIZE = 8 * 1024 + +let buffer = null +let bufIdx = BUFFER_SIZE + +const randomFillSync = runtimeFeatures.has('crypto') + ? require('node:crypto').randomFillSync + // not full compatibility, but minimum. + : function randomFillSync (buffer, _offset, _size) { + for (let i = 0; i < buffer.length; ++i) { + buffer[i] = Math.random() * 255 | 0 + } + return buffer + } + +function generateMask () { + if (bufIdx === BUFFER_SIZE) { + bufIdx = 0 + randomFillSync((buffer ??= Buffer.allocUnsafeSlow(BUFFER_SIZE)), 0, BUFFER_SIZE) + } + return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]] +} + +class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data + } + + createFrame (opcode) { + const frameData = this.frameData + const maskKey = generateMask() + const bodyLength = frameData?.byteLength ?? 0 + + /** @type {number} */ + let payloadLength = bodyLength // 0-125 + let offset = 6 + + if (bodyLength > maxUnsigned16Bit) { + offset += 8 // payload length is next 8 bytes + payloadLength = 127 + } else if (bodyLength > 125) { + offset += 2 // payload length is next 2 bytes + payloadLength = 126 + } + + const buffer = Buffer.allocUnsafe(bodyLength + offset) + + // Clear first 2 bytes, everything else is overwritten + buffer[0] = buffer[1] = 0 + buffer[0] |= 0x80 // FIN + buffer[0] = (buffer[0] & 0xF0) + opcode // opcode + + /*! ws. MIT License. Einar Otto Stangvik */ + buffer[offset - 4] = maskKey[0] + buffer[offset - 3] = maskKey[1] + buffer[offset - 2] = maskKey[2] + buffer[offset - 1] = maskKey[3] + + buffer[1] = payloadLength + + if (payloadLength === 126) { + buffer.writeUInt16BE(bodyLength, 2) + } else if (payloadLength === 127) { + // Clear extended payload length + buffer[2] = buffer[3] = 0 + buffer.writeUIntBE(bodyLength, 4, 6) + } + + buffer[1] |= 0x80 // MASK + + // mask body + for (let i = 0; i < bodyLength; ++i) { + buffer[offset + i] = frameData[i] ^ maskKey[i & 3] + } + + return buffer + } + + /** + * @param {Uint8Array} buffer + */ + static createFastTextFrame (buffer) { + const maskKey = generateMask() + + const bodyLength = buffer.length + + // mask body + for (let i = 0; i < bodyLength; ++i) { + buffer[i] ^= maskKey[i & 3] + } + + let payloadLength = bodyLength + let offset = 6 + + if (bodyLength > maxUnsigned16Bit) { + offset += 8 // payload length is next 8 bytes + payloadLength = 127 + } else if (bodyLength > 125) { + offset += 2 // payload length is next 2 bytes + payloadLength = 126 + } + const head = Buffer.allocUnsafeSlow(offset) + + head[0] = 0x80 /* FIN */ | opcodes.TEXT /* opcode TEXT */ + head[1] = payloadLength | 0x80 /* MASK */ + head[offset - 4] = maskKey[0] + head[offset - 3] = maskKey[1] + head[offset - 2] = maskKey[2] + head[offset - 1] = maskKey[3] + + if (payloadLength === 126) { + head.writeUInt16BE(bodyLength, 2) + } else if (payloadLength === 127) { + head[2] = head[3] = 0 + head.writeUIntBE(bodyLength, 4, 6) + } + + return [head, buffer] + } +} + +module.exports = { + WebsocketFrameSend, + generateMask // for benchmark +} diff --git a/node_modules/undici/lib/web/websocket/permessage-deflate.js b/node_modules/undici/lib/web/websocket/permessage-deflate.js new file mode 100644 index 000000000..76cb366d5 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/permessage-deflate.js @@ -0,0 +1,70 @@ +'use strict' + +const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = require('node:zlib') +const { isValidClientWindowBits } = require('./util') + +const tail = Buffer.from([0x00, 0x00, 0xff, 0xff]) +const kBuffer = Symbol('kBuffer') +const kLength = Symbol('kLength') + +class PerMessageDeflate { + /** @type {import('node:zlib').InflateRaw} */ + #inflate + + #options = {} + + constructor (extensions) { + this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover') + this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits') + } + + decompress (chunk, fin, callback) { + // An endpoint uses the following algorithm to decompress a message. + // 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the + // payload of the message. + // 2. Decompress the resulting data using DEFLATE. + + if (!this.#inflate) { + let windowBits = Z_DEFAULT_WINDOWBITS + + if (this.#options.serverMaxWindowBits) { // empty values default to Z_DEFAULT_WINDOWBITS + if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) { + callback(new Error('Invalid server_max_window_bits')) + return + } + + windowBits = Number.parseInt(this.#options.serverMaxWindowBits) + } + + this.#inflate = createInflateRaw({ windowBits }) + this.#inflate[kBuffer] = [] + this.#inflate[kLength] = 0 + + this.#inflate.on('data', (data) => { + this.#inflate[kBuffer].push(data) + this.#inflate[kLength] += data.length + }) + + this.#inflate.on('error', (err) => { + this.#inflate = null + callback(err) + }) + } + + this.#inflate.write(chunk) + if (fin) { + this.#inflate.write(tail) + } + + this.#inflate.flush(() => { + const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]) + + this.#inflate[kBuffer].length = 0 + this.#inflate[kLength] = 0 + + callback(null, full) + }) + } +} + +module.exports = { PerMessageDeflate } diff --git a/node_modules/undici/lib/web/websocket/receiver.js b/node_modules/undici/lib/web/websocket/receiver.js new file mode 100644 index 000000000..ba0a5aa07 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/receiver.js @@ -0,0 +1,444 @@ +'use strict' + +const { Writable } = require('node:stream') +const assert = require('node:assert') +const { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require('./constants') +const { + isValidStatusCode, + isValidOpcode, + websocketMessageReceived, + utf8Decode, + isControlFrame, + isTextBinaryFrame, + isContinuationFrame +} = require('./util') +const { failWebsocketConnection } = require('./connection') +const { WebsocketFrameSend } = require('./frame') +const { PerMessageDeflate } = require('./permessage-deflate') + +// This code was influenced by ws released under the MIT license. +// Copyright (c) 2011 Einar Otto Stangvik +// Copyright (c) 2013 Arnout Kazemier and contributors +// Copyright (c) 2016 Luigi Pinca and contributors + +class ByteParser extends Writable { + #buffers = [] + #fragmentsBytes = 0 + #byteOffset = 0 + #loop = false + + #state = parserStates.INFO + + #info = {} + #fragments = [] + + /** @type {Map} */ + #extensions + + /** @type {import('./websocket').Handler} */ + #handler + + constructor (handler, extensions) { + super() + + this.#handler = handler + this.#extensions = extensions == null ? new Map() : extensions + + if (this.#extensions.has('permessage-deflate')) { + this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions)) + } + } + + /** + * @param {Buffer} chunk + * @param {() => void} callback + */ + _write (chunk, _, callback) { + this.#buffers.push(chunk) + this.#byteOffset += chunk.length + this.#loop = true + + this.run(callback) + } + + /** + * Runs whenever a new chunk is received. + * Callback is called whenever there are no more chunks buffering, + * or not enough bytes are buffered to parse. + */ + run (callback) { + while (this.#loop) { + if (this.#state === parserStates.INFO) { + // If there aren't enough bytes to parse the payload length, etc. + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + const fin = (buffer[0] & 0x80) !== 0 + const opcode = buffer[0] & 0x0F + const masked = (buffer[1] & 0x80) === 0x80 + + const fragmented = !fin && opcode !== opcodes.CONTINUATION + const payloadLength = buffer[1] & 0x7F + + const rsv1 = buffer[0] & 0x40 + const rsv2 = buffer[0] & 0x20 + const rsv3 = buffer[0] & 0x10 + + if (!isValidOpcode(opcode)) { + failWebsocketConnection(this.#handler, 1002, 'Invalid opcode received') + return callback() + } + + if (masked) { + failWebsocketConnection(this.#handler, 1002, 'Frame cannot be masked') + return callback() + } + + // MUST be 0 unless an extension is negotiated that defines meanings + // for non-zero values. If a nonzero value is received and none of + // the negotiated extensions defines the meaning of such a nonzero + // value, the receiving endpoint MUST _Fail the WebSocket + // Connection_. + // This document allocates the RSV1 bit of the WebSocket header for + // PMCEs and calls the bit the "Per-Message Compressed" bit. On a + // WebSocket connection where a PMCE is in use, this bit indicates + // whether a message is compressed or not. + if (rsv1 !== 0 && !this.#extensions.has('permessage-deflate')) { + failWebsocketConnection(this.#handler, 1002, 'Expected RSV1 to be clear.') + return + } + + if (rsv2 !== 0 || rsv3 !== 0) { + failWebsocketConnection(this.#handler, 1002, 'RSV1, RSV2, RSV3 must be clear') + return + } + + if (fragmented && !isTextBinaryFrame(opcode)) { + // Only text and binary frames can be fragmented + failWebsocketConnection(this.#handler, 1002, 'Invalid frame type was fragmented.') + return + } + + // If we are already parsing a text/binary frame and do not receive either + // a continuation frame or close frame, fail the connection. + if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) { + failWebsocketConnection(this.#handler, 1002, 'Expected continuation frame') + return + } + + if (this.#info.fragmented && fragmented) { + // A fragmented frame can't be fragmented itself + failWebsocketConnection(this.#handler, 1002, 'Fragmented frame exceeded 125 bytes.') + return + } + + // "All control frames MUST have a payload length of 125 bytes or less + // and MUST NOT be fragmented." + if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) { + failWebsocketConnection(this.#handler, 1002, 'Control frame either too large or fragmented') + return + } + + if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) { + failWebsocketConnection(this.#handler, 1002, 'Unexpected continuation frame') + return + } + + if (payloadLength <= 125) { + this.#info.payloadLength = payloadLength + this.#state = parserStates.READ_DATA + } else if (payloadLength === 126) { + this.#state = parserStates.PAYLOADLENGTH_16 + } else if (payloadLength === 127) { + this.#state = parserStates.PAYLOADLENGTH_64 + } + + if (isTextBinaryFrame(opcode)) { + this.#info.binaryType = opcode + this.#info.compressed = rsv1 !== 0 + } + + this.#info.opcode = opcode + this.#info.masked = masked + this.#info.fin = fin + this.#info.fragmented = fragmented + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + + this.#info.payloadLength = buffer.readUInt16BE(0) + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.PAYLOADLENGTH_64) { + if (this.#byteOffset < 8) { + return callback() + } + + const buffer = this.consume(8) + const upper = buffer.readUInt32BE(0) + + // 2^31 is the maximum bytes an arraybuffer can contain + // on 32-bit systems. Although, on 64-bit systems, this is + // 2^53-1 bytes. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e + if (upper > 2 ** 31 - 1) { + failWebsocketConnection(this.#handler, 1009, 'Received payload length > 2^31 bytes.') + return + } + + const lower = buffer.readUInt32BE(4) + + this.#info.payloadLength = (upper << 8) + lower + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.READ_DATA) { + if (this.#byteOffset < this.#info.payloadLength) { + return callback() + } + + const body = this.consume(this.#info.payloadLength) + + if (isControlFrame(this.#info.opcode)) { + this.#loop = this.parseControlFrame(body) + this.#state = parserStates.INFO + } else { + if (!this.#info.compressed) { + this.writeFragments(body) + + // If the frame is not fragmented, a message has been received. + // If the frame is fragmented, it will terminate with a fin bit set + // and an opcode of 0 (continuation), therefore we handle that when + // parsing continuation frames, not here. + if (!this.#info.fragmented && this.#info.fin) { + websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments()) + } + + this.#state = parserStates.INFO + } else { + this.#extensions.get('permessage-deflate').decompress(body, this.#info.fin, (error, data) => { + if (error) { + failWebsocketConnection(this.#handler, 1007, error.message) + return + } + + this.writeFragments(data) + + if (!this.#info.fin) { + this.#state = parserStates.INFO + this.#loop = true + this.run(callback) + return + } + + websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments()) + + this.#loop = true + this.#state = parserStates.INFO + this.run(callback) + }) + + this.#loop = false + break + } + } + } + } + } + + /** + * Take n bytes from the buffered Buffers + * @param {number} n + * @returns {Buffer} + */ + consume (n) { + if (n > this.#byteOffset) { + throw new Error('Called consume() before buffers satiated.') + } else if (n === 0) { + return emptyBuffer + } + + this.#byteOffset -= n + + const first = this.#buffers[0] + + if (first.length > n) { + // replace with remaining buffer + this.#buffers[0] = first.subarray(n, first.length) + return first.subarray(0, n) + } else if (first.length === n) { + // prefect match + return this.#buffers.shift() + } else { + let offset = 0 + // If Buffer.allocUnsafe is used, extra copies will be made because the offset is non-zero. + const buffer = Buffer.allocUnsafeSlow(n) + while (offset !== n) { + const next = this.#buffers[0] + const length = next.length + + if (length + offset === n) { + buffer.set(this.#buffers.shift(), offset) + break + } else if (length + offset > n) { + buffer.set(next.subarray(0, n - offset), offset) + this.#buffers[0] = next.subarray(n - offset) + break + } else { + buffer.set(this.#buffers.shift(), offset) + offset += length + } + } + + return buffer + } + } + + writeFragments (fragment) { + this.#fragmentsBytes += fragment.length + this.#fragments.push(fragment) + } + + consumeFragments () { + const fragments = this.#fragments + + if (fragments.length === 1) { + // single fragment + this.#fragmentsBytes = 0 + return fragments.shift() + } + + let offset = 0 + // If Buffer.allocUnsafe is used, extra copies will be made because the offset is non-zero. + const output = Buffer.allocUnsafeSlow(this.#fragmentsBytes) + + for (let i = 0; i < fragments.length; ++i) { + const buffer = fragments[i] + output.set(buffer, offset) + offset += buffer.length + } + + this.#fragments = [] + this.#fragmentsBytes = 0 + + return output + } + + parseCloseBody (data) { + assert(data.length !== 1) + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code + + if (data.length >= 2) { + // _The WebSocket Connection Close Code_ is + // defined as the status code (Section 7.4) contained in the first Close + // control frame received by the application + code = data.readUInt16BE(0) + } + + if (code !== undefined && !isValidStatusCode(code)) { + return { code: 1002, reason: 'Invalid status code', error: true } + } + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2) + + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3) + } + + try { + reason = utf8Decode(reason) + } catch { + return { code: 1007, reason: 'Invalid UTF-8', error: true } + } + + return { code, reason, error: false } + } + + /** + * Parses control frames. + * @param {Buffer} body + */ + parseControlFrame (body) { + const { opcode, payloadLength } = this.#info + + if (opcode === opcodes.CLOSE) { + if (payloadLength === 1) { + failWebsocketConnection(this.#handler, 1002, 'Received close frame with a 1-byte body.') + return false + } + + this.#info.closeInfo = this.parseCloseBody(body) + + if (this.#info.closeInfo.error) { + const { code, reason } = this.#info.closeInfo + + failWebsocketConnection(this.#handler, code, reason) + return false + } + + // Upon receiving such a frame, the other peer sends a + // Close frame in response, if it hasn't already sent one. + if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + // If an endpoint receives a Close frame and did not previously send a + // Close frame, the endpoint MUST send a Close frame in response. (When + // sending a Close frame in response, the endpoint typically echos the + // status code it received.) + let body = emptyBuffer + if (this.#info.closeInfo.code) { + body = Buffer.allocUnsafe(2) + body.writeUInt16BE(this.#info.closeInfo.code, 0) + } + const closeFrame = new WebsocketFrameSend(body) + + this.#handler.socket.write(closeFrame.createFrame(opcodes.CLOSE)) + this.#handler.closeState.add(sentCloseFrameState.SENT) + } + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this.#handler.readyState = states.CLOSING + this.#handler.closeState.add(sentCloseFrameState.RECEIVED) + + return false + } else if (opcode === opcodes.PING) { + // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in + // response, unless it already received a Close frame. + // A Pong frame sent in response to a Ping frame must have identical + // "Application data" + + if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + const frame = new WebsocketFrameSend(body) + + this.#handler.socket.write(frame.createFrame(opcodes.PONG)) + + this.#handler.onPing(body) + } + } else if (opcode === opcodes.PONG) { + // A Pong frame MAY be sent unsolicited. This serves as a + // unidirectional heartbeat. A response to an unsolicited Pong frame is + // not expected. + this.#handler.onPong(body) + } + + return true + } + + get closingInfo () { + return this.#info.closeInfo + } +} + +module.exports = { + ByteParser +} diff --git a/node_modules/undici/lib/web/websocket/sender.js b/node_modules/undici/lib/web/websocket/sender.js new file mode 100644 index 000000000..c647bf629 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/sender.js @@ -0,0 +1,109 @@ +'use strict' + +const { WebsocketFrameSend } = require('./frame') +const { opcodes, sendHints } = require('./constants') +const FixedQueue = require('../../dispatcher/fixed-queue') + +/** + * @typedef {object} SendQueueNode + * @property {Promise | null} promise + * @property {((...args: any[]) => any)} callback + * @property {Buffer | null} frame + */ + +class SendQueue { + /** + * @type {FixedQueue} + */ + #queue = new FixedQueue() + + /** + * @type {boolean} + */ + #running = false + + /** @type {import('node:net').Socket} */ + #socket + + constructor (socket) { + this.#socket = socket + } + + add (item, cb, hint) { + if (hint !== sendHints.blob) { + if (!this.#running) { + // TODO(@tsctx): support fast-path for string on running + if (hint === sendHints.text) { + // special fast-path for string + const { 0: head, 1: body } = WebsocketFrameSend.createFastTextFrame(item) + this.#socket.cork() + this.#socket.write(head) + this.#socket.write(body, cb) + this.#socket.uncork() + } else { + // direct writing + this.#socket.write(createFrame(item, hint), cb) + } + } else { + /** @type {SendQueueNode} */ + const node = { + promise: null, + callback: cb, + frame: createFrame(item, hint) + } + this.#queue.push(node) + } + return + } + + /** @type {SendQueueNode} */ + const node = { + promise: item.arrayBuffer().then((ab) => { + node.promise = null + node.frame = createFrame(ab, hint) + }), + callback: cb, + frame: null + } + + this.#queue.push(node) + + if (!this.#running) { + this.#run() + } + } + + async #run () { + this.#running = true + const queue = this.#queue + while (!queue.isEmpty()) { + const node = queue.shift() + // wait pending promise + if (node.promise !== null) { + await node.promise + } + // write + this.#socket.write(node.frame, node.callback) + // cleanup + node.callback = node.frame = null + } + this.#running = false + } +} + +function createFrame (data, hint) { + return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.text ? opcodes.TEXT : opcodes.BINARY) +} + +function toBuffer (data, hint) { + switch (hint) { + case sendHints.text: + case sendHints.typedArray: + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength) + case sendHints.arrayBuffer: + case sendHints.blob: + return new Uint8Array(data) + } +} + +module.exports = { SendQueue } diff --git a/node_modules/undici/lib/web/websocket/stream/websocketerror.js b/node_modules/undici/lib/web/websocket/stream/websocketerror.js new file mode 100644 index 000000000..a34c5213a --- /dev/null +++ b/node_modules/undici/lib/web/websocket/stream/websocketerror.js @@ -0,0 +1,104 @@ +'use strict' + +const { webidl } = require('../../webidl') +const { validateCloseCodeAndReason } = require('../util') +const { kConstruct } = require('../../../core/symbols') +const { kEnumerableProperty } = require('../../../core/util') + +function createInheritableDOMException () { + // https://github.com/nodejs/node/issues/59677 + class Test extends DOMException { + get reason () { + return '' + } + } + + if (new Test().reason !== undefined) { + return DOMException + } + + return new Proxy(DOMException, { + construct (target, args, newTarget) { + const instance = Reflect.construct(target, args, target) + Object.setPrototypeOf(instance, newTarget.prototype) + return instance + } + }) +} + +class WebSocketError extends createInheritableDOMException() { + #closeCode + #reason + + constructor (message = '', init = undefined) { + message = webidl.converters.DOMString(message, 'WebSocketError', 'message') + + // 1. Set this 's name to " WebSocketError ". + // 2. Set this 's message to message . + super(message, 'WebSocketError') + + if (init === kConstruct) { + return + } else if (init !== null) { + init = webidl.converters.WebSocketCloseInfo(init) + } + + // 3. Let code be init [" closeCode "] if it exists , or null otherwise. + let code = init.closeCode ?? null + + // 4. Let reason be init [" reason "] if it exists , or the empty string otherwise. + const reason = init.reason ?? '' + + // 5. Validate close code and reason with code and reason . + validateCloseCodeAndReason(code, reason) + + // 6. If reason is non-empty, but code is not set, then set code to 1000 ("Normal Closure"). + if (reason.length !== 0 && code === null) { + code = 1000 + } + + // 7. Set this 's closeCode to code . + this.#closeCode = code + + // 8. Set this 's reason to reason . + this.#reason = reason + } + + get closeCode () { + return this.#closeCode + } + + get reason () { + return this.#reason + } + + /** + * @param {string} message + * @param {number|null} code + * @param {string} reason + */ + static createUnvalidatedWebSocketError (message, code, reason) { + const error = new WebSocketError(message, kConstruct) + error.#closeCode = code + error.#reason = reason + return error + } +} + +const { createUnvalidatedWebSocketError } = WebSocketError +delete WebSocketError.createUnvalidatedWebSocketError + +Object.defineProperties(WebSocketError.prototype, { + closeCode: kEnumerableProperty, + reason: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocketError', + writable: false, + enumerable: false, + configurable: true + } +}) + +webidl.is.WebSocketError = webidl.util.MakeTypeAssertion(WebSocketError) + +module.exports = { WebSocketError, createUnvalidatedWebSocketError } diff --git a/node_modules/undici/lib/web/websocket/stream/websocketstream.js b/node_modules/undici/lib/web/websocket/stream/websocketstream.js new file mode 100644 index 000000000..ce3be84fc --- /dev/null +++ b/node_modules/undici/lib/web/websocket/stream/websocketstream.js @@ -0,0 +1,497 @@ +'use strict' + +const { createDeferredPromise } = require('../../../util/promise') +const { environmentSettingsObject } = require('../../fetch/util') +const { states, opcodes, sentCloseFrameState } = require('../constants') +const { webidl } = require('../../webidl') +const { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = require('../util') +const { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } = require('../connection') +const { channels } = require('../../../core/diagnostics') +const { WebsocketFrameSend } = require('../frame') +const { ByteParser } = require('../receiver') +const { WebSocketError, createUnvalidatedWebSocketError } = require('./websocketerror') +const { kEnumerableProperty } = require('../../../core/util') +const { utf8DecodeBytes } = require('../../../encoding') + +let emittedExperimentalWarning = false + +class WebSocketStream { + // Each WebSocketStream object has an associated url , which is a URL record . + /** @type {URL} */ + #url + + // Each WebSocketStream object has an associated opened promise , which is a promise. + /** @type {import('../../../util/promise').DeferredPromise} */ + #openedPromise + + // Each WebSocketStream object has an associated closed promise , which is a promise. + /** @type {import('../../../util/promise').DeferredPromise} */ + #closedPromise + + // Each WebSocketStream object has an associated readable stream , which is a ReadableStream . + /** @type {ReadableStream} */ + #readableStream + /** @type {ReadableStreamDefaultController} */ + #readableStreamController + + // Each WebSocketStream object has an associated writable stream , which is a WritableStream . + /** @type {WritableStream} */ + #writableStream + + // Each WebSocketStream object has an associated boolean handshake aborted , which is initially false. + #handshakeAborted = false + + /** @type {import('../websocket').Handler} */ + #handler = { + // https://whatpr.org/websockets/48/7b748d3...d5570f3.html#feedback-to-websocket-stream-from-the-protocol + onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions), + onMessage: (opcode, data) => this.#onMessage(opcode, data), + onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message), + onParserDrain: () => this.#handler.socket.resume(), + onSocketData: (chunk) => { + if (!this.#parser.write(chunk)) { + this.#handler.socket.pause() + } + }, + onSocketError: (err) => { + this.#handler.readyState = states.CLOSING + + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(err) + } + + this.#handler.socket.destroy() + }, + onSocketClose: () => this.#onSocketClose(), + onPing: () => {}, + onPong: () => {}, + + readyState: states.CONNECTING, + socket: null, + closeState: new Set(), + controller: null, + wasEverConnected: false + } + + /** @type {import('../receiver').ByteParser} */ + #parser + + constructor (url, options = undefined) { + if (!emittedExperimentalWarning) { + process.emitWarning('WebSocketStream is experimental! Expect it to change at any time.', { + code: 'UNDICI-WSS' + }) + emittedExperimentalWarning = true + } + + webidl.argumentLengthCheck(arguments, 1, 'WebSocket') + + url = webidl.converters.USVString(url) + if (options !== null) { + options = webidl.converters.WebSocketStreamOptions(options) + } + + // 1. Let baseURL be this 's relevant settings object 's API base URL . + const baseURL = environmentSettingsObject.settingsObject.baseUrl + + // 2. Let urlRecord be the result of getting a URL record given url and baseURL . + const urlRecord = getURLRecord(url, baseURL) + + // 3. Let protocols be options [" protocols "] if it exists , otherwise an empty sequence. + const protocols = options.protocols + + // 4. If any of the values in protocols occur more than once or otherwise fail to match the requirements for elements that comprise the value of ` Sec-WebSocket-Protocol ` fields as defined by The WebSocket Protocol , then throw a " SyntaxError " DOMException . [WSP] + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 5. Set this 's url to urlRecord . + this.#url = urlRecord.toString() + + // 6. Set this 's opened promise and closed promise to new promises. + this.#openedPromise = createDeferredPromise() + this.#closedPromise = createDeferredPromise() + + // 7. Apply backpressure to the WebSocket. + // TODO + + // 8. If options [" signal "] exists , + if (options.signal != null) { + // 8.1. Let signal be options [" signal "]. + const signal = options.signal + + // 8.2. If signal is aborted , then reject this 's opened promise and closed promise with signal ’s abort reason + // and return. + if (signal.aborted) { + this.#openedPromise.reject(signal.reason) + this.#closedPromise.reject(signal.reason) + return + } + + // 8.3. Add the following abort steps to signal : + signal.addEventListener('abort', () => { + // 8.3.1. If the WebSocket connection is not yet established : [WSP] + if (!isEstablished(this.#handler.readyState)) { + // 8.3.1.1. Fail the WebSocket connection . + failWebsocketConnection(this.#handler) + + // Set this 's ready state to CLOSING . + this.#handler.readyState = states.CLOSING + + // Reject this 's opened promise and closed promise with signal ’s abort reason . + this.#openedPromise.reject(signal.reason) + this.#closedPromise.reject(signal.reason) + + // Set this 's handshake aborted to true. + this.#handshakeAborted = true + } + }, { once: true }) + } + + // 9. Let client be this 's relevant settings object . + const client = environmentSettingsObject.settingsObject + + // 10. Run this step in parallel : + // 10.1. Establish a WebSocket connection given urlRecord , protocols , and client . [FETCH] + this.#handler.controller = establishWebSocketConnection( + urlRecord, + protocols, + client, + this.#handler, + options + ) + } + + // The url getter steps are to return this 's url , serialized . + get url () { + return this.#url.toString() + } + + // The opened getter steps are to return this 's opened promise . + get opened () { + return this.#openedPromise.promise + } + + // The closed getter steps are to return this 's closed promise . + get closed () { + return this.#closedPromise.promise + } + + // The close( closeInfo ) method steps are: + close (closeInfo = undefined) { + if (closeInfo !== null) { + closeInfo = webidl.converters.WebSocketCloseInfo(closeInfo) + } + + // 1. Let code be closeInfo [" closeCode "] if present, or null otherwise. + const code = closeInfo.closeCode ?? null + + // 2. Let reason be closeInfo [" reason "]. + const reason = closeInfo.reason + + // 3. Close the WebSocket with this , code , and reason . + closeWebSocketConnection(this.#handler, code, reason, true) + } + + #write (chunk) { + // See /websockets/stream/tentative/write.any.html + chunk = webidl.converters.WebSocketStreamWrite(chunk) + + // 1. Let promise be a new promise created in stream ’s relevant realm . + const promise = createDeferredPromise() + + // 2. Let data be null. + let data = null + + // 3. Let opcode be null. + let opcode = null + + // 4. If chunk is a BufferSource , + if (webidl.is.BufferSource(chunk)) { + // 4.1. Set data to a copy of the bytes given chunk . + data = new Uint8Array(ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength) : chunk.slice()) + + // 4.2. Set opcode to a binary frame opcode. + opcode = opcodes.BINARY + } else { + // 5. Otherwise, + + // 5.1. Let string be the result of converting chunk to an IDL USVString . + // If this throws an exception, return a promise rejected with the exception. + let string + + try { + string = webidl.converters.DOMString(chunk) + } catch (e) { + promise.reject(e) + return promise.promise + } + + // 5.2. Set data to the result of UTF-8 encoding string . + data = new TextEncoder().encode(string) + + // 5.3. Set opcode to a text frame opcode. + opcode = opcodes.TEXT + } + + // 6. In parallel, + // 6.1. Wait until there is sufficient buffer space in stream to send the message. + + // 6.2. If the closing handshake has not yet started , Send a WebSocket Message to stream comprised of data using opcode . + if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + const frame = new WebsocketFrameSend(data) + + this.#handler.socket.write(frame.createFrame(opcode), () => { + promise.resolve(undefined) + }) + } + + // 6.3. Queue a global task on the WebSocket task source given stream ’s relevant global object to resolve promise with undefined. + return promise.promise + } + + /** @type {import('../websocket').Handler['onConnectionEstablished']} */ + #onConnectionEstablished (response, parsedExtensions) { + this.#handler.socket = response.socket + + const parser = new ByteParser(this.#handler, parsedExtensions) + parser.on('drain', () => this.#handler.onParserDrain()) + parser.on('error', (err) => this.#handler.onParserError(err)) + + this.#parser = parser + + // 1. Change stream ’s ready state to OPEN (1). + this.#handler.readyState = states.OPEN + + // 2. Set stream ’s was ever connected to true. + // This is done in the opening handshake. + + // 3. Let extensions be the extensions in use . + const extensions = parsedExtensions ?? '' + + // 4. Let protocol be the subprotocol in use . + const protocol = response.headersList.get('sec-websocket-protocol') ?? '' + + // 5. Let pullAlgorithm be an action that pulls bytes from stream . + // 6. Let cancelAlgorithm be an action that cancels stream with reason , given reason . + // 7. Let readable be a new ReadableStream . + // 8. Set up readable with pullAlgorithm and cancelAlgorithm . + const readable = new ReadableStream({ + start: (controller) => { + this.#readableStreamController = controller + }, + pull (controller) { + let chunk + while (controller.desiredSize > 0 && (chunk = response.socket.read()) !== null) { + controller.enqueue(chunk) + } + }, + cancel: (reason) => this.#cancel(reason) + }) + + // 9. Let writeAlgorithm be an action that writes chunk to stream , given chunk . + // 10. Let closeAlgorithm be an action that closes stream . + // 11. Let abortAlgorithm be an action that aborts stream with reason , given reason . + // 12. Let writable be a new WritableStream . + // 13. Set up writable with writeAlgorithm , closeAlgorithm , and abortAlgorithm . + const writable = new WritableStream({ + write: (chunk) => this.#write(chunk), + close: () => closeWebSocketConnection(this.#handler, null, null), + abort: (reason) => this.#closeUsingReason(reason) + }) + + // Set stream ’s readable stream to readable . + this.#readableStream = readable + + // Set stream ’s writable stream to writable . + this.#writableStream = writable + + // Resolve stream ’s opened promise with WebSocketOpenInfo «[ " extensions " → extensions , " protocol " → protocol , " readable " → readable , " writable " → writable ]». + this.#openedPromise.resolve({ + extensions, + protocol, + readable, + writable + }) + } + + /** @type {import('../websocket').Handler['onMessage']} */ + #onMessage (type, data) { + // 1. If stream’s ready state is not OPEN (1), then return. + if (this.#handler.readyState !== states.OPEN) { + return + } + + // 2. Let chunk be determined by switching on type: + // - type indicates that the data is Text + // a new DOMString containing data + // - type indicates that the data is Binary + // a new Uint8Array object, created in the relevant Realm of the + // WebSocketStream object, whose contents are data + let chunk + + if (type === opcodes.TEXT) { + try { + chunk = utf8Decode(data) + } catch { + failWebsocketConnection(this.#handler, 'Received invalid UTF-8 in text frame.') + return + } + } else if (type === opcodes.BINARY) { + chunk = new Uint8Array(data.buffer, data.byteOffset, data.byteLength) + } + + // 3. Enqueue chunk into stream’s readable stream. + this.#readableStreamController.enqueue(chunk) + + // 4. Apply backpressure to the WebSocket. + } + + /** @type {import('../websocket').Handler['onSocketClose']} */ + #onSocketClose () { + const wasClean = + this.#handler.closeState.has(sentCloseFrameState.SENT) && + this.#handler.closeState.has(sentCloseFrameState.RECEIVED) + + // 1. Change the ready state to CLOSED (3). + this.#handler.readyState = states.CLOSED + + // 2. If stream ’s handshake aborted is true, then return. + if (this.#handshakeAborted) { + return + } + + // 3. If stream ’s was ever connected is false, then reject stream ’s opened promise with a new WebSocketError. + if (!this.#handler.wasEverConnected) { + this.#openedPromise.reject(new WebSocketError('Socket never opened')) + } + + const result = this.#parser?.closingInfo + + // 4. Let code be the WebSocket connection close code . + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + // If this Close control frame contains no status code, _The WebSocket + // Connection Close Code_ is considered to be 1005. If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + let code = result?.code ?? 1005 + + if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + code = 1006 + } + + // 5. Let reason be the result of applying UTF-8 decode without BOM to the WebSocket connection close reason . + const reason = result?.reason == null ? '' : utf8DecodeBytes(Buffer.from(result.reason)) + + // 6. If the connection was closed cleanly , + if (wasClean) { + // 6.1. Close stream ’s readable stream . + this.#readableStreamController.close() + + // 6.2. Error stream ’s writable stream with an " InvalidStateError " DOMException indicating that a closed WebSocketStream cannot be written to. + if (!this.#writableStream.locked) { + this.#writableStream.abort(new DOMException('A closed WebSocketStream cannot be written to', 'InvalidStateError')) + } + + // 6.3. Resolve stream ’s closed promise with WebSocketCloseInfo «[ " closeCode " → code , " reason " → reason ]». + this.#closedPromise.resolve({ + closeCode: code, + reason + }) + } else { + // 7. Otherwise, + + // 7.1. Let error be a new WebSocketError whose closeCode is code and reason is reason . + const error = createUnvalidatedWebSocketError('unclean close', code, reason) + + // 7.2. Error stream ’s readable stream with error . + this.#readableStreamController?.error(error) + + // 7.3. Error stream ’s writable stream with error . + this.#writableStream?.abort(error) + + // 7.4. Reject stream ’s closed promise with error . + this.#closedPromise.reject(error) + } + } + + #closeUsingReason (reason) { + // 1. Let code be null. + let code = null + + // 2. Let reasonString be the empty string. + let reasonString = '' + + // 3. If reason implements WebSocketError , + if (webidl.is.WebSocketError(reason)) { + // 3.1. Set code to reason ’s closeCode . + code = reason.closeCode + + // 3.2. Set reasonString to reason ’s reason . + reasonString = reason.reason + } + + // 4. Close the WebSocket with stream , code , and reasonString . If this throws an exception, + // discard code and reasonString and close the WebSocket with stream . + closeWebSocketConnection(this.#handler, code, reasonString) + } + + // To cancel a WebSocketStream stream given reason , close using reason giving stream and reason . + #cancel (reason) { + this.#closeUsingReason(reason) + } +} + +Object.defineProperties(WebSocketStream.prototype, { + url: kEnumerableProperty, + opened: kEnumerableProperty, + closed: kEnumerableProperty, + close: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocketStream', + writable: false, + enumerable: false, + configurable: true + } +}) + +webidl.converters.WebSocketStreamOptions = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.sequenceConverter(webidl.converters.USVString), + defaultValue: () => [] + }, + { + key: 'signal', + converter: webidl.nullableConverter(webidl.converters.AbortSignal), + defaultValue: () => null + } +]) + +webidl.converters.WebSocketCloseInfo = webidl.dictionaryConverter([ + { + key: 'closeCode', + converter: (V) => webidl.converters['unsigned short'](V, webidl.attributes.EnforceRange) + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: () => '' + } +]) + +webidl.converters.WebSocketStreamWrite = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + return webidl.converters.BufferSource(V) +} + +module.exports = { WebSocketStream } diff --git a/node_modules/undici/lib/web/websocket/util.js b/node_modules/undici/lib/web/websocket/util.js new file mode 100644 index 000000000..eaa5e7a1b --- /dev/null +++ b/node_modules/undici/lib/web/websocket/util.js @@ -0,0 +1,339 @@ +'use strict' + +const { states, opcodes } = require('./constants') +const { isUtf8 } = require('node:buffer') +const { removeHTTPWhitespace } = require('../fetch/data-url') +const { collectASequenceOfCodePointsFast } = require('../infra') + +/** + * @param {number} readyState + * @returns {boolean} + */ +function isConnecting (readyState) { + // If the WebSocket connection is not yet established, and the connection + // is not yet closed, then the WebSocket connection is in the CONNECTING state. + return readyState === states.CONNECTING +} + +/** + * @param {number} readyState + * @returns {boolean} + */ +function isEstablished (readyState) { + // If the server's response is validated as provided for above, it is + // said that _The WebSocket Connection is Established_ and that the + // WebSocket Connection is in the OPEN state. + return readyState === states.OPEN +} + +/** + * @param {number} readyState + * @returns {boolean} + */ +function isClosing (readyState) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + return readyState === states.CLOSING +} + +/** + * @param {number} readyState + * @returns {boolean} + */ +function isClosed (readyState) { + return readyState === states.CLOSED +} + +/** + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e + * @param {EventTarget} target + * @param {(...args: ConstructorParameters) => Event} eventFactory + * @param {EventInit | undefined} eventInitDict + * @returns {void} + */ +function fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) { + // 1. If eventConstructor is not given, then let eventConstructor be Event. + + // 2. Let event be the result of creating an event given eventConstructor, + // in the relevant realm of target. + // 3. Initialize event’s type attribute to e. + const event = eventFactory(e, eventInitDict) + + // 4. Initialize any other IDL attributes of event as described in the + // invocation of this algorithm. + + // 5. Return the result of dispatching event at target, with legacy target + // override flag set if set. + target.dispatchEvent(event) +} + +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @param {import('./websocket').Handler} handler + * @param {number} type Opcode + * @param {Buffer} data application data + * @returns {void} + */ +function websocketMessageReceived (handler, type, data) { + handler.onMessage(type, data) +} + +/** + * @param {Buffer} buffer + * @returns {ArrayBuffer} + */ +function toArrayBuffer (buffer) { + if (buffer.byteLength === buffer.buffer.byteLength) { + return buffer.buffer + } + return new Uint8Array(buffer).buffer +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455 + * @see https://datatracker.ietf.org/doc/html/rfc2616 + * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 + * @param {string} protocol + * @returns {boolean} + */ +function isValidSubprotocol (protocol) { + // If present, this value indicates one + // or more comma-separated subprotocol the client wishes to speak, + // ordered by preference. The elements that comprise this value + // MUST be non-empty strings with characters in the range U+0021 to + // U+007E not including separator characters as defined in + // [RFC2616] and MUST all be unique strings. + if (protocol.length === 0) { + return false + } + + for (let i = 0; i < protocol.length; ++i) { + const code = protocol.charCodeAt(i) + + if ( + code < 0x21 || // CTL, contains SP (0x20) and HT (0x09) + code > 0x7E || + code === 0x22 || // " + code === 0x28 || // ( + code === 0x29 || // ) + code === 0x2C || // , + code === 0x2F || // / + code === 0x3A || // : + code === 0x3B || // ; + code === 0x3C || // < + code === 0x3D || // = + code === 0x3E || // > + code === 0x3F || // ? + code === 0x40 || // @ + code === 0x5B || // [ + code === 0x5C || // \ + code === 0x5D || // ] + code === 0x7B || // { + code === 0x7D // } + ) { + return false + } + } + + return true +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 + * @param {number} code + * @returns {boolean} + */ +function isValidStatusCode (code) { + if (code >= 1000 && code < 1015) { + return ( + code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006 // "MUST NOT be set as a status code" + ) + } + + return code >= 3000 && code <= 4999 +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5 + * @param {number} opcode + * @returns {boolean} + */ +function isControlFrame (opcode) { + return ( + opcode === opcodes.CLOSE || + opcode === opcodes.PING || + opcode === opcodes.PONG + ) +} + +/** + * @param {number} opcode + * @returns {boolean} + */ +function isContinuationFrame (opcode) { + return opcode === opcodes.CONTINUATION +} + +/** + * @param {number} opcode + * @returns {boolean} + */ +function isTextBinaryFrame (opcode) { + return opcode === opcodes.TEXT || opcode === opcodes.BINARY +} + +/** + * + * @param {number} opcode + * @returns {boolean} + */ +function isValidOpcode (opcode) { + return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode) +} + +/** + * Parses a Sec-WebSocket-Extensions header value. + * @param {string} extensions + * @returns {Map} + */ +// TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 +function parseExtensions (extensions) { + const position = { position: 0 } + const extensionList = new Map() + + while (position.position < extensions.length) { + const pair = collectASequenceOfCodePointsFast(';', extensions, position) + const [name, value = ''] = pair.split('=', 2) + + extensionList.set( + removeHTTPWhitespace(name, true, false), + removeHTTPWhitespace(value, false, true) + ) + + position.position++ + } + + return extensionList +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2 + * @description "client-max-window-bits = 1*DIGIT" + * @param {string} value + * @returns {boolean} + */ +function isValidClientWindowBits (value) { + for (let i = 0; i < value.length; i++) { + const byte = value.charCodeAt(i) + + if (byte < 0x30 || byte > 0x39) { + return false + } + } + + return true +} + +/** + * @see https://whatpr.org/websockets/48/7b748d3...d5570f3.html#get-a-url-record + * @param {string} url + * @param {string} [baseURL] + */ +function getURLRecord (url, baseURL) { + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL . + // 2. If urlRecord is failure, then throw a " SyntaxError " DOMException . + let urlRecord + + try { + urlRecord = new URL(url, baseURL) + } catch (e) { + throw new DOMException(e, 'SyntaxError') + } + + // 3. If urlRecord ’s scheme is " http ", then set urlRecord ’s scheme to " ws ". + // 4. Otherwise, if urlRecord ’s scheme is " https ", set urlRecord ’s scheme to " wss ". + if (urlRecord.protocol === 'http:') { + urlRecord.protocol = 'ws:' + } else if (urlRecord.protocol === 'https:') { + urlRecord.protocol = 'wss:' + } + + // 5. If urlRecord ’s scheme is not " ws " or " wss ", then throw a " SyntaxError " DOMException . + if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { + throw new DOMException('expected a ws: or wss: url', 'SyntaxError') + } + + // If urlRecord ’s fragment is non-null, then throw a " SyntaxError " DOMException . + if (urlRecord.hash.length || urlRecord.href.endsWith('#')) { + throw new DOMException('hash', 'SyntaxError') + } + + // Return urlRecord . + return urlRecord +} + +// https://whatpr.org/websockets/48.html#validate-close-code-and-reason +function validateCloseCodeAndReason (code, reason) { + // 1. If code is not null, but is neither an integer equal to + // 1000 nor an integer in the range 3000 to 4999, inclusive, + // throw an "InvalidAccessError" DOMException. + if (code !== null) { + if (code !== 1000 && (code < 3000 || code > 4999)) { + throw new DOMException('invalid code', 'InvalidAccessError') + } + } + + // 2. If reason is not null, then: + if (reason !== null) { + // 2.1. Let reasonBytes be the result of UTF-8 encoding reason. + // 2.2. If reasonBytes is longer than 123 bytes, then throw a + // "SyntaxError" DOMException. + const reasonBytesLength = Buffer.byteLength(reason) + + if (reasonBytesLength > 123) { + throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`, 'SyntaxError') + } + } +} + +/** + * Converts a Buffer to utf-8, even on platforms without icu. + * @type {(buffer: Buffer) => string} + */ +const utf8Decode = (() => { + if (typeof process.versions.icu === 'string') { + const fatalDecoder = new TextDecoder('utf-8', { fatal: true }) + return fatalDecoder.decode.bind(fatalDecoder) + } + return function (buffer) { + if (isUtf8(buffer)) { + return buffer.toString('utf-8') + } + throw new TypeError('Invalid utf-8 received.') + } +})() + +module.exports = { + isConnecting, + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + websocketMessageReceived, + utf8Decode, + isControlFrame, + isContinuationFrame, + isTextBinaryFrame, + isValidOpcode, + parseExtensions, + isValidClientWindowBits, + toArrayBuffer, + getURLRecord, + validateCloseCodeAndReason +} diff --git a/node_modules/undici/lib/web/websocket/websocket.js b/node_modules/undici/lib/web/websocket/websocket.js new file mode 100644 index 000000000..331497677 --- /dev/null +++ b/node_modules/undici/lib/web/websocket/websocket.js @@ -0,0 +1,739 @@ +'use strict' + +const { isArrayBuffer } = require('node:util/types') +const { webidl } = require('../webidl') +const { URLSerializer } = require('../fetch/data-url') +const { environmentSettingsObject } = require('../fetch/util') +const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints, opcodes } = require('./constants') +const { + isConnecting, + isEstablished, + isClosing, + isClosed, + isValidSubprotocol, + fireEvent, + utf8Decode, + toArrayBuffer, + getURLRecord +} = require('./util') +const { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = require('./connection') +const { ByteParser } = require('./receiver') +const { kEnumerableProperty } = require('../../core/util') +const { getGlobalDispatcher } = require('../../global') +const { ErrorEvent, CloseEvent, createFastMessageEvent } = require('./events') +const { SendQueue } = require('./sender') +const { WebsocketFrameSend } = require('./frame') +const { channels } = require('../../core/diagnostics') + +/** + * @typedef {object} Handler + * @property {(response: any, extensions?: string[]) => void} onConnectionEstablished + * @property {(opcode: number, data: Buffer) => void} onMessage + * @property {(error: Error) => void} onParserError + * @property {() => void} onParserDrain + * @property {(chunk: Buffer) => void} onSocketData + * @property {(err: Error) => void} onSocketError + * @property {() => void} onSocketClose + * @property {(body: Buffer) => void} onPing + * @property {(body: Buffer) => void} onPong + * + * @property {number} readyState + * @property {import('stream').Duplex} socket + * @property {Set} closeState + * @property {import('../fetch/index').Fetch} controller + * @property {boolean} [wasEverConnected=false] + */ + +// https://websockets.spec.whatwg.org/#interface-definition +class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } + + #bufferedAmount = 0 + #protocol = '' + #extensions = '' + + /** @type {SendQueue} */ + #sendQueue + + /** @type {Handler} */ + #handler = { + onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions), + onMessage: (opcode, data) => this.#onMessage(opcode, data), + onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message), + onParserDrain: () => this.#onParserDrain(), + onSocketData: (chunk) => { + if (!this.#parser.write(chunk)) { + this.#handler.socket.pause() + } + }, + onSocketError: (err) => { + this.#handler.readyState = states.CLOSING + + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(err) + } + + this.#handler.socket.destroy() + }, + onSocketClose: () => this.#onSocketClose(), + onPing: (body) => { + if (channels.ping.hasSubscribers) { + channels.ping.publish({ + payload: body, + websocket: this + }) + } + }, + onPong: (body) => { + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body, + websocket: this + }) + } + }, + + readyState: states.CONNECTING, + socket: null, + closeState: new Set(), + controller: null, + wasEverConnected: false + } + + #url + #binaryType + /** @type {import('./receiver').ByteParser} */ + #parser + + /** + * @param {string} url + * @param {string|string[]} protocols + */ + constructor (url, protocols = []) { + super() + + webidl.util.markAsUncloneable(this) + + const prefix = 'WebSocket constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols, prefix, 'options') + + url = webidl.converters.USVString(url) + protocols = options.protocols + + // 1. Let baseURL be this's relevant settings object's API base URL. + const baseURL = environmentSettingsObject.settingsObject.baseUrl + + // 2. Let urlRecord be the result of getting a URL record given url and baseURL. + const urlRecord = getURLRecord(url, baseURL) + + // 3. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols] + } + + // 4. If any of the values in protocols occur more than once or otherwise + // fail to match the requirements for elements that comprise the value + // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket + // protocol, then throw a "SyntaxError" DOMException. + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 5. Set this's url to urlRecord. + this.#url = new URL(urlRecord.href) + + // 6. Let client be this's relevant settings object. + const client = environmentSettingsObject.settingsObject + + // 7. Run this step in parallel: + // 7.1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this.#handler.controller = establishWebSocketConnection( + urlRecord, + protocols, + client, + this.#handler, + options + ) + + // Each WebSocket object has an associated ready state, which is a + // number representing the state of the connection. Initially it must + // be CONNECTING (0). + this.#handler.readyState = WebSocket.CONNECTING + + // The extensions attribute must initially return the empty string. + + // The protocol attribute must initially return the empty string. + + // Each WebSocket object has an associated binary type, which is a + // BinaryType. Initially it must be "blob". + this.#binaryType = 'blob' + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ + close (code = undefined, reason = undefined) { + webidl.brandCheck(this, WebSocket) + + const prefix = 'WebSocket.close' + + if (code !== undefined) { + code = webidl.converters['unsigned short'](code, prefix, 'code', webidl.attributes.Clamp) + } + + if (reason !== undefined) { + reason = webidl.converters.USVString(reason) + } + + // 1. If code is the special value "missing", then set code to null. + code ??= null + + // 2. If reason is the special value "missing", then set reason to the empty string. + reason ??= '' + + // 3. Close the WebSocket with this, code, and reason. + closeWebSocketConnection(this.#handler, code, reason, true) + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-send + * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + */ + send (data) { + webidl.brandCheck(this, WebSocket) + + const prefix = 'WebSocket.send' + webidl.argumentLengthCheck(arguments, 1, prefix) + + data = webidl.converters.WebSocketSendData(data, prefix, 'data') + + // 1. If this's ready state is CONNECTING, then throw an + // "InvalidStateError" DOMException. + if (isConnecting(this.#handler.readyState)) { + throw new DOMException('Sent before connected.', 'InvalidStateError') + } + + // 2. Run the appropriate set of steps from the following list: + // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 + // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + + if (!isEstablished(this.#handler.readyState) || isClosing(this.#handler.readyState)) { + return + } + + // If data is a string + if (typeof data === 'string') { + // If the WebSocket connection is established and the WebSocket + // closing handshake has not yet started, then the user agent + // must send a WebSocket Message comprised of the data argument + // using a text frame opcode; if the data cannot be sent, e.g. + // because it would need to be buffered but the buffer is full, + // the user agent must flag the WebSocket as full and then close + // the WebSocket connection. Any invocation of this method with a + // string argument that does not throw an exception must increase + // the bufferedAmount attribute by the number of bytes needed to + // express the argument as UTF-8. + + const buffer = Buffer.from(data) + + this.#bufferedAmount += buffer.byteLength + this.#sendQueue.add(buffer, () => { + this.#bufferedAmount -= buffer.byteLength + }, sendHints.text) + } else if (isArrayBuffer(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need + // to be buffered but the buffer is full, the user agent must flag + // the WebSocket as full and then close the WebSocket connection. + // The data to be sent is the data stored in the buffer described + // by the ArrayBuffer object. Any invocation of this method with an + // ArrayBuffer argument that does not throw an exception must + // increase the bufferedAmount attribute by the length of the + // ArrayBuffer in bytes. + + this.#bufferedAmount += data.byteLength + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.byteLength + }, sendHints.arrayBuffer) + } else if (ArrayBuffer.isView(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The + // data to be sent is the data stored in the section of the buffer + // described by the ArrayBuffer object that data references. Any + // invocation of this method with this kind of argument that does + // not throw an exception must increase the bufferedAmount attribute + // by the length of data’s buffer in bytes. + + this.#bufferedAmount += data.byteLength + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.byteLength + }, sendHints.typedArray) + } else if (webidl.is.Blob(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The data + // to be sent is the raw data represented by the Blob object. Any + // invocation of this method with a Blob argument that does not throw + // an exception must increase the bufferedAmount attribute by the size + // of the Blob object’s raw data, in bytes. + + this.#bufferedAmount += data.size + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.size + }, sendHints.blob) + } + } + + get readyState () { + webidl.brandCheck(this, WebSocket) + + // The readyState getter steps are to return this's ready state. + return this.#handler.readyState + } + + get bufferedAmount () { + webidl.brandCheck(this, WebSocket) + + return this.#bufferedAmount + } + + get url () { + webidl.brandCheck(this, WebSocket) + + // The url getter steps are to return this's url, serialized. + return URLSerializer(this.#url) + } + + get extensions () { + webidl.brandCheck(this, WebSocket) + + return this.#extensions + } + + get protocol () { + webidl.brandCheck(this, WebSocket) + + return this.#protocol + } + + get onopen () { + webidl.brandCheck(this, WebSocket) + + return this.#events.open + } + + set onopen (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) + } + + const listener = webidl.converters.EventHandlerNonNull(fn) + + if (listener !== null) { + this.addEventListener('open', listener) + this.#events.open = fn + } else { + this.#events.open = null + } + } + + get onerror () { + webidl.brandCheck(this, WebSocket) + + return this.#events.error + } + + set onerror (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) + } + + const listener = webidl.converters.EventHandlerNonNull(fn) + + if (listener !== null) { + this.addEventListener('error', listener) + this.#events.error = fn + } else { + this.#events.error = null + } + } + + get onclose () { + webidl.brandCheck(this, WebSocket) + + return this.#events.close + } + + set onclose (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.close) { + this.removeEventListener('close', this.#events.close) + } + + const listener = webidl.converters.EventHandlerNonNull(fn) + + if (listener !== null) { + this.addEventListener('close', listener) + this.#events.close = fn + } else { + this.#events.close = null + } + } + + get onmessage () { + webidl.brandCheck(this, WebSocket) + + return this.#events.message + } + + set onmessage (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } + + const listener = webidl.converters.EventHandlerNonNull(fn) + + if (listener !== null) { + this.addEventListener('message', listener) + this.#events.message = fn + } else { + this.#events.message = null + } + } + + get binaryType () { + webidl.brandCheck(this, WebSocket) + + return this.#binaryType + } + + set binaryType (type) { + webidl.brandCheck(this, WebSocket) + + if (type !== 'blob' && type !== 'arraybuffer') { + this.#binaryType = 'blob' + } else { + this.#binaryType = type + } + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ + #onConnectionEstablished (response, parsedExtensions) { + // processResponse is called when the "response’s header list has been received and initialized." + // once this happens, the connection is open + this.#handler.socket = response.socket + + const parser = new ByteParser(this.#handler, parsedExtensions) + parser.on('drain', () => this.#handler.onParserDrain()) + parser.on('error', (err) => this.#handler.onParserError(err)) + + this.#parser = parser + this.#sendQueue = new SendQueue(response.socket) + + // 1. Change the ready state to OPEN (1). + this.#handler.readyState = states.OPEN + + // 2. Change the extensions attribute’s value to the extensions in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 + const extensions = response.headersList.get('sec-websocket-extensions') + + if (extensions !== null) { + this.#extensions = extensions + } + + // 3. Change the protocol attribute’s value to the subprotocol in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 + const protocol = response.headersList.get('sec-websocket-protocol') + + if (protocol !== null) { + this.#protocol = protocol + } + + // 4. Fire an event named open at the WebSocket object. + fireEvent('open', this) + + if (channels.open.hasSubscribers) { + // Convert headers to a plain object for the event + const headers = response.headersList.entries + channels.open.publish({ + address: response.socket.address(), + protocol: this.#protocol, + extensions: this.#extensions, + websocket: this, + handshakeResponse: { + status: response.status, + statusText: response.statusText, + headers + } + }) + } + } + + #onMessage (type, data) { + // 1. If ready state is not OPEN (1), then return. + if (this.#handler.readyState !== states.OPEN) { + return + } + + // 2. Let dataForEvent be determined by switching on type and binary type: + let dataForEvent + + if (type === opcodes.TEXT) { + // -> type indicates that the data is Text + // a new DOMString containing data + try { + dataForEvent = utf8Decode(data) + } catch { + failWebsocketConnection(this.#handler, 1007, 'Received invalid UTF-8 in text frame.') + return + } + } else if (type === opcodes.BINARY) { + if (this.#binaryType === 'blob') { + // -> type indicates that the data is Binary and binary type is "blob" + // a new Blob object, created in the relevant Realm of the WebSocket + // object, that represents data as its raw data + dataForEvent = new Blob([data]) + } else { + // -> type indicates that the data is Binary and binary type is "arraybuffer" + // a new ArrayBuffer object, created in the relevant Realm of the + // WebSocket object, whose contents are data + dataForEvent = toArrayBuffer(data) + } + } + + // 3. Fire an event named message at the WebSocket object, using MessageEvent, + // with the origin attribute initialized to the serialization of the WebSocket + // object’s url's origin, and the data attribute initialized to dataForEvent. + fireEvent('message', this, createFastMessageEvent, { + origin: this.#url.origin, + data: dataForEvent + }) + } + + #onParserDrain () { + this.#handler.socket.resume() + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + */ + #onSocketClose () { + // If the TCP connection was closed after the + // WebSocket closing handshake was completed, the WebSocket connection + // is said to have been closed _cleanly_. + const wasClean = + this.#handler.closeState.has(sentCloseFrameState.SENT) && + this.#handler.closeState.has(sentCloseFrameState.RECEIVED) + + let code = 1005 + let reason = '' + + const result = this.#parser?.closingInfo + + if (result && !result.error) { + code = result.code ?? 1005 + reason = result.reason + } + + // 1. Change the ready state to CLOSED (3). + this.#handler.readyState = states.CLOSED + + // 2. If the user agent was required to fail the WebSocket + // connection, or if the WebSocket connection was closed + // after being flagged as full, fire an event named error + // at the WebSocket object. + if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + // If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + code = 1006 + + fireEvent('error', this, (type, init) => new ErrorEvent(type, init), { + error: new TypeError(reason) + }) + } + + // 3. Fire an event named close at the WebSocket object, + // using CloseEvent, with the wasClean attribute + // initialized to true if the connection closed cleanly + // and false otherwise, the code attribute initialized to + // the WebSocket connection close code, and the reason + // attribute initialized to the result of applying UTF-8 + // decode without BOM to the WebSocket connection close + // reason. + // TODO: process.nextTick + fireEvent('close', this, (type, init) => new CloseEvent(type, init), { + wasClean, code, reason + }) + + if (channels.close.hasSubscribers) { + channels.close.publish({ + websocket: this, + code, + reason + }) + } + } + + /** + * @param {WebSocket} ws + * @param {Buffer|undefined} buffer + */ + static ping (ws, buffer) { + if (Buffer.isBuffer(buffer)) { + if (buffer.length > 125) { + throw new TypeError('A PING frame cannot have a body larger than 125 bytes.') + } + } else if (buffer !== undefined) { + throw new TypeError('Expected buffer payload') + } + + // An endpoint MAY send a Ping frame any time after the connection is + // established and before the connection is closed. + const readyState = ws.#handler.readyState + + if (isEstablished(readyState) && !isClosing(readyState) && !isClosed(readyState)) { + const frame = new WebsocketFrameSend(buffer) + ws.#handler.socket.write(frame.createFrame(opcodes.PING)) + } + } +} + +const { ping } = WebSocket +Reflect.deleteProperty(WebSocket, 'ping') + +// https://websockets.spec.whatwg.org/#dom-websocket-connecting +WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING +// https://websockets.spec.whatwg.org/#dom-websocket-open +WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN +// https://websockets.spec.whatwg.org/#dom-websocket-closing +WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING +// https://websockets.spec.whatwg.org/#dom-websocket-closed +WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED + +Object.defineProperties(WebSocket.prototype, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors, + url: kEnumerableProperty, + readyState: kEnumerableProperty, + bufferedAmount: kEnumerableProperty, + onopen: kEnumerableProperty, + onerror: kEnumerableProperty, + onclose: kEnumerableProperty, + close: kEnumerableProperty, + onmessage: kEnumerableProperty, + binaryType: kEnumerableProperty, + send: kEnumerableProperty, + extensions: kEnumerableProperty, + protocol: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocket', + writable: false, + enumerable: false, + configurable: true + } +}) + +Object.defineProperties(WebSocket, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors +}) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.DOMString +) + +webidl.converters['DOMString or sequence'] = function (V, prefix, argument) { + if (webidl.util.Type(V) === webidl.util.Types.OBJECT && Symbol.iterator in V) { + return webidl.converters['sequence'](V) + } + + return webidl.converters.DOMString(V, prefix, argument) +} + +// This implements the proposal made in https://github.com/whatwg/websockets/issues/42 +webidl.converters.WebSocketInit = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.converters['DOMString or sequence'], + defaultValue: () => [] + }, + { + key: 'dispatcher', + converter: webidl.converters.any, + defaultValue: () => getGlobalDispatcher() + }, + { + key: 'headers', + converter: webidl.nullableConverter(webidl.converters.HeadersInit) + } +]) + +webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { + if (webidl.util.Type(V) === webidl.util.Types.OBJECT && !(Symbol.iterator in V)) { + return webidl.converters.WebSocketInit(V) + } + + return { protocols: webidl.converters['DOMString or sequence'](V) } +} + +webidl.converters.WebSocketSendData = function (V) { + if (webidl.util.Type(V) === webidl.util.Types.OBJECT) { + if (webidl.is.Blob(V)) { + return V + } + + if (webidl.is.BufferSource(V)) { + return V + } + } + + return webidl.converters.USVString(V) +} + +module.exports = { + WebSocket, + ping +} diff --git a/node_modules/undici/package.json b/node_modules/undici/package.json new file mode 100644 index 000000000..95a13d54f --- /dev/null +++ b/node_modules/undici/package.json @@ -0,0 +1,152 @@ +{ + "name": "undici", + "version": "7.19.1", + "description": "An HTTP/1.1 client, written from scratch for Node.js", + "homepage": "https://undici.nodejs.org", + "bugs": { + "url": "https://github.com/nodejs/undici/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/undici.git" + }, + "license": "MIT", + "contributors": [ + { + "name": "Daniele Belardi", + "url": "https://github.com/dnlup", + "author": true + }, + { + "name": "Ethan Arrowood", + "url": "https://github.com/ethan-arrowood", + "author": true + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina", + "author": true + }, + { + "name": "Matthew Aitken", + "url": "https://github.com/KhafraDev", + "author": true + }, + { + "name": "Robert Nagy", + "url": "https://github.com/ronag", + "author": true + }, + { + "name": "Szymon Marczak", + "url": "https://github.com/szmarczak", + "author": true + }, + { + "name": "Tomas Della Vedova", + "url": "https://github.com/delvedor", + "author": true + } + ], + "keywords": [ + "fetch", + "http", + "https", + "promise", + "request", + "curl", + "wget", + "xhr", + "whatwg" + ], + "main": "index.js", + "types": "index.d.ts", + "scripts": { + "build:node": "esbuild index-fetch.js --bundle --platform=node --outfile=undici-fetch.js --define:esbuildDetection=1 --keep-names && node scripts/strip-comments.js", + "build:wasm": "node build/wasm.js --docker", + "generate-pem": "node scripts/generate-pem.js", + "lint": "eslint --cache", + "lint:fix": "eslint --fix --cache", + "test": "npm run test:javascript && cross-env NODE_V8_COVERAGE= npm run test:typescript", + "test:javascript": "npm run test:javascript:no-jest && npm run test:jest", + "test:javascript:no-jest": "npm run generate-pem && npm run test:unit && npm run test:fetch && npm run test:node-fetch && npm run test:infra && npm run test:cache && npm run test:cache-interceptor && npm run test:interceptors && npm run test:cookies && npm run test:eventsource && npm run test:subresource-integrity && npm run test:wpt && npm run test:websocket && npm run test:node-test && npm run test:cache-tests", + "test:javascript:without-intl": "npm run test:javascript:no-jest", + "test:busboy": "borp -p \"test/busboy/*.js\"", + "test:cache": "borp -p \"test/cache/*.js\"", + "test:cache-interceptor": "borp -p \"test/cache-interceptor/*.js\"", + "test:cache-interceptor:sqlite": "cross-env NODE_OPTIONS=--experimental-sqlite npm run test:cache-interceptor", + "test:cookies": "borp -p \"test/cookie/*.js\"", + "test:eventsource": "npm run build:node && borp --expose-gc -p \"test/eventsource/*.js\"", + "test:fuzzing": "node test/fuzzing/fuzzing.test.js", + "test:fetch": "npm run build:node && borp --timeout 180000 --expose-gc --concurrency 1 -p \"test/fetch/*.js\" && npm run test:webidl && npm run test:busboy", + "test:subresource-integrity": "borp -p \"test/subresource-integrity/*.js\"", + "test:h2": "npm run test:h2:core && npm run test:h2:fetch", + "test:h2:core": "borp -p \"test/+(http2|h2)*.js\"", + "test:h2:fetch": "npm run build:node && borp -p \"test/fetch/http2*.js\"", + "test:infra": "borp -p \"test/infra/*.js\"", + "test:interceptors": "borp -p \"test/interceptors/*.js\"", + "test:jest": "cross-env NODE_V8_COVERAGE= jest", + "test:unit": "borp --expose-gc -p \"test/*.js\"", + "test:node-fetch": "borp -p \"test/node-fetch/**/*.js\"", + "test:node-test": "borp -p \"test/node-test/**/*.js\"", + "test:tdd": "borp --expose-gc -p \"test/*.js\"", + "test:tdd:node-test": "borp -p \"test/node-test/**/*.js\" -w", + "test:typescript": "tsd && tsc test/imports/undici-import.ts --typeRoots ./types --noEmit && tsc ./types/*.d.ts --noEmit --typeRoots ./types", + "test:webidl": "borp -p \"test/webidl/*.js\"", + "test:websocket": "borp -p \"test/websocket/**/*.js\"", + "test:websocket:autobahn": "node test/autobahn/client.js", + "test:websocket:autobahn:report": "node test/autobahn/report.js", + "test:wpt:setup": "node test/web-platform-tests/wpt-runner.mjs setup", + "test:wpt": "npm run test:wpt:setup && node test/web-platform-tests/wpt-runner.mjs run /fetch /mimesniff /xhr /websockets /serviceWorkers /eventsource", + "test:cache-tests": "node test/cache-interceptor/cache-tests.mjs --ci", + "coverage": "npm run coverage:clean && cross-env NODE_V8_COVERAGE=./coverage/tmp npm run test:javascript && npm run coverage:report", + "coverage:ci": "npm run coverage:clean && cross-env NODE_V8_COVERAGE=./coverage/tmp npm run test:javascript && npm run coverage:report:ci", + "coverage:clean": "node ./scripts/clean-coverage.js", + "coverage:report": "cross-env NODE_V8_COVERAGE= c8 report", + "coverage:report:ci": "c8 report", + "bench": "echo \"Error: Benchmarks have been moved to '/benchmarks'\" && exit 1", + "serve:website": "echo \"Error: Documentation has been moved to '/docs'\" && exit 1", + "prepare": "husky && node ./scripts/platform-shell.js" + }, + "devDependencies": { + "@fastify/busboy": "3.2.0", + "@matteo.collina/tspl": "^0.2.0", + "@metcoder95/https-pem": "^1.0.0", + "@sinonjs/fake-timers": "^12.0.0", + "@types/node": "^20.19.22", + "abort-controller": "^3.0.0", + "borp": "^0.20.0", + "c8": "^10.0.0", + "cross-env": "^10.0.0", + "dns-packet": "^5.4.0", + "esbuild": "^0.25.2", + "eslint": "^9.9.0", + "fast-check": "^4.1.1", + "husky": "^9.0.7", + "jest": "^30.0.5", + "jsondiffpatch": "^0.7.3", + "neostandard": "^0.12.0", + "node-forge": "^1.3.1", + "proxy": "^2.1.1", + "tsd": "^0.33.0", + "typescript": "^5.6.2", + "ws": "^8.11.0" + }, + "engines": { + "node": ">=20.18.1" + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "esModuleInterop": true, + "lib": [ + "esnext" + ] + } + }, + "jest": { + "testMatch": [ + "/test/jest/**" + ] + } +} diff --git a/node_modules/undici/scripts/strip-comments.js b/node_modules/undici/scripts/strip-comments.js new file mode 100644 index 000000000..d687a2680 --- /dev/null +++ b/node_modules/undici/scripts/strip-comments.js @@ -0,0 +1,10 @@ +'use strict' + +const { readFileSync, writeFileSync } = require('node:fs') +const { transcode } = require('node:buffer') + +const buffer = transcode + ? transcode(readFileSync('./undici-fetch.js'), 'utf8', 'latin1') + : readFileSync('./undici-fetch.js') + +writeFileSync('./undici-fetch.js', buffer.toString('latin1')) diff --git a/node_modules/undici/types/README.md b/node_modules/undici/types/README.md new file mode 100644 index 000000000..20a721c44 --- /dev/null +++ b/node_modules/undici/types/README.md @@ -0,0 +1,6 @@ +# undici-types + +This package is a dual-publish of the [undici](https://www.npmjs.com/package/undici) library types. The `undici` package **still contains types**. This package is for users who _only_ need undici types (such as for `@types/node`). It is published alongside every release of `undici`, so you can always use the same version. + +- [GitHub nodejs/undici](https://github.com/nodejs/undici) +- [Undici Documentation](https://undici.nodejs.org/#/) diff --git a/node_modules/undici/types/agent.d.ts b/node_modules/undici/types/agent.d.ts new file mode 100644 index 000000000..b3b376d20 --- /dev/null +++ b/node_modules/undici/types/agent.d.ts @@ -0,0 +1,32 @@ +import { URL } from 'node:url' +import Pool from './pool' +import Dispatcher from './dispatcher' +import TClientStats from './client-stats' +import TPoolStats from './pool-stats' + +export default Agent + +declare class Agent extends Dispatcher { + constructor (opts?: Agent.Options) + /** `true` after `dispatcher.close()` has been called. */ + closed: boolean + /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */ + destroyed: boolean + /** Dispatches a request. */ + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean + /** Aggregate stats for a Agent by origin. */ + readonly stats: Record +} + +declare namespace Agent { + export interface Options extends Pool.Options { + /** Default: `(origin, opts) => new Pool(origin, opts)`. */ + factory?(origin: string | URL, opts: Object): Dispatcher; + + interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options['interceptors'] + maxOrigins?: number + } + + export interface DispatchOptions extends Dispatcher.DispatchOptions { + } +} diff --git a/node_modules/undici/types/api.d.ts b/node_modules/undici/types/api.d.ts new file mode 100644 index 000000000..b362b14f2 --- /dev/null +++ b/node_modules/undici/types/api.d.ts @@ -0,0 +1,43 @@ +import { URL, UrlObject } from 'node:url' +import { Duplex } from 'node:stream' +import Dispatcher from './dispatcher' + +/** Performs an HTTP request. */ +declare function request ( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path' | 'method'> & Partial>, +): Promise> + +/** A faster version of `request`. */ +declare function stream ( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path'>, + factory: Dispatcher.StreamFactory +): Promise> + +/** For easy use with `stream.pipeline`. */ +declare function pipeline ( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path'>, + handler: Dispatcher.PipelineHandler +): Duplex + +/** Starts two-way communications with the requested resource. */ +declare function connect ( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path'> +): Promise> + +/** Upgrade to a different protocol. */ +declare function upgrade ( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise + +export { + request, + stream, + pipeline, + connect, + upgrade +} diff --git a/node_modules/undici/types/balanced-pool.d.ts b/node_modules/undici/types/balanced-pool.d.ts new file mode 100644 index 000000000..1813e0ca9 --- /dev/null +++ b/node_modules/undici/types/balanced-pool.d.ts @@ -0,0 +1,30 @@ +import Pool from './pool' +import Dispatcher from './dispatcher' +import { URL } from 'node:url' + +export default BalancedPool + +type BalancedPoolConnectOptions = Omit + +declare class BalancedPool extends Dispatcher { + constructor (url: string | string[] | URL | URL[], options?: Pool.Options) + + addUpstream (upstream: string | URL): BalancedPool + removeUpstream (upstream: string | URL): BalancedPool + getUpstream (upstream: string | URL): Pool | undefined + upstreams: Array + + /** `true` after `pool.close()` has been called. */ + closed: boolean + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean + + // Override dispatcher APIs. + override connect ( + options: BalancedPoolConnectOptions + ): Promise + override connect ( + options: BalancedPoolConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} diff --git a/node_modules/undici/types/cache-interceptor.d.ts b/node_modules/undici/types/cache-interceptor.d.ts new file mode 100644 index 000000000..8588ccdcb --- /dev/null +++ b/node_modules/undici/types/cache-interceptor.d.ts @@ -0,0 +1,179 @@ +import { Readable, Writable } from 'node:stream' + +export default CacheHandler + +declare namespace CacheHandler { + export type CacheMethods = 'GET' | 'HEAD' | 'OPTIONS' | 'TRACE' + + export interface CacheHandlerOptions { + store: CacheStore + + cacheByDefault?: number + + type?: CacheOptions['type'] + } + + export interface CacheOptions { + store?: CacheStore + + /** + * The methods to cache + * Note we can only cache safe methods. Unsafe methods (i.e. PUT, POST) + * invalidate the cache for a origin. + * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-invalidating-stored-respons + * @see https://www.rfc-editor.org/rfc/rfc9110#section-9.2.1 + */ + methods?: CacheMethods[] + + /** + * RFC9111 allows for caching responses that we aren't explicitly told to + * cache or to not cache. + * @see https://www.rfc-editor.org/rfc/rfc9111.html#section-3-5 + * @default undefined + */ + cacheByDefault?: number + + /** + * TODO docs + * @default 'shared' + */ + type?: 'shared' | 'private' + + /** + * Array of origins to cache. Only requests to these origins will be cached. + * Supports strings (case insensitive) and RegExp patterns. + * @default undefined (cache all origins) + */ + origins?: (string | RegExp)[] + } + + export interface CacheControlDirectives { + 'max-stale'?: number; + 'min-fresh'?: number; + 'max-age'?: number; + 's-maxage'?: number; + 'stale-while-revalidate'?: number; + 'stale-if-error'?: number; + public?: true; + private?: true | string[]; + 'no-store'?: true; + 'no-cache'?: true | string[]; + 'must-revalidate'?: true; + 'proxy-revalidate'?: true; + immutable?: true; + 'no-transform'?: true; + 'must-understand'?: true; + 'only-if-cached'?: true; + } + + export interface CacheKey { + origin: string + method: string + path: string + headers?: Record + } + + export interface CacheValue { + statusCode: number + statusMessage: string + headers: Record + vary?: Record + etag?: string + cacheControlDirectives?: CacheControlDirectives + cachedAt: number + staleAt: number + deleteAt: number + } + + export interface DeleteByUri { + origin: string + method: string + path: string + } + + type GetResult = { + statusCode: number + statusMessage: string + headers: Record + vary?: Record + etag?: string + body?: Readable | Iterable | AsyncIterable | Buffer | Iterable | AsyncIterable | string + cacheControlDirectives: CacheControlDirectives, + cachedAt: number + staleAt: number + deleteAt: number + } + + /** + * Underlying storage provider for cached responses + */ + export interface CacheStore { + get(key: CacheKey): GetResult | Promise | undefined + + createWriteStream(key: CacheKey, val: CacheValue): Writable | undefined + + delete(key: CacheKey): void | Promise + } + + export interface MemoryCacheStoreOpts { + /** + * @default Infinity + */ + maxCount?: number + + /** + * @default Infinity + */ + maxSize?: number + + /** + * @default Infinity + */ + maxEntrySize?: number + + errorCallback?: (err: Error) => void + } + + export class MemoryCacheStore implements CacheStore { + constructor (opts?: MemoryCacheStoreOpts) + + get (key: CacheKey): GetResult | Promise | undefined + + createWriteStream (key: CacheKey, value: CacheValue): Writable | undefined + + delete (key: CacheKey): void | Promise + } + + export interface SqliteCacheStoreOpts { + /** + * Location of the database + * @default ':memory:' + */ + location?: string + + /** + * @default Infinity + */ + maxCount?: number + + /** + * @default Infinity + */ + maxEntrySize?: number + } + + export class SqliteCacheStore implements CacheStore { + constructor (opts?: SqliteCacheStoreOpts) + + /** + * Closes the connection to the database + */ + close (): void + + get (key: CacheKey): GetResult | Promise | undefined + + createWriteStream (key: CacheKey, value: CacheValue): Writable | undefined + + delete (key: CacheKey): void | Promise + } +} diff --git a/node_modules/undici/types/cache.d.ts b/node_modules/undici/types/cache.d.ts new file mode 100644 index 000000000..4c3333576 --- /dev/null +++ b/node_modules/undici/types/cache.d.ts @@ -0,0 +1,36 @@ +import type { RequestInfo, Response, Request } from './fetch' + +export interface CacheStorage { + match (request: RequestInfo, options?: MultiCacheQueryOptions): Promise, + has (cacheName: string): Promise, + open (cacheName: string): Promise, + delete (cacheName: string): Promise, + keys (): Promise +} + +declare const CacheStorage: { + prototype: CacheStorage + new(): CacheStorage +} + +export interface Cache { + match (request: RequestInfo, options?: CacheQueryOptions): Promise, + matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise, + add (request: RequestInfo): Promise, + addAll (requests: RequestInfo[]): Promise, + put (request: RequestInfo, response: Response): Promise, + delete (request: RequestInfo, options?: CacheQueryOptions): Promise, + keys (request?: RequestInfo, options?: CacheQueryOptions): Promise +} + +export interface CacheQueryOptions { + ignoreSearch?: boolean, + ignoreMethod?: boolean, + ignoreVary?: boolean +} + +export interface MultiCacheQueryOptions extends CacheQueryOptions { + cacheName?: string +} + +export declare const caches: CacheStorage diff --git a/node_modules/undici/types/client-stats.d.ts b/node_modules/undici/types/client-stats.d.ts new file mode 100644 index 000000000..ad9bd8482 --- /dev/null +++ b/node_modules/undici/types/client-stats.d.ts @@ -0,0 +1,15 @@ +import Client from './client' + +export default ClientStats + +declare class ClientStats { + constructor (pool: Client) + /** If socket has open connection. */ + connected: boolean + /** Number of open socket connections in this client that do not have an active request. */ + pending: number + /** Number of currently active requests of this client. */ + running: number + /** Number of active, pending, or queued requests of this client. */ + size: number +} diff --git a/node_modules/undici/types/client.d.ts b/node_modules/undici/types/client.d.ts new file mode 100644 index 000000000..f5ccde2be --- /dev/null +++ b/node_modules/undici/types/client.d.ts @@ -0,0 +1,118 @@ +import { URL } from 'node:url' +import Dispatcher from './dispatcher' +import buildConnector from './connector' +import TClientStats from './client-stats' + +type ClientConnectOptions = Omit + +/** + * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + */ +export class Client extends Dispatcher { + constructor (url: string | URL, options?: Client.Options) + /** Property to get and set the pipelining factor. */ + pipelining: number + /** `true` after `client.close()` has been called. */ + closed: boolean + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean + /** Aggregate stats for a Client. */ + readonly stats: TClientStats + + // Override dispatcher APIs. + override connect ( + options: ClientConnectOptions + ): Promise + override connect ( + options: ClientConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} + +export declare namespace Client { + export interface OptionsInterceptors { + Client: readonly Dispatcher.DispatchInterceptor[]; + } + export interface Options { + /** TODO */ + interceptors?: OptionsInterceptors; + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */ + socketTimeout?: never; + /** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */ + requestTimeout?: never; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */ + idleTimeout?: never; + /** @deprecated unsupported keepAlive, use pipelining=0 instead */ + keepAlive?: never; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */ + maxKeepAliveTimeout?: never; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** @deprecated use the connect option instead */ + tls?: never; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + connect?: Partial | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. + * @default false + */ + allowH2?: boolean; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number; + /** + * @description Sets the HTTP/2 stream-level flow-control window size (SETTINGS_INITIAL_WINDOW_SIZE). + * @default 262144 + */ + initialWindowSize?: number; + /** + * @description Sets the HTTP/2 connection-level flow-control window size (ClientHttp2Session.setLocalWindowSize). + * @default 524288 + */ + connectionWindowSize?: number; + } + export interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number + } +} + +export default Client diff --git a/node_modules/undici/types/connector.d.ts b/node_modules/undici/types/connector.d.ts new file mode 100644 index 000000000..3376df739 --- /dev/null +++ b/node_modules/undici/types/connector.d.ts @@ -0,0 +1,34 @@ +import { TLSSocket, ConnectionOptions } from 'node:tls' +import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'node:net' + +export default buildConnector +declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector + +declare namespace buildConnector { + export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { + allowH2?: boolean; + maxCachedSessions?: number | null; + socketPath?: string | null; + timeout?: number | null; + port?: number; + keepAlive?: boolean | null; + keepAliveInitialDelay?: number | null; + } + + export interface Options { + hostname: string + host?: string + protocol: string + port: string + servername?: string + localAddress?: string | null + httpSocket?: Socket + } + + export type Callback = (...args: CallbackArgs) => void + type CallbackArgs = [null, Socket | TLSSocket] | [Error, null] + + export interface connector { + (options: buildConnector.Options, callback: buildConnector.Callback): void + } +} diff --git a/node_modules/undici/types/content-type.d.ts b/node_modules/undici/types/content-type.d.ts new file mode 100644 index 000000000..f2a87f1b7 --- /dev/null +++ b/node_modules/undici/types/content-type.d.ts @@ -0,0 +1,21 @@ +/// + +interface MIMEType { + type: string + subtype: string + parameters: Map + essence: string +} + +/** + * Parse a string to a {@link MIMEType} object. Returns `failure` if the string + * couldn't be parsed. + * @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type + */ +export function parseMIMEType (input: string): 'failure' | MIMEType + +/** + * Convert a MIMEType object to a string. + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +export function serializeAMimeType (mimeType: MIMEType): string diff --git a/node_modules/undici/types/cookies.d.ts b/node_modules/undici/types/cookies.d.ts new file mode 100644 index 000000000..f746d3585 --- /dev/null +++ b/node_modules/undici/types/cookies.d.ts @@ -0,0 +1,30 @@ +/// + +import type { Headers } from './fetch' + +export interface Cookie { + name: string + value: string + expires?: Date | number + maxAge?: number + domain?: string + path?: string + secure?: boolean + httpOnly?: boolean + sameSite?: 'Strict' | 'Lax' | 'None' + unparsed?: string[] +} + +export function deleteCookie ( + headers: Headers, + name: string, + attributes?: { name?: string, domain?: string } +): void + +export function getCookies (headers: Headers): Record + +export function getSetCookies (headers: Headers): Cookie[] + +export function setCookie (headers: Headers, cookie: Cookie): void + +export function parseCookie (cookie: string): Cookie | null diff --git a/node_modules/undici/types/diagnostics-channel.d.ts b/node_modules/undici/types/diagnostics-channel.d.ts new file mode 100644 index 000000000..3c6a5299d --- /dev/null +++ b/node_modules/undici/types/diagnostics-channel.d.ts @@ -0,0 +1,74 @@ +import { Socket } from 'node:net' +import { URL } from 'node:url' +import buildConnector from './connector' +import Dispatcher from './dispatcher' + +declare namespace DiagnosticsChannel { + interface Request { + origin?: string | URL; + completed: boolean; + method?: Dispatcher.HttpMethod; + path: string; + headers: any; + } + interface Response { + statusCode: number; + statusText: string; + headers: Array; + } + interface ConnectParams { + host: URL['host']; + hostname: URL['hostname']; + protocol: URL['protocol']; + port: URL['port']; + servername: string | null; + } + type Connector = buildConnector.connector + export interface RequestCreateMessage { + request: Request; + } + export interface RequestBodySentMessage { + request: Request; + } + + export interface RequestBodyChunkSentMessage { + request: Request; + chunk: Uint8Array | string; + } + export interface RequestBodyChunkReceivedMessage { + request: Request; + chunk: Buffer; + } + export interface RequestHeadersMessage { + request: Request; + response: Response; + } + export interface RequestTrailersMessage { + request: Request; + trailers: Array; + } + export interface RequestErrorMessage { + request: Request; + error: Error; + } + export interface ClientSendHeadersMessage { + request: Request; + headers: string; + socket: Socket; + } + export interface ClientBeforeConnectMessage { + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectedMessage { + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectErrorMessage { + error: Error; + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } +} diff --git a/node_modules/undici/types/dispatcher.d.ts b/node_modules/undici/types/dispatcher.d.ts new file mode 100644 index 000000000..13b33ecec --- /dev/null +++ b/node_modules/undici/types/dispatcher.d.ts @@ -0,0 +1,276 @@ +import { URL } from 'node:url' +import { Duplex, Readable, Writable } from 'node:stream' +import { EventEmitter } from 'node:events' +import { Blob } from 'node:buffer' +import { IncomingHttpHeaders } from './header' +import BodyReadable from './readable' +import { FormData } from './formdata' +import Errors from './errors' +import { Autocomplete } from './utility' + +type AbortSignal = unknown + +export default Dispatcher + +export type UndiciHeaders = Record | IncomingHttpHeaders | string[] | Iterable<[string, string | string[] | undefined]> | null + +/** Dispatcher is the core API used to dispatch requests. */ +declare class Dispatcher extends EventEmitter { + /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */ + dispatch (options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean + /** Starts two-way communications with the requested resource. */ + connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void + connect(options: Dispatcher.ConnectOptions): Promise> + /** Compose a chain of dispatchers */ + compose (dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher + compose (...dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher + /** Performs an HTTP request. */ + request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void + request(options: Dispatcher.RequestOptions): Promise> + /** For easy use with `stream.pipeline`. */ + pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex + /** A faster version of `Dispatcher.request`. */ + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise> + /** Upgrade to a different protocol. */ + upgrade (options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void + upgrade (options: Dispatcher.UpgradeOptions): Promise + /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */ + close (callback: () => void): void + close (): Promise + /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */ + destroy (err: Error | null, callback: () => void): void + destroy (callback: () => void): void + destroy (err: Error | null): Promise + destroy (): Promise + + on (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + on (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + on (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + on (eventName: 'drain', callback: (origin: URL) => void): this + + once (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + once (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + once (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + once (eventName: 'drain', callback: (origin: URL) => void): this + + off (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + off (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + off (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + off (eventName: 'drain', callback: (origin: URL) => void): this + + addListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + addListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + addListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + addListener (eventName: 'drain', callback: (origin: URL) => void): this + + removeListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + removeListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + removeListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + removeListener (eventName: 'drain', callback: (origin: URL) => void): this + + prependListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + prependListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependListener (eventName: 'drain', callback: (origin: URL) => void): this + + prependOnceListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + prependOnceListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependOnceListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependOnceListener (eventName: 'drain', callback: (origin: URL) => void): this + + listeners (eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + listeners (eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + listeners (eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + listeners (eventName: 'drain'): ((origin: URL) => void)[] + + rawListeners (eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + rawListeners (eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + rawListeners (eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + rawListeners (eventName: 'drain'): ((origin: URL) => void)[] + + emit (eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean + emit (eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean + emit (eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean + emit (eventName: 'drain', origin: URL): boolean +} + +declare namespace Dispatcher { + export interface ComposedDispatcher extends Dispatcher {} + export type Dispatch = Dispatcher['dispatch'] + export type DispatcherComposeInterceptor = (dispatch: Dispatch) => Dispatch + export interface DispatchOptions { + origin?: string | URL; + path: string; + method: HttpMethod; + /** Default: `null` */ + body?: string | Buffer | Uint8Array | Readable | null | FormData; + /** Default: `null` */ + headers?: UndiciHeaders; + /** Query string params to be embedded in the request URL. Default: `null` */ + query?: Record; + /** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */ + idempotent?: boolean; + /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. Defaults to `method !== 'HEAD'`. */ + blocking?: boolean; + /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */ + upgrade?: boolean | string | null; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */ + headersTimeout?: number | null; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */ + bodyTimeout?: number | null; + /** Whether the request should stablish a keep-alive or not. Default `false` */ + reset?: boolean; + /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */ + throwOnError?: boolean; + /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server */ + expectContinue?: boolean; + } + export interface ConnectOptions { + origin: string | URL; + path: string; + /** Default: `null` */ + headers?: UndiciHeaders; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** This argument parameter is passed through to `ConnectData` */ + opaque?: TOpaque; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + responseHeaders?: 'raw' | null; + } + export interface RequestOptions extends DispatchOptions { + /** Default: `null` */ + opaque?: TOpaque; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + onInfo?: (info: { statusCode: number, headers: Record }) => void; + /** Default: `null` */ + responseHeaders?: 'raw' | null; + /** Default: `64 KiB` */ + highWaterMark?: number; + } + export interface PipelineOptions extends RequestOptions { + /** `true` if the `handler` will return an object stream. Default: `false` */ + objectMode?: boolean; + } + export interface UpgradeOptions { + path: string; + /** Default: `'GET'` */ + method?: string; + /** Default: `null` */ + headers?: UndiciHeaders; + /** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */ + protocol?: string; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + responseHeaders?: 'raw' | null; + } + export interface ConnectData { + statusCode: number; + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: TOpaque; + } + export interface ResponseData { + statusCode: number; + headers: IncomingHttpHeaders; + body: BodyReadable & BodyMixin; + trailers: Record; + opaque: TOpaque; + context: object; + } + export interface PipelineHandlerData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: TOpaque; + body: BodyReadable; + context: object; + } + export interface StreamData { + opaque: TOpaque; + trailers: Record; + } + export interface UpgradeData { + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: TOpaque; + } + export interface StreamFactoryData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: TOpaque; + context: object; + } + export type StreamFactory = (data: StreamFactoryData) => Writable + + export interface DispatchController { + get aborted () : boolean + get paused () : boolean + get reason () : Error | null + abort (reason: Error): void + pause(): void + resume(): void + } + + export interface DispatchHandler { + onRequestStart?(controller: DispatchController, context: any): void; + onRequestUpgrade?(controller: DispatchController, statusCode: number, headers: IncomingHttpHeaders, socket: Duplex): void; + onResponseStart?(controller: DispatchController, statusCode: number, headers: IncomingHttpHeaders, statusMessage?: string): void; + onResponseData?(controller: DispatchController, chunk: Buffer): void; + onResponseEnd?(controller: DispatchController, trailers: IncomingHttpHeaders): void; + onResponseError?(controller: DispatchController, error: Error): void; + + /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */ + /** @deprecated */ + onConnect?(abort: (err?: Error) => void): void; + /** Invoked when an error has occurred. */ + /** @deprecated */ + onError?(err: Error): void; + /** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */ + /** @deprecated */ + onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void; + /** Invoked when response is received, before headers have been read. **/ + /** @deprecated */ + onResponseStarted?(): void; + /** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */ + /** @deprecated */ + onHeaders?(statusCode: number, headers: Buffer[], resume: () => void, statusText: string): boolean; + /** Invoked when response payload data is received. */ + /** @deprecated */ + onData?(chunk: Buffer): boolean; + /** Invoked when response payload and trailers have been received and the request has completed. */ + /** @deprecated */ + onComplete?(trailers: string[] | null): void; + /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */ + /** @deprecated */ + onBodySent?(chunkSize: number, totalBytesSent: number): void; + } + export type PipelineHandler = (data: PipelineHandlerData) => Readable + export type HttpMethod = Autocomplete<'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'> + + /** + * @link https://fetch.spec.whatwg.org/#body-mixin + */ + interface BodyMixin { + readonly body?: never; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + bytes(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; + } + + export interface DispatchInterceptor { + (dispatch: Dispatch): Dispatch + } +} diff --git a/node_modules/undici/types/env-http-proxy-agent.d.ts b/node_modules/undici/types/env-http-proxy-agent.d.ts new file mode 100644 index 000000000..1733d7f6e --- /dev/null +++ b/node_modules/undici/types/env-http-proxy-agent.d.ts @@ -0,0 +1,22 @@ +import Agent from './agent' +import ProxyAgent from './proxy-agent' +import Dispatcher from './dispatcher' + +export default EnvHttpProxyAgent + +declare class EnvHttpProxyAgent extends Dispatcher { + constructor (opts?: EnvHttpProxyAgent.Options) + + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean +} + +declare namespace EnvHttpProxyAgent { + export interface Options extends Omit { + /** Overrides the value of the HTTP_PROXY environment variable */ + httpProxy?: string; + /** Overrides the value of the HTTPS_PROXY environment variable */ + httpsProxy?: string; + /** Overrides the value of the NO_PROXY environment variable */ + noProxy?: string; + } +} diff --git a/node_modules/undici/types/errors.d.ts b/node_modules/undici/types/errors.d.ts new file mode 100644 index 000000000..fbf319556 --- /dev/null +++ b/node_modules/undici/types/errors.d.ts @@ -0,0 +1,161 @@ +import { IncomingHttpHeaders } from './header' +import Client from './client' + +export default Errors + +declare namespace Errors { + export class UndiciError extends Error { + name: string + code: string + } + + /** Connect timeout error. */ + export class ConnectTimeoutError extends UndiciError { + name: 'ConnectTimeoutError' + code: 'UND_ERR_CONNECT_TIMEOUT' + } + + /** A header exceeds the `headersTimeout` option. */ + export class HeadersTimeoutError extends UndiciError { + name: 'HeadersTimeoutError' + code: 'UND_ERR_HEADERS_TIMEOUT' + } + + /** Headers overflow error. */ + export class HeadersOverflowError extends UndiciError { + name: 'HeadersOverflowError' + code: 'UND_ERR_HEADERS_OVERFLOW' + } + + /** A body exceeds the `bodyTimeout` option. */ + export class BodyTimeoutError extends UndiciError { + name: 'BodyTimeoutError' + code: 'UND_ERR_BODY_TIMEOUT' + } + + export class ResponseError extends UndiciError { + constructor ( + message: string, + code: number, + options: { + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + } + ) + name: 'ResponseError' + code: 'UND_ERR_RESPONSE' + statusCode: number + body: null | Record | string + headers: IncomingHttpHeaders | string[] | null + } + + /** Passed an invalid argument. */ + export class InvalidArgumentError extends UndiciError { + name: 'InvalidArgumentError' + code: 'UND_ERR_INVALID_ARG' + } + + /** Returned an invalid value. */ + export class InvalidReturnValueError extends UndiciError { + name: 'InvalidReturnValueError' + code: 'UND_ERR_INVALID_RETURN_VALUE' + } + + /** The request has been aborted by the user. */ + export class RequestAbortedError extends UndiciError { + name: 'AbortError' + code: 'UND_ERR_ABORTED' + } + + /** Expected error with reason. */ + export class InformationalError extends UndiciError { + name: 'InformationalError' + code: 'UND_ERR_INFO' + } + + /** Request body length does not match content-length header. */ + export class RequestContentLengthMismatchError extends UndiciError { + name: 'RequestContentLengthMismatchError' + code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' + } + + /** Response body length does not match content-length header. */ + export class ResponseContentLengthMismatchError extends UndiciError { + name: 'ResponseContentLengthMismatchError' + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } + + /** Trying to use a destroyed client. */ + export class ClientDestroyedError extends UndiciError { + name: 'ClientDestroyedError' + code: 'UND_ERR_DESTROYED' + } + + /** Trying to use a closed client. */ + export class ClientClosedError extends UndiciError { + name: 'ClientClosedError' + code: 'UND_ERR_CLOSED' + } + + /** There is an error with the socket. */ + export class SocketError extends UndiciError { + name: 'SocketError' + code: 'UND_ERR_SOCKET' + socket: Client.SocketInfo | null + } + + /** Encountered unsupported functionality. */ + export class NotSupportedError extends UndiciError { + name: 'NotSupportedError' + code: 'UND_ERR_NOT_SUPPORTED' + } + + /** No upstream has been added to the BalancedPool. */ + export class BalancedPoolMissingUpstreamError extends UndiciError { + name: 'MissingUpstreamError' + code: 'UND_ERR_BPL_MISSING_UPSTREAM' + } + + export class HTTPParserError extends UndiciError { + name: 'HTTPParserError' + code: string + } + + /** The response exceed the length allowed. */ + export class ResponseExceededMaxSizeError extends UndiciError { + name: 'ResponseExceededMaxSizeError' + code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } + + export class RequestRetryError extends UndiciError { + constructor ( + message: string, + statusCode: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ) + name: 'RequestRetryError' + code: 'UND_ERR_REQ_RETRY' + statusCode: number + data: { + count: number; + } + + headers: Record + } + + export class SecureProxyConnectionError extends UndiciError { + constructor ( + cause?: Error, + message?: string, + options?: Record + ) + name: 'SecureProxyConnectionError' + code: 'UND_ERR_PRX_TLS' + } + + class MaxOriginsReachedError extends UndiciError { + name: 'MaxOriginsReachedError' + code: 'UND_ERR_MAX_ORIGINS_REACHED' + } +} diff --git a/node_modules/undici/types/eventsource.d.ts b/node_modules/undici/types/eventsource.d.ts new file mode 100644 index 000000000..081ca09ae --- /dev/null +++ b/node_modules/undici/types/eventsource.d.ts @@ -0,0 +1,66 @@ +import { MessageEvent, ErrorEvent } from './websocket' +import Dispatcher from './dispatcher' + +import { + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' + +interface EventSourceEventMap { + error: ErrorEvent + message: MessageEvent + open: Event +} + +interface EventSource extends EventTarget { + close(): void + readonly CLOSED: 2 + readonly CONNECTING: 0 + readonly OPEN: 1 + onerror: ((this: EventSource, ev: ErrorEvent) => any) | null + onmessage: ((this: EventSource, ev: MessageEvent) => any) | null + onopen: ((this: EventSource, ev: Event) => any) | null + readonly readyState: 0 | 1 | 2 + readonly url: string + readonly withCredentials: boolean + + addEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const EventSource: { + prototype: EventSource + new (url: string | URL, init?: EventSourceInit): EventSource + readonly CLOSED: 2 + readonly CONNECTING: 0 + readonly OPEN: 1 +} + +interface EventSourceInit { + withCredentials?: boolean + // @deprecated use `node.dispatcher` instead + dispatcher?: Dispatcher + node?: { + dispatcher?: Dispatcher + reconnectionTime?: number + } +} diff --git a/node_modules/undici/types/fetch.d.ts b/node_modules/undici/types/fetch.d.ts new file mode 100644 index 000000000..ec33e5b2f --- /dev/null +++ b/node_modules/undici/types/fetch.d.ts @@ -0,0 +1,211 @@ +// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license) +// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license) +/// + +import { Blob } from 'node:buffer' +import { URL, URLSearchParams } from 'node:url' +import { ReadableStream } from 'node:stream/web' +import { FormData } from './formdata' +import { HeaderRecord } from './header' +import Dispatcher from './dispatcher' + +export type RequestInfo = string | URL | Request + +export declare function fetch ( + input: RequestInfo, + init?: RequestInit +): Promise + +export type BodyInit = + | ArrayBuffer + | AsyncIterable + | Blob + | FormData + | Iterable + | NodeJS.ArrayBufferView + | URLSearchParams + | null + | string + +export class BodyMixin { + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly bytes: () => Promise + /** + * @deprecated This method is not recommended for parsing multipart/form-data bodies in server environments. + * It is recommended to use a library such as [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy) as follows: + * + * @example + * ```js + * import { Busboy } from '@fastify/busboy' + * import { Readable } from 'node:stream' + * + * const response = await fetch('...') + * const busboy = new Busboy({ headers: { 'content-type': response.headers.get('content-type') } }) + * + * // handle events emitted from `busboy` + * + * Readable.fromWeb(response.body).pipe(busboy) + * ``` + */ + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise +} + +export interface SpecIterator { + next(...args: [] | [TNext]): IteratorResult; +} + +export interface SpecIterableIterator extends SpecIterator { + [Symbol.iterator](): SpecIterableIterator; +} + +export interface SpecIterable { + [Symbol.iterator](): SpecIterator; +} + +export type HeadersInit = [string, string][] | HeaderRecord | Headers + +export declare class Headers implements SpecIterable<[string, string]> { + constructor (init?: HeadersInit) + readonly append: (name: string, value: string) => void + readonly delete: (name: string) => void + readonly get: (name: string) => string | null + readonly has: (name: string) => boolean + readonly set: (name: string, value: string) => void + readonly getSetCookie: () => string[] + readonly forEach: ( + callbackfn: (value: string, key: string, iterable: Headers) => void, + thisArg?: unknown + ) => void + + readonly keys: () => SpecIterableIterator + readonly values: () => SpecIterableIterator + readonly entries: () => SpecIterableIterator<[string, string]> + readonly [Symbol.iterator]: () => SpecIterableIterator<[string, string]> +} + +export type RequestCache = + | 'default' + | 'force-cache' + | 'no-cache' + | 'no-store' + | 'only-if-cached' + | 'reload' + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +type RequestDestination = + | '' + | 'audio' + | 'audioworklet' + | 'document' + | 'embed' + | 'font' + | 'image' + | 'manifest' + | 'object' + | 'paintworklet' + | 'report' + | 'script' + | 'sharedworker' + | 'style' + | 'track' + | 'video' + | 'worker' + | 'xslt' + +export interface RequestInit { + body?: BodyInit | null + cache?: RequestCache + credentials?: RequestCredentials + dispatcher?: Dispatcher + duplex?: RequestDuplex + headers?: HeadersInit + integrity?: string + keepalive?: boolean + method?: string + mode?: RequestMode + redirect?: RequestRedirect + referrer?: string + referrerPolicy?: ReferrerPolicy + signal?: AbortSignal | null + window?: null +} + +export type ReferrerPolicy = + | '' + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url' + +export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin' + +export type RequestRedirect = 'error' | 'follow' | 'manual' + +export type RequestDuplex = 'half' + +export declare class Request extends BodyMixin { + constructor (input: RequestInfo, init?: RequestInit) + + readonly cache: RequestCache + readonly credentials: RequestCredentials + readonly destination: RequestDestination + readonly headers: Headers + readonly integrity: string + readonly method: string + readonly mode: RequestMode + readonly redirect: RequestRedirect + readonly referrer: string + readonly referrerPolicy: ReferrerPolicy + readonly url: string + + readonly keepalive: boolean + readonly signal: AbortSignal + readonly duplex: RequestDuplex + + readonly clone: () => Request +} + +export interface ResponseInit { + readonly status?: number + readonly statusText?: string + readonly headers?: HeadersInit +} + +export type ResponseType = + | 'basic' + | 'cors' + | 'default' + | 'error' + | 'opaque' + | 'opaqueredirect' + +export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308 + +export declare class Response extends BodyMixin { + constructor (body?: BodyInit, init?: ResponseInit) + + readonly headers: Headers + readonly ok: boolean + readonly status: number + readonly statusText: string + readonly type: ResponseType + readonly url: string + readonly redirected: boolean + + readonly clone: () => Response + + static error (): Response + static json (data: any, init?: ResponseInit): Response + static redirect (url: string | URL, status?: ResponseRedirectStatus): Response +} diff --git a/node_modules/undici/types/formdata.d.ts b/node_modules/undici/types/formdata.d.ts new file mode 100644 index 000000000..b9819a7e7 --- /dev/null +++ b/node_modules/undici/types/formdata.d.ts @@ -0,0 +1,108 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT) +/// + +import { File } from 'node:buffer' +import { SpecIterableIterator } from './fetch' + +/** + * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. + */ +declare type FormDataEntryValue = string | File + +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch(). + */ +export declare class FormData { + /** + * Appends a new value onto an existing key inside a FormData object, + * or adds the key if it does not already exist. + * + * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + */ + append (name: string, value: unknown, fileName?: string): void + + /** + * Set a new value for an existing key inside FormData, + * or add the new field if it does not already exist. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + * + */ + set (name: string, value: unknown, fileName?: string): void + + /** + * Returns the first value associated with a given key from within a `FormData` object. + * If you expect multiple values and want all of them, use the `getAll()` method instead. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null. + */ + get (name: string): FormDataEntryValue | null + + /** + * Returns all the values associated with a given key from within a `FormData` object. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. + */ + getAll (name: string): FormDataEntryValue[] + + /** + * Returns a boolean stating whether a `FormData` object contains a certain key. + * + * @param name A string representing the name of the key you want to test for. + * + * @return A boolean value. + */ + has (name: string): boolean + + /** + * Deletes a key and its value(s) from a `FormData` object. + * + * @param name The name of the key you want to delete. + */ + delete (name: string): void + + /** + * Executes given callback function for each field of the FormData instance + */ + forEach: ( + callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void, + thisArg?: unknown + ) => void + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. + * Each key is a `string`. + */ + keys: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. + * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + values: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. + * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + entries: () => SpecIterableIterator<[string, FormDataEntryValue]> + + /** + * An alias for FormData#entries() + */ + [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]> + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici/types/global-dispatcher.d.ts b/node_modules/undici/types/global-dispatcher.d.ts new file mode 100644 index 000000000..2760e136d --- /dev/null +++ b/node_modules/undici/types/global-dispatcher.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from './dispatcher' + +declare function setGlobalDispatcher (dispatcher: DispatcherImplementation): void +declare function getGlobalDispatcher (): Dispatcher + +export { + getGlobalDispatcher, + setGlobalDispatcher +} diff --git a/node_modules/undici/types/global-origin.d.ts b/node_modules/undici/types/global-origin.d.ts new file mode 100644 index 000000000..265769b7b --- /dev/null +++ b/node_modules/undici/types/global-origin.d.ts @@ -0,0 +1,7 @@ +declare function setGlobalOrigin (origin: string | URL | undefined): void +declare function getGlobalOrigin (): URL | undefined + +export { + setGlobalOrigin, + getGlobalOrigin +} diff --git a/node_modules/undici/types/h2c-client.d.ts b/node_modules/undici/types/h2c-client.d.ts new file mode 100644 index 000000000..7b9744970 --- /dev/null +++ b/node_modules/undici/types/h2c-client.d.ts @@ -0,0 +1,73 @@ +import { URL } from 'node:url' +import Dispatcher from './dispatcher' +import buildConnector from './connector' + +type H2ClientOptions = Omit + +/** + * A basic H2C client, mapped on top a single TCP connection. Pipelining is disabled by default. + */ +export class H2CClient extends Dispatcher { + constructor (url: string | URL, options?: H2CClient.Options) + /** Property to get and set the pipelining factor. */ + pipelining: number + /** `true` after `client.close()` has been called. */ + closed: boolean + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean + + // Override dispatcher APIs. + override connect ( + options: H2ClientOptions + ): Promise + override connect ( + options: H2ClientOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} + +export declare namespace H2CClient { + export interface Options { + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + connect?: Omit, 'allowH2'> | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number + } +} + +export default H2CClient diff --git a/node_modules/undici/types/handlers.d.ts b/node_modules/undici/types/handlers.d.ts new file mode 100644 index 000000000..8007dbf8e --- /dev/null +++ b/node_modules/undici/types/handlers.d.ts @@ -0,0 +1,15 @@ +import Dispatcher from './dispatcher' + +export declare class RedirectHandler implements Dispatcher.DispatchHandler { + constructor ( + dispatch: Dispatcher.Dispatch, + maxRedirections: number, + opts: Dispatcher.DispatchOptions, + handler: Dispatcher.DispatchHandler, + redirectionLimitReached: boolean + ) +} + +export declare class DecoratorHandler implements Dispatcher.DispatchHandler { + constructor (handler: Dispatcher.DispatchHandler) +} diff --git a/node_modules/undici/types/header.d.ts b/node_modules/undici/types/header.d.ts new file mode 100644 index 000000000..efd7b1dd0 --- /dev/null +++ b/node_modules/undici/types/header.d.ts @@ -0,0 +1,160 @@ +import { Autocomplete } from './utility' + +/** + * The header type declaration of `undici`. + */ +export type IncomingHttpHeaders = Record + +type HeaderNames = Autocomplete< + | 'Accept' + | 'Accept-CH' + | 'Accept-Charset' + | 'Accept-Encoding' + | 'Accept-Language' + | 'Accept-Patch' + | 'Accept-Post' + | 'Accept-Ranges' + | 'Access-Control-Allow-Credentials' + | 'Access-Control-Allow-Headers' + | 'Access-Control-Allow-Methods' + | 'Access-Control-Allow-Origin' + | 'Access-Control-Expose-Headers' + | 'Access-Control-Max-Age' + | 'Access-Control-Request-Headers' + | 'Access-Control-Request-Method' + | 'Age' + | 'Allow' + | 'Alt-Svc' + | 'Alt-Used' + | 'Authorization' + | 'Cache-Control' + | 'Clear-Site-Data' + | 'Connection' + | 'Content-Disposition' + | 'Content-Encoding' + | 'Content-Language' + | 'Content-Length' + | 'Content-Location' + | 'Content-Range' + | 'Content-Security-Policy' + | 'Content-Security-Policy-Report-Only' + | 'Content-Type' + | 'Cookie' + | 'Cross-Origin-Embedder-Policy' + | 'Cross-Origin-Opener-Policy' + | 'Cross-Origin-Resource-Policy' + | 'Date' + | 'Device-Memory' + | 'ETag' + | 'Expect' + | 'Expect-CT' + | 'Expires' + | 'Forwarded' + | 'From' + | 'Host' + | 'If-Match' + | 'If-Modified-Since' + | 'If-None-Match' + | 'If-Range' + | 'If-Unmodified-Since' + | 'Keep-Alive' + | 'Last-Modified' + | 'Link' + | 'Location' + | 'Max-Forwards' + | 'Origin' + | 'Permissions-Policy' + | 'Priority' + | 'Proxy-Authenticate' + | 'Proxy-Authorization' + | 'Range' + | 'Referer' + | 'Referrer-Policy' + | 'Retry-After' + | 'Sec-Fetch-Dest' + | 'Sec-Fetch-Mode' + | 'Sec-Fetch-Site' + | 'Sec-Fetch-User' + | 'Sec-Purpose' + | 'Sec-WebSocket-Accept' + | 'Server' + | 'Server-Timing' + | 'Service-Worker-Navigation-Preload' + | 'Set-Cookie' + | 'SourceMap' + | 'Strict-Transport-Security' + | 'TE' + | 'Timing-Allow-Origin' + | 'Trailer' + | 'Transfer-Encoding' + | 'Upgrade' + | 'Upgrade-Insecure-Requests' + | 'User-Agent' + | 'Vary' + | 'Via' + | 'WWW-Authenticate' + | 'X-Content-Type-Options' + | 'X-Frame-Options' +> + +type IANARegisteredMimeType = Autocomplete< + | 'audio/aac' + | 'video/x-msvideo' + | 'image/avif' + | 'video/av1' + | 'application/octet-stream' + | 'image/bmp' + | 'text/css' + | 'text/csv' + | 'application/vnd.ms-fontobject' + | 'application/epub+zip' + | 'image/gif' + | 'application/gzip' + | 'text/html' + | 'image/x-icon' + | 'text/calendar' + | 'image/jpeg' + | 'text/javascript' + | 'application/json' + | 'application/ld+json' + | 'audio/x-midi' + | 'audio/mpeg' + | 'video/mp4' + | 'video/mpeg' + | 'audio/ogg' + | 'video/ogg' + | 'application/ogg' + | 'audio/opus' + | 'font/otf' + | 'application/pdf' + | 'image/png' + | 'application/rtf' + | 'image/svg+xml' + | 'image/tiff' + | 'video/mp2t' + | 'font/ttf' + | 'text/plain' + | 'application/wasm' + | 'video/webm' + | 'audio/webm' + | 'image/webp' + | 'font/woff' + | 'font/woff2' + | 'application/xhtml+xml' + | 'application/xml' + | 'application/zip' + | 'video/3gpp' + | 'video/3gpp2' + | 'model/gltf+json' + | 'model/gltf-binary' +> + +type KnownHeaderValues = { + 'content-type': IANARegisteredMimeType +} + +export type HeaderRecord = { + [K in HeaderNames | Lowercase]?: Lowercase extends keyof KnownHeaderValues + ? KnownHeaderValues[Lowercase] + : string +} diff --git a/node_modules/undici/types/index.d.ts b/node_modules/undici/types/index.d.ts new file mode 100644 index 000000000..78ddeaae7 --- /dev/null +++ b/node_modules/undici/types/index.d.ts @@ -0,0 +1,88 @@ +import Dispatcher from './dispatcher' +import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher' +import { setGlobalOrigin, getGlobalOrigin } from './global-origin' +import Pool from './pool' +import { RedirectHandler, DecoratorHandler } from './handlers' + +import BalancedPool from './balanced-pool' +import RoundRobinPool from './round-robin-pool' +import Client from './client' +import H2CClient from './h2c-client' +import buildConnector from './connector' +import errors from './errors' +import Agent from './agent' +import MockClient from './mock-client' +import MockPool from './mock-pool' +import MockAgent from './mock-agent' +import { SnapshotAgent } from './snapshot-agent' +import { MockCallHistory, MockCallHistoryLog } from './mock-call-history' +import mockErrors from './mock-errors' +import ProxyAgent from './proxy-agent' +import EnvHttpProxyAgent from './env-http-proxy-agent' +import RetryHandler from './retry-handler' +import RetryAgent from './retry-agent' +import { request, pipeline, stream, connect, upgrade } from './api' +import interceptors from './interceptors' + +import CacheInterceptor from './cache-interceptor' +declare const cacheStores: { + MemoryCacheStore: typeof CacheInterceptor.MemoryCacheStore; + SqliteCacheStore: typeof CacheInterceptor.SqliteCacheStore; +} + +export * from './util' +export * from './cookies' +export * from './eventsource' +export * from './fetch' +export * from './formdata' +export * from './diagnostics-channel' +export * from './websocket' +export * from './content-type' +export * from './cache' +export { Interceptable } from './mock-interceptor' + +declare function globalThisInstall (): void + +export { Dispatcher, BalancedPool, RoundRobinPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, cacheStores, MockClient, MockPool, MockAgent, SnapshotAgent, MockCallHistory, MockCallHistoryLog, mockErrors, ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent, H2CClient, globalThisInstall as install } +export default Undici + +declare namespace Undici { + const Dispatcher: typeof import('./dispatcher').default + const Pool: typeof import('./pool').default + const RedirectHandler: typeof import ('./handlers').RedirectHandler + const DecoratorHandler: typeof import ('./handlers').DecoratorHandler + const RetryHandler: typeof import ('./retry-handler').default + const BalancedPool: typeof import('./balanced-pool').default + const RoundRobinPool: typeof import('./round-robin-pool').default + const Client: typeof import('./client').default + const H2CClient: typeof import('./h2c-client').default + const buildConnector: typeof import('./connector').default + const errors: typeof import('./errors').default + const Agent: typeof import('./agent').default + const setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher + const getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher + const request: typeof import('./api').request + const stream: typeof import('./api').stream + const pipeline: typeof import('./api').pipeline + const connect: typeof import('./api').connect + const upgrade: typeof import('./api').upgrade + const MockClient: typeof import('./mock-client').default + const MockPool: typeof import('./mock-pool').default + const MockAgent: typeof import('./mock-agent').default + const SnapshotAgent: typeof import('./snapshot-agent').SnapshotAgent + const MockCallHistory: typeof import('./mock-call-history').MockCallHistory + const MockCallHistoryLog: typeof import('./mock-call-history').MockCallHistoryLog + const mockErrors: typeof import('./mock-errors').default + const fetch: typeof import('./fetch').fetch + const Headers: typeof import('./fetch').Headers + const Response: typeof import('./fetch').Response + const Request: typeof import('./fetch').Request + const FormData: typeof import('./formdata').FormData + const caches: typeof import('./cache').caches + const interceptors: typeof import('./interceptors').default + const cacheStores: { + MemoryCacheStore: typeof import('./cache-interceptor').default.MemoryCacheStore, + SqliteCacheStore: typeof import('./cache-interceptor').default.SqliteCacheStore + } + const install: typeof globalThisInstall +} diff --git a/node_modules/undici/types/interceptors.d.ts b/node_modules/undici/types/interceptors.d.ts new file mode 100644 index 000000000..1dfd04f2a --- /dev/null +++ b/node_modules/undici/types/interceptors.d.ts @@ -0,0 +1,73 @@ +import CacheHandler from './cache-interceptor' +import Dispatcher from './dispatcher' +import RetryHandler from './retry-handler' +import { LookupOptions } from 'node:dns' + +export default Interceptors + +declare namespace Interceptors { + export type DumpInterceptorOpts = { maxSize?: number } + export type RetryInterceptorOpts = RetryHandler.RetryOptions + export type RedirectInterceptorOpts = { maxRedirections?: number } + export type DecompressInterceptorOpts = { + skipErrorResponses?: boolean + skipStatusCodes?: number[] + } + + export type ResponseErrorInterceptorOpts = { throwOnError: boolean } + export type CacheInterceptorOpts = CacheHandler.CacheOptions + + // DNS interceptor + export type DNSInterceptorRecord = { address: string, ttl: number, family: 4 | 6 } + export type DNSInterceptorOriginRecords = { records: { 4: { ips: DNSInterceptorRecord[] } | null, 6: { ips: DNSInterceptorRecord[] } | null } } + export type DNSStorage = { + size: number + get(origin: string): DNSInterceptorOriginRecords | null + set(origin: string, records: DNSInterceptorOriginRecords | null, options: { ttl: number }): void + delete(origin: string): void + full(): boolean + } + export type DNSInterceptorOpts = { + maxTTL?: number + maxItems?: number + lookup?: (origin: URL, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, addresses: DNSInterceptorRecord[]) => void) => void + pick?: (origin: URL, records: DNSInterceptorOriginRecords, affinity: 4 | 6) => DNSInterceptorRecord + dualStack?: boolean + affinity?: 4 | 6 + storage?: DNSStorage + } + + // Deduplicate interceptor + export type DeduplicateMethods = 'GET' | 'HEAD' | 'OPTIONS' | 'TRACE' + export type DeduplicateInterceptorOpts = { + /** + * The HTTP methods to deduplicate. + * Note: Only safe HTTP methods can be deduplicated. + * @default ['GET'] + */ + methods?: DeduplicateMethods[] + /** + * Header names that, if present in a request, will cause the request to skip deduplication. + * Header name matching is case-insensitive. + * @default [] + */ + skipHeaderNames?: string[] + /** + * Header names to exclude from the deduplication key. + * Requests with different values for these headers will still be deduplicated together. + * Useful for headers like `x-request-id` that vary per request but shouldn't affect deduplication. + * Header name matching is case-insensitive. + * @default [] + */ + excludeHeaderNames?: string[] + } + + export function dump (opts?: DumpInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function retry (opts?: RetryInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function redirect (opts?: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function decompress (opts?: DecompressInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function responseError (opts?: ResponseErrorInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function dns (opts?: DNSInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function cache (opts?: CacheInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function deduplicate (opts?: DeduplicateInterceptorOpts): Dispatcher.DispatcherComposeInterceptor +} diff --git a/node_modules/undici/types/mock-agent.d.ts b/node_modules/undici/types/mock-agent.d.ts new file mode 100644 index 000000000..330926be1 --- /dev/null +++ b/node_modules/undici/types/mock-agent.d.ts @@ -0,0 +1,68 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import MockDispatch = MockInterceptor.MockDispatch +import { MockCallHistory } from './mock-call-history' + +export default MockAgent + +interface PendingInterceptor extends MockDispatch { + origin: string; +} + +/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */ +declare class MockAgent extends Dispatcher { + constructor (options?: TMockAgentOptions) + /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */ + get(origin: string): TInterceptable + get(origin: RegExp): TInterceptable + get(origin: ((origin: string) => boolean)): TInterceptable + /** Dispatches a mocked request. */ + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean + /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */ + close (): Promise + /** Disables mocking in MockAgent. */ + deactivate (): void + /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */ + activate (): void + /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */ + enableNetConnect (): void + enableNetConnect (host: string): void + enableNetConnect (host: RegExp): void + enableNetConnect (host: ((host: string) => boolean)): void + /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */ + disableNetConnect (): void + /** get call history. returns the MockAgent call history or undefined if the option is not enabled. */ + getCallHistory (): MockCallHistory | undefined + /** clear every call history. Any MockCallHistoryLog will be deleted on the MockCallHistory instance */ + clearCallHistory (): void + /** Enable call history. Any subsequence calls will then be registered. */ + enableCallHistory (): this + /** Disable call history. Any subsequence calls will then not be registered. */ + disableCallHistory (): this + pendingInterceptors (): PendingInterceptor[] + assertNoPendingInterceptors (options?: { + pendingInterceptorsFormatter?: PendingInterceptorsFormatter; + }): void +} + +interface PendingInterceptorsFormatter { + format(pendingInterceptors: readonly PendingInterceptor[]): string; +} + +declare namespace MockAgent { + /** MockAgent options. */ + export interface Options extends Agent.Options { + /** A custom agent to be encapsulated by the MockAgent. */ + agent?: Dispatcher; + + /** Ignore trailing slashes in the path */ + ignoreTrailingSlash?: boolean; + + /** Accept URLs with search parameters using non standard syntaxes. default false */ + acceptNonStandardSearchParameters?: boolean; + + /** Enable call history. you can either call MockAgent.enableCallHistory(). default false */ + enableCallHistory?: boolean + } +} diff --git a/node_modules/undici/types/mock-call-history.d.ts b/node_modules/undici/types/mock-call-history.d.ts new file mode 100644 index 000000000..df07fa0dc --- /dev/null +++ b/node_modules/undici/types/mock-call-history.d.ts @@ -0,0 +1,111 @@ +import Dispatcher from './dispatcher' + +declare namespace MockCallHistoryLog { + /** request's configuration properties */ + export type MockCallHistoryLogProperties = 'protocol' | 'host' | 'port' | 'origin' | 'path' | 'hash' | 'fullUrl' | 'method' | 'searchParams' | 'body' | 'headers' +} + +/** a log reflecting request configuration */ +declare class MockCallHistoryLog { + constructor (requestInit: Dispatcher.DispatchOptions) + /** protocol used. ie. 'https:' or 'http:' etc... */ + protocol: string + /** request's host. */ + host: string + /** request's port. */ + port: string + /** request's origin. ie. https://localhost:3000. */ + origin: string + /** path. never contains searchParams. */ + path: string + /** request's hash. */ + hash: string + /** the full url requested. */ + fullUrl: string + /** request's method. */ + method: string + /** search params. */ + searchParams: Record + /** request's body */ + body: string | null | undefined + /** request's headers */ + headers: Record | null | undefined + + /** returns an Map of property / value pair */ + toMap (): Map | null | undefined> + + /** returns a string computed with all key value pair */ + toString (): string +} + +declare namespace MockCallHistory { + export type FilterCallsOperator = 'AND' | 'OR' + + /** modify the filtering behavior */ + export interface FilterCallsOptions { + /** the operator to apply when filtering. 'OR' will adds any MockCallHistoryLog matching any criteria given. 'AND' will adds only MockCallHistoryLog matching every criteria given. (default 'OR') */ + operator?: FilterCallsOperator | Lowercase + } + /** a function to be executed for filtering MockCallHistoryLog */ + export type FilterCallsFunctionCriteria = (log: MockCallHistoryLog) => boolean + + /** parameter to filter MockCallHistoryLog */ + export type FilterCallsParameter = string | RegExp | undefined | null + + /** an object to execute multiple filtering at once */ + export interface FilterCallsObjectCriteria extends Record { + /** filter by request protocol. ie https: */ + protocol?: FilterCallsParameter; + /** filter by request host. */ + host?: FilterCallsParameter; + /** filter by request port. */ + port?: FilterCallsParameter; + /** filter by request origin. */ + origin?: FilterCallsParameter; + /** filter by request path. */ + path?: FilterCallsParameter; + /** filter by request hash. */ + hash?: FilterCallsParameter; + /** filter by request fullUrl. */ + fullUrl?: FilterCallsParameter; + /** filter by request method. */ + method?: FilterCallsParameter; + } +} + +/** a call history to track requests configuration */ +declare class MockCallHistory { + constructor (name: string) + /** returns an array of MockCallHistoryLog. */ + calls (): Array + /** returns the first MockCallHistoryLog */ + firstCall (): MockCallHistoryLog | undefined + /** returns the last MockCallHistoryLog. */ + lastCall (): MockCallHistoryLog | undefined + /** returns the nth MockCallHistoryLog. */ + nthCall (position: number): MockCallHistoryLog | undefined + /** return all MockCallHistoryLog matching any of criteria given. if an object is used with multiple properties, you can change the operator to apply during filtering on options */ + filterCalls (criteria: MockCallHistory.FilterCallsFunctionCriteria | MockCallHistory.FilterCallsObjectCriteria | RegExp, options?: MockCallHistory.FilterCallsOptions): Array + /** return all MockCallHistoryLog matching the given protocol. if a string is given, it is matched with includes */ + filterCallsByProtocol (protocol: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given host. if a string is given, it is matched with includes */ + filterCallsByHost (host: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given port. if a string is given, it is matched with includes */ + filterCallsByPort (port: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given origin. if a string is given, it is matched with includes */ + filterCallsByOrigin (origin: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given path. if a string is given, it is matched with includes */ + filterCallsByPath (path: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given hash. if a string is given, it is matched with includes */ + filterCallsByHash (hash: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given fullUrl. if a string is given, it is matched with includes */ + filterCallsByFullUrl (fullUrl: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given method. if a string is given, it is matched with includes */ + filterCallsByMethod (method: MockCallHistory.FilterCallsParameter): Array + /** clear all MockCallHistoryLog on this MockCallHistory. */ + clear (): void + /** use it with for..of loop or spread operator */ + [Symbol.iterator]: () => Generator +} + +export { MockCallHistoryLog, MockCallHistory } diff --git a/node_modules/undici/types/mock-client.d.ts b/node_modules/undici/types/mock-client.d.ts new file mode 100644 index 000000000..702e82464 --- /dev/null +++ b/node_modules/undici/types/mock-client.d.ts @@ -0,0 +1,27 @@ +import Client from './client' +import Dispatcher from './dispatcher' +import MockAgent from './mock-agent' +import { MockInterceptor, Interceptable } from './mock-interceptor' + +export default MockClient + +/** MockClient extends the Client API and allows one to mock requests. */ +declare class MockClient extends Client implements Interceptable { + constructor (origin: string, options: MockClient.Options) + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept (options: MockInterceptor.Options): MockInterceptor + /** Dispatches a mocked request. */ + dispatch (options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandler): boolean + /** Closes the mock client and gracefully waits for enqueued requests to complete. */ + close (): Promise + /** Clean up all the prepared mocks. */ + cleanMocks (): void +} + +declare namespace MockClient { + /** MockClient options. */ + export interface Options extends Client.Options { + /** The agent to associate this MockClient with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici/types/mock-errors.d.ts b/node_modules/undici/types/mock-errors.d.ts new file mode 100644 index 000000000..eefeecd62 --- /dev/null +++ b/node_modules/undici/types/mock-errors.d.ts @@ -0,0 +1,12 @@ +import Errors from './errors' + +export default MockErrors + +declare namespace MockErrors { + /** The request does not match any registered mock dispatches. */ + export class MockNotMatchedError extends Errors.UndiciError { + constructor (message?: string) + name: 'MockNotMatchedError' + code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED' + } +} diff --git a/node_modules/undici/types/mock-interceptor.d.ts b/node_modules/undici/types/mock-interceptor.d.ts new file mode 100644 index 000000000..a48d715a4 --- /dev/null +++ b/node_modules/undici/types/mock-interceptor.d.ts @@ -0,0 +1,94 @@ +import { IncomingHttpHeaders } from './header' +import Dispatcher from './dispatcher' +import { BodyInit, Headers } from './fetch' + +/** The scope associated with a mock dispatch. */ +declare class MockScope { + constructor (mockDispatch: MockInterceptor.MockDispatch) + /** Delay a reply by a set amount of time in ms. */ + delay (waitInMs: number): MockScope + /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */ + persist (): MockScope + /** Define a reply for a set amount of matching requests. */ + times (repeatTimes: number): MockScope +} + +/** The interceptor for a Mock. */ +declare class MockInterceptor { + constructor (options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]) + /** Mock an undici request with the defined reply. */ + reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope + reply( + statusCode: number, + data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler, + responseOptions?: MockInterceptor.MockResponseOptions + ): MockScope + /** Mock an undici request by throwing the defined reply error. */ + replyWithError(error: TError): MockScope + /** Set default reply headers on the interceptor for subsequent mocked replies. */ + defaultReplyHeaders (headers: IncomingHttpHeaders): MockInterceptor + /** Set default reply trailers on the interceptor for subsequent mocked replies. */ + defaultReplyTrailers (trailers: Record): MockInterceptor + /** Set automatically calculated content-length header on subsequent mocked replies. */ + replyContentLength (): MockInterceptor +} + +declare namespace MockInterceptor { + /** MockInterceptor options. */ + export interface Options { + /** Path to intercept on. */ + path: string | RegExp | ((path: string) => boolean); + /** Method to intercept on. Defaults to GET. */ + method?: string | RegExp | ((method: string) => boolean); + /** Body to intercept on. */ + body?: string | RegExp | ((body: string) => boolean); + /** Headers to intercept on. */ + headers?: Record boolean)> | ((headers: Record) => boolean); + /** Query params to intercept on */ + query?: Record; + } + export interface MockDispatch extends Options { + times: number | null; + persist: boolean; + consumed: boolean; + data: MockDispatchData; + } + export interface MockDispatchData extends MockResponseOptions { + error: TError | null; + statusCode?: number; + data?: TData | string; + } + export interface MockResponseOptions { + headers?: IncomingHttpHeaders; + trailers?: Record; + } + + export interface MockResponseCallbackOptions { + path: string; + method: string; + headers?: Headers | Record; + origin?: string; + body?: BodyInit | Dispatcher.DispatchOptions['body'] | null; + } + + export type MockResponseDataHandler = ( + opts: MockResponseCallbackOptions + ) => TData | Buffer | string + + export type MockReplyOptionsCallback = ( + opts: MockResponseCallbackOptions + ) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions } +} + +interface Interceptable extends Dispatcher { + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Clean up all the prepared mocks. */ + cleanMocks (): void +} + +export { + Interceptable, + MockInterceptor, + MockScope +} diff --git a/node_modules/undici/types/mock-pool.d.ts b/node_modules/undici/types/mock-pool.d.ts new file mode 100644 index 000000000..f35f357bc --- /dev/null +++ b/node_modules/undici/types/mock-pool.d.ts @@ -0,0 +1,27 @@ +import Pool from './pool' +import MockAgent from './mock-agent' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import Dispatcher from './dispatcher' + +export default MockPool + +/** MockPool extends the Pool API and allows one to mock requests. */ +declare class MockPool extends Pool implements Interceptable { + constructor (origin: string, options: MockPool.Options) + /** Intercepts any matching requests that use the same origin as this mock pool. */ + intercept (options: MockInterceptor.Options): MockInterceptor + /** Dispatches a mocked request. */ + dispatch (options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandler): boolean + /** Closes the mock pool and gracefully waits for enqueued requests to complete. */ + close (): Promise + /** Clean up all the prepared mocks. */ + cleanMocks (): void +} + +declare namespace MockPool { + /** MockPool options. */ + export interface Options extends Pool.Options { + /** The agent to associate this MockPool with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici/types/patch.d.ts b/node_modules/undici/types/patch.d.ts new file mode 100644 index 000000000..8f7acbb06 --- /dev/null +++ b/node_modules/undici/types/patch.d.ts @@ -0,0 +1,29 @@ +/// + +// See https://github.com/nodejs/undici/issues/1740 + +export interface EventInit { + bubbles?: boolean + cancelable?: boolean + composed?: boolean +} + +export interface EventListenerOptions { + capture?: boolean +} + +export interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean + passive?: boolean + signal?: AbortSignal +} + +export type EventListenerOrEventListenerObject = EventListener | EventListenerObject + +export interface EventListenerObject { + handleEvent (object: Event): void +} + +export interface EventListener { + (evt: Event): void +} diff --git a/node_modules/undici/types/pool-stats.d.ts b/node_modules/undici/types/pool-stats.d.ts new file mode 100644 index 000000000..f76a5f61d --- /dev/null +++ b/node_modules/undici/types/pool-stats.d.ts @@ -0,0 +1,19 @@ +import Pool from './pool' + +export default PoolStats + +declare class PoolStats { + constructor (pool: Pool) + /** Number of open socket connections in this pool. */ + connected: number + /** Number of open socket connections in this pool that do not have an active request. */ + free: number + /** Number of pending requests across all clients in this pool. */ + pending: number + /** Number of queued requests across all clients in this pool. */ + queued: number + /** Number of currently active requests across all clients in this pool. */ + running: number + /** Number of active, pending, or queued requests across all clients in this pool. */ + size: number +} diff --git a/node_modules/undici/types/pool.d.ts b/node_modules/undici/types/pool.d.ts new file mode 100644 index 000000000..120bb8b25 --- /dev/null +++ b/node_modules/undici/types/pool.d.ts @@ -0,0 +1,41 @@ +import Client from './client' +import TPoolStats from './pool-stats' +import { URL } from 'node:url' +import Dispatcher from './dispatcher' + +export default Pool + +type PoolConnectOptions = Omit + +declare class Pool extends Dispatcher { + constructor (url: string | URL, options?: Pool.Options) + /** `true` after `pool.close()` has been called. */ + closed: boolean + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean + /** Aggregate stats for a Pool. */ + readonly stats: TPoolStats + + // Override dispatcher APIs. + override connect ( + options: PoolConnectOptions + ): Promise + override connect ( + options: PoolConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} + +declare namespace Pool { + export type PoolStats = TPoolStats + export interface Options extends Client.Options { + /** Default: `(origin, opts) => new Client(origin, opts)`. */ + factory?(origin: URL, opts: object): Dispatcher; + /** The max number of clients to create. `null` if no limit. Default `null`. */ + connections?: number | null; + /** The amount of time before a client is removed from the pool and closed. `null` if no time limit. Default `null` */ + clientTtl?: number | null; + + interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options['interceptors'] + } +} diff --git a/node_modules/undici/types/proxy-agent.d.ts b/node_modules/undici/types/proxy-agent.d.ts new file mode 100644 index 000000000..415554221 --- /dev/null +++ b/node_modules/undici/types/proxy-agent.d.ts @@ -0,0 +1,29 @@ +import Agent from './agent' +import buildConnector from './connector' +import Dispatcher from './dispatcher' +import { IncomingHttpHeaders } from './header' + +export default ProxyAgent + +declare class ProxyAgent extends Dispatcher { + constructor (options: ProxyAgent.Options | string) + + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean + close (): Promise +} + +declare namespace ProxyAgent { + export interface Options extends Agent.Options { + uri: string; + /** + * @deprecated use opts.token + */ + auth?: string; + token?: string; + headers?: IncomingHttpHeaders; + requestTls?: buildConnector.BuildOptions; + proxyTls?: buildConnector.BuildOptions; + clientFactory?(origin: URL, opts: object): Dispatcher; + proxyTunnel?: boolean; + } +} diff --git a/node_modules/undici/types/readable.d.ts b/node_modules/undici/types/readable.d.ts new file mode 100644 index 000000000..723ed1f44 --- /dev/null +++ b/node_modules/undici/types/readable.d.ts @@ -0,0 +1,68 @@ +import { Readable } from 'node:stream' +import { Blob } from 'node:buffer' + +export default BodyReadable + +declare class BodyReadable extends Readable { + constructor (opts: { + resume: (this: Readable, size: number) => void | null; + abort: () => void | null; + contentType?: string; + contentLength?: number; + highWaterMark?: number; + }) + + /** Consumes and returns the body as a string + * https://fetch.spec.whatwg.org/#dom-body-text + */ + text (): Promise + + /** Consumes and returns the body as a JavaScript Object + * https://fetch.spec.whatwg.org/#dom-body-json + */ + json (): Promise + + /** Consumes and returns the body as a Blob + * https://fetch.spec.whatwg.org/#dom-body-blob + */ + blob (): Promise + + /** Consumes and returns the body as an Uint8Array + * https://fetch.spec.whatwg.org/#dom-body-bytes + */ + bytes (): Promise + + /** Consumes and returns the body as an ArrayBuffer + * https://fetch.spec.whatwg.org/#dom-body-arraybuffer + */ + arrayBuffer (): Promise + + /** Not implemented + * + * https://fetch.spec.whatwg.org/#dom-body-formdata + */ + formData (): Promise + + /** Returns true if the body is not null and the body has been consumed + * + * Otherwise, returns false + * + * https://fetch.spec.whatwg.org/#dom-body-bodyused + */ + readonly bodyUsed: boolean + + /** + * If body is null, it should return null as the body + * + * If body is not null, should return the body as a ReadableStream + * + * https://fetch.spec.whatwg.org/#dom-body-body + */ + readonly body: never | undefined + + /** Dumps the response body by reading `limit` number of bytes. + * @param opts.limit Number of bytes to read (optional) - Default: 131072 + * @param opts.signal AbortSignal to cancel the operation (optional) + */ + dump (opts?: { limit: number; signal?: AbortSignal }): Promise +} diff --git a/node_modules/undici/types/retry-agent.d.ts b/node_modules/undici/types/retry-agent.d.ts new file mode 100644 index 000000000..82268c373 --- /dev/null +++ b/node_modules/undici/types/retry-agent.d.ts @@ -0,0 +1,8 @@ +import Dispatcher from './dispatcher' +import RetryHandler from './retry-handler' + +export default RetryAgent + +declare class RetryAgent extends Dispatcher { + constructor (dispatcher: Dispatcher, options?: RetryHandler.RetryOptions) +} diff --git a/node_modules/undici/types/retry-handler.d.ts b/node_modules/undici/types/retry-handler.d.ts new file mode 100644 index 000000000..3bc484b2d --- /dev/null +++ b/node_modules/undici/types/retry-handler.d.ts @@ -0,0 +1,125 @@ +import Dispatcher from './dispatcher' + +export default RetryHandler + +declare class RetryHandler implements Dispatcher.DispatchHandler { + constructor ( + options: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }, + retryHandlers: RetryHandler.RetryHandlers + ) +} + +declare namespace RetryHandler { + export type RetryState = { counter: number; } + + export type RetryContext = { + state: RetryState; + opts: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }; + } + + export type OnRetryCallback = (result?: Error | null) => void + + export type RetryCallback = ( + err: Error, + context: { + state: RetryState; + opts: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }; + }, + callback: OnRetryCallback + ) => void + + export interface RetryOptions { + /** + * If true, the retry handler will throw an error if the request fails, + * this will prevent the folling handlers from being called, and will destroy the socket. + * + * @type {boolean} + * @memberof RetryOptions + * @default true + */ + throwOnError?: boolean; + /** + * Callback to be invoked on every retry iteration. + * It receives the error, current state of the retry object and the options object + * passed when instantiating the retry handler. + * + * @type {RetryCallback} + * @memberof RetryOptions + */ + retry?: RetryCallback; + /** + * Maximum number of retries to allow. + * + * @type {number} + * @memberof RetryOptions + * @default 5 + */ + maxRetries?: number; + /** + * Max number of milliseconds allow between retries + * + * @type {number} + * @memberof RetryOptions + * @default 30000 + */ + maxTimeout?: number; + /** + * Initial number of milliseconds to wait before retrying for the first time. + * + * @type {number} + * @memberof RetryOptions + * @default 500 + */ + minTimeout?: number; + /** + * Factior to multiply the timeout factor between retries. + * + * @type {number} + * @memberof RetryOptions + * @default 2 + */ + timeoutFactor?: number; + /** + * It enables to automatically infer timeout between retries based on the `Retry-After` header. + * + * @type {boolean} + * @memberof RetryOptions + * @default true + */ + retryAfter?: boolean; + /** + * HTTP methods to retry. + * + * @type {Dispatcher.HttpMethod[]} + * @memberof RetryOptions + * @default ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + */ + methods?: Dispatcher.HttpMethod[]; + /** + * Error codes to be retried. e.g. `ECONNRESET`, `ENOTFOUND`, `ETIMEDOUT`, `ECONNREFUSED`, etc. + * + * @type {string[]} + * @default ['ECONNRESET','ECONNREFUSED','ENOTFOUND','ENETDOWN','ENETUNREACH','EHOSTDOWN','EHOSTUNREACH','EPIPE'] + */ + errorCodes?: string[]; + /** + * HTTP status codes to be retried. + * + * @type {number[]} + * @memberof RetryOptions + * @default [500, 502, 503, 504, 429], + */ + statusCodes?: number[]; + } + + export interface RetryHandlers { + dispatch: Dispatcher['dispatch']; + handler: Dispatcher.DispatchHandler; + } +} diff --git a/node_modules/undici/types/round-robin-pool.d.ts b/node_modules/undici/types/round-robin-pool.d.ts new file mode 100644 index 000000000..05ce2107a --- /dev/null +++ b/node_modules/undici/types/round-robin-pool.d.ts @@ -0,0 +1,41 @@ +import Client from './client' +import TPoolStats from './pool-stats' +import { URL } from 'node:url' +import Dispatcher from './dispatcher' + +export default RoundRobinPool + +type RoundRobinPoolConnectOptions = Omit + +declare class RoundRobinPool extends Dispatcher { + constructor (url: string | URL, options?: RoundRobinPool.Options) + /** `true` after `pool.close()` has been called. */ + closed: boolean + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean + /** Aggregate stats for a RoundRobinPool. */ + readonly stats: TPoolStats + + // Override dispatcher APIs. + override connect ( + options: RoundRobinPoolConnectOptions + ): Promise + override connect ( + options: RoundRobinPoolConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} + +declare namespace RoundRobinPool { + export type RoundRobinPoolStats = TPoolStats + export interface Options extends Client.Options { + /** Default: `(origin, opts) => new Client(origin, opts)`. */ + factory?(origin: URL, opts: object): Dispatcher; + /** The max number of clients to create. `null` if no limit. Default `null`. */ + connections?: number | null; + /** The amount of time before a client is removed from the pool and closed. `null` if no time limit. Default `null` */ + clientTtl?: number | null; + + interceptors?: { RoundRobinPool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options['interceptors'] + } +} diff --git a/node_modules/undici/types/snapshot-agent.d.ts b/node_modules/undici/types/snapshot-agent.d.ts new file mode 100644 index 000000000..f1d1ccdbb --- /dev/null +++ b/node_modules/undici/types/snapshot-agent.d.ts @@ -0,0 +1,109 @@ +import MockAgent from './mock-agent' + +declare class SnapshotRecorder { + constructor (options?: SnapshotRecorder.Options) + + record (requestOpts: any, response: any): Promise + findSnapshot (requestOpts: any): SnapshotRecorder.Snapshot | undefined + loadSnapshots (filePath?: string): Promise + saveSnapshots (filePath?: string): Promise + clear (): void + getSnapshots (): SnapshotRecorder.Snapshot[] + size (): number + resetCallCounts (): void + deleteSnapshot (requestOpts: any): boolean + getSnapshotInfo (requestOpts: any): SnapshotRecorder.SnapshotInfo | null + replaceSnapshots (snapshotData: SnapshotRecorder.SnapshotData[]): void + destroy (): void +} + +declare namespace SnapshotRecorder { + type SnapshotRecorderMode = 'record' | 'playback' | 'update' + + export interface Options { + snapshotPath?: string + mode?: SnapshotRecorderMode + maxSnapshots?: number + autoFlush?: boolean + flushInterval?: number + matchHeaders?: string[] + ignoreHeaders?: string[] + excludeHeaders?: string[] + matchBody?: boolean + matchQuery?: boolean + caseSensitive?: boolean + shouldRecord?: (requestOpts: any) => boolean + shouldPlayback?: (requestOpts: any) => boolean + excludeUrls?: (string | RegExp)[] + } + + export interface Snapshot { + request: { + method: string + url: string + headers: Record + body?: string + } + responses: { + statusCode: number + headers: Record + body: string + trailers: Record + }[] + callCount: number + timestamp: string + } + + export interface SnapshotInfo { + hash: string + request: { + method: string + url: string + headers: Record + body?: string + } + responseCount: number + callCount: number + timestamp: string + } + + export interface SnapshotData { + hash: string + snapshot: Snapshot + } +} + +declare class SnapshotAgent extends MockAgent { + constructor (options?: SnapshotAgent.Options) + + saveSnapshots (filePath?: string): Promise + loadSnapshots (filePath?: string): Promise + getRecorder (): SnapshotRecorder + getMode (): SnapshotRecorder.SnapshotRecorderMode + clearSnapshots (): void + resetCallCounts (): void + deleteSnapshot (requestOpts: any): boolean + getSnapshotInfo (requestOpts: any): SnapshotRecorder.SnapshotInfo | null + replaceSnapshots (snapshotData: SnapshotRecorder.SnapshotData[]): void +} + +declare namespace SnapshotAgent { + export interface Options extends MockAgent.Options { + mode?: SnapshotRecorder.SnapshotRecorderMode + snapshotPath?: string + maxSnapshots?: number + autoFlush?: boolean + flushInterval?: number + matchHeaders?: string[] + ignoreHeaders?: string[] + excludeHeaders?: string[] + matchBody?: boolean + matchQuery?: boolean + caseSensitive?: boolean + shouldRecord?: (requestOpts: any) => boolean + shouldPlayback?: (requestOpts: any) => boolean + excludeUrls?: (string | RegExp)[] + } +} + +export { SnapshotAgent, SnapshotRecorder } diff --git a/node_modules/undici/types/util.d.ts b/node_modules/undici/types/util.d.ts new file mode 100644 index 000000000..8fc50cc42 --- /dev/null +++ b/node_modules/undici/types/util.d.ts @@ -0,0 +1,18 @@ +export namespace util { + /** + * Retrieves a header name and returns its lowercase value. + * @param value Header name + */ + export function headerNameToString (value: string | Buffer): string + + /** + * Receives a header object and returns the parsed value. + * @param headers Header object + * @param obj Object to specify a proxy object. Used to assign parsed values. + * @returns If `obj` is specified, it is equivalent to `obj`. + */ + export function parseHeaders ( + headers: (Buffer | string | (Buffer | string)[])[], + obj?: Record + ): Record +} diff --git a/node_modules/undici/types/utility.d.ts b/node_modules/undici/types/utility.d.ts new file mode 100644 index 000000000..bfb3ca770 --- /dev/null +++ b/node_modules/undici/types/utility.d.ts @@ -0,0 +1,7 @@ +type AutocompletePrimitiveBaseType = + T extends string ? string : + T extends number ? number : + T extends boolean ? boolean : + never + +export type Autocomplete = T | (AutocompletePrimitiveBaseType & Record) diff --git a/node_modules/undici/types/webidl.d.ts b/node_modules/undici/types/webidl.d.ts new file mode 100644 index 000000000..d2a8eb9c3 --- /dev/null +++ b/node_modules/undici/types/webidl.d.ts @@ -0,0 +1,341 @@ +// These types are not exported, and are only used internally +import * as undici from './index' + +/** + * Take in an unknown value and return one that is of type T + */ +type Converter = (object: unknown) => T + +type SequenceConverter = (object: unknown, iterable?: IterableIterator) => T[] + +type RecordConverter = (object: unknown) => Record + +interface WebidlErrors { + /** + * @description Instantiate an error + */ + exception (opts: { header: string, message: string }): TypeError + /** + * @description Instantiate an error when conversion from one type to another has failed + */ + conversionFailed (opts: { + prefix: string + argument: string + types: string[] + }): TypeError + /** + * @description Throw an error when an invalid argument is provided + */ + invalidArgument (opts: { + prefix: string + value: string + type: string + }): TypeError +} + +interface WebIDLTypes { + UNDEFINED: 1, + BOOLEAN: 2, + STRING: 3, + SYMBOL: 4, + NUMBER: 5, + BIGINT: 6, + NULL: 7 + OBJECT: 8 +} + +interface WebidlUtil { + /** + * @see https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + */ + Type (object: unknown): WebIDLTypes[keyof WebIDLTypes] + + TypeValueToString (o: unknown): + | 'Undefined' + | 'Boolean' + | 'String' + | 'Symbol' + | 'Number' + | 'BigInt' + | 'Null' + | 'Object' + + Types: WebIDLTypes + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + ConvertToInt ( + V: unknown, + bitLength: number, + signedness: 'signed' | 'unsigned', + flags?: number + ): number + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-integerpart + */ + IntegerPart (N: number): number + + /** + * Stringifies {@param V} + */ + Stringify (V: any): string + + MakeTypeAssertion (I: I): (arg: any) => arg is I + + /** + * Mark a value as uncloneable for Node.js. + * This is only effective in some newer Node.js versions. + */ + markAsUncloneable (V: any): void + + IsResizableArrayBuffer (V: ArrayBufferLike): boolean + + HasFlag (flag: number, attributes: number): boolean +} + +interface WebidlConverters { + /** + * @see https://webidl.spec.whatwg.org/#es-DOMString + */ + DOMString (V: unknown, prefix: string, argument: string, flags?: number): string + + /** + * @see https://webidl.spec.whatwg.org/#es-ByteString + */ + ByteString (V: unknown, prefix: string, argument: string): string + + /** + * @see https://webidl.spec.whatwg.org/#es-USVString + */ + USVString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-boolean + */ + boolean (V: unknown): boolean + + /** + * @see https://webidl.spec.whatwg.org/#es-any + */ + any (V: Value): Value + + /** + * @see https://webidl.spec.whatwg.org/#es-long-long + */ + ['long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long-long + */ + ['unsigned long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long + */ + ['unsigned long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-short + */ + ['unsigned short'] (V: unknown, flags?: number): number + + /** + * @see https://webidl.spec.whatwg.org/#idl-ArrayBuffer + */ + ArrayBuffer ( + V: unknown, + prefix: string, + argument: string, + options?: { allowResizable: boolean } + ): ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#idl-SharedArrayBuffer + */ + SharedArrayBuffer ( + V: unknown, + prefix: string, + argument: string, + options?: { allowResizable: boolean } + ): SharedArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + TypedArray ( + V: unknown, + T: new () => NodeJS.TypedArray, + prefix: string, + argument: string, + flags?: number + ): NodeJS.TypedArray + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + DataView ( + V: unknown, + prefix: string, + argument: string, + flags?: number + ): DataView + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + ArrayBufferView ( + V: unknown, + prefix: string, + argument: string, + flags?: number + ): NodeJS.ArrayBufferView + + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource ( + V: unknown, + prefix: string, + argument: string, + flags?: number + ): ArrayBuffer | NodeJS.ArrayBufferView + + /** + * @see https://webidl.spec.whatwg.org/#AllowSharedBufferSource + */ + AllowSharedBufferSource ( + V: unknown, + prefix: string, + argument: string, + flags?: number + ): ArrayBuffer | SharedArrayBuffer | NodeJS.ArrayBufferView + + ['sequence']: SequenceConverter + + ['sequence>']: SequenceConverter + + ['record']: RecordConverter + + /** + * @see https://fetch.spec.whatwg.org/#requestinfo + */ + RequestInfo (V: unknown): undici.Request | string + + /** + * @see https://fetch.spec.whatwg.org/#requestinit + */ + RequestInit (V: unknown): undici.RequestInit + + /** + * @see https://html.spec.whatwg.org/multipage/webappapis.html#eventhandlernonnull + */ + EventHandlerNonNull (V: unknown): Function | null + + WebSocketStreamWrite (V: unknown): ArrayBuffer | NodeJS.TypedArray | string + + [Key: string]: (...args: any[]) => unknown +} + +type WebidlIsFunction = (arg: any) => arg is T + +interface WebidlIs { + Request: WebidlIsFunction + Response: WebidlIsFunction + ReadableStream: WebidlIsFunction + Blob: WebidlIsFunction + URLSearchParams: WebidlIsFunction + File: WebidlIsFunction + FormData: WebidlIsFunction + URL: WebidlIsFunction + WebSocketError: WebidlIsFunction + AbortSignal: WebidlIsFunction + MessagePort: WebidlIsFunction + USVString: WebidlIsFunction + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource: WebidlIsFunction +} + +export interface Webidl { + errors: WebidlErrors + util: WebidlUtil + converters: WebidlConverters + is: WebidlIs + attributes: WebIDLExtendedAttributes + + /** + * @description Performs a brand-check on {@param V} to ensure it is a + * {@param cls} object. + */ + brandCheck unknown>(V: unknown, cls: Interface): asserts V is Interface + + brandCheckMultiple unknown)[]> (list: Interfaces): (V: any) => asserts V is Interfaces[number] + + /** + * @see https://webidl.spec.whatwg.org/#es-sequence + * @description Convert a value, V, to a WebIDL sequence type. + */ + sequenceConverter (C: Converter): SequenceConverter + + illegalConstructor (): never + + /** + * @see https://webidl.spec.whatwg.org/#es-to-record + * @description Convert a value, V, to a WebIDL record type. + */ + recordConverter ( + keyConverter: Converter, + valueConverter: Converter + ): RecordConverter + + /** + * Similar to {@link Webidl.brandCheck} but allows skipping the check if third party + * interfaces are allowed. + */ + interfaceConverter (typeCheck: WebidlIsFunction, name: string): ( + V: unknown, + prefix: string, + argument: string + ) => asserts V is Interface + + // TODO(@KhafraDev): a type could likely be implemented that can infer the return type + // from the converters given? + /** + * Converts a value, V, to a WebIDL dictionary types. Allows limiting which keys are + * allowed, values allowed, optional and required keys. Auto converts the value to + * a type given a converter. + */ + dictionaryConverter (converters: { + key: string, + defaultValue?: () => unknown, + required?: boolean, + converter: (...args: unknown[]) => unknown, + allowedValues?: unknown[] + }[]): (V: unknown) => Record + + /** + * @see https://webidl.spec.whatwg.org/#idl-nullable-type + * @description allows a type, V, to be null + */ + nullableConverter ( + converter: Converter + ): (V: unknown) => ReturnType | null + + argumentLengthCheck (args: { length: number }, min: number, context: string): void +} + +interface WebIDLExtendedAttributes { + /** https://webidl.spec.whatwg.org/#Clamp */ + Clamp: number + /** https://webidl.spec.whatwg.org/#EnforceRange */ + EnforceRange: number + /** https://webidl.spec.whatwg.org/#AllowShared */ + AllowShared: number + /** https://webidl.spec.whatwg.org/#AllowResizable */ + AllowResizable: number + /** https://webidl.spec.whatwg.org/#LegacyNullToEmptyString */ + LegacyNullToEmptyString: number +} diff --git a/node_modules/undici/types/websocket.d.ts b/node_modules/undici/types/websocket.d.ts new file mode 100644 index 000000000..6d81a2553 --- /dev/null +++ b/node_modules/undici/types/websocket.d.ts @@ -0,0 +1,186 @@ +/// + +import type { Blob } from 'node:buffer' +import type { ReadableStream, WritableStream } from 'node:stream/web' +import type { MessagePort } from 'node:worker_threads' +import { + EventInit, + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' +import Dispatcher from './dispatcher' +import { HeadersInit } from './fetch' + +export type BinaryType = 'blob' | 'arraybuffer' + +interface WebSocketEventMap { + close: CloseEvent + error: ErrorEvent + message: MessageEvent + open: Event +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType + + readonly bufferedAmount: number + readonly extensions: string + + onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null + onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null + onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null + onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null + + readonly protocol: string + readonly readyState: number + readonly url: string + + close(code?: number, reason?: string): void + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void + + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number + + addEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const WebSocket: { + prototype: WebSocket + new (url: string | URL, protocols?: string | string[] | WebSocketInit): WebSocket + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +interface CloseEvent extends Event { + readonly code: number + readonly reason: string + readonly wasClean: boolean +} + +export declare const CloseEvent: { + prototype: CloseEvent + new (type: string, eventInitDict?: CloseEventInit): CloseEvent +} + +interface MessageEventInit extends EventInit { + data?: T + lastEventId?: string + origin?: string + ports?: MessagePort[] + source?: MessagePort | null +} + +interface MessageEvent extends Event { + readonly data: T + readonly lastEventId: string + readonly origin: string + readonly ports: readonly MessagePort[] + readonly source: MessagePort | null + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: MessagePort | null, + ports?: MessagePort[] + ): void; +} + +export declare const MessageEvent: { + prototype: MessageEvent + new(type: string, eventInitDict?: MessageEventInit): MessageEvent +} + +interface ErrorEventInit extends EventInit { + message?: string + filename?: string + lineno?: number + colno?: number + error?: any +} + +interface ErrorEvent extends Event { + readonly message: string + readonly filename: string + readonly lineno: number + readonly colno: number + readonly error: Error +} + +export declare const ErrorEvent: { + prototype: ErrorEvent + new (type: string, eventInitDict?: ErrorEventInit): ErrorEvent +} + +interface WebSocketInit { + protocols?: string | string[], + dispatcher?: Dispatcher, + headers?: HeadersInit +} + +interface WebSocketStreamOptions { + protocols?: string | string[] + signal?: AbortSignal +} + +interface WebSocketCloseInfo { + closeCode: number + reason: string +} + +interface WebSocketStream { + closed: Promise + opened: Promise<{ + extensions: string + protocol: string + readable: ReadableStream + writable: WritableStream + }> + url: string +} + +export declare const WebSocketStream: { + prototype: WebSocketStream + new (url: string | URL, options?: WebSocketStreamOptions): WebSocketStream +} + +interface WebSocketError extends Event, WebSocketCloseInfo {} + +export declare const WebSocketError: { + prototype: WebSocketError + new (type: string, init?: WebSocketCloseInfo): WebSocketError +} + +export declare const ping: (ws: WebSocket, body?: Buffer) => void diff --git a/node_modules/unpipe/HISTORY.md b/node_modules/unpipe/HISTORY.md new file mode 100644 index 000000000..85e0f8d74 --- /dev/null +++ b/node_modules/unpipe/HISTORY.md @@ -0,0 +1,4 @@ +1.0.0 / 2015-06-14 +================== + + * Initial release diff --git a/node_modules/unpipe/LICENSE b/node_modules/unpipe/LICENSE new file mode 100644 index 000000000..aed013827 --- /dev/null +++ b/node_modules/unpipe/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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/unpipe/README.md b/node_modules/unpipe/README.md new file mode 100644 index 000000000..e536ad2c0 --- /dev/null +++ b/node_modules/unpipe/README.md @@ -0,0 +1,43 @@ +# unpipe + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Unpipe a stream from all destinations. + +## Installation + +```sh +$ npm install unpipe +``` + +## API + +```js +var unpipe = require('unpipe') +``` + +### unpipe(stream) + +Unpipes all destinations from a given stream. With stream 2+, this is +equivalent to `stream.unpipe()`. When used with streams 1 style streams +(typically Node.js 0.8 and below), this module attempts to undo the +actions done in `stream.pipe(dest)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/unpipe.svg +[npm-url]: https://npmjs.org/package/unpipe +[node-image]: https://img.shields.io/node/v/unpipe.svg +[node-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg +[travis-url]: https://travis-ci.org/stream-utils/unpipe +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master +[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg +[downloads-url]: https://npmjs.org/package/unpipe diff --git a/node_modules/unpipe/index.js b/node_modules/unpipe/index.js new file mode 100644 index 000000000..15c3d97a1 --- /dev/null +++ b/node_modules/unpipe/index.js @@ -0,0 +1,69 @@ +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = unpipe + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data') + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/node_modules/unpipe/package.json b/node_modules/unpipe/package.json new file mode 100644 index 000000000..a2b73583b --- /dev/null +++ b/node_modules/unpipe/package.json @@ -0,0 +1,27 @@ +{ + "name": "unpipe", + "description": "Unpipe a stream from all destinations", + "version": "1.0.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "stream-utils/unpipe", + "devDependencies": { + "istanbul": "0.3.15", + "mocha": "2.2.5", + "readable-stream": "1.1.13" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/vary/HISTORY.md b/node_modules/vary/HISTORY.md new file mode 100644 index 000000000..f6cbcf7f9 --- /dev/null +++ b/node_modules/vary/HISTORY.md @@ -0,0 +1,39 @@ +1.1.2 / 2017-09-23 +================== + + * perf: improve header token parsing speed + +1.1.1 / 2017-03-20 +================== + + * perf: hoist regular expression + +1.1.0 / 2015-09-29 +================== + + * Only accept valid field names in the `field` argument + - Ensures the resulting string is a valid HTTP header value + +1.0.1 / 2015-07-08 +================== + + * Fix setting empty header from empty `field` + * perf: enable strict mode + * perf: remove argument reassignments + +1.0.0 / 2014-08-10 +================== + + * Accept valid `Vary` header string as `field` + * Add `vary.append` for low-level string manipulation + * Move to `jshttp` orgainzation + +0.1.0 / 2014-06-05 +================== + + * Support array of fields to set + +0.0.0 / 2014-06-04 +================== + + * Initial release diff --git a/node_modules/vary/LICENSE b/node_modules/vary/LICENSE new file mode 100644 index 000000000..84441fbb5 --- /dev/null +++ b/node_modules/vary/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 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/vary/README.md b/node_modules/vary/README.md new file mode 100644 index 000000000..cc000b346 --- /dev/null +++ b/node_modules/vary/README.md @@ -0,0 +1,101 @@ +# vary + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Manipulate the HTTP Vary header + +## 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 vary +``` + +## API + + + +```js +var vary = require('vary') +``` + +### vary(res, field) + +Adds the given header `field` to the `Vary` response header of `res`. +This can be a string of a single field, a string of a valid `Vary` +header, or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. + + + +```js +// Append "Origin" to the Vary header of the response +vary(res, 'Origin') +``` + +### vary.append(header, field) + +Adds the given header `field` to the `Vary` response header string `header`. +This can be a string of a single field, a string of a valid `Vary` header, +or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. The new header string is returned. + + + +```js +// Get header string appending "Origin" to "Accept, User-Agent" +vary.append('Accept, User-Agent', 'Origin') +``` + +## Examples + +### Updating the Vary header when content is based on it + +```js +var http = require('http') +var vary = require('vary') + +http.createServer(function onRequest (req, res) { + // about to user-agent sniff + vary(res, 'User-Agent') + + var ua = req.headers['user-agent'] || '' + var isMobile = /mobi|android|touch|mini/i.test(ua) + + // serve site, depending on isMobile + res.setHeader('Content-Type', 'text/html') + res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user') +}) +``` + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/vary.svg +[npm-url]: https://npmjs.org/package/vary +[node-version-image]: https://img.shields.io/node/v/vary.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/jshttp/vary/master.svg +[travis-url]: https://travis-ci.org/jshttp/vary +[coveralls-image]: https://img.shields.io/coveralls/jshttp/vary/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/vary +[downloads-image]: https://img.shields.io/npm/dm/vary.svg +[downloads-url]: https://npmjs.org/package/vary diff --git a/node_modules/vary/index.js b/node_modules/vary/index.js new file mode 100644 index 000000000..5b5e74127 --- /dev/null +++ b/node_modules/vary/index.js @@ -0,0 +1,149 @@ +/*! + * vary + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = vary +module.exports.append = append + +/** + * RegExp to match field-name in RFC 7230 sec 3.2 + * + * field-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + */ + +var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/ + +/** + * Append a field to a vary header. + * + * @param {String} header + * @param {String|Array} field + * @return {String} + * @public + */ + +function append (header, field) { + if (typeof header !== 'string') { + throw new TypeError('header argument is required') + } + + if (!field) { + throw new TypeError('field argument is required') + } + + // get fields array + var fields = !Array.isArray(field) + ? parse(String(field)) + : field + + // assert on invalid field names + for (var j = 0; j < fields.length; j++) { + if (!FIELD_NAME_REGEXP.test(fields[j])) { + throw new TypeError('field argument contains an invalid header name') + } + } + + // existing, unspecified vary + if (header === '*') { + return header + } + + // enumerate current values + var val = header + var vals = parse(header.toLowerCase()) + + // unspecified vary + if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) { + return '*' + } + + for (var i = 0; i < fields.length; i++) { + var fld = fields[i].toLowerCase() + + // append value (case-preserving) + if (vals.indexOf(fld) === -1) { + vals.push(fld) + val = val + ? val + ', ' + fields[i] + : fields[i] + } + } + + return val +} + +/** + * Parse a vary header into an array. + * + * @param {String} header + * @return {Array} + * @private + */ + +function parse (header) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = header.length; i < len; i++) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(header.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(header.substring(start, end)) + + return list +} + +/** + * Mark that a request is varied on a header field. + * + * @param {Object} res + * @param {String|Array} field + * @public + */ + +function vary (res, field) { + if (!res || !res.getHeader || !res.setHeader) { + // quack quack + throw new TypeError('res argument is required') + } + + // get existing header + var val = res.getHeader('Vary') || '' + var header = Array.isArray(val) + ? val.join(', ') + : String(val) + + // set new header + if ((val = append(header, field))) { + res.setHeader('Vary', val) + } +} diff --git a/node_modules/vary/package.json b/node_modules/vary/package.json new file mode 100644 index 000000000..028f72a93 --- /dev/null +++ b/node_modules/vary/package.json @@ -0,0 +1,43 @@ +{ + "name": "vary", + "description": "Manipulate the HTTP Vary header", + "version": "1.1.2", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "http", + "res", + "vary" + ], + "repository": "jshttp/vary", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3", + "supertest": "1.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/which/CHANGELOG.md b/node_modules/which/CHANGELOG.md new file mode 100644 index 000000000..7fb1f2033 --- /dev/null +++ b/node_modules/which/CHANGELOG.md @@ -0,0 +1,166 @@ +# Changes + + +## 2.0.2 + +* Rename bin to `node-which` + +## 2.0.1 + +* generate changelog and publish on version bump +* enforce 100% test coverage +* Promise interface + +## 2.0.0 + +* Parallel tests, modern JavaScript, and drop support for node < 8 + +## 1.3.1 + +* update deps +* update travis + +## v1.3.0 + +* Add nothrow option to which.sync +* update tap + +## v1.2.14 + +* appveyor: drop node 5 and 0.x +* travis-ci: add node 6, drop 0.x + +## v1.2.13 + +* test: Pass missing option to pass on windows +* update tap +* update isexe to 2.0.0 +* neveragain.tech pledge request + +## v1.2.12 + +* Removed unused require + +## v1.2.11 + +* Prevent changelog script from being included in package + +## v1.2.10 + +* Use env.PATH only, not env.Path + +## v1.2.9 + +* fix for paths starting with ../ +* Remove unused `is-absolute` module + +## v1.2.8 + +* bullet items in changelog that contain (but don't start with) # + +## v1.2.7 + +* strip 'update changelog' changelog entries out of changelog + +## v1.2.6 + +* make the changelog bulleted + +## v1.2.5 + +* make a changelog, and keep it up to date +* don't include tests in package +* Properly handle relative-path executables +* appveyor +* Attach error code to Not Found error +* Make tests pass on Windows + +## v1.2.4 + +* Fix typo + +## v1.2.3 + +* update isexe, fix regression in pathExt handling + +## v1.2.2 + +* update deps, use isexe module, test windows + +## v1.2.1 + +* Sometimes windows PATH entries are quoted +* Fixed a bug in the check for group and user mode bits. This bug was introduced during refactoring for supporting strict mode. +* doc cli + +## v1.2.0 + +* Add support for opt.all and -as cli flags +* test the bin +* update travis +* Allow checking for multiple programs in bin/which +* tap 2 + +## v1.1.2 + +* travis +* Refactored and fixed undefined error on Windows +* Support strict mode + +## v1.1.1 + +* test +g exes against secondary groups, if available +* Use windows exe semantics on cygwin & msys +* cwd should be first in path on win32, not last +* Handle lower-case 'env.Path' on Windows +* Update docs +* use single-quotes + +## v1.1.0 + +* Add tests, depend on is-absolute + +## v1.0.9 + +* which.js: root is allowed to execute files owned by anyone + +## v1.0.8 + +* don't use graceful-fs + +## v1.0.7 + +* add license to package.json + +## v1.0.6 + +* isc license + +## 1.0.5 + +* Awful typo + +## 1.0.4 + +* Test for path absoluteness properly +* win: Allow '' as a pathext if cmd has a . in it + +## 1.0.3 + +* Remove references to execPath +* Make `which.sync()` work on Windows by honoring the PATHEXT variable. +* Make `isExe()` always return true on Windows. +* MIT + +## 1.0.2 + +* Only files can be exes + +## 1.0.1 + +* Respect the PATHEXT env for win32 support +* should 0755 the bin +* binary +* guts +* package +* 1st diff --git a/node_modules/which/LICENSE b/node_modules/which/LICENSE new file mode 100644 index 000000000..19129e315 --- /dev/null +++ b/node_modules/which/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/which/README.md b/node_modules/which/README.md new file mode 100644 index 000000000..cd833509f --- /dev/null +++ b/node_modules/which/README.md @@ -0,0 +1,54 @@ +# which + +Like the unix `which` utility. + +Finds the first instance of a specified executable in the PATH +environment variable. Does not cache the results, so `hash -r` is not +needed when the PATH changes. + +## USAGE + +```javascript +var which = require('which') + +// async usage +which('node', function (er, resolvedPath) { + // er is returned if no "node" is found on the PATH + // if it is found, then the absolute path to the exec is returned +}) + +// or promise +which('node').then(resolvedPath => { ... }).catch(er => { ... not found ... }) + +// sync usage +// throws if not found +var resolved = which.sync('node') + +// if nothrow option is used, returns null if not found +resolved = which.sync('node', {nothrow: true}) + +// Pass options to override the PATH and PATHEXT environment vars. +which('node', { path: someOtherPath }, function (er, resolved) { + if (er) + throw er + console.log('found at %j', resolved) +}) +``` + +## CLI USAGE + +Same as the BSD `which(1)` binary. + +``` +usage: which [-as] program ... +``` + +## OPTIONS + +You may pass an options object as the second argument. + +- `path`: Use instead of the `PATH` environment variable. +- `pathExt`: Use instead of the `PATHEXT` environment variable. +- `all`: Return all matches, instead of just the first one. Note that + this means the function returns an array of strings instead of a + single string. diff --git a/node_modules/which/package.json b/node_modules/which/package.json new file mode 100644 index 000000000..97ad7fbab --- /dev/null +++ b/node_modules/which/package.json @@ -0,0 +1,43 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me)", + "name": "which", + "description": "Like which(1) unix command. Find the first instance of an executable in the PATH.", + "version": "2.0.2", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-which.git" + }, + "main": "which.js", + "bin": { + "node-which": "./bin/node-which" + }, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "devDependencies": { + "mkdirp": "^0.5.0", + "rimraf": "^2.6.2", + "tap": "^14.6.9" + }, + "scripts": { + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "prepublish": "npm run changelog", + "prechangelog": "bash gen-changelog.sh", + "changelog": "git add CHANGELOG.md", + "postchangelog": "git commit -m 'update changelog - '${npm_package_version}", + "postpublish": "git push origin --follow-tags" + }, + "files": [ + "which.js", + "bin/node-which" + ], + "tap": { + "check-coverage": true + }, + "engines": { + "node": ">= 8" + } +} diff --git a/node_modules/which/which.js b/node_modules/which/which.js new file mode 100644 index 000000000..82afffd21 --- /dev/null +++ b/node_modules/which/which.js @@ -0,0 +1,125 @@ +const isWindows = process.platform === 'win32' || + process.env.OSTYPE === 'cygwin' || + process.env.OSTYPE === 'msys' + +const path = require('path') +const COLON = isWindows ? ';' : ':' +const isexe = require('isexe') + +const getNotFoundError = (cmd) => + Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) + +const getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON + + // If it has a slash, then we don't bother searching the pathenv. + // just check the file itself, and that's it. + const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] + : ( + [ + // windows always checks the cwd first + ...(isWindows ? [process.cwd()] : []), + ...(opt.path || process.env.PATH || + /* istanbul ignore next: very unusual */ '').split(colon), + ] + ) + const pathExtExe = isWindows + ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' + : '' + const pathExt = isWindows ? pathExtExe.split(colon) : [''] + + if (isWindows) { + if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') + pathExt.unshift('') + } + + return { + pathEnv, + pathExt, + pathExtExe, + } +} + +const which = (cmd, opt, cb) => { + if (typeof opt === 'function') { + cb = opt + opt = {} + } + if (!opt) + opt = {} + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) + const found = [] + + const step = i => new Promise((resolve, reject) => { + if (i === pathEnv.length) + return opt.all && found.length ? resolve(found) + : reject(getNotFoundError(cmd)) + + const ppRaw = pathEnv[i] + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw + + const pCmd = path.join(pathPart, cmd) + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd + + resolve(subStep(p, i, 0)) + }) + + const subStep = (p, i, ii) => new Promise((resolve, reject) => { + if (ii === pathExt.length) + return resolve(step(i + 1)) + const ext = pathExt[ii] + isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) { + if (opt.all) + found.push(p + ext) + else + return resolve(p + ext) + } + return resolve(subStep(p, i, ii + 1)) + }) + }) + + return cb ? step(0).then(res => cb(null, res), cb) : step(0) +} + +const whichSync = (cmd, opt) => { + opt = opt || {} + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) + const found = [] + + for (let i = 0; i < pathEnv.length; i ++) { + const ppRaw = pathEnv[i] + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw + + const pCmd = path.join(pathPart, cmd) + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd + + for (let j = 0; j < pathExt.length; j ++) { + const cur = p + pathExt[j] + try { + const is = isexe.sync(cur, { pathExt: pathExtExe }) + if (is) { + if (opt.all) + found.push(cur) + else + return cur + } + } catch (ex) {} + } + } + + if (opt.all && found.length) + return found + + if (opt.nothrow) + return null + + throw getNotFoundError(cmd) +} + +module.exports = which +which.sync = whichSync diff --git a/node_modules/wrappy/LICENSE b/node_modules/wrappy/LICENSE new file mode 100644 index 000000000..19129e315 --- /dev/null +++ b/node_modules/wrappy/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/wrappy/README.md b/node_modules/wrappy/README.md new file mode 100644 index 000000000..98eab2522 --- /dev/null +++ b/node_modules/wrappy/README.md @@ -0,0 +1,36 @@ +# wrappy + +Callback wrapping utility + +## USAGE + +```javascript +var wrappy = require("wrappy") + +// var wrapper = wrappy(wrapperFunction) + +// make sure a cb is called only once +// See also: http://npm.im/once for this specific use case +var once = wrappy(function (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } +}) + +function printBoo () { + console.log('boo') +} +// has some rando property +printBoo.iAmBooPrinter = true + +var onlyPrintOnce = once(printBoo) + +onlyPrintOnce() // prints 'boo' +onlyPrintOnce() // does nothing + +// random property is retained! +assert.equal(onlyPrintOnce.iAmBooPrinter, true) +``` diff --git a/node_modules/wrappy/package.json b/node_modules/wrappy/package.json new file mode 100644 index 000000000..130752046 --- /dev/null +++ b/node_modules/wrappy/package.json @@ -0,0 +1,29 @@ +{ + "name": "wrappy", + "version": "1.0.2", + "description": "Callback wrapping utility", + "main": "wrappy.js", + "files": [ + "wrappy.js" + ], + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "tap": "^2.3.1" + }, + "scripts": { + "test": "tap --coverage test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/npm/wrappy" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "bugs": { + "url": "https://github.com/npm/wrappy/issues" + }, + "homepage": "https://github.com/npm/wrappy" +} diff --git a/node_modules/wrappy/wrappy.js b/node_modules/wrappy/wrappy.js new file mode 100644 index 000000000..bb7e7d6fc --- /dev/null +++ b/node_modules/wrappy/wrappy.js @@ -0,0 +1,33 @@ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} diff --git a/node_modules/yaml/LICENSE b/node_modules/yaml/LICENSE new file mode 100644 index 000000000..e060aaa1f --- /dev/null +++ b/node_modules/yaml/LICENSE @@ -0,0 +1,13 @@ +Copyright Eemeli Aro + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/node_modules/yaml/README.md b/node_modules/yaml/README.md new file mode 100644 index 000000000..1613c1d64 --- /dev/null +++ b/node_modules/yaml/README.md @@ -0,0 +1,172 @@ +# YAML + +`yaml` is a definitive library for [YAML](https://yaml.org/), the human friendly data serialization standard. +This library: + +- Supports both YAML 1.1 and YAML 1.2 and all common data schemas, +- Passes all of the [yaml-test-suite](https://github.com/yaml/yaml-test-suite) tests, +- Can accept any string as input without throwing, parsing as much YAML out of it as it can, and +- Supports parsing, modifying, and writing YAML comments and blank lines. + +The library is released under the ISC open source license, and the code is [available on GitHub](https://github.com/eemeli/yaml/). +It has no external dependencies and runs on Node.js as well as modern browsers. + +For the purposes of versioning, any changes that break any of the documented endpoints or APIs will be considered semver-major breaking changes. +Undocumented library internals may change between minor versions, and previous APIs may be deprecated (but not removed). + +The minimum supported TypeScript version of the included typings is 3.9; +for use in earlier versions you may need to set `skipLibCheck: true` in your config. +This requirement may be updated between minor versions of the library. + +For more information, see the project's documentation site: [**eemeli.org/yaml**](https://eemeli.org/yaml/) + +For build instructions and contribution guidelines, see [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md). + +To install: + +```sh +npm install yaml +# or +deno add jsr:@eemeli/yaml +``` + +**Note:** These docs are for `yaml@2`. For v1, see the [v1.10.0 tag](https://github.com/eemeli/yaml/tree/v1.10.0) for the source and [eemeli.org/yaml/v1](https://eemeli.org/yaml/v1/) for the documentation. + +## API Overview + +The API provided by `yaml` has three layers, depending on how deep you need to go: [Parse & Stringify](https://eemeli.org/yaml/#parse-amp-stringify), [Documents](https://eemeli.org/yaml/#documents), and the underlying [Lexer/Parser/Composer](https://eemeli.org/yaml/#parsing-yaml). +The first has the simplest API and "just works", the second gets you all the bells and whistles supported by the library along with a decent [AST](https://eemeli.org/yaml/#content-nodes), and the third lets you get progressively closer to YAML source, if that's your thing. + +A [command-line tool](https://eemeli.org/yaml/#command-line-tool) is also included. + +### Parse & Stringify + +```js +import { parse, stringify } from 'yaml' +``` + +- [`parse(str, reviver?, options?): value`](https://eemeli.org/yaml/#yaml-parse) +- [`stringify(value, replacer?, options?): string`](https://eemeli.org/yaml/#yaml-stringify) + +### Documents + + +```js +import { + Document, + isDocument, + parseAllDocuments, + parseDocument +} from 'yaml' +``` + +- [`Document`](https://eemeli.org/yaml/#documents) + - [`constructor(value, replacer?, options?)`](https://eemeli.org/yaml/#creating-documents) + - [`#contents`](https://eemeli.org/yaml/#content-nodes) + - [`#directives`](https://eemeli.org/yaml/#stream-directives) + - [`#errors`](https://eemeli.org/yaml/#errors) + - [`#warnings`](https://eemeli.org/yaml/#errors) +- [`isDocument(foo): boolean`](https://eemeli.org/yaml/#identifying-node-types) +- [`parseAllDocuments(str, options?): Document[]`](https://eemeli.org/yaml/#parsing-documents) +- [`parseDocument(str, options?): Document`](https://eemeli.org/yaml/#parsing-documents) + +### Content Nodes + + +```js +import { + isAlias, isCollection, isMap, isNode, + isPair, isScalar, isSeq, Scalar, + visit, visitAsync, YAMLMap, YAMLSeq +} from 'yaml' +``` + +- [`isAlias(foo): boolean`](https://eemeli.org/yaml/#identifying-node-types) +- [`isCollection(foo): boolean`](https://eemeli.org/yaml/#identifying-node-types) +- [`isMap(foo): boolean`](https://eemeli.org/yaml/#identifying-node-types) +- [`isNode(foo): boolean`](https://eemeli.org/yaml/#identifying-node-types) +- [`isPair(foo): boolean`](https://eemeli.org/yaml/#identifying-node-types) +- [`isScalar(foo): boolean`](https://eemeli.org/yaml/#identifying-node-types) +- [`isSeq(foo): boolean`](https://eemeli.org/yaml/#identifying-node-types) +- [`new Scalar(value)`](https://eemeli.org/yaml/#scalar-values) +- [`new YAMLMap()`](https://eemeli.org/yaml/#collections) +- [`new YAMLSeq()`](https://eemeli.org/yaml/#collections) +- [`doc.createAlias(node, name?): Alias`](https://eemeli.org/yaml/#creating-nodes) +- [`doc.createNode(value, options?): Node`](https://eemeli.org/yaml/#creating-nodes) +- [`doc.createPair(key, value): Pair`](https://eemeli.org/yaml/#creating-nodes) +- [`visit(node, visitor)`](https://eemeli.org/yaml/#finding-and-modifying-nodes) +- [`visitAsync(node, visitor)`](https://eemeli.org/yaml/#finding-and-modifying-nodes) + +### Parsing YAML + +```js +import { Composer, Lexer, Parser } from 'yaml' +``` + +- [`new Lexer().lex(src)`](https://eemeli.org/yaml/#lexer) +- [`new Parser(onNewLine?).parse(src)`](https://eemeli.org/yaml/#parser) +- [`new Composer(options?).compose(tokens)`](https://eemeli.org/yaml/#composer) + +## YAML.parse + +```yaml +# file.yml +YAML: + - A human-readable data serialization language + - https://en.wikipedia.org/wiki/YAML +yaml: + - A complete JavaScript implementation + - https://www.npmjs.com/package/yaml +``` + +```js +import fs from 'fs' +import YAML from 'yaml' + +YAML.parse('3.14159') +// 3.14159 + +YAML.parse('[ true, false, maybe, null ]\n') +// [ true, false, 'maybe', null ] + +const file = fs.readFileSync('./file.yml', 'utf8') +YAML.parse(file) +// { YAML: +// [ 'A human-readable data serialization language', +// 'https://en.wikipedia.org/wiki/YAML' ], +// yaml: +// [ 'A complete JavaScript implementation', +// 'https://www.npmjs.com/package/yaml' ] } +``` + +## YAML.stringify + +```js +import YAML from 'yaml' + +YAML.stringify(3.14159) +// '3.14159\n' + +YAML.stringify([true, false, 'maybe', null]) +// `- true +// - false +// - maybe +// - null +// ` + +YAML.stringify({ number: 3, plain: 'string', block: 'two\nlines\n' }) +// `number: 3 +// plain: string +// block: | +// two +// lines +// ` +``` + +--- + +Browser testing provided by: + + +BrowserStack + diff --git a/node_modules/yaml/bin.mjs b/node_modules/yaml/bin.mjs new file mode 100755 index 000000000..7504ae13b --- /dev/null +++ b/node_modules/yaml/bin.mjs @@ -0,0 +1,11 @@ +#!/usr/bin/env node + +import { UserError, cli, help } from './dist/cli.mjs' + +cli(process.stdin, error => { + if (error instanceof UserError) { + if (error.code === UserError.ARGS) console.error(`${help}\n`) + console.error(error.message) + process.exitCode = error.code + } else if (error) throw error +}) diff --git a/node_modules/yaml/browser/dist/compose/compose-collection.js b/node_modules/yaml/browser/dist/compose/compose-collection.js new file mode 100644 index 000000000..cb8eff768 --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/compose-collection.js @@ -0,0 +1,88 @@ +import { isNode } from '../nodes/identity.js'; +import { Scalar } from '../nodes/Scalar.js'; +import { YAMLMap } from '../nodes/YAMLMap.js'; +import { YAMLSeq } from '../nodes/YAMLSeq.js'; +import { resolveBlockMap } from './resolve-block-map.js'; +import { resolveBlockSeq } from './resolve-block-seq.js'; +import { resolveFlowCollection } from './resolve-flow-collection.js'; + +function resolveCollection(CN, ctx, token, onError, tagName, tag) { + const coll = token.type === 'block-map' + ? resolveBlockMap(CN, ctx, token, onError, tag) + : token.type === 'block-seq' + ? resolveBlockSeq(CN, ctx, token, onError, tag) + : resolveFlowCollection(CN, ctx, token, onError, tag); + const Coll = coll.constructor; + // If we got a tagName matching the class, or the tag name is '!', + // then use the tagName from the node class used to create it. + if (tagName === '!' || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken + ? null + : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg)); + if (token.type === 'block-seq') { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken + ? anchor.offset > tagToken.offset + ? anchor + : tagToken + : (anchor ?? tagToken); + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = 'Missing newline after block sequence props'; + onError(lastProp, 'MISSING_CHAR', message); + } + } + const expType = token.type === 'block-map' + ? 'map' + : token.type === 'block-seq' + ? 'seq' + : token.start.source === '{' + ? 'map' + : 'seq'; + // shortcut: check if it's a generic YAMLMap or YAMLSeq + // before jumping into the custom tag logic. + if (!tagToken || + !tagName || + tagName === '!' || + (tagName === YAMLMap.tagName && expType === 'map') || + (tagName === YAMLSeq.tagName && expType === 'seq')) { + return resolveCollection(CN, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } + else { + if (kt) { + onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? 'scalar'}`, true); + } + else { + onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll; + const node = isNode(res) + ? res + : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +export { composeCollection }; diff --git a/node_modules/yaml/browser/dist/compose/compose-doc.js b/node_modules/yaml/browser/dist/compose/compose-doc.js new file mode 100644 index 000000000..9827b53ca --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/compose-doc.js @@ -0,0 +1,43 @@ +import { Document } from '../doc/Document.js'; +import { composeNode, composeEmptyNode } from './compose-node.js'; +import { resolveEnd } from './resolve-end.js'; +import { resolveProps } from './resolve-props.js'; + +function composeDoc(options, directives, { offset, start, value, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(undefined, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: 'doc-start', + next: value ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value && + (value.type === 'block-map' || value.type === 'block-seq') && + !props.hasNewline) + onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker'); + } + // @ts-expect-error If Contents is set, let's trust the user + doc.contents = value + ? composeNode(ctx, value, props, onError) + : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +export { composeDoc }; diff --git a/node_modules/yaml/browser/dist/compose/compose-node.js b/node_modules/yaml/browser/dist/compose/compose-node.js new file mode 100644 index 000000000..cdc91b555 --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/compose-node.js @@ -0,0 +1,102 @@ +import { Alias } from '../nodes/Alias.js'; +import { isScalar } from '../nodes/identity.js'; +import { composeCollection } from './compose-collection.js'; +import { composeScalar } from './compose-scalar.js'; +import { resolveEnd } from './resolve-end.js'; +import { emptyScalarPosition } from './util-empty-scalar-position.js'; + +const CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case 'alias': + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties'); + break; + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + case 'block-scalar': + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case 'block-map': + case 'block-seq': + case 'flow-collection': + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + default: { + const message = token.type === 'error' + ? token.message + : `Unsupported token (type: ${token.type})`; + onError(token, 'UNEXPECTED_TOKEN', message); + node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError); + isSrcToken = false; + } + } + if (anchor && node.anchor === '') + onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string'); + if (atKey && + ctx.options.stringKeys && + (!isScalar(node) || + typeof node.value !== 'string' || + (node.tag && node.tag !== 'tag:yaml.org,2002:str'))) { + const msg = 'With stringKeys, all keys must be strings'; + onError(tag ?? token, 'NON_STRING_KEY', msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === 'scalar' && token.source === '') + node.comment = comment; + else + node.commentBefore = comment; + } + // @ts-expect-error Type checking misses meaning of isSrcToken + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: 'scalar', + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: '' + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === '') + onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string'); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === '') + onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string'); + if (alias.source.endsWith(':')) + onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +export { composeEmptyNode, composeNode }; diff --git a/node_modules/yaml/browser/dist/compose/compose-scalar.js b/node_modules/yaml/browser/dist/compose/compose-scalar.js new file mode 100644 index 000000000..13ceda554 --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/compose-scalar.js @@ -0,0 +1,86 @@ +import { isScalar, SCALAR } from '../nodes/identity.js'; +import { Scalar } from '../nodes/Scalar.js'; +import { resolveBlockScalar } from './resolve-block-scalar.js'; +import { resolveFlowScalar } from './resolve-flow-scalar.js'; + +function composeScalar(ctx, token, tagToken, onError) { + const { value, type, comment, range } = token.type === 'block-scalar' + ? resolveBlockScalar(ctx, token, onError) + : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken + ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg)) + : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } + else if (tagName) + tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError); + else if (token.type === 'scalar') + tag = findScalarTagByTest(ctx, value, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } + catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg); + scalar = new Scalar(value); + } + scalar.range = range; + scalar.source = value; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema, value, tagName, tagToken, onError) { + if (tagName === '!') + return schema[SCALAR]; // non-specific tag + const matchWithTest = []; + for (const tag of schema.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value)) + return tag; + const kt = schema.knownTags[tagName]; + if (kt && !kt.collection) { + // Ensure that the known tag is available for stringifying, + // but does not get used by default. + schema.tags.push(Object.assign({}, kt, { default: false, test: undefined })); + return kt; + } + onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str'); + return schema[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) { + const tag = schema.tags.find(tag => (tag.default === true || (atKey && tag.default === 'key')) && + tag.test?.test(value)) || schema[SCALAR]; + if (schema.compat) { + const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ?? + schema[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, 'TAG_RESOLVE_FAILED', msg, true); + } + } + return tag; +} + +export { composeScalar }; diff --git a/node_modules/yaml/browser/dist/compose/composer.js b/node_modules/yaml/browser/dist/compose/composer.js new file mode 100644 index 000000000..01b387f21 --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/composer.js @@ -0,0 +1,217 @@ +import { Directives } from '../doc/directives.js'; +import { Document } from '../doc/Document.js'; +import { YAMLWarning, YAMLParseError } from '../errors.js'; +import { isCollection, isPair } from '../nodes/identity.js'; +import { composeDoc } from './compose-doc.js'; +import { resolveEnd } from './resolve-end.js'; + +function getErrorPos(src) { + if (typeof src === 'number') + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === 'string' ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ''; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case '#': + comment += + (comment === '' ? '' : afterEmptyLine ? '\n\n' : '\n') + + (source.substring(1) || ' '); + atComment = true; + afterEmptyLine = false; + break; + case '%': + if (prelude[i + 1]?.[0] !== '#') + i += 1; + atComment = false; + break; + default: + // This may be wrong after doc-end, but in that case it doesn't matter + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +/** + * Compose a stream of CST nodes into a stream of YAML Documents. + * + * ```ts + * import { Composer, Parser } from 'yaml' + * + * const src: string = ... + * const tokens = new Parser().parse(src) + * const docs = new Composer().compose(tokens) + * ``` + */ +class Composer { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + this.directives = new Directives({ version: options.version || '1.2' }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + //console.log({ dc: doc.comment, prelude, comment }) + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment}\n${comment}` : comment; + } + else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } + else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment}\n${cb}` : comment; + } + else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment}\n${cb}` : comment; + } + } + if (afterDoc) { + Array.prototype.push.apply(doc.errors, this.errors); + Array.prototype.push.apply(doc.warnings, this.warnings); + } + else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case 'directive': + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, 'BAD_DIRECTIVE', message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case 'document': { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line'); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case 'byte-order-mark': + case 'space': + break; + case 'comment': + case 'newline': + this.prelude.push(token.source); + break; + case 'error': { + const msg = token.source + ? `${token.message}: ${JSON.stringify(token.source)}` + : token.message; + const error = new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case 'doc-end': { + if (!this.doc) { + const msg = 'Unexpected doc-end without preceding document'; + this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc}\n${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } + else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(undefined, opts); + if (this.atDirectives) + this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line'); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +} + +export { Composer }; diff --git a/node_modules/yaml/browser/dist/compose/resolve-block-map.js b/node_modules/yaml/browser/dist/compose/resolve-block-map.js new file mode 100644 index 000000000..d9b965d16 --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/resolve-block-map.js @@ -0,0 +1,115 @@ +import { Pair } from '../nodes/Pair.js'; +import { YAMLMap } from '../nodes/YAMLMap.js'; +import { resolveProps } from './resolve-props.js'; +import { containsNewline } from './util-contains-newline.js'; +import { flowIndentCheck } from './util-flow-indent-check.js'; +import { mapIncludes } from './util-map-includes.js'; + +const startColMsg = 'All mapping items must start at the same column'; +function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value } = collItem; + // key properties + const keyProps = resolveProps(start, { + indicator: 'explicit-key-ind', + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === 'block-seq') + onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key'); + else if ('indent' in key && key.indent !== bm.indent) + onError(offset, 'BAD_INDENT', startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map.comment) + map.comment += '\n' + keyProps.comment; + else + map.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line'); + } + } + else if (keyProps.found?.indent !== bm.indent) { + onError(offset, 'BAD_INDENT', startColMsg); + } + // key value + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key + ? composeNode(ctx, key, keyProps, onError) + : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map.items, keyNode)) + onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique'); + // value properties + const valueProps = resolveProps(sep ?? [], { + indicator: 'map-value-ind', + next: value, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === 'block-scalar' + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value?.type === 'block-map' && !valueProps.hasNewline) + onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings'); + if (ctx.options.strict && + keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key'); + } + // value value + const valueNode = value + ? composeNode(ctx, value, valueProps, onError) + : composeEmptyNode(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map.items.push(pair); + } + else { + // key with no value + if (implicitKey) + onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values'); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += '\n' + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content'); + map.range = [bm.offset, offset, commentEnd ?? offset]; + return map; +} + +export { resolveBlockMap }; diff --git a/node_modules/yaml/browser/dist/compose/resolve-block-scalar.js b/node_modules/yaml/browser/dist/compose/resolve-block-scalar.js new file mode 100644 index 000000000..9b7b7b558 --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/resolve-block-scalar.js @@ -0,0 +1,198 @@ +import { Scalar } from '../nodes/Scalar.js'; + +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: '', type: null, comment: '', range: [start, start, start] }; + const type = header.mode === '>' ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines = scalar.source ? splitLines(scalar.source) : []; + // determine the end of content & start of chomping + let chompStart = lines.length; + for (let i = lines.length - 1; i >= 0; --i) { + const content = lines[i][1]; + if (content === '' || content === '\r') + chompStart = i; + else + break; + } + // shortcut for empty contents + if (chompStart === 0) { + const value = header.chomp === '+' && lines.length > 0 + ? '\n'.repeat(Math.max(1, lines.length - 1)) + : ''; + let end = start + header.length; + if (scalar.source) + end += scalar.source.length; + return { value, type, comment: header.comment, range: [start, end, end] }; + } + // find the indentation level to trim from start + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines[i]; + if (content === '' || content === '\r') { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } + else { + if (indent.length < trimIndent) { + const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator'; + onError(offset + indent.length, 'MISSING_CHAR', message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = 'Block scalar values in collections must be indented'; + onError(offset, 'BAD_INDENT', message); + } + break; + } + offset += indent.length + content.length + 1; + } + // include trailing more-indented empty lines in content + for (let i = lines.length - 1; i >= chompStart; --i) { + if (lines[i][0].length > trimIndent) + chompStart = i + 1; + } + let value = ''; + let sep = ''; + let prevMoreIndented = false; + // leading whitespace is kept intact + for (let i = 0; i < contentStart; ++i) + value += lines[i][0].slice(trimIndent) + '\n'; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === '\r'; + if (crlf) + content = content.slice(0, -1); + /* istanbul ignore if already caught in lexer */ + if (content && indent.length < trimIndent) { + const src = header.indent + ? 'explicit indentation indicator' + : 'first line'; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message); + indent = ''; + } + if (type === Scalar.BLOCK_LITERAL) { + value += sep + indent.slice(trimIndent) + content; + sep = '\n'; + } + else if (indent.length > trimIndent || content[0] === '\t') { + // more-indented content within a folded block + if (sep === ' ') + sep = '\n'; + else if (!prevMoreIndented && sep === '\n') + sep = '\n\n'; + value += sep + indent.slice(trimIndent) + content; + sep = '\n'; + prevMoreIndented = true; + } + else if (content === '') { + // empty line + if (sep === '\n') + value += '\n'; + else + sep = '\n'; + } + else { + value += sep + content; + sep = ' '; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case '-': + break; + case '+': + for (let i = chompStart; i < lines.length; ++i) + value += '\n' + lines[i][0].slice(trimIndent); + if (value[value.length - 1] !== '\n') + value += '\n'; + break; + default: + value += '\n'; + } + const end = start + header.length + scalar.source.length; + return { value, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + /* istanbul ignore if should not happen */ + if (props[0].type !== 'block-scalar-header') { + onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found'); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ''; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === '-' || ch === '+')) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ''; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case 'space': + hasSpace = true; + // fallthrough + case 'newline': + length += token.source.length; + break; + case 'comment': + if (strict && !hasSpace) { + const message = 'Comments must be separated from other tokens by white space characters'; + onError(token, 'MISSING_CHAR', message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case 'error': + onError(token, 'UNEXPECTED_TOKEN', token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, 'UNEXPECTED_TOKEN', message); + const ts = token.source; + if (ts && typeof ts === 'string') + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +/** @returns Array of lines split up as `[indent, content]` */ +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] + ? [m[1], first.slice(m[1].length)] + : ['', first]; + const lines = [line0]; + for (let i = 1; i < split.length; i += 2) + lines.push([split[i], split[i + 1]]); + return lines; +} + +export { resolveBlockScalar }; diff --git a/node_modules/yaml/browser/dist/compose/resolve-block-seq.js b/node_modules/yaml/browser/dist/compose/resolve-block-seq.js new file mode 100644 index 000000000..ffc5289ac --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/resolve-block-seq.js @@ -0,0 +1,49 @@ +import { YAMLSeq } from '../nodes/YAMLSeq.js'; +import { resolveProps } from './resolve-props.js'; +import { flowIndentCheck } from './util-flow-indent-check.js'; + +function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value } of bs.items) { + const props = resolveProps(start, { + indicator: 'seq-item-ind', + next: value, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value) { + if (value?.type === 'block-seq') + onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column'); + else + onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator'); + } + else { + commentEnd = props.end; + if (props.comment) + seq.comment = props.comment; + continue; + } + } + const node = value + ? composeNode(ctx, value, props, onError) + : composeEmptyNode(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value, onError); + offset = node.range[2]; + seq.items.push(node); + } + seq.range = [bs.offset, offset, commentEnd ?? offset]; + return seq; +} + +export { resolveBlockSeq }; diff --git a/node_modules/yaml/browser/dist/compose/resolve-end.js b/node_modules/yaml/browser/dist/compose/resolve-end.js new file mode 100644 index 000000000..d5c65d7e8 --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/resolve-end.js @@ -0,0 +1,37 @@ +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ''; + if (end) { + let hasSpace = false; + let sep = ''; + for (const token of end) { + const { source, type } = token; + switch (type) { + case 'space': + hasSpace = true; + break; + case 'comment': { + if (reqSpace && !hasSpace) + onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters'); + const cb = source.substring(1) || ' '; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ''; + break; + } + case 'newline': + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +export { resolveEnd }; diff --git a/node_modules/yaml/browser/dist/compose/resolve-flow-collection.js b/node_modules/yaml/browser/dist/compose/resolve-flow-collection.js new file mode 100644 index 000000000..866efb75b --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/resolve-flow-collection.js @@ -0,0 +1,207 @@ +import { isPair } from '../nodes/identity.js'; +import { Pair } from '../nodes/Pair.js'; +import { YAMLMap } from '../nodes/YAMLMap.js'; +import { YAMLSeq } from '../nodes/YAMLSeq.js'; +import { resolveEnd } from './resolve-end.js'; +import { resolveProps } from './resolve-props.js'; +import { containsNewline } from './util-contains-newline.js'; +import { mapIncludes } from './util-map-includes.js'; + +const blockMsg = 'Block collections are not allowed within flow collections'; +const isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq'); +function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) { + const isMap = fc.start.source === '{'; + const fcName = isMap ? 'flow map' : 'flow sequence'; + const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap : YAMLSeq)); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: 'explicit-key-ind', + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value) { + if (i === 0 && props.comma) + onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += '\n' + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap && ctx.options.strict && containsNewline(key)) + onError(key, // checked by containsNewline() + 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line'); + } + if (i === 0) { + if (props.comma) + onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`); + } + else { + if (!props.comma) + onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ''; + loop: for (const st of start) { + switch (st.type) { + case 'comma': + case 'space': + break; + case 'comment': + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += '\n' + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap && !sep && !props.found) { + // item is a value in a seq + // → key & sep are empty, start does not include ? or : + const valueNode = value + ? composeNode(ctx, value, props, onError) + : composeEmptyNode(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value)) + onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg); + } + else { + // item is a key+value pair + // key value + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key + ? composeNode(ctx, key, props, onError) + : composeEmptyNode(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg); + ctx.atKey = false; + // value properties + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: 'map-value-ind', + next: value, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === 'newline') { + onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line'); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key'); + } + } + else if (value) { + if ('source' in value && value.source?.[0] === ':') + onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`); + else + onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`); + } + // value value + const valueNode = value + ? composeNode(ctx, value, valueProps, onError) + : valueProps.found + ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) + : null; + if (valueNode) { + if (isBlock(value)) + onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg); + } + else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += '\n' + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap) { + const map = coll; + if (mapIncludes(ctx, map.items, keyNode)) + onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique'); + map.items.push(pair); + } + else { + const map = new YAMLMap(ctx.schema); + map.flow = true; + map.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap ? '}' : ']'; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot + ? `${name} must end with a ${expectedEnd}` + : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += '\n' + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } + else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +export { resolveFlowCollection }; diff --git a/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js b/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js new file mode 100644 index 000000000..5da852698 --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js @@ -0,0 +1,223 @@ +import { Scalar } from '../nodes/Scalar.js'; +import { resolveEnd } from './resolve-end.js'; + +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case 'scalar': + _type = Scalar.PLAIN; + value = plainValue(source, _onError); + break; + case 'single-quoted-scalar': + _type = Scalar.QUOTE_SINGLE; + value = singleQuotedValue(source, _onError); + break; + case 'double-quoted-scalar': + _type = Scalar.QUOTE_DOUBLE; + value = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`); + return { + value: '', + type: null, + comment: '', + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ''; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case '\t': + badChar = 'a tab character'; + break; + case ',': + badChar = 'flow indicator character ,'; + break; + case '%': + badChar = 'directive indicator character %'; + break; + case '|': + case '>': { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case '@': + case '`': { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`); + return foldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, 'MISSING_CHAR', "Missing closing 'quote"); + return foldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function foldLines(source) { + /** + * The negative lookbehind here and in the `re` RegExp is to + * prevent causing a polynomial search time in certain cases. + * + * The try-catch is for Safari, which doesn't support this yet: + * https://caniuse.com/js-regexp-lookbehind + */ + let first, line; + try { + first = new RegExp('(.*?)(? wsStart ? source.slice(wsStart, i + 1) : ch; + } + else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, 'MISSING_CHAR', 'Missing closing "quote'); + return res; +} +/** + * Fold a single newline into a space, multiple newlines to N - 1 newlines. + * Presumes `source[offset] === '\n'` + */ +function foldNewline(source, offset) { + let fold = ''; + let ch = source[offset + 1]; + while (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') { + if (ch === '\r' && source[offset + 2] !== '\n') + break; + if (ch === '\n') + fold += '\n'; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = ' '; + return { fold, offset }; +} +const escapeCodes = { + '0': '\0', // null character + a: '\x07', // bell character + b: '\b', // backspace + e: '\x1b', // escape character + f: '\f', // form feed + n: '\n', // line feed + r: '\r', // carriage return + t: '\t', // horizontal tab + v: '\v', // vertical tab + N: '\u0085', // Unicode next line + _: '\u00a0', // Unicode non-breaking space + L: '\u2028', // Unicode line separator + P: '\u2029', // Unicode paragraph separator + ' ': ' ', + '"': '"', + '/': '/', + '\\': '\\', + '\t': '\t' +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + if (isNaN(code)) { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`); + return raw; + } + return String.fromCodePoint(code); +} + +export { resolveFlowScalar }; diff --git a/node_modules/yaml/browser/dist/compose/resolve-props.js b/node_modules/yaml/browser/dist/compose/resolve-props.js new file mode 100644 index 000000000..b6336e1eb --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/resolve-props.js @@ -0,0 +1,146 @@ +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ''; + let commentSep = ''; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== 'space' && + token.type !== 'newline' && + token.type !== 'comma') + onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space'); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== 'comment' && token.type !== 'newline') { + onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation'); + } + tab = null; + } + switch (token.type) { + case 'space': + // At the doc level, tabs at line start may be parsed + // as leading white space rather than indentation. + // In a flow collection, only the parser handles indent. + if (!flow && + (indicator !== 'doc-start' || next?.type !== 'flow-collection') && + token.source.includes('\t')) { + tab = token; + } + hasSpace = true; + break; + case 'comment': { + if (!hasSpace) + onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters'); + const cb = token.source.substring(1) || ' '; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ''; + atNewline = false; + break; + } + case 'newline': + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== 'seq-item-ind') + spaceBefore = true; + } + else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case 'anchor': + if (anchor) + onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor'); + if (token.source.endsWith(':')) + onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case 'tag': { + if (tag) + onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag'); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + // Could here handle preceding comments differently + if (anchor || tag) + onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`); + found = token; + atNewline = + indicator === 'seq-item-ind' || indicator === 'explicit-key-ind'; + hasSpace = false; + break; + case 'comma': + if (flow) { + if (comma) + onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && + next && + next.type !== 'space' && + next.type !== 'newline' && + next.type !== 'comma' && + (next.type !== 'scalar' || next.source !== '')) { + onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space'); + } + if (tab && + ((atNewline && tab.indent <= parentIndent) || + next?.type === 'block-map' || + next?.type === 'block-seq')) + onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation'); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +export { resolveProps }; diff --git a/node_modules/yaml/browser/dist/compose/util-contains-newline.js b/node_modules/yaml/browser/dist/compose/util-contains-newline.js new file mode 100644 index 000000000..2d65390d6 --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/util-contains-newline.js @@ -0,0 +1,34 @@ +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case 'alias': + case 'scalar': + case 'double-quoted-scalar': + case 'single-quoted-scalar': + if (key.source.includes('\n')) + return true; + if (key.end) + for (const st of key.end) + if (st.type === 'newline') + return true; + return false; + case 'flow-collection': + for (const it of key.items) { + for (const st of it.start) + if (st.type === 'newline') + return true; + if (it.sep) + for (const st of it.sep) + if (st.type === 'newline') + return true; + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +export { containsNewline }; diff --git a/node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js b/node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js new file mode 100644 index 000000000..26f238c5f --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js @@ -0,0 +1,26 @@ +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case 'space': + case 'comment': + case 'newline': + offset -= st.source.length; + continue; + } + // Technically, an empty scalar is immediately after the last non-empty + // node, but it's more useful to place it after any whitespace. + st = before[++i]; + while (st?.type === 'space') { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +export { emptyScalarPosition }; diff --git a/node_modules/yaml/browser/dist/compose/util-flow-indent-check.js b/node_modules/yaml/browser/dist/compose/util-flow-indent-check.js new file mode 100644 index 000000000..c20e67019 --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/util-flow-indent-check.js @@ -0,0 +1,15 @@ +import { containsNewline } from './util-contains-newline.js'; + +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === 'flow-collection') { + const end = fc.end[0]; + if (end.indent === indent && + (end.source === ']' || end.source === '}') && + containsNewline(fc)) { + const msg = 'Flow end indicator should be more indented than parent'; + onError(end, 'BAD_INDENT', msg, true); + } + } +} + +export { flowIndentCheck }; diff --git a/node_modules/yaml/browser/dist/compose/util-map-includes.js b/node_modules/yaml/browser/dist/compose/util-map-includes.js new file mode 100644 index 000000000..48444b641 --- /dev/null +++ b/node_modules/yaml/browser/dist/compose/util-map-includes.js @@ -0,0 +1,13 @@ +import { isScalar } from '../nodes/identity.js'; + +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === 'function' + ? uniqueKeys + : (a, b) => a === b || (isScalar(a) && isScalar(b) && a.value === b.value); + return items.some(pair => isEqual(pair.key, search)); +} + +export { mapIncludes }; diff --git a/node_modules/yaml/browser/dist/doc/Document.js b/node_modules/yaml/browser/dist/doc/Document.js new file mode 100644 index 000000000..f1f427807 --- /dev/null +++ b/node_modules/yaml/browser/dist/doc/Document.js @@ -0,0 +1,335 @@ +import { Alias } from '../nodes/Alias.js'; +import { isEmptyPath, collectionFromPath } from '../nodes/Collection.js'; +import { NODE_TYPE, DOC, isNode, isCollection, isScalar } from '../nodes/identity.js'; +import { Pair } from '../nodes/Pair.js'; +import { toJS } from '../nodes/toJS.js'; +import { Schema } from '../schema/Schema.js'; +import { stringifyDocument } from '../stringify/stringifyDocument.js'; +import { anchorNames, findNewAnchor, createNodeAnchors } from './anchors.js'; +import { applyReviver } from './applyReviver.js'; +import { createNode } from './createNode.js'; +import { Directives } from './directives.js'; + +class Document { + constructor(value, replacer, options) { + /** A comment before this Document */ + this.commentBefore = null; + /** A comment immediately after this Document */ + this.comment = null; + /** Errors encountered during parsing. */ + this.errors = []; + /** Warnings encountered during parsing. */ + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === 'function' || Array.isArray(replacer)) { + _replacer = replacer; + } + else if (options === undefined && replacer) { + options = replacer; + replacer = undefined; + } + const opt = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: 'warn', + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: '1.2' + }, options); + this.options = opt; + let { version } = opt; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } + else + this.directives = new Directives({ version }); + this.setSchema(version, options); + // @ts-expect-error We can't really know that this matches Contents. + this.contents = + value === undefined ? null : this.createNode(value, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy = Object.create(Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy.commentBefore = this.commentBefore; + copy.comment = this.comment; + copy.errors = this.errors.slice(); + copy.warnings = this.warnings.slice(); + copy.options = Object.assign({}, this.options); + if (this.directives) + copy.directives = this.directives.clone(); + copy.schema = this.schema.clone(); + // @ts-expect-error We can't really know that this matches Contents. + copy.contents = isNode(this.contents) + ? this.contents.clone(copy.schema) + : this.contents; + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** Adds a value to the document. */ + add(value) { + if (assertCollection(this.contents)) + this.contents.add(value); + } + /** Adds a value to the document. */ + addIn(path, value) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name; + } + return new Alias(node.anchor); + } + createNode(value, replacer, options) { + let _replacer = undefined; + if (typeof replacer === 'function') { + value = replacer.call({ '': value }, '', value); + _replacer = replacer; + } + else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } + else if (options === undefined && replacer) { + options = replacer; + replacer = undefined; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || 'a'); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode(value, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + // @ts-expect-error Presumed impossible if Strict extends false + this.contents = null; + return true; + } + return assertCollection(this.contents) + ? this.contents.deleteIn(path) + : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) + ? this.contents.get(key, keepScalar) + : undefined; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) + ? this.contents.value + : this.contents; + return isCollection(this.contents) + ? this.contents.getIn(path, keepScalar) + : undefined; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== undefined; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value) { + if (this.contents == null) { + // @ts-expect-error We can't really know that this matches Contents. + this.contents = collectionFromPath(this.schema, [key], value); + } + else if (assertCollection(this.contents)) { + this.contents.set(key, value); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + if (isEmptyPath(path)) { + // @ts-expect-error We can't really know that this matches Contents. + this.contents = value; + } + else if (this.contents == null) { + // @ts-expect-error We can't really know that this matches Contents. + this.contents = collectionFromPath(this.schema, Array.from(path), value); + } + else if (assertCollection(this.contents)) { + this.contents.setIn(path, value); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === 'number') + version = String(version); + let opt; + switch (version) { + case '1.1': + if (this.directives) + this.directives.yaml.version = '1.1'; + else + this.directives = new Directives({ version: '1.1' }); + opt = { resolveKnownTags: false, schema: 'yaml-1.1' }; + break; + case '1.2': + case 'next': + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt = { resolveKnownTags: true, schema: 'core' }; + break; + case null: + if (this.directives) + delete this.directives; + opt = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + // Not using `instanceof Schema` to allow for duck typing + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt) + this.schema = new Schema(Object.assign(opt, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? '', ctx); + if (typeof onAnchor === 'function') + for (const { count, res } of ctx.anchors.values()) + onAnchor(res, count); + return typeof reviver === 'function' + ? applyReviver(reviver, { '': res }, '', res) + : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error('Document with errors cannot be stringified'); + if ('indent' in options && + (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +} +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error('Expected a YAML collection as document contents'); +} + +export { Document }; diff --git a/node_modules/yaml/browser/dist/doc/anchors.js b/node_modules/yaml/browser/dist/doc/anchors.js new file mode 100644 index 000000000..64810d144 --- /dev/null +++ b/node_modules/yaml/browser/dist/doc/anchors.js @@ -0,0 +1,71 @@ +import { isScalar, isCollection } from '../nodes/identity.js'; +import { visit } from '../visit.js'; + +/** + * Verify that the input string is a valid anchor. + * + * Will throw on errors. + */ +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root) { + const anchors = new Set(); + visit(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */ +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === 'object' && + ref.anchor && + (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } + else { + const error = new Error('Failed to resolve repeated object (this should not happen)'); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +export { anchorIsValid, anchorNames, createNodeAnchors, findNewAnchor }; diff --git a/node_modules/yaml/browser/dist/doc/applyReviver.js b/node_modules/yaml/browser/dist/doc/applyReviver.js new file mode 100644 index 000000000..6e77336ea --- /dev/null +++ b/node_modules/yaml/browser/dist/doc/applyReviver.js @@ -0,0 +1,55 @@ +/** + * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec, + * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the + * 2021 edition: https://tc39.es/ecma262/#sec-json.parse + * + * Includes extensions for handling Map and Set objects. + */ +function applyReviver(reviver, obj, key, val) { + if (val && typeof val === 'object') { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + // eslint-disable-next-line @typescript-eslint/no-array-delete + if (v1 === undefined) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } + else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === undefined) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } + else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === undefined) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } + else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === undefined) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj, key, val); +} + +export { applyReviver }; diff --git a/node_modules/yaml/browser/dist/doc/createNode.js b/node_modules/yaml/browser/dist/doc/createNode.js new file mode 100644 index 000000000..ddcc2111f --- /dev/null +++ b/node_modules/yaml/browser/dist/doc/createNode.js @@ -0,0 +1,88 @@ +import { Alias } from '../nodes/Alias.js'; +import { isNode, isPair, MAP, SEQ, isDocument } from '../nodes/identity.js'; +import { Scalar } from '../nodes/Scalar.js'; + +const defaultTagPrefix = 'tag:yaml.org,2002:'; +function findTagObject(value, tagName, tags) { + if (tagName) { + const match = tags.filter(t => t.tag === tagName); + const tagObj = match.find(t => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find(t => t.identify?.(value) && !t.format); +} +function createNode(value, tagName, ctx) { + if (isDocument(value)) + value = value.contents; + if (isNode(value)) + return value; + if (isPair(value)) { + const map = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map.items.push(value); + return map; + } + if (value instanceof String || + value instanceof Number || + value instanceof Boolean || + (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere + ) { + // https://tc39.es/ecma262/#sec-serializejsonproperty + value = value.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx; + // Detect duplicate references to the same object & use Alias nodes for all + // after first. The `ref` wrapper allows for circular references to resolve. + let ref = undefined; + if (aliasDuplicateObjects && value && typeof value === 'object') { + ref = sourceObjects.get(value); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value)); + return new Alias(ref.anchor); + } + else { + ref = { anchor: null, node: null }; + sourceObjects.set(value, ref); + } + } + if (tagName?.startsWith('!!')) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema.tags); + if (!tagObj) { + if (value && typeof value.toJSON === 'function') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + value = value.toJSON(); + } + if (!value || typeof value !== 'object') { + const node = new Scalar(value); + if (ref) + ref.node = node; + return node; + } + tagObj = + value instanceof Map + ? schema[MAP] + : Symbol.iterator in Object(value) + ? schema[SEQ] + : schema[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode + ? tagObj.createNode(ctx.schema, value, ctx) + : typeof tagObj?.nodeClass?.from === 'function' + ? tagObj.nodeClass.from(ctx.schema, value, ctx) + : new Scalar(value); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +export { createNode }; diff --git a/node_modules/yaml/browser/dist/doc/directives.js b/node_modules/yaml/browser/dist/doc/directives.js new file mode 100644 index 000000000..c66e61203 --- /dev/null +++ b/node_modules/yaml/browser/dist/doc/directives.js @@ -0,0 +1,176 @@ +import { isNode } from '../nodes/identity.js'; +import { visit } from '../visit.js'; + +const escapeChars = { + '!': '%21', + ',': '%2C', + '[': '%5B', + ']': '%5D', + '{': '%7B', + '}': '%7D' +}; +const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, ch => escapeChars[ch]); +class Directives { + constructor(yaml, tags) { + /** + * The directives-end/doc-start marker `---`. If `null`, a marker may still be + * included in the document's stringified representation. + */ + this.docStart = null; + /** The doc-end marker `...`. */ + this.docEnd = false; + this.yaml = Object.assign({}, Directives.defaultYaml, yaml); + this.tags = Object.assign({}, Directives.defaultTags, tags); + } + clone() { + const copy = new Directives(this.yaml, this.tags); + copy.docStart = this.docStart; + return copy; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case '1.1': + this.atNextDocument = true; + break; + case '1.2': + this.atNextDocument = false; + this.yaml = { + explicit: Directives.defaultYaml.explicit, + version: '1.2' + }; + this.tags = Object.assign({}, Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' }; + this.tags = Object.assign({}, Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case '%TAG': { + if (parts.length !== 2) { + onError(0, '%TAG directive should contain exactly two parts'); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case '%YAML': { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, '%YAML directive should contain exactly one part'); + return false; + } + const [version] = parts; + if (version === '1.1' || version === '1.2') { + this.yaml.version = version; + return true; + } + else { + const isValid = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === '!') + return '!'; // non-specific tag + if (source[0] !== '!') { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === '<') { + const verbatim = source.slice(2, -1); + if (verbatim === '!' || verbatim === '!!') { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== '>') + onError('Verbatim tags must end with a >'); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } + catch (error) { + onError(String(error)); + return null; + } + } + if (handle === '!') + return source; // local tag + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === '!' ? tag : `!<${tag}>`; + } + toString(doc) { + const lines = this.yaml.explicit + ? [`%YAML ${this.yaml.version || '1.2'}`] + : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } + else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === '!!' && prefix === 'tag:yaml.org,2002:') + continue; + if (!doc || tagNames.some(tn => tn.startsWith(prefix))) + lines.push(`%TAG ${handle} ${prefix}`); + } + return lines.join('\n'); + } +} +Directives.defaultYaml = { explicit: false, version: '1.2' }; +Directives.defaultTags = { '!!': 'tag:yaml.org,2002:' }; + +export { Directives }; diff --git a/node_modules/yaml/browser/dist/errors.js b/node_modules/yaml/browser/dist/errors.js new file mode 100644 index 000000000..06f05fa30 --- /dev/null +++ b/node_modules/yaml/browser/dist/errors.js @@ -0,0 +1,57 @@ +class YAMLError extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +} +class YAMLParseError extends YAMLError { + constructor(pos, code, message) { + super('YAMLParseError', pos, code, message); + } +} +class YAMLWarning extends YAMLError { + constructor(pos, code, message) { + super('YAMLWarning', pos, code, message); + } +} +const prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map(pos => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src + .substring(lc.lineStarts[line - 1], lc.lineStarts[line]) + .replace(/[\n\r]+$/, ''); + // Trim to max 80 chars, keeping col position near the middle + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = '…' + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + '…'; + // Include previous line in context if pointing at line start + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + // Regexp won't match if start is trimmed + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + '…\n'; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer = ' '.repeat(ci) + '^'.repeat(count); + error.message += `:\n\n${lineStr}\n${pointer}\n`; + } +}; + +export { YAMLError, YAMLParseError, YAMLWarning, prettifyError }; diff --git a/node_modules/yaml/browser/dist/index.js b/node_modules/yaml/browser/dist/index.js new file mode 100644 index 000000000..097bf249f --- /dev/null +++ b/node_modules/yaml/browser/dist/index.js @@ -0,0 +1,17 @@ +export { Composer } from './compose/composer.js'; +export { Document } from './doc/Document.js'; +export { Schema } from './schema/Schema.js'; +export { YAMLError, YAMLParseError, YAMLWarning } from './errors.js'; +export { Alias } from './nodes/Alias.js'; +export { isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq } from './nodes/identity.js'; +export { Pair } from './nodes/Pair.js'; +export { Scalar } from './nodes/Scalar.js'; +export { YAMLMap } from './nodes/YAMLMap.js'; +export { YAMLSeq } from './nodes/YAMLSeq.js'; +import * as cst from './parse/cst.js'; +export { cst as CST }; +export { Lexer } from './parse/lexer.js'; +export { LineCounter } from './parse/line-counter.js'; +export { Parser } from './parse/parser.js'; +export { parse, parseAllDocuments, parseDocument, stringify } from './public-api.js'; +export { visit, visitAsync } from './visit.js'; diff --git a/node_modules/yaml/browser/dist/log.js b/node_modules/yaml/browser/dist/log.js new file mode 100644 index 000000000..d9ec3578e --- /dev/null +++ b/node_modules/yaml/browser/dist/log.js @@ -0,0 +1,11 @@ +function debug(logLevel, ...messages) { + if (logLevel === 'debug') + console.log(...messages); +} +function warn(logLevel, warning) { + if (logLevel === 'debug' || logLevel === 'warn') { + console.warn(warning); + } +} + +export { debug, warn }; diff --git a/node_modules/yaml/browser/dist/nodes/Alias.js b/node_modules/yaml/browser/dist/nodes/Alias.js new file mode 100644 index 000000000..e301ab826 --- /dev/null +++ b/node_modules/yaml/browser/dist/nodes/Alias.js @@ -0,0 +1,114 @@ +import { anchorIsValid } from '../doc/anchors.js'; +import { visit } from '../visit.js'; +import { ALIAS, isAlias, isCollection, isPair, hasAnchor } from './identity.js'; +import { NodeBase } from './Node.js'; +import { toJS } from './toJS.js'; + +class Alias extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, 'tag', { + set() { + throw new Error('Alias nodes cannot have tags'); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } + else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = undefined; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const { anchors, doc, maxAliasCount } = ctx; + const source = this.resolve(doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + let data = anchors.get(source); + if (!data) { + // Resolve anchors for Node.prototype.toJS() + toJS(source, null, ctx); + data = anchors.get(source); + } + /* istanbul ignore if */ + if (data?.res === undefined) { + const msg = 'This should not happen: Alias anchor was not resolved?'; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc, source, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = 'Excessive alias count indicates a resource exhaustion attack'; + throw new ReferenceError(msg); + } + } + return data.res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +} +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } + else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } + else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +export { Alias }; diff --git a/node_modules/yaml/browser/dist/nodes/Collection.js b/node_modules/yaml/browser/dist/nodes/Collection.js new file mode 100644 index 000000000..0ebdeda03 --- /dev/null +++ b/node_modules/yaml/browser/dist/nodes/Collection.js @@ -0,0 +1,147 @@ +import { createNode } from '../doc/createNode.js'; +import { isNode, isPair, isCollection, isScalar } from './identity.js'; +import { NodeBase } from './Node.js'; + +function collectionFromPath(schema, path, value) { + let v = value; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === 'number' && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } + else { + v = new Map([[k, v]]); + } + } + return createNode(v, undefined, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error('This should not happen, please report a bug.'); + }, + schema, + sourceObjects: new Map() + }); +} +// Type guard is intentionally a little wrong so as to be more useful, +// as it does not cover untypable empty non-string iterables (e.g. []). +const isEmptyPath = (path) => path == null || + (typeof path === 'object' && !!path[Symbol.iterator]().next().done); +class Collection extends NodeBase { + constructor(type, schema) { + super(type); + Object.defineProperty(this, 'schema', { + value: schema, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema) { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema) + copy.schema = schema; + copy.items = copy.items.map(it => isNode(it) || isPair(it) ? it.clone(schema) : it); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value) { + if (isEmptyPath(path)) + this.add(value); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value); + else if (node === undefined && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : undefined; + } + hasAllNullValues(allowScalar) { + return this.items.every(node => { + if (!isPair(node)) + return false; + const n = node.value; + return (n == null || + (allowScalar && + isScalar(n) && + n.value == null && + !n.commentBefore && + !n.comment && + !n.tag)); + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value); + } + else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value); + else if (node === undefined && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +} + +export { Collection, collectionFromPath, isEmptyPath }; diff --git a/node_modules/yaml/browser/dist/nodes/Node.js b/node_modules/yaml/browser/dist/nodes/Node.js new file mode 100644 index 000000000..b0eb96b2d --- /dev/null +++ b/node_modules/yaml/browser/dist/nodes/Node.js @@ -0,0 +1,38 @@ +import { applyReviver } from '../doc/applyReviver.js'; +import { NODE_TYPE, isDocument } from './identity.js'; +import { toJS } from './toJS.js'; + +class NodeBase { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError('A document argument is required'); + const ctx = { + anchors: new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100 + }; + const res = toJS(this, '', ctx); + if (typeof onAnchor === 'function') + for (const { count, res } of ctx.anchors.values()) + onAnchor(res, count); + return typeof reviver === 'function' + ? applyReviver(reviver, { '': res }, '', res) + : res; + } +} + +export { NodeBase }; diff --git a/node_modules/yaml/browser/dist/nodes/Pair.js b/node_modules/yaml/browser/dist/nodes/Pair.js new file mode 100644 index 000000000..6e419f6b1 --- /dev/null +++ b/node_modules/yaml/browser/dist/nodes/Pair.js @@ -0,0 +1,36 @@ +import { createNode } from '../doc/createNode.js'; +import { stringifyPair } from '../stringify/stringifyPair.js'; +import { addPairToJSMap } from './addPairToJSMap.js'; +import { NODE_TYPE, PAIR, isNode } from './identity.js'; + +function createPair(key, value, ctx) { + const k = createNode(key, undefined, ctx); + const v = createNode(value, undefined, ctx); + return new Pair(k, v); +} +class Pair { + constructor(key, value = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value; + } + clone(schema) { + let { key, value } = this; + if (isNode(key)) + key = key.clone(schema); + if (isNode(value)) + value = value.clone(schema); + return new Pair(key, value); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc + ? stringifyPair(this, ctx, onComment, onChompKeep) + : JSON.stringify(this); + } +} + +export { Pair, createPair }; diff --git a/node_modules/yaml/browser/dist/nodes/Scalar.js b/node_modules/yaml/browser/dist/nodes/Scalar.js new file mode 100644 index 000000000..a9f2673b2 --- /dev/null +++ b/node_modules/yaml/browser/dist/nodes/Scalar.js @@ -0,0 +1,24 @@ +import { SCALAR } from './identity.js'; +import { NodeBase } from './Node.js'; +import { toJS } from './toJS.js'; + +const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object'); +class Scalar extends NodeBase { + constructor(value) { + super(SCALAR); + this.value = value; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +} +Scalar.BLOCK_FOLDED = 'BLOCK_FOLDED'; +Scalar.BLOCK_LITERAL = 'BLOCK_LITERAL'; +Scalar.PLAIN = 'PLAIN'; +Scalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE'; +Scalar.QUOTE_SINGLE = 'QUOTE_SINGLE'; + +export { Scalar, isScalarValue }; diff --git a/node_modules/yaml/browser/dist/nodes/YAMLMap.js b/node_modules/yaml/browser/dist/nodes/YAMLMap.js new file mode 100644 index 000000000..6c6a50470 --- /dev/null +++ b/node_modules/yaml/browser/dist/nodes/YAMLMap.js @@ -0,0 +1,144 @@ +import { stringifyCollection } from '../stringify/stringifyCollection.js'; +import { addPairToJSMap } from './addPairToJSMap.js'; +import { Collection } from './Collection.js'; +import { MAP, isPair, isScalar } from './identity.js'; +import { Pair, createPair } from './Pair.js'; +import { isScalarValue } from './Scalar.js'; + +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return undefined; +} +class YAMLMap extends Collection { + static get tagName() { + return 'tag:yaml.org,2002:map'; + } + constructor(schema) { + super(MAP, schema); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema, obj, ctx) { + const { keepUndefined, replacer } = ctx; + const map = new this(schema); + const add = (key, value) => { + if (typeof replacer === 'function') + value = replacer.call(obj, key, value); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value !== undefined || keepUndefined) + map.items.push(createPair(key, value, ctx)); + }; + if (obj instanceof Map) { + for (const [key, value] of obj) + add(key, value); + } + else if (obj && typeof obj === 'object') { + for (const key of Object.keys(obj)) + add(key, obj[key]); + } + if (typeof schema.sortMapEntries === 'function') { + map.items.sort(schema.sortMapEntries); + } + return map; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== 'object' || !('key' in pair)) { + // In TypeScript, this never happens. + _pair = new Pair(pair, pair?.value); + } + else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + // For scalars, keep the old node & its comments and anchors + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } + else if (sortEntries) { + const i = this.items.findIndex(item => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } + else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? undefined; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value) { + this.add(new Pair(key, value), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map); + for (const item of this.items) + addPairToJSMap(ctx, map, item); + return map; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: '', + flowChars: { start: '{', end: '}' }, + itemIndent: ctx.indent || '', + onChompKeep, + onComment + }); + } +} + +export { YAMLMap, findPair }; diff --git a/node_modules/yaml/browser/dist/nodes/YAMLSeq.js b/node_modules/yaml/browser/dist/nodes/YAMLSeq.js new file mode 100644 index 000000000..b80de40a2 --- /dev/null +++ b/node_modules/yaml/browser/dist/nodes/YAMLSeq.js @@ -0,0 +1,113 @@ +import { createNode } from '../doc/createNode.js'; +import { stringifyCollection } from '../stringify/stringifyCollection.js'; +import { Collection } from './Collection.js'; +import { SEQ, isScalar } from './identity.js'; +import { isScalarValue } from './Scalar.js'; +import { toJS } from './toJS.js'; + +class YAMLSeq extends Collection { + static get tagName() { + return 'tag:yaml.org,2002:seq'; + } + constructor(schema) { + super(SEQ, schema); + this.items = []; + } + add(value) { + this.items.push(value); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') + return undefined; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === 'number' && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value)) + prev.value = value; + else + this.items[idx] = value; + } + toJSON(_, ctx) { + const seq = []; + if (ctx?.onCreate) + ctx.onCreate(seq); + let i = 0; + for (const item of this.items) + seq.push(toJS(item, String(i++), ctx)); + return seq; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: '- ', + flowChars: { start: '[', end: ']' }, + itemIndent: (ctx.indent || '') + ' ', + onChompKeep, + onComment + }); + } + static from(schema, obj, ctx) { + const { replacer } = ctx; + const seq = new this(schema); + if (obj && Symbol.iterator in Object(obj)) { + let i = 0; + for (let it of obj) { + if (typeof replacer === 'function') { + const key = obj instanceof Set ? it : String(i++); + it = replacer.call(obj, key, it); + } + seq.items.push(createNode(it, undefined, ctx)); + } + } + return seq; + } +} +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === 'string') + idx = Number(idx); + return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0 + ? idx + : null; +} + +export { YAMLSeq }; diff --git a/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js b/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js new file mode 100644 index 000000000..8e671cb4f --- /dev/null +++ b/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js @@ -0,0 +1,63 @@ +import { warn } from '../log.js'; +import { isMergeKey, addMergeToJSMap } from '../schema/yaml-1.1/merge.js'; +import { createStringifyContext } from '../stringify/stringify.js'; +import { isNode } from './identity.js'; +import { toJS } from './toJS.js'; + +function addPairToJSMap(ctx, map, { key, value }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map, value); + // TODO: Should drop this special case for bare << handling + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map, value); + else { + const jsKey = toJS(key, '', ctx); + if (map instanceof Map) { + map.set(jsKey, toJS(value, jsKey, ctx)); + } + else if (map instanceof Set) { + map.add(jsKey); + } + else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value, stringKey, ctx); + if (stringKey in map) + Object.defineProperty(map, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map[stringKey] = jsValue; + } + } + return map; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ''; + // eslint-disable-next-line @typescript-eslint/no-base-to-string + if (typeof jsKey !== 'object') + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +export { addPairToJSMap }; diff --git a/node_modules/yaml/browser/dist/nodes/identity.js b/node_modules/yaml/browser/dist/nodes/identity.js new file mode 100644 index 000000000..7b79920dc --- /dev/null +++ b/node_modules/yaml/browser/dist/nodes/identity.js @@ -0,0 +1,36 @@ +const ALIAS = Symbol.for('yaml.alias'); +const DOC = Symbol.for('yaml.document'); +const MAP = Symbol.for('yaml.map'); +const PAIR = Symbol.for('yaml.pair'); +const SCALAR = Symbol.for('yaml.scalar'); +const SEQ = Symbol.for('yaml.seq'); +const NODE_TYPE = Symbol.for('yaml.node.type'); +const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS; +const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC; +const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP; +const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR; +const isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR; +const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === 'object') + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === 'object') + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +export { ALIAS, DOC, MAP, NODE_TYPE, PAIR, SCALAR, SEQ, hasAnchor, isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq }; diff --git a/node_modules/yaml/browser/dist/nodes/toJS.js b/node_modules/yaml/browser/dist/nodes/toJS.js new file mode 100644 index 000000000..0ca625095 --- /dev/null +++ b/node_modules/yaml/browser/dist/nodes/toJS.js @@ -0,0 +1,37 @@ +import { hasAnchor } from './identity.js'; + +/** + * Recursively convert any node or its contents to native JavaScript + * + * @param value - The input value + * @param arg - If `value` defines a `toJSON()` method, use this + * as its first argument + * @param ctx - Conversion context, originally set in Document#toJS(). If + * `{ keep: true }` is not set, output should be suitable for JSON + * stringification. + */ +function toJS(value, arg, ctx) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + if (Array.isArray(value)) + return value.map((v, i) => toJS(v, String(i), ctx)); + if (value && typeof value.toJSON === 'function') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + if (!ctx || !hasAnchor(value)) + return value.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: undefined }; + ctx.anchors.set(value, data); + ctx.onCreate = res => { + data.res = res; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value === 'bigint' && !ctx?.keep) + return Number(value); + return value; +} + +export { toJS }; diff --git a/node_modules/yaml/browser/dist/parse/cst-scalar.js b/node_modules/yaml/browser/dist/parse/cst-scalar.js new file mode 100644 index 000000000..29ab354b5 --- /dev/null +++ b/node_modules/yaml/browser/dist/parse/cst-scalar.js @@ -0,0 +1,214 @@ +import { resolveBlockScalar } from '../compose/resolve-block-scalar.js'; +import { resolveFlowScalar } from '../compose/resolve-flow-scalar.js'; +import { YAMLParseError } from '../errors.js'; +import { stringifyString } from '../stringify/stringifyString.js'; + +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + return resolveFlowScalar(token, strict, _onError); + case 'block-scalar': + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +/** + * Create a new scalar token with `value` + * + * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`, + * as this function does not support any schema operations and won't check for such conflicts. + * + * @param value The string representation of the value, which will have its content properly indented. + * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added. + * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value. + * @param context.indent The indent level of the token. + * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value. + * @param context.offset The offset position of the token. + * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`. + */ +function createScalarToken(value, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context; + const source = stringifyString({ type, value }, { + implicitKey, + indent: indent > 0 ? ' '.repeat(indent) : '', + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: 'newline', offset: -1, indent, source: '\n' } + ]; + switch (source[0]) { + case '|': + case '>': { + const he = source.indexOf('\n'); + const head = source.substring(0, he); + const body = source.substring(he + 1) + '\n'; + const props = [ + { type: 'block-scalar-header', offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: 'newline', offset: -1, indent, source: '\n' }); + return { type: 'block-scalar', offset, indent, props, source: body }; + } + case '"': + return { type: 'double-quoted-scalar', offset, indent, source, end }; + case "'": + return { type: 'single-quoted-scalar', offset, indent, source, end }; + default: + return { type: 'scalar', offset, indent, source, end }; + } +} +/** + * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have. + * + * Best efforts are made to retain any comments previously associated with the `token`, + * though all contents within a collection's `items` will be overwritten. + * + * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`, + * as this function does not support any schema operations and won't check for such conflicts. + * + * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key. + * @param value The string representation of the value, which will have its content properly indented. + * @param context.afterKey In most cases, values after a key should have an additional level of indentation. + * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value. + * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value. + * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`. + */ +function setScalarValue(token, value, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = 'indent' in token ? token.indent : null; + if (afterKey && typeof indent === 'number') + indent += 2; + if (!type) + switch (token.type) { + case 'single-quoted-scalar': + type = 'QUOTE_SINGLE'; + break; + case 'double-quoted-scalar': + type = 'QUOTE_DOUBLE'; + break; + case 'block-scalar': { + const header = token.props[0]; + if (header.type !== 'block-scalar-header') + throw new Error('Invalid block scalar header'); + type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL'; + break; + } + default: + type = 'PLAIN'; + } + const source = stringifyString({ type, value }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '', + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case '|': + case '>': + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, 'double-quoted-scalar'); + break; + case "'": + setFlowScalarValue(token, source, 'single-quoted-scalar'); + break; + default: + setFlowScalarValue(token, source, 'scalar'); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf('\n'); + const head = source.substring(0, he); + const body = source.substring(he + 1) + '\n'; + if (token.type === 'block-scalar') { + const header = token.props[0]; + if (header.type !== 'block-scalar-header') + throw new Error('Invalid block scalar header'); + header.source = head; + token.source = body; + } + else { + const { offset } = token; + const indent = 'indent' in token ? token.indent : -1; + const props = [ + { type: 'block-scalar-header', offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined)) + props.push({ type: 'newline', offset: -1, indent, source: '\n' }); + for (const key of Object.keys(token)) + if (key !== 'type' && key !== 'offset') + delete token[key]; + Object.assign(token, { type: 'block-scalar', indent, props, source: body }); + } +} +/** @returns `true` if last token is a newline */ +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case 'space': + case 'comment': + props.push(st); + break; + case 'newline': + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case 'scalar': + case 'double-quoted-scalar': + case 'single-quoted-scalar': + token.type = type; + token.source = source; + break; + case 'block-scalar': { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === 'block-scalar-header') + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case 'block-map': + case 'block-seq': { + const offset = token.offset + source.length; + const nl = { type: 'newline', offset, indent: token.indent, source: '\n' }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = 'indent' in token ? token.indent : -1; + const end = 'end' in token && Array.isArray(token.end) + ? token.end.filter(st => st.type === 'space' || + st.type === 'comment' || + st.type === 'newline') + : []; + for (const key of Object.keys(token)) + if (key !== 'type' && key !== 'offset') + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +export { createScalarToken, resolveAsScalar, setScalarValue }; diff --git a/node_modules/yaml/browser/dist/parse/cst-stringify.js b/node_modules/yaml/browser/dist/parse/cst-stringify.js new file mode 100644 index 000000000..d6ab58c3a --- /dev/null +++ b/node_modules/yaml/browser/dist/parse/cst-stringify.js @@ -0,0 +1,61 @@ +/** + * Stringify a CST document, token, or collection item + * + * Fair warning: This applies no validation whatsoever, and + * simply concatenates the sources in their logical order. + */ +const stringify = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case 'block-scalar': { + let res = ''; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case 'block-map': + case 'block-seq': { + let res = ''; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case 'flow-collection': { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case 'document': { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ('end' in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value }) { + let res = ''; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value) + res += stringifyToken(value); + return res; +} + +export { stringify }; diff --git a/node_modules/yaml/browser/dist/parse/cst-visit.js b/node_modules/yaml/browser/dist/parse/cst-visit.js new file mode 100644 index 000000000..deca086b7 --- /dev/null +++ b/node_modules/yaml/browser/dist/parse/cst-visit.js @@ -0,0 +1,97 @@ +const BREAK = Symbol('break visit'); +const SKIP = Symbol('skip children'); +const REMOVE = Symbol('remove item'); +/** + * Apply a visitor to a CST document or item. + * + * Walks through the tree (depth-first) starting from the root, calling a + * `visitor` function with two arguments when entering each item: + * - `item`: The current item, which included the following members: + * - `start: SourceToken[]` – Source tokens before the key or value, + * possibly including its anchor or tag. + * - `key?: Token | null` – Set for pair values. May then be `null`, if + * the key before the `:` separator is empty. + * - `sep?: SourceToken[]` – Source tokens between the key and the value, + * which should include the `:` map value indicator if `value` is set. + * - `value?: Token` – The value of a sequence item, or of a map pair. + * - `path`: The steps from the root to the current node, as an array of + * `['key' | 'value', number]` tuples. + * + * The return value of the visitor may be used to control the traversal: + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this token, continue with + * next sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current item, then continue with the next one + * - `number`: Set the index of the next step. This is useful especially if + * the index of the current token has changed. + * - `function`: Define the next visitor for this item. After the original + * visitor is called on item entry, next visitors are called after handling + * a non-empty `key` and when exiting the item. + */ +function visit(cst, visitor) { + if ('type' in cst && cst.type === 'document') + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +// Without the `as symbol` casts, TS declares these in the `visit` +// namespace using `var`, but then complains about that because +// `unique symbol` must be `const`. +/** Terminate visit traversal completely */ +visit.BREAK = BREAK; +/** Do not visit the children of the current item */ +visit.SKIP = SKIP; +/** Remove the current item */ +visit.REMOVE = REMOVE; +/** Find the item at `path` from `cst` as the root */ +visit.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && 'items' in tok) { + item = tok.items[index]; + } + else + return undefined; + } + return item; +}; +/** + * Get the immediate parent collection of the item at `path` from `cst` as the root. + * + * Throws an error if the collection is not found, which should never happen if the item itself exists. + */ +visit.parentCollection = (cst, path) => { + const parent = visit.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && 'items' in coll) + return coll; + throw new Error('Parent collection not found'); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === 'symbol') + return ctrl; + for (const field of ['key', 'value']) { + const token = item[field]; + if (token && 'items' in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === 'number') + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === 'function' && field === 'key') + ctrl = ctrl(item, path); + } + } + return typeof ctrl === 'function' ? ctrl(item, path) : ctrl; +} + +export { visit }; diff --git a/node_modules/yaml/browser/dist/parse/cst.js b/node_modules/yaml/browser/dist/parse/cst.js new file mode 100644 index 000000000..8bb2f4ad9 --- /dev/null +++ b/node_modules/yaml/browser/dist/parse/cst.js @@ -0,0 +1,98 @@ +export { createScalarToken, resolveAsScalar, setScalarValue } from './cst-scalar.js'; +export { stringify } from './cst-stringify.js'; +export { visit } from './cst-visit.js'; + +/** The byte order mark */ +const BOM = '\u{FEFF}'; +/** Start of doc-mode */ +const DOCUMENT = '\x02'; // C0: Start of Text +/** Unexpected end of flow-mode */ +const FLOW_END = '\x18'; // C0: Cancel +/** Next token is a scalar value */ +const SCALAR = '\x1f'; // C0: Unit Separator +/** @returns `true` if `token` is a flow or block collection */ +const isCollection = (token) => !!token && 'items' in token; +/** @returns `true` if `token` is a flow or block scalar; not an alias */ +const isScalar = (token) => !!token && + (token.type === 'scalar' || + token.type === 'single-quoted-scalar' || + token.type === 'double-quoted-scalar' || + token.type === 'block-scalar'); +/* istanbul ignore next */ +/** Get a printable representation of a lexer token */ +function prettyToken(token) { + switch (token) { + case BOM: + return ''; + case DOCUMENT: + return ''; + case FLOW_END: + return ''; + case SCALAR: + return ''; + default: + return JSON.stringify(token); + } +} +/** Identify the type of a lexer token. May return `null` for unknown tokens. */ +function tokenType(source) { + switch (source) { + case BOM: + return 'byte-order-mark'; + case DOCUMENT: + return 'doc-mode'; + case FLOW_END: + return 'flow-error-end'; + case SCALAR: + return 'scalar'; + case '---': + return 'doc-start'; + case '...': + return 'doc-end'; + case '': + case '\n': + case '\r\n': + return 'newline'; + case '-': + return 'seq-item-ind'; + case '?': + return 'explicit-key-ind'; + case ':': + return 'map-value-ind'; + case '{': + return 'flow-map-start'; + case '}': + return 'flow-map-end'; + case '[': + return 'flow-seq-start'; + case ']': + return 'flow-seq-end'; + case ',': + return 'comma'; + } + switch (source[0]) { + case ' ': + case '\t': + return 'space'; + case '#': + return 'comment'; + case '%': + return 'directive-line'; + case '*': + return 'alias'; + case '&': + return 'anchor'; + case '!': + return 'tag'; + case "'": + return 'single-quoted-scalar'; + case '"': + return 'double-quoted-scalar'; + case '|': + case '>': + return 'block-scalar-header'; + } + return null; +} + +export { BOM, DOCUMENT, FLOW_END, SCALAR, isCollection, isScalar, prettyToken, tokenType }; diff --git a/node_modules/yaml/browser/dist/parse/lexer.js b/node_modules/yaml/browser/dist/parse/lexer.js new file mode 100644 index 000000000..fbab236e3 --- /dev/null +++ b/node_modules/yaml/browser/dist/parse/lexer.js @@ -0,0 +1,717 @@ +import { BOM, DOCUMENT, FLOW_END, SCALAR } from './cst.js'; + +/* +START -> stream + +stream + directive -> line-end -> stream + indent + line-end -> stream + [else] -> line-start + +line-end + comment -> line-end + newline -> . + input-end -> END + +line-start + doc-start -> doc + doc-end -> stream + [else] -> indent -> block-start + +block-start + seq-item-start -> block-start + explicit-key-start -> block-start + map-value-start -> block-start + [else] -> doc + +doc + line-end -> line-start + spaces -> doc + anchor -> doc + tag -> doc + flow-start -> flow -> doc + flow-end -> error -> doc + seq-item-start -> error -> doc + explicit-key-start -> error -> doc + map-value-start -> doc + alias -> doc + quote-start -> quoted-scalar -> doc + block-scalar-header -> line-end -> block-scalar(min) -> line-start + [else] -> plain-scalar(false, min) -> doc + +flow + line-end -> flow + spaces -> flow + anchor -> flow + tag -> flow + flow-start -> flow -> flow + flow-end -> . + seq-item-start -> error -> flow + explicit-key-start -> flow + map-value-start -> flow + alias -> flow + quote-start -> quoted-scalar -> flow + comma -> flow + [else] -> plain-scalar(true, 0) -> flow + +quoted-scalar + quote-end -> . + [else] -> quoted-scalar + +block-scalar(min) + newline + peek(indent < min) -> . + [else] -> block-scalar(min) + +plain-scalar(is-flow, min) + scalar-end(is-flow) -> . + peek(newline + (indent < min)) -> . + [else] -> plain-scalar(min) +*/ +function isEmpty(ch) { + switch (ch) { + case undefined: + case ' ': + case '\n': + case '\r': + case '\t': + return true; + default: + return false; + } +} +const hexDigits = new Set('0123456789ABCDEFabcdef'); +const tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +const flowIndicatorChars = new Set(',[]{}'); +const invalidAnchorChars = new Set(' ,[]{}\n\r\t'); +const isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +/** + * Splits an input string into lexical tokens, i.e. smaller strings that are + * easily identifiable by `tokens.tokenType()`. + * + * Lexing starts always in a "stream" context. Incomplete input may be buffered + * until a complete token can be emitted. + * + * In addition to slices of the original input, the following control characters + * may also be emitted: + * + * - `\x02` (Start of Text): A document starts with the next token + * - `\x18` (Cancel): Unexpected end of flow-mode (indicates an error) + * - `\x1f` (Unit Separator): Next token is a scalar value + * - `\u{FEFF}` (Byte order mark): Emitted separately outside documents + */ +class Lexer { + constructor() { + /** + * Flag indicating whether the end of the current buffer marks the end of + * all input + */ + this.atEnd = false; + /** + * Explicit indent set in block scalar header, as an offset from the current + * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not + * explicitly set. + */ + this.blockScalarIndent = -1; + /** + * Block scalars that include a + (keep) chomping indicator in their header + * include trailing empty lines, which are otherwise excluded from the + * scalar's contents. + */ + this.blockScalarKeep = false; + /** Current input */ + this.buffer = ''; + /** + * Flag noting whether the map value indicator : can immediately follow this + * node within a flow context. + */ + this.flowKey = false; + /** Count of surrounding flow collection levels. */ + this.flowLevel = 0; + /** + * Minimum level of indentation required for next lines to be parsed as a + * part of the current scalar value. + */ + this.indentNext = 0; + /** Indentation level of the current line. */ + this.indentValue = 0; + /** Position of the next \n character. */ + this.lineEndPos = null; + /** Stores the state of the lexer if reaching the end of incpomplete input */ + this.next = null; + /** A pointer to `buffer`; the current position of the lexer. */ + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== 'string') + throw TypeError('source is not a string'); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? 'stream'; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === ' ' || ch === '\t') + ch = this.buffer[++i]; + if (!ch || ch === '#' || ch === '\n') + return true; + if (ch === '\r') + return this.buffer[i + 1] === '\n'; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === ' ') + ch = this.buffer[++indent + offset]; + if (ch === '\r') { + const next = this.buffer[indent + offset + 1]; + if (next === '\n' || (!next && !this.atEnd)) + return offset + indent + 1; + } + return ch === '\n' || indent >= this.indentNext || (!ch && !this.atEnd) + ? offset + indent + : -1; + } + if (ch === '-' || ch === '.') { + const dt = this.buffer.substr(offset, 3); + if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== 'number' || (end !== -1 && end < this.pos)) { + end = this.buffer.indexOf('\n', this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === '\r') + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case 'stream': + return yield* this.parseStream(); + case 'line-start': + return yield* this.parseLineStart(); + case 'block-start': + return yield* this.parseBlockStart(); + case 'doc': + return yield* this.parseDocument(); + case 'flow': + return yield* this.parseFlowCollection(); + case 'quoted-scalar': + return yield* this.parseQuotedScalar(); + case 'block-scalar': + return yield* this.parseBlockScalar(); + case 'plain-scalar': + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext('stream'); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === '%') { + let dirEnd = line.length; + let cs = line.indexOf('#'); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === ' ' || ch === '\t') { + dirEnd = cs - 1; + break; + } + else { + cs = line.indexOf('#', cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === ' ' || ch === '\t') + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); // possible comment + this.pushNewline(); + return 'stream'; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return 'stream'; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext('line-start'); + if (ch === '-' || ch === '.') { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext('line-start'); + const s = this.peek(3); + if ((s === '---' || s === '...') && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === '---' ? 'doc' : 'stream'; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext('block-start'); + if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return yield* this.parseBlockStart(); + } + return 'doc'; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext('doc'); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case '#': + yield* this.pushCount(line.length - n); + // fallthrough + case undefined: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case '{': + case '[': + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return 'flow'; + case '}': + case ']': + // this is an error + yield* this.pushCount(1); + return 'doc'; + case '*': + yield* this.pushUntil(isNotAnchorChar); + return 'doc'; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case '|': + case '>': + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } + else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext('flow'); + if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') || + (indent === 0 && + (line.startsWith('---') || line.startsWith('...')) && + isEmpty(line[3]))) { + // Allowing for the terminal ] or } at the same (rather than greater) + // indent level as the initial [ or { is technically invalid, but + // failing here would be surprising to users. + const atFlowEndMarker = indent === this.indentNext - 1 && + this.flowLevel === 1 && + (line[0] === ']' || line[0] === '}'); + if (!atFlowEndMarker) { + // this is an error + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ',') { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case undefined: + return 'flow'; + case '#': + yield* this.pushCount(line.length - n); + return 'flow'; + case '{': + case '[': + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return 'flow'; + case '}': + case ']': + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? 'flow' : 'doc'; + case '*': + yield* this.pushUntil(isNotAnchorChar); + return 'flow'; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ':': { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ',') { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return 'flow'; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } + else { + // double-quote + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === '\\') + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + // Only looking for newlines within the quotes + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf('\n', this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf('\n', cs); + } + if (nl !== -1) { + // this is an error caused by an unexpected unindent + end = nl - (qb[nl - 1] === '\r' ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext('quoted-scalar'); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? 'flow' : 'doc'; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === '+') + this.blockScalarKeep = true; + else if (ch > '0' && ch <= '9') + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== '-') + break; + } + return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#'); + } + *parseBlockScalar() { + let nl = this.pos - 1; // may be -1 if this.pos === 0 + let indent = 0; + let ch; + loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) { + switch (ch) { + case ' ': + indent += 1; + break; + case '\n': + nl = i; + indent = 0; + break; + case '\r': { + const next = this.buffer[i + 1]; + if (!next && !this.atEnd) + return this.setNext('block-scalar'); + if (next === '\n') + break; + } // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext('block-scalar'); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = + this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf('\n', cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext('block-scalar'); + nl = this.buffer.length; + } + } + // Trailing insufficiently indented tabs are invalid. + // To catch that during parsing, we include them in the block scalar value. + let i = nl + 1; + ch = this.buffer[i]; + while (ch === ' ') + ch = this.buffer[++i]; + if (ch === '\t') { + while (ch === '\t' || ch === ' ' || ch === '\r' || ch === '\n') + ch = this.buffer[++i]; + nl = i - 1; + } + else if (!this.blockScalarKeep) { + do { + let i = nl - 1; + let ch = this.buffer[i]; + if (ch === '\r') + ch = this.buffer[--i]; + const lastChar = i; // Drop the line if last char not more indented + while (ch === ' ') + ch = this.buffer[--i]; + if (ch === '\n' && i >= this.pos && i + 1 + indent > lastChar) + nl = i; + else + break; + } while (true); + } + yield SCALAR; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while ((ch = this.buffer[++i])) { + if (ch === ':') { + const next = this.buffer[i + 1]; + if (isEmpty(next) || (inFlow && flowIndicatorChars.has(next))) + break; + end = i; + } + else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === '\r') { + if (next === '\n') { + i += 1; + ch = '\n'; + next = this.buffer[i + 1]; + } + else + end = i; + } + if (next === '#' || (inFlow && flowIndicatorChars.has(next))) + break; + if (ch === '\n') { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); // to advance, but still account for ' #' + } + } + else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext('plain-scalar'); + yield SCALAR; + yield* this.pushToIndex(end + 1, true); + return inFlow ? 'flow' : 'doc'; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } + else if (allowEmpty) + yield ''; + return 0; + } + *pushIndicators() { + switch (this.charAt(0)) { + case '!': + return ((yield* this.pushTag()) + + (yield* this.pushSpaces(true)) + + (yield* this.pushIndicators())); + case '&': + return ((yield* this.pushUntil(isNotAnchorChar)) + + (yield* this.pushSpaces(true)) + + (yield* this.pushIndicators())); + case '-': // this is an error + case '?': // this is an error outside flow collections + case ':': { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || (inFlow && flowIndicatorChars.has(ch1))) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + return ((yield* this.pushCount(1)) + + (yield* this.pushSpaces(true)) + + (yield* this.pushIndicators())); + } + } + } + return 0; + } + *pushTag() { + if (this.charAt(1) === '<') { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== '>') + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false); + } + else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === '%' && + hexDigits.has(this.buffer[i + 1]) && + hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[(i += 3)]; + } + else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === '\n') + return yield* this.pushCount(1); + else if (ch === '\r' && this.charAt(1) === '\n') + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === ' ' || (allowTabs && ch === '\t')); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +} + +export { Lexer }; diff --git a/node_modules/yaml/browser/dist/parse/line-counter.js b/node_modules/yaml/browser/dist/parse/line-counter.js new file mode 100644 index 000000000..002ce246d --- /dev/null +++ b/node_modules/yaml/browser/dist/parse/line-counter.js @@ -0,0 +1,39 @@ +/** + * Tracks newlines during parsing in order to provide an efficient API for + * determining the one-indexed `{ line, col }` position for any offset + * within the input. + */ +class LineCounter { + constructor() { + this.lineStarts = []; + /** + * Should be called in ascending order. Otherwise, call + * `lineCounter.lineStarts.sort()` before calling `linePos()`. + */ + this.addNewLine = (offset) => this.lineStarts.push(offset); + /** + * Performs a binary search and returns the 1-indexed { line, col } + * position of `offset`. If `line === 0`, `addNewLine` has never been + * called or `offset` is before the first known newline. + */ + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = (low + high) >> 1; // Math.floor((low + high) / 2) + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +} + +export { LineCounter }; diff --git a/node_modules/yaml/browser/dist/parse/parser.js b/node_modules/yaml/browser/dist/parse/parser.js new file mode 100644 index 000000000..349004094 --- /dev/null +++ b/node_modules/yaml/browser/dist/parse/parser.js @@ -0,0 +1,967 @@ +import { tokenType } from './cst.js'; +import { Lexer } from './lexer.js'; + +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case 'space': + case 'comment': + case 'newline': + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + case 'flow-collection': + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case 'document': + return parent.start; + case 'block-map': { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case 'block-seq': + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +/** Note: May modify input array */ +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case 'doc-start': + case 'explicit-key-ind': + case 'map-value-ind': + case 'seq-item-ind': + case 'newline': + break loop; + } + } + while (prev[++i]?.type === 'space') { + /* loop */ + } + return prev.splice(i, prev.length); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === 'flow-seq-start') { + for (const it of fc.items) { + if (it.sep && + !it.value && + !includesToken(it.start, 'explicit-key-ind') && + !includesToken(it.sep, 'map-value-ind')) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + Array.prototype.push.apply(it.value.end, it.sep); + else + it.value.end = it.sep; + } + else + Array.prototype.push.apply(it.start, it.sep); + delete it.sep; + } + } + } +} +/** + * A YAML concrete syntax tree (CST) parser + * + * ```ts + * const src: string = ... + * for (const token of new Parser().parse(src)) { + * // token: Token + * } + * ``` + * + * To use the parser with a user-provided lexer: + * + * ```ts + * function* parse(source: string, lexer: Lexer) { + * const parser = new Parser() + * for (const lexeme of lexer.lex(source)) + * yield* parser.next(lexeme) + * yield* parser.end() + * } + * + * const src: string = ... + * const lexer = new Lexer() + * for (const token of parse(src, lexer)) { + * // token: Token + * } + * ``` + */ +class Parser { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + /** If true, space and sequence indicators count as indentation */ + this.atNewLine = true; + /** If true, next token is a scalar value */ + this.atScalar = false; + /** Current indentation level */ + this.indent = 0; + /** Current offset since the start of parsing */ + this.offset = 0; + /** On the same line with a block map key */ + this.onKeyLine = false; + /** Top indicates the node that's currently being built */ + this.stack = []; + /** The source of the current token, set in parse() */ + this.source = ''; + /** The type of the current token, set in parse() */ + this.type = ''; + // Must be defined after `next()` + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: 'error', offset: this.offset, message, source }); + this.offset += source.length; + } + else if (type === 'scalar') { + this.atNewLine = false; + this.atScalar = true; + this.type = 'scalar'; + } + else { + this.type = type; + yield* this.step(); + switch (type) { + case 'newline': + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case 'space': + if (this.atNewLine && source[0] === ' ') + this.indent += source.length; + break; + case 'explicit-key-ind': + case 'map-value-ind': + case 'seq-item-ind': + if (this.atNewLine) + this.indent += source.length; + break; + case 'doc-mode': + case 'flow-error-end': + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === 'doc-end' && top?.type !== 'doc-end') { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: 'doc-end', + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case 'document': + return yield* this.document(top); + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + return yield* this.scalar(top); + case 'block-scalar': + return yield* this.blockScalar(top); + case 'block-map': + return yield* this.blockMap(top); + case 'block-seq': + return yield* this.blockSequence(top); + case 'flow-collection': + return yield* this.flowCollection(top); + case 'doc-end': + return yield* this.documentEnd(top); + } + /* istanbul ignore next should not happen */ + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + /* istanbul ignore if should not happen */ + if (!token) { + const message = 'Tried to pop an empty stack'; + yield { type: 'error', offset: this.offset, source: '', message }; + } + else if (this.stack.length === 0) { + yield token; + } + else { + const top = this.peek(1); + if (token.type === 'block-scalar') { + // Block scalars use their parent rather than header indent + token.indent = 'indent' in top ? top.indent : 0; + } + else if (token.type === 'flow-collection' && top.type === 'document') { + // Ignore all indent for top-level flow collections + token.indent = 0; + } + if (token.type === 'flow-collection') + fixFlowSeqItems(token); + switch (top.type) { + case 'document': + top.value = token; + break; + case 'block-scalar': + top.props.push(token); // error + break; + case 'block-map': { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } + else if (it.sep) { + it.value = token; + } + else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case 'block-seq': { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case 'flow-collection': { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === 'document' || + top.type === 'block-map' || + top.type === 'block-seq') && + (token.type === 'block-map' || token.type === 'block-seq')) { + const last = token.items[token.items.length - 1]; + if (last && + !last.sep && + !last.value && + last.start.length > 0 && + findNonEmptyIndex(last.start) === -1 && + (token.indent === 0 || + last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) { + if (top.type === 'document') + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case 'directive-line': + yield { type: 'directive', offset: this.offset, source: this.source }; + return; + case 'byte-order-mark': + case 'space': + case 'comment': + case 'newline': + yield this.sourceToken; + return; + case 'doc-mode': + case 'doc-start': { + const doc = { + type: 'document', + offset: this.offset, + start: [] + }; + if (this.type === 'doc-start') + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: 'error', + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case 'doc-start': { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } + else + doc.start.push(this.sourceToken); + return; + } + case 'anchor': + case 'tag': + case 'space': + case 'comment': + case 'newline': + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: 'error', + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === 'map-value-ind') { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } + else + sep = [this.sourceToken]; + const map = { + type: 'block-map', + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map; + } + else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case 'space': + case 'comment': + case 'newline': + scalar.props.push(this.sourceToken); + return; + case 'scalar': + scalar.source = this.source; + // block-scalar source includes trailing newline + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf('\n') + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf('\n', nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map) { + const it = map.items[map.items.length - 1]; + // it.sep is true-ish if pair already has key or : separator + switch (this.type) { + case 'newline': + this.onKeyLine = false; + if (it.value) { + const end = 'end' in it.value ? it.value.end : undefined; + const last = Array.isArray(end) ? end[end.length - 1] : undefined; + if (last?.type === 'comment') + end?.push(this.sourceToken); + else + map.items.push({ start: [this.sourceToken] }); + } + else if (it.sep) { + it.sep.push(this.sourceToken); + } + else { + it.start.push(this.sourceToken); + } + return; + case 'space': + case 'comment': + if (it.value) { + map.items.push({ start: [this.sourceToken] }); + } + else if (it.sep) { + it.sep.push(this.sourceToken); + } + else { + if (this.atIndentedComment(it.start, map.indent)) { + const prev = map.items[map.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + map.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map.indent; + const atNextItem = atMapIndent && + (it.sep || it.explicitKey) && + this.type !== 'seq-item-ind'; + // For empty nodes, assign newline-separated not indented empty tokens to following node + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case 'newline': + nl.push(i); + break; + case 'space': + break; + case 'comment': + if (st.indent > map.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case 'anchor': + case 'tag': + if (atNextItem || it.value) { + start.push(this.sourceToken); + map.items.push({ start }); + this.onKeyLine = true; + } + else if (it.sep) { + it.sep.push(this.sourceToken); + } + else { + it.start.push(this.sourceToken); + } + return; + case 'explicit-key-ind': + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } + else if (atNextItem || it.value) { + start.push(this.sourceToken); + map.items.push({ start, explicitKey: true }); + } + else { + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case 'map-value-ind': + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, 'newline')) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } + else { + const start = getFirstKeyStartProps(it.start); + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } + } + else if (it.value) { + map.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } + else if (includesToken(it.sep, 'map-value-ind')) { + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } + else if (isFlowToken(it.key) && + !includesToken(it.sep, 'newline')) { + const start = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + // @ts-expect-error type guard is wrong here + delete it.key; + // @ts-expect-error type guard is wrong here + delete it.sep; + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, key, sep }] + }); + } + else if (start.length > 0) { + // Not actually at next item + it.sep = it.sep.concat(start, this.sourceToken); + } + else { + it.sep.push(this.sourceToken); + } + } + else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } + else if (it.value || atNextItem) { + map.items.push({ start, key: null, sep: [this.sourceToken] }); + } + else if (includesToken(it.sep, 'map-value-ind')) { + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } + else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': { + const fs = this.flowScalar(this.type); + if (atNextItem || it.value) { + map.items.push({ start, key: fs, sep: [] }); + this.onKeyLine = true; + } + else if (it.sep) { + this.stack.push(fs); + } + else { + Object.assign(it, { key: fs, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map); + if (bv) { + if (bv.type === 'block-seq') { + if (!it.explicitKey && + it.sep && + !includesToken(it.sep, 'newline')) { + yield* this.pop({ + type: 'error', + offset: this.offset, + message: 'Unexpected block-seq-ind on same line with key', + source: this.source + }); + return; + } + } + else if (atMapIndent) { + map.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq) { + const it = seq.items[seq.items.length - 1]; + switch (this.type) { + case 'newline': + if (it.value) { + const end = 'end' in it.value ? it.value.end : undefined; + const last = Array.isArray(end) ? end[end.length - 1] : undefined; + if (last?.type === 'comment') + end?.push(this.sourceToken); + else + seq.items.push({ start: [this.sourceToken] }); + } + else + it.start.push(this.sourceToken); + return; + case 'space': + case 'comment': + if (it.value) + seq.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq.indent)) { + const prev = seq.items[seq.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + seq.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case 'anchor': + case 'tag': + if (it.value || this.indent <= seq.indent) + break; + it.start.push(this.sourceToken); + return; + case 'seq-item-ind': + if (this.indent !== seq.indent) + break; + if (it.value || includesToken(it.start, 'seq-item-ind')) + seq.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq.indent) { + const bv = this.startBlockValue(seq); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === 'flow-error-end') { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === 'flow-collection'); + } + else if (fc.end.length === 0) { + switch (this.type) { + case 'comma': + case 'explicit-key-ind': + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case 'map-value-ind': + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case 'space': + case 'comment': + case 'newline': + case 'anchor': + case 'tag': + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': { + const fs = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs, sep: [] }); + else if (it.sep) + this.stack.push(fs); + else + Object.assign(it, { key: fs, sep: [] }); + return; + } + case 'flow-map-end': + case 'flow-seq-end': + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + /* istanbul ignore else should not happen */ + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } + else { + const parent = this.peek(2); + if (parent.type === 'block-map' && + ((this.type === 'map-value-ind' && parent.indent === fc.indent) || + (this.type === 'newline' && + !parent.items[parent.items.length - 1].sep))) { + yield* this.pop(); + yield* this.step(); + } + else if (this.type === 'map-value-ind' && + parent.type !== 'flow-collection') { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map = { + type: 'block-map', + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map; + } + else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf('\n') + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf('\n', nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + return this.flowScalar(this.type); + case 'block-scalar-header': + return { + type: 'block-scalar', + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: '' + }; + case 'flow-map-start': + case 'flow-seq-start': + return { + type: 'flow-collection', + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case 'seq-item-ind': + return { + type: 'block-seq', + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case 'explicit-key-ind': { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case 'map-value-ind': { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== 'comment') + return false; + if (this.indent <= indent) + return false; + return start.every(st => st.type === 'newline' || st.type === 'space'); + } + *documentEnd(docEnd) { + if (this.type !== 'doc-mode') { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === 'newline') + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case 'comma': + case 'doc-start': + case 'doc-end': + case 'flow-seq-end': + case 'flow-map-end': + case 'map-value-ind': + yield* this.pop(); + yield* this.step(); + break; + case 'newline': + this.onKeyLine = false; + // fallthrough + case 'space': + case 'comment': + default: + // all other values are errors + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === 'newline') + yield* this.pop(); + } + } +} + +export { Parser }; diff --git a/node_modules/yaml/browser/dist/public-api.js b/node_modules/yaml/browser/dist/public-api.js new file mode 100644 index 000000000..116f6eebc --- /dev/null +++ b/node_modules/yaml/browser/dist/public-api.js @@ -0,0 +1,102 @@ +import { Composer } from './compose/composer.js'; +import { Document } from './doc/Document.js'; +import { prettifyError, YAMLParseError } from './errors.js'; +import { warn } from './log.js'; +import { isDocument } from './nodes/identity.js'; +import { LineCounter } from './parse/line-counter.js'; +import { Parser } from './parse/parser.js'; + +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || (prettyErrors && new LineCounter()) || null; + return { lineCounter, prettyErrors }; +} +/** + * Parse the input as a stream of YAML documents. + * + * Documents should be separated from each other by `...` or `---` marker lines. + * + * @returns If an empty `docs` array is returned, it will be of type + * EmptyStream and contain additional stream information. In + * TypeScript, you should use `'empty' in docs` as a type guard for it. + */ +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +/** Parse an input string into a single YAML.Document */ +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + // `doc` is always set by compose.end(true) at the very latest + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== 'silent') { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()')); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = undefined; + if (typeof reviver === 'function') { + _reviver = reviver; + } + else if (options === undefined && reviver && typeof reviver === 'object') { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach(warning => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== 'silent') + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify(value, replacer, options) { + let _replacer = null; + if (typeof replacer === 'function' || Array.isArray(replacer)) { + _replacer = replacer; + } + else if (options === undefined && replacer) { + options = replacer; + } + if (typeof options === 'string') + options = options.length; + if (typeof options === 'number') { + const indent = Math.round(options); + options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent }; + } + if (value === undefined) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return undefined; + } + if (isDocument(value) && !_replacer) + return value.toString(options); + return new Document(value, _replacer, options).toString(options); +} + +export { parse, parseAllDocuments, parseDocument, stringify }; diff --git a/node_modules/yaml/browser/dist/schema/Schema.js b/node_modules/yaml/browser/dist/schema/Schema.js new file mode 100644 index 000000000..60a85c532 --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/Schema.js @@ -0,0 +1,37 @@ +import { MAP, SCALAR, SEQ } from '../nodes/identity.js'; +import { map } from './common/map.js'; +import { seq } from './common/seq.js'; +import { string } from './common/string.js'; +import { getTags, coreKnownTags } from './tags.js'; + +const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +class Schema { + constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) + ? getTags(compat, 'compat') + : compat + ? getTags(null, compat) + : null; + this.name = (typeof schema === 'string' && schema) || 'core'; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + // Used by createMap() + this.sortMapEntries = + typeof sortMapEntries === 'function' + ? sortMapEntries + : sortMapEntries === true + ? sortMapEntriesByKey + : null; + } + clone() { + const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy.tags = this.tags.slice(); + return copy; + } +} + +export { Schema }; diff --git a/node_modules/yaml/browser/dist/schema/common/map.js b/node_modules/yaml/browser/dist/schema/common/map.js new file mode 100644 index 000000000..af97b787e --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/common/map.js @@ -0,0 +1,17 @@ +import { isMap } from '../../nodes/identity.js'; +import { YAMLMap } from '../../nodes/YAMLMap.js'; + +const map = { + collection: 'map', + default: true, + nodeClass: YAMLMap, + tag: 'tag:yaml.org,2002:map', + resolve(map, onError) { + if (!isMap(map)) + onError('Expected a mapping for this tag'); + return map; + }, + createNode: (schema, obj, ctx) => YAMLMap.from(schema, obj, ctx) +}; + +export { map }; diff --git a/node_modules/yaml/browser/dist/schema/common/null.js b/node_modules/yaml/browser/dist/schema/common/null.js new file mode 100644 index 000000000..fcbe1b7a5 --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/common/null.js @@ -0,0 +1,15 @@ +import { Scalar } from '../../nodes/Scalar.js'; + +const nullTag = { + identify: value => value == null, + createNode: () => new Scalar(null), + default: true, + tag: 'tag:yaml.org,2002:null', + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source) + ? source + : ctx.options.nullStr +}; + +export { nullTag }; diff --git a/node_modules/yaml/browser/dist/schema/common/seq.js b/node_modules/yaml/browser/dist/schema/common/seq.js new file mode 100644 index 000000000..1915b6059 --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/common/seq.js @@ -0,0 +1,17 @@ +import { isSeq } from '../../nodes/identity.js'; +import { YAMLSeq } from '../../nodes/YAMLSeq.js'; + +const seq = { + collection: 'seq', + default: true, + nodeClass: YAMLSeq, + tag: 'tag:yaml.org,2002:seq', + resolve(seq, onError) { + if (!isSeq(seq)) + onError('Expected a sequence for this tag'); + return seq; + }, + createNode: (schema, obj, ctx) => YAMLSeq.from(schema, obj, ctx) +}; + +export { seq }; diff --git a/node_modules/yaml/browser/dist/schema/common/string.js b/node_modules/yaml/browser/dist/schema/common/string.js new file mode 100644 index 000000000..a064f7b31 --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/common/string.js @@ -0,0 +1,14 @@ +import { stringifyString } from '../../stringify/stringifyString.js'; + +const string = { + identify: value => typeof value === 'string', + default: true, + tag: 'tag:yaml.org,2002:str', + resolve: str => str, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +export { string }; diff --git a/node_modules/yaml/browser/dist/schema/core/bool.js b/node_modules/yaml/browser/dist/schema/core/bool.js new file mode 100644 index 000000000..ab3c9430a --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/core/bool.js @@ -0,0 +1,19 @@ +import { Scalar } from '../../nodes/Scalar.js'; + +const boolTag = { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: str => new Scalar(str[0] === 't' || str[0] === 'T'), + stringify({ source, value }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === 't' || source[0] === 'T'; + if (value === sv) + return source; + } + return value ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +export { boolTag }; diff --git a/node_modules/yaml/browser/dist/schema/core/float.js b/node_modules/yaml/browser/dist/schema/core/float.js new file mode 100644 index 000000000..3fa9cf85c --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/core/float.js @@ -0,0 +1,43 @@ +import { Scalar } from '../../nodes/Scalar.js'; +import { stringifyNumber } from '../../stringify/stringifyNumber.js'; + +const floatNaN = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: str => str.slice(-3).toLowerCase() === 'nan' + ? NaN + : str[0] === '-' + ? Number.NEGATIVE_INFINITY + : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +const floatExp = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'EXP', + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: str => parseFloat(str), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber(node); + } +}; +const float = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str) { + const node = new Scalar(parseFloat(str)); + const dot = str.indexOf('.'); + if (dot !== -1 && str[str.length - 1] === '0') + node.minFractionDigits = str.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +export { float, floatExp, floatNaN }; diff --git a/node_modules/yaml/browser/dist/schema/core/int.js b/node_modules/yaml/browser/dist/schema/core/int.js new file mode 100644 index 000000000..7091235ff --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/core/int.js @@ -0,0 +1,38 @@ +import { stringifyNumber } from '../../stringify/stringifyNumber.js'; + +const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value); +const intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix)); +function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value) && value >= 0) + return prefix + value.toString(radix); + return stringifyNumber(node); +} +const intOct = { + identify: value => intIdentify(value) && value >= 0, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'OCT', + test: /^0o[0-7]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt), + stringify: node => intStringify(node, 8, '0o') +}; +const int = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^[-+]?[0-9]+$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber +}; +const intHex = { + identify: value => intIdentify(value) && value >= 0, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'HEX', + test: /^0x[0-9a-fA-F]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: node => intStringify(node, 16, '0x') +}; + +export { int, intHex, intOct }; diff --git a/node_modules/yaml/browser/dist/schema/core/schema.js b/node_modules/yaml/browser/dist/schema/core/schema.js new file mode 100644 index 000000000..dd02b2e3d --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/core/schema.js @@ -0,0 +1,23 @@ +import { map } from '../common/map.js'; +import { nullTag } from '../common/null.js'; +import { seq } from '../common/seq.js'; +import { string } from '../common/string.js'; +import { boolTag } from './bool.js'; +import { floatNaN, floatExp, float } from './float.js'; +import { intOct, int, intHex } from './int.js'; + +const schema = [ + map, + seq, + string, + nullTag, + boolTag, + intOct, + int, + intHex, + floatNaN, + floatExp, + float +]; + +export { schema }; diff --git a/node_modules/yaml/browser/dist/schema/json/schema.js b/node_modules/yaml/browser/dist/schema/json/schema.js new file mode 100644 index 000000000..ada1c6349 --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/json/schema.js @@ -0,0 +1,62 @@ +import { Scalar } from '../../nodes/Scalar.js'; +import { map } from '../common/map.js'; +import { seq } from '../common/seq.js'; + +function intIdentify(value) { + return typeof value === 'bigint' || Number.isInteger(value); +} +const stringifyJSON = ({ value }) => JSON.stringify(value); +const jsonScalars = [ + { + identify: value => typeof value === 'string', + default: true, + tag: 'tag:yaml.org,2002:str', + resolve: str => str, + stringify: stringifyJSON + }, + { + identify: value => value == null, + createNode: () => new Scalar(null), + default: true, + tag: 'tag:yaml.org,2002:null', + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^true$|^false$/, + resolve: str => str === 'true', + stringify: stringifyJSON + }, + { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value) + }, + { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: str => parseFloat(str), + stringify: stringifyJSON + } +]; +const jsonError = { + default: true, + tag: '', + test: /^/, + resolve(str, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str)}`); + return str; + } +}; +const schema = [map, seq].concat(jsonScalars, jsonError); + +export { schema }; diff --git a/node_modules/yaml/browser/dist/schema/tags.js b/node_modules/yaml/browser/dist/schema/tags.js new file mode 100644 index 000000000..5acd99f71 --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/tags.js @@ -0,0 +1,96 @@ +import { map } from './common/map.js'; +import { nullTag } from './common/null.js'; +import { seq } from './common/seq.js'; +import { string } from './common/string.js'; +import { boolTag } from './core/bool.js'; +import { floatNaN, floatExp, float } from './core/float.js'; +import { intOct, intHex, int } from './core/int.js'; +import { schema } from './core/schema.js'; +import { schema as schema$1 } from './json/schema.js'; +import { binary } from './yaml-1.1/binary.js'; +import { merge } from './yaml-1.1/merge.js'; +import { omap } from './yaml-1.1/omap.js'; +import { pairs } from './yaml-1.1/pairs.js'; +import { schema as schema$2 } from './yaml-1.1/schema.js'; +import { set } from './yaml-1.1/set.js'; +import { timestamp, intTime, floatTime } from './yaml-1.1/timestamp.js'; + +const schemas = new Map([ + ['core', schema], + ['failsafe', [map, seq, string]], + ['json', schema$1], + ['yaml11', schema$2], + ['yaml-1.1', schema$2] +]); +const tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int, + intHex, + intOct, + intTime, + map, + merge, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +const coreKnownTags = { + 'tag:yaml.org,2002:binary': binary, + 'tag:yaml.org,2002:merge': merge, + 'tag:yaml.org,2002:omap': omap, + 'tag:yaml.org,2002:pairs': pairs, + 'tag:yaml.org,2002:set': set, + 'tag:yaml.org,2002:timestamp': timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge) + ? schemaTags.concat(merge) + : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()) + .filter(key => key !== 'yaml11') + .map(key => JSON.stringify(key)) + .join(', '); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } + else if (typeof customTags === 'function') { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge); + return tags.reduce((tags, tag) => { + const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName) + .map(key => JSON.stringify(key)) + .join(', '); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags.includes(tagObj)) + tags.push(tagObj); + return tags; + }, []); +} + +export { coreKnownTags, getTags }; diff --git a/node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js b/node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js new file mode 100644 index 000000000..2deda7a61 --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js @@ -0,0 +1,58 @@ +import { Scalar } from '../../nodes/Scalar.js'; +import { stringifyString } from '../../stringify/stringifyString.js'; + +const binary = { + identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array + default: false, + tag: 'tag:yaml.org,2002:binary', + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === 'function') { + // On IE 11, atob() can't handle newlines + const str = atob(src.replace(/[\n\r]/g, '')); + const buffer = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) + buffer[i] = str.charCodeAt(i); + return buffer; + } + else { + onError('This environment does not support reading binary tags; either Buffer or atob is required'); + return src; + } + }, + stringify({ comment, type, value }, ctx, onComment, onChompKeep) { + if (!value) + return ''; + const buf = value; // checked earlier by binary.identify() + let str; + if (typeof btoa === 'function') { + let s = ''; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str = btoa(s); + } + else { + throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required'); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str.length / lineWidth); + const lines = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines[i] = str.substr(o, lineWidth); + } + str = lines.join(type === Scalar.BLOCK_LITERAL ? '\n' : ' '); + } + return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep); + } +}; + +export { binary }; diff --git a/node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js b/node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js new file mode 100644 index 000000000..999b59d46 --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js @@ -0,0 +1,26 @@ +import { Scalar } from '../../nodes/Scalar.js'; + +function boolStringify({ value, source }, ctx) { + const boolObj = value ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value ? ctx.options.trueStr : ctx.options.falseStr; +} +const trueTag = { + identify: value => value === true, + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +const falseTag = { + identify: value => value === false, + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +export { falseTag, trueTag }; diff --git a/node_modules/yaml/browser/dist/schema/yaml-1.1/float.js b/node_modules/yaml/browser/dist/schema/yaml-1.1/float.js new file mode 100644 index 000000000..2f06117ed --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/yaml-1.1/float.js @@ -0,0 +1,46 @@ +import { Scalar } from '../../nodes/Scalar.js'; +import { stringifyNumber } from '../../stringify/stringifyNumber.js'; + +const floatNaN = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === 'nan' + ? NaN + : str[0] === '-' + ? Number.NEGATIVE_INFINITY + : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +const floatExp = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'EXP', + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str.replace(/_/g, '')), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber(node); + } +}; +const float = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str) { + const node = new Scalar(parseFloat(str.replace(/_/g, ''))); + const dot = str.indexOf('.'); + if (dot !== -1) { + const f = str.substring(dot + 1).replace(/_/g, ''); + if (f[f.length - 1] === '0') + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +export { float, floatExp, floatNaN }; diff --git a/node_modules/yaml/browser/dist/schema/yaml-1.1/int.js b/node_modules/yaml/browser/dist/schema/yaml-1.1/int.js new file mode 100644 index 000000000..f572823f9 --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/yaml-1.1/int.js @@ -0,0 +1,71 @@ +import { stringifyNumber } from '../../stringify/stringifyNumber.js'; + +const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value); +function intResolve(str, offset, radix, { intAsBigInt }) { + const sign = str[0]; + if (sign === '-' || sign === '+') + offset += 1; + str = str.substring(offset).replace(/_/g, ''); + if (intAsBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + case 8: + str = `0o${str}`; + break; + case 16: + str = `0x${str}`; + break; + } + const n = BigInt(str); + return sign === '-' ? BigInt(-1) * n : n; + } + const n = parseInt(str, radix); + return sign === '-' ? -1 * n : n; +} +function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? '-' + prefix + str.substr(1) : prefix + str; + } + return stringifyNumber(node); +} +const intBin = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'BIN', + test: /^[-+]?0b[0-1_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt), + stringify: node => intStringify(node, 2, '0b') +}; +const intOct = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'OCT', + test: /^[-+]?0[0-7_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt), + stringify: node => intStringify(node, 8, '0') +}; +const int = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber +}; +const intHex = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'HEX', + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: node => intStringify(node, 16, '0x') +}; + +export { int, intBin, intHex, intOct }; diff --git a/node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js b/node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js new file mode 100644 index 000000000..d361f36f4 --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js @@ -0,0 +1,64 @@ +import { isScalar, isAlias, isSeq, isMap } from '../../nodes/identity.js'; +import { Scalar } from '../../nodes/Scalar.js'; + +// If the value associated with a merge key is a single mapping node, each of +// its key/value pairs is inserted into the current mapping, unless the key +// already exists in it. If the value associated with the merge key is a +// sequence, then this sequence is expected to contain mapping nodes and each +// of these nodes is merged in turn according to its order in the sequence. +// Keys in mapping nodes earlier in the sequence override keys specified in +// later mapping nodes. -- http://yaml.org/type/merge.html +const MERGE_KEY = '<<'; +const merge = { + identify: value => value === MERGE_KEY || + (typeof value === 'symbol' && value.description === MERGE_KEY), + default: 'key', + tag: 'tag:yaml.org,2002:merge', + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +const isMergeKey = (ctx, key) => (merge.identify(key) || + (isScalar(key) && + (!key.type || key.type === Scalar.PLAIN) && + merge.identify(key.value))) && + ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default); +function addMergeToJSMap(ctx, map, value) { + value = ctx && isAlias(value) ? value.resolve(ctx.doc) : value; + if (isSeq(value)) + for (const it of value.items) + mergeValue(ctx, map, it); + else if (Array.isArray(value)) + for (const it of value) + mergeValue(ctx, map, it); + else + mergeValue(ctx, map, value); +} +function mergeValue(ctx, map, value) { + const source = ctx && isAlias(value) ? value.resolve(ctx.doc) : value; + if (!isMap(source)) + throw new Error('Merge sources must be maps or map aliases'); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value] of srcMap) { + if (map instanceof Map) { + if (!map.has(key)) + map.set(key, value); + } + else if (map instanceof Set) { + map.add(key); + } + else if (!Object.prototype.hasOwnProperty.call(map, key)) { + Object.defineProperty(map, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map; +} + +export { addMergeToJSMap, isMergeKey, merge }; diff --git a/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js b/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js new file mode 100644 index 000000000..5574ac5ec --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js @@ -0,0 +1,74 @@ +import { isScalar, isPair } from '../../nodes/identity.js'; +import { toJS } from '../../nodes/toJS.js'; +import { YAMLMap } from '../../nodes/YAMLMap.js'; +import { YAMLSeq } from '../../nodes/YAMLSeq.js'; +import { resolvePairs, createPairs } from './pairs.js'; + +class YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map = new Map(); + if (ctx?.onCreate) + ctx.onCreate(map); + for (const pair of this.items) { + let key, value; + if (isPair(pair)) { + key = toJS(pair.key, '', ctx); + value = toJS(pair.value, key, ctx); + } + else { + key = toJS(pair, '', ctx); + } + if (map.has(key)) + throw new Error('Ordered maps must not include duplicate keys'); + map.set(key, value); + } + return map; + } + static from(schema, iterable, ctx) { + const pairs = createPairs(schema, iterable, ctx); + const omap = new this(); + omap.items = pairs.items; + return omap; + } +} +YAMLOMap.tag = 'tag:yaml.org,2002:omap'; +const omap = { + collection: 'seq', + identify: value => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: 'tag:yaml.org,2002:omap', + resolve(seq, onError) { + const pairs = resolvePairs(seq, onError); + const seenKeys = []; + for (const { key } of pairs.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } + else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs); + }, + createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx) +}; + +export { YAMLOMap, omap }; diff --git a/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js b/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js new file mode 100644 index 000000000..579f08020 --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js @@ -0,0 +1,78 @@ +import { isSeq, isPair, isMap } from '../../nodes/identity.js'; +import { createPair, Pair } from '../../nodes/Pair.js'; +import { Scalar } from '../../nodes/Scalar.js'; +import { YAMLSeq } from '../../nodes/YAMLSeq.js'; + +function resolvePairs(seq, onError) { + if (isSeq(seq)) { + for (let i = 0; i < seq.items.length; ++i) { + let item = seq.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError('Each pair must have its own sequence indicator'); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore + ? `${item.commentBefore}\n${pair.key.commentBefore}` + : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment + ? `${item.comment}\n${cn.comment}` + : item.comment; + } + item = pair; + } + seq.items[i] = isPair(item) ? item : new Pair(item); + } + } + else + onError('Expected a sequence for this tag'); + return seq; +} +function createPairs(schema, iterable, ctx) { + const { replacer } = ctx; + const pairs = new YAMLSeq(schema); + pairs.tag = 'tag:yaml.org,2002:pairs'; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === 'function') + it = replacer.call(iterable, String(i++), it); + let key, value; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value = it[1]; + } + else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } + else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } + else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } + else { + key = it; + } + pairs.items.push(createPair(key, value, ctx)); + } + return pairs; +} +const pairs = { + collection: 'seq', + default: false, + tag: 'tag:yaml.org,2002:pairs', + resolve: resolvePairs, + createNode: createPairs +}; + +export { createPairs, pairs, resolvePairs }; diff --git a/node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js b/node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js new file mode 100644 index 000000000..e516ced2b --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js @@ -0,0 +1,39 @@ +import { map } from '../common/map.js'; +import { nullTag } from '../common/null.js'; +import { seq } from '../common/seq.js'; +import { string } from '../common/string.js'; +import { binary } from './binary.js'; +import { trueTag, falseTag } from './bool.js'; +import { floatNaN, floatExp, float } from './float.js'; +import { intBin, intOct, int, intHex } from './int.js'; +import { merge } from './merge.js'; +import { omap } from './omap.js'; +import { pairs } from './pairs.js'; +import { set } from './set.js'; +import { intTime, floatTime, timestamp } from './timestamp.js'; + +const schema = [ + map, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct, + int, + intHex, + floatNaN, + floatExp, + float, + binary, + merge, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +export { schema }; diff --git a/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js b/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js new file mode 100644 index 000000000..a3cf4ecfa --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js @@ -0,0 +1,93 @@ +import { isMap, isPair, isScalar } from '../../nodes/identity.js'; +import { Pair, createPair } from '../../nodes/Pair.js'; +import { YAMLMap, findPair } from '../../nodes/YAMLMap.js'; + +class YAMLSet extends YAMLMap { + constructor(schema) { + super(schema); + this.tag = YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && + typeof key === 'object' && + 'key' in key && + 'value' in key && + key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) + ? isScalar(pair.key) + ? pair.key.value + : pair.key + : pair; + } + set(key, value) { + if (typeof value !== 'boolean') + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = findPair(this.items, key); + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } + else if (!prev && value) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error('Set items must all have null values'); + } + static from(schema, iterable, ctx) { + const { replacer } = ctx; + const set = new this(schema); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value of iterable) { + if (typeof replacer === 'function') + value = replacer.call(iterable, value, value); + set.items.push(createPair(value, null, ctx)); + } + return set; + } +} +YAMLSet.tag = 'tag:yaml.org,2002:set'; +const set = { + collection: 'map', + identify: value => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: 'tag:yaml.org,2002:set', + createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx), + resolve(map, onError) { + if (isMap(map)) { + if (map.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map); + else + onError('Set items must all have null values'); + } + else + onError('Expected a mapping for this tag'); + return map; + } +}; + +export { YAMLSet, set }; diff --git a/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js b/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js new file mode 100644 index 000000000..77e3dbe3b --- /dev/null +++ b/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js @@ -0,0 +1,101 @@ +import { stringifyNumber } from '../../stringify/stringifyNumber.js'; + +/** Internal types handle bigint as number, because TS can't figure it out. */ +function parseSexagesimal(str, asBigInt) { + const sign = str[0]; + const parts = sign === '-' || sign === '+' ? str.substring(1) : str; + const num = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts + .replace(/_/g, '') + .split(':') + .reduce((res, p) => res * num(60) + num(p), num(0)); + return (sign === '-' ? num(-1) * res : res); +} +/** + * hhhh:mm:ss.sss + * + * Internal types handle bigint as number, because TS can't figure it out. + */ +function stringifySexagesimal(node) { + let { value } = node; + let num = (n) => n; + if (typeof value === 'bigint') + num = n => BigInt(n); + else if (isNaN(value) || !isFinite(value)) + return stringifyNumber(node); + let sign = ''; + if (value < 0) { + sign = '-'; + value *= num(-1); + } + const _60 = num(60); + const parts = [value % _60]; // seconds, including ms + if (value < 60) { + parts.unshift(0); // at least one : is required + } + else { + value = (value - parts[0]) / _60; + parts.unshift(value % _60); // minutes + if (value >= 60) { + value = (value - parts[0]) / _60; + parts.unshift(value); // hours + } + } + return (sign + + parts + .map(n => String(n).padStart(2, '0')) + .join(':') + .replace(/000000\d*$/, '') // % 60 may introduce error + ); +} +const intTime = { + identify: value => typeof value === 'bigint' || Number.isInteger(value), + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'TIME', + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), + stringify: stringifySexagesimal +}; +const floatTime = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'TIME', + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: str => parseSexagesimal(str, false), + stringify: stringifySexagesimal +}; +const timestamp = { + identify: value => value instanceof Date, + default: true, + tag: 'tag:yaml.org,2002:timestamp', + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd + '(?:' + // time is optional + '(?:t|T|[ \\t]+)' + // t | T | whitespace + '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)? + '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30 + ')?$'), + resolve(str) { + const match = str.match(timestamp.test); + if (!match) + throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd'); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== 'Z') { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 60000 * d; + } + return new Date(date); + }, + stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, '') ?? '' +}; + +export { floatTime, intTime, timestamp }; diff --git a/node_modules/yaml/browser/dist/stringify/foldFlowLines.js b/node_modules/yaml/browser/dist/stringify/foldFlowLines.js new file mode 100644 index 000000000..2f0bd0775 --- /dev/null +++ b/node_modules/yaml/browser/dist/stringify/foldFlowLines.js @@ -0,0 +1,146 @@ +const FOLD_FLOW = 'flow'; +const FOLD_BLOCK = 'block'; +const FOLD_QUOTED = 'quoted'; +/** + * Tries to keep input at up to `lineWidth` characters, splitting only on spaces + * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are + * terminated with `\n` and started with `indent`. + */ +function foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === 'number') { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = undefined; + let prev = undefined; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; (ch = text[(i += 1)]);) { + if (mode === FOLD_QUOTED && ch === '\\') { + escStart = i; + switch (text[i + 1]) { + case 'x': + i += 3; + break; + case 'u': + i += 5; + break; + case 'U': + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === '\n') { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = undefined; + } + else { + if (ch === ' ' && + prev && + prev !== ' ' && + prev !== '\n' && + prev !== '\t') { + // space surrounded by non-space can be replaced with newline + indent + const next = text[i + 1]; + if (next && next !== ' ' && next !== '\n' && next !== '\t') + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = undefined; + } + else if (mode === FOLD_QUOTED) { + // white-space collected at end may stretch past lineWidth + while (prev === ' ' || prev === '\t') { + prev = ch; + ch = text[(i += 1)]; + overflow = true; + } + // Account for newline escape, but don't break preceding escape + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + // Bail out if lineWidth & minContentWidth are shorter than an escape string + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = undefined; + } + else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i = 0; i < folds.length; ++i) { + const fold = folds[i]; + const end = folds[i + 1] || text.length; + if (fold === 0) + res = `\n${indent}${text.slice(0, end)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += `\n${indent}${text.slice(fold + 1, end)}`; + } + } + return res; +} +/** + * Presumes `i + 1` is at the start of a line + * @returns index of last newline in more-indented block + */ +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === ' ' || ch === '\t') { + if (i < start + indent) { + ch = text[++i]; + } + else { + do { + ch = text[++i]; + } while (ch && ch !== '\n'); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +export { FOLD_BLOCK, FOLD_FLOW, FOLD_QUOTED, foldFlowLines }; diff --git a/node_modules/yaml/browser/dist/stringify/stringify.js b/node_modules/yaml/browser/dist/stringify/stringify.js new file mode 100644 index 000000000..7d27bf421 --- /dev/null +++ b/node_modules/yaml/browser/dist/stringify/stringify.js @@ -0,0 +1,128 @@ +import { anchorIsValid } from '../doc/anchors.js'; +import { isPair, isAlias, isNode, isScalar, isCollection } from '../nodes/identity.js'; +import { stringifyComment } from './stringifyComment.js'; +import { stringifyString } from './stringifyString.js'; + +function createStringifyContext(doc, options) { + const opt = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: 'PLAIN', + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: 'false', + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: 'null', + simpleKeys: false, + singleQuote: null, + trueStr: 'true', + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt.collectionStyle) { + case 'block': + inFlow = false; + break; + case 'flow': + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: new Set(), + doc, + flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '', + indent: '', + indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ', + inFlow, + options: opt + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter(t => t.tag === item.tag); + if (match.length > 0) + return match.find(t => t.format === item.format) ?? match[0]; + } + let tagObj = undefined; + let obj; + if (isScalar(item)) { + obj = item.value; + let match = tags.filter(t => t.identify?.(obj)); + if (match.length > 1) { + const testMatch = match.filter(t => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = + match.find(t => t.format === item.format) ?? match.find(t => !t.format); + } + else { + obj = item; + tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj?.constructor?.name ?? (obj === null ? 'null' : typeof obj); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +// needs to be called before value stringifier to allow for circular anchor refs +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ''; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(' '); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } + else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = undefined; + const node = isNode(item) + ? item + : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str = typeof tagObj.stringify === 'function' + ? tagObj.stringify(node, ctx, onComment, onChompKeep) + : isScalar(node) + ? stringifyString(node, ctx, onComment, onChompKeep) + : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str; + return isScalar(node) || str[0] === '{' || str[0] === '[' + ? `${props} ${str}` + : `${props}\n${ctx.indent}${str}`; +} + +export { createStringifyContext, stringify }; diff --git a/node_modules/yaml/browser/dist/stringify/stringifyCollection.js b/node_modules/yaml/browser/dist/stringify/stringifyCollection.js new file mode 100644 index 000000000..9019400f9 --- /dev/null +++ b/node_modules/yaml/browser/dist/stringify/stringifyCollection.js @@ -0,0 +1,143 @@ +import { isNode, isPair } from '../nodes/identity.js'; +import { stringify } from './stringify.js'; +import { lineComment, indentComment } from './stringifyComment.js'; + +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; // flag for the preceding node's status + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines.push(''); + addCommentBefore(ctx, lines, item.commentBefore, chompKeep); + if (item.comment) + comment = item.comment; + } + else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines.push(''); + addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str = stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true)); + if (comment) + str += lineComment(str, itemIndent, commentString(comment)); + if (chompKeep && comment) + chompKeep = false; + lines.push(blockItemPrefix + str); + } + let str; + if (lines.length === 0) { + str = flowChars.start + flowChars.end; + } + else { + str = lines[0]; + for (let i = 1; i < lines.length; ++i) { + const line = lines[i]; + str += line ? `\n${indent}${line}` : '\n'; + } + } + if (comment) { + str += '\n' + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } + else if (chompKeep && onChompKeep) + onChompKeep(); + return str; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines.push(''); + addCommentBefore(ctx, lines, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } + else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines.push(''); + addCommentBefore(ctx, lines, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } + else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str = stringify(item, itemCtx, () => (comment = null)); + if (i < items.length - 1) + str += ','; + if (comment) + str += lineComment(str, itemIndent, commentString(comment)); + if (!reqNewline && (lines.length > linesAtValue || str.includes('\n'))) + reqNewline = true; + lines.push(str); + linesAtValue = lines.length; + } + const { start, end } = flowChars; + if (lines.length === 0) { + return start + end; + } + else { + if (!reqNewline) { + const len = lines.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str = start; + for (const line of lines) + str += line ? `\n${indentStep}${indent}${line}` : '\n'; + return `${str}\n${indent}${end}`; + } + else { + return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ''); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines.push(ic.trimStart()); // Avoid double indent on first line + } +} + +export { stringifyCollection }; diff --git a/node_modules/yaml/browser/dist/stringify/stringifyComment.js b/node_modules/yaml/browser/dist/stringify/stringifyComment.js new file mode 100644 index 000000000..f16fc917a --- /dev/null +++ b/node_modules/yaml/browser/dist/stringify/stringifyComment.js @@ -0,0 +1,20 @@ +/** + * Stringifies a comment. + * + * Empty comment lines are left empty, + * lines consisting of a single space are replaced by `#`, + * and all other lines are prefixed with a `#`. + */ +const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#'); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +const lineComment = (str, indent, comment) => str.endsWith('\n') + ? indentComment(comment, indent) + : comment.includes('\n') + ? '\n' + indentComment(comment, indent) + : (str.endsWith(' ') ? '' : ' ') + comment; + +export { indentComment, lineComment, stringifyComment }; diff --git a/node_modules/yaml/browser/dist/stringify/stringifyDocument.js b/node_modules/yaml/browser/dist/stringify/stringifyDocument.js new file mode 100644 index 000000000..2a9defa2a --- /dev/null +++ b/node_modules/yaml/browser/dist/stringify/stringifyDocument.js @@ -0,0 +1,85 @@ +import { isNode } from '../nodes/identity.js'; +import { createStringifyContext, stringify } from './stringify.js'; +import { indentComment, lineComment } from './stringifyComment.js'; + +function stringifyDocument(doc, options) { + const lines = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines.push(dir); + hasDirectives = true; + } + else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines.push('---'); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines.length !== 1) + lines.unshift(''); + const cs = commentString(doc.commentBefore); + lines.unshift(indentComment(cs, '')); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines.push(''); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines.push(indentComment(cs, '')); + } + // top-level block scalars need to be indented if followed by a comment + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? undefined : () => (chompKeep = true); + let body = stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep); + if (contentComment) + body += lineComment(body, '', commentString(contentComment)); + if ((body[0] === '|' || body[0] === '>') && + lines[lines.length - 1] === '---') { + // Top-level block scalars with a preceding doc marker ought to use the + // same line for their header. + lines[lines.length - 1] = `--- ${body}`; + } + else + lines.push(body); + } + else { + lines.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes('\n')) { + lines.push('...'); + lines.push(indentComment(cs, '')); + } + else { + lines.push(`... ${cs}`); + } + } + else { + lines.push('...'); + } + } + else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ''); + if (dc) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') + lines.push(''); + lines.push(indentComment(commentString(dc), '')); + } + } + return lines.join('\n') + '\n'; +} + +export { stringifyDocument }; diff --git a/node_modules/yaml/browser/dist/stringify/stringifyNumber.js b/node_modules/yaml/browser/dist/stringify/stringifyNumber.js new file mode 100644 index 000000000..f49bf3fe8 --- /dev/null +++ b/node_modules/yaml/browser/dist/stringify/stringifyNumber.js @@ -0,0 +1,24 @@ +function stringifyNumber({ format, minFractionDigits, tag, value }) { + if (typeof value === 'bigint') + return String(value); + const num = typeof value === 'number' ? value : Number(value); + if (!isFinite(num)) + return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf'; + let n = Object.is(value, -0) ? '-0' : JSON.stringify(value); + if (!format && + minFractionDigits && + (!tag || tag === 'tag:yaml.org,2002:float') && + /^\d/.test(n)) { + let i = n.indexOf('.'); + if (i < 0) { + i = n.length; + n += '.'; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += '0'; + } + return n; +} + +export { stringifyNumber }; diff --git a/node_modules/yaml/browser/dist/stringify/stringifyPair.js b/node_modules/yaml/browser/dist/stringify/stringifyPair.js new file mode 100644 index 000000000..d299f08dd --- /dev/null +++ b/node_modules/yaml/browser/dist/stringify/stringifyPair.js @@ -0,0 +1,150 @@ +import { isCollection, isNode, isScalar, isSeq } from '../nodes/identity.js'; +import { Scalar } from '../nodes/Scalar.js'; +import { stringify } from './stringify.js'; +import { lineComment, indentComment } from './stringifyComment.js'; + +function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = (isNode(key) && key.comment) || null; + if (simpleKeys) { + if (keyComment) { + throw new Error('With simple keys, key nodes cannot have comments'); + } + if (isCollection(key) || (!isNode(key) && typeof key === 'object')) { + const msg = 'With simple keys, collection cannot be used as a key value'; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && + (!key || + (keyComment && value == null && !ctx.inFlow) || + isCollection(key) || + (isScalar(key) + ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL + : typeof key === 'object')); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str = stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true)); + if (!explicitKey && !ctx.inFlow && str.length > 1024) { + if (simpleKeys) + throw new Error('With simple keys, single line scalar must not span more than 1024 characters'); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value == null) { + if (keyCommentDone && onComment) + onComment(); + return str === '' ? '?' : explicitKey ? `? ${str}` : str; + } + } + else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) { + str = `? ${str}`; + if (keyComment && !keyCommentDone) { + str += lineComment(str, ctx.indent, commentString(keyComment)); + } + else if (chompKeep && onChompKeep) + onChompKeep(); + return str; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str += lineComment(str, ctx.indent, commentString(keyComment)); + str = `? ${str}\n${indent}:`; + } + else { + str = `${str}:`; + if (keyComment) + str += lineComment(str, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value)) { + vsb = !!value.spaceBefore; + vcb = value.commentBefore; + valueComment = value.comment; + } + else { + vsb = false; + vcb = null; + valueComment = null; + if (value && typeof value === 'object') + value = doc.createNode(value); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value)) + ctx.indentAtStart = str.length + 1; + chompKeep = false; + if (!indentSeq && + indentStep.length >= 2 && + !ctx.inFlow && + !explicitKey && + isSeq(value) && + !value.flow && + !value.tag && + !value.anchor) { + // If indentSeq === false, consider '- ' as part of indentation where possible + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true)); + let ws = ' '; + if (keyComment || vsb || vcb) { + ws = vsb ? '\n' : ''; + if (vcb) { + const cs = commentString(vcb); + ws += `\n${indentComment(cs, ctx.indent)}`; + } + if (valueStr === '' && !ctx.inFlow) { + if (ws === '\n' && valueComment) + ws = '\n\n'; + } + else { + ws += `\n${ctx.indent}`; + } + } + else if (!explicitKey && isCollection(value)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf('\n'); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === '&' || vs0 === '!')) { + let sp0 = valueStr.indexOf(' '); + if (vs0 === '&' && + sp0 !== -1 && + sp0 < nl0 && + valueStr[sp0 + 1] === '!') { + sp0 = valueStr.indexOf(' ', sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = `\n${ctx.indent}`; + } + } + else if (valueStr === '' || valueStr[0] === '\n') { + ws = ''; + } + str += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } + else if (valueComment && !valueCommentDone) { + str += lineComment(str, ctx.indent, commentString(valueComment)); + } + else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str; +} + +export { stringifyPair }; diff --git a/node_modules/yaml/browser/dist/stringify/stringifyString.js b/node_modules/yaml/browser/dist/stringify/stringifyString.js new file mode 100644 index 000000000..1591ce6bf --- /dev/null +++ b/node_modules/yaml/browser/dist/stringify/stringifyString.js @@ -0,0 +1,336 @@ +import { Scalar } from '../nodes/Scalar.js'; +import { foldFlowLines, FOLD_FLOW, FOLD_QUOTED, FOLD_BLOCK } from './foldFlowLines.js'; + +const getFoldOptions = (ctx, isBlock) => ({ + indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +// Also checks for lines starting with %, as parsing the output as YAML 1.1 will +// presume that's starting a new document. +const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); +function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str[i] === '\n') { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value, ctx) { + const json = JSON.stringify(value); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); + let str = ''; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') { + // space before newline needs to be escaped to not be folded + str += json.slice(start, i) + '\\ '; + i += 1; + start = i; + ch = '\\'; + } + if (ch === '\\') + switch (json[i + 1]) { + case 'u': + { + str += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case '0000': + str += '\\0'; + break; + case '0007': + str += '\\a'; + break; + case '000b': + str += '\\v'; + break; + case '001b': + str += '\\e'; + break; + case '0085': + str += '\\N'; + break; + case '00a0': + str += '\\_'; + break; + case '2028': + str += '\\L'; + break; + case '2029': + str += '\\P'; + break; + default: + if (code.substr(0, 2) === '00') + str += '\\x' + code.substr(2); + else + str += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case 'n': + if (implicitKey || + json[i + 2] === '"' || + json.length < minMultiLineLength) { + i += 1; + } + else { + // folding will eat first newline + str += json.slice(start, i) + '\n\n'; + while (json[i + 2] === '\\' && + json[i + 3] === 'n' && + json[i + 4] !== '"') { + str += '\n'; + i += 2; + } + str += indent; + // space after newline needs to be escaped to not be folded + if (json[i + 2] === ' ') + str += '\\'; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str = start ? str + json.slice(start) : json; + return implicitKey + ? str + : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value, ctx) { + if (ctx.options.singleQuote === false || + (ctx.implicitKey && value.includes('\n')) || + /[ \t]\n|\n[ \t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline + ) + return doubleQuotedString(value, ctx); + const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'"; + return ctx.implicitKey + ? res + : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value.includes('"'); + const hasSingle = value.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value, ctx); +} +// The negative lookbehind avoids a polynomial search, +// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind +let blockEndNewlines; +try { + blockEndNewlines = new RegExp('(^|(?\n'; + // determine chomping from whitespace at value end + let chomp; + let endStart; + for (endStart = value.length; endStart > 0; --endStart) { + const ch = value[endStart - 1]; + if (ch !== '\n' && ch !== '\t' && ch !== ' ') + break; + } + let end = value.substring(endStart); + const endNlPos = end.indexOf('\n'); + if (endNlPos === -1) { + chomp = '-'; // strip + } + else if (value === end || endNlPos !== end.length - 1) { + chomp = '+'; // keep + if (onChompKeep) + onChompKeep(); + } + else { + chomp = ''; // clip + } + if (end) { + value = value.slice(0, -end.length); + if (end[end.length - 1] === '\n') + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + // determine indent indicator from whitespace at value start + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value.length; ++startEnd) { + const ch = value[startEnd]; + if (ch === ' ') + startWithSpace = true; + else if (ch === '\n') + startNlPos = startEnd; + else + break; + } + let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value = value.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? '2' : '1'; // root is at -1 + // Leading | or > is added later + let header = (startWithSpace ? indentSize : '') + chomp; + if (comment) { + header += ' ' + commentString(comment.replace(/ ?[\r\n]+/g, ' ')); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value + .replace(/\n+/g, '\n$&') + .replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded + // ^ more-ind. ^ empty ^ capture next empty lines only at end of indent + .replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== 'folded' && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header}\n${indent}${body}`; + } + value = value.replace(/\n+/g, `$&${indent}`); + return `|${header}\n${indent}${start}${value}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if ((implicitKey && value.includes('\n')) || + (inFlow && /[[\]{},]/.test(value))) { + return quotedString(value, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + // not allowed: + // - '-' or '?' + // - start with an indicator character (except [?:-]) or /[?-] / + // - '\n ', ': ' or ' \n' anywhere + // - '#' not preceded by a non-space char + // - end with ' ' or ':' + return implicitKey || inFlow || !value.includes('\n') + ? quotedString(value, ctx) + : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && + !inFlow && + type !== Scalar.PLAIN && + value.includes('\n')) { + // Where allowed & type not set explicitly, prefer block style for multiline strings + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value)) { + if (indent === '') { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } + else if (implicitKey && indent === indentStep) { + return quotedString(value, ctx); + } + } + const str = value.replace(/\n+/g, `$&\n${indent}`); + // Verify that output will be parsed as a string, as e.g. plain numbers and + // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'), + // and others in v1.1. + if (actualString) { + const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value, ctx); + } + return implicitKey + ? str + : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === 'string' + ? item + : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + // force double quotes on control characters & unpaired surrogates + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow + ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers + : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = (implicitKey && defaultKeyType) || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +export { stringifyString }; diff --git a/node_modules/yaml/browser/dist/util.js b/node_modules/yaml/browser/dist/util.js new file mode 100644 index 000000000..dfb18ed73 --- /dev/null +++ b/node_modules/yaml/browser/dist/util.js @@ -0,0 +1,11 @@ +export { createNode } from './doc/createNode.js'; +export { debug, warn } from './log.js'; +export { createPair } from './nodes/Pair.js'; +export { toJS } from './nodes/toJS.js'; +export { findPair } from './nodes/YAMLMap.js'; +export { map as mapTag } from './schema/common/map.js'; +export { seq as seqTag } from './schema/common/seq.js'; +export { string as stringTag } from './schema/common/string.js'; +export { foldFlowLines } from './stringify/foldFlowLines.js'; +export { stringifyNumber } from './stringify/stringifyNumber.js'; +export { stringifyString } from './stringify/stringifyString.js'; diff --git a/node_modules/yaml/browser/dist/visit.js b/node_modules/yaml/browser/dist/visit.js new file mode 100644 index 000000000..b5eef41df --- /dev/null +++ b/node_modules/yaml/browser/dist/visit.js @@ -0,0 +1,233 @@ +import { isDocument, isNode, isPair, isCollection, isMap, isSeq, isScalar, isAlias } from './nodes/identity.js'; + +const BREAK = Symbol('break visit'); +const SKIP = Symbol('skip children'); +const REMOVE = Symbol('remove node'); +/** + * Apply a visitor to an AST node or document. + * + * Walks through the tree (depth-first) starting from `node`, calling a + * `visitor` function with three arguments: + * - `key`: For sequence values and map `Pair`, the node's index in the + * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. + * `null` for the root node. + * - `node`: The current node. + * - `path`: The ancestry of the current node. + * + * The return value of the visitor may be used to control the traversal: + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this node, continue with next + * sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current node, then continue with the next one + * - `Node`: Replace the current node, then continue by visiting it + * - `number`: While iterating the items of a sequence or map, set the index + * of the next step. This is useful especially if the index of the current + * node has changed. + * + * If `visitor` is a single function, it will be called with all values + * encountered in the tree, including e.g. `null` values. Alternatively, + * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, + * `Alias` and `Scalar` node. To define the same visitor function for more than + * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) + * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most + * specific defined one will be used for each node. + */ +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } + else + visit_(null, node, visitor_, Object.freeze([])); +} +// Without the `as symbol` casts, TS declares these in the `visit` +// namespace using `var`, but then complains about that because +// `unique symbol` must be `const`. +/** Terminate visit traversal completely */ +visit.BREAK = BREAK; +/** Do not visit the children of the current node */ +visit.SKIP = SKIP; +/** Remove the current node */ +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== 'symbol') { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === 'number') + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } + else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_('key', node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_('value', node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +/** + * Apply an async visitor to an AST node or document. + * + * Walks through the tree (depth-first) starting from `node`, calling a + * `visitor` function with three arguments: + * - `key`: For sequence values and map `Pair`, the node's index in the + * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. + * `null` for the root node. + * - `node`: The current node. + * - `path`: The ancestry of the current node. + * + * The return value of the visitor may be used to control the traversal: + * - `Promise`: Must resolve to one of the following values + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this node, continue with next + * sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current node, then continue with the next one + * - `Node`: Replace the current node, then continue by visiting it + * - `number`: While iterating the items of a sequence or map, set the index + * of the next step. This is useful especially if the index of the current + * node has changed. + * + * If `visitor` is a single function, it will be called with all values + * encountered in the tree, including e.g. `null` values. Alternatively, + * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, + * `Alias` and `Scalar` node. To define the same visitor function for more than + * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) + * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most + * specific defined one will be used for each node. + */ +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } + else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +// Without the `as symbol` casts, TS declares these in the `visit` +// namespace using `var`, but then complains about that because +// `unique symbol` must be `const`. +/** Terminate visit traversal completely */ +visitAsync.BREAK = BREAK; +/** Do not visit the children of the current node */ +visitAsync.SKIP = SKIP; +/** Remove the current node */ +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== 'symbol') { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === 'number') + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } + else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_('key', node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_('value', node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === 'object' && + (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === 'function') + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return undefined; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } + else if (isPair(parent)) { + if (key === 'key') + parent.key = node; + else + parent.value = node; + } + else if (isDocument(parent)) { + parent.contents = node; + } + else { + const pt = isAlias(parent) ? 'alias' : 'scalar'; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +export { visit, visitAsync }; diff --git a/node_modules/yaml/browser/index.js b/node_modules/yaml/browser/index.js new file mode 100644 index 000000000..5f7327183 --- /dev/null +++ b/node_modules/yaml/browser/index.js @@ -0,0 +1,5 @@ +// `export * as default from ...` fails on Webpack v4 +// https://github.com/eemeli/yaml/issues/228 +import * as YAML from './dist/index.js' +export default YAML +export * from './dist/index.js' diff --git a/node_modules/yaml/browser/package.json b/node_modules/yaml/browser/package.json new file mode 100644 index 000000000..3dbc1ca59 --- /dev/null +++ b/node_modules/yaml/browser/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/yaml/dist/cli.d.ts b/node_modules/yaml/dist/cli.d.ts new file mode 100644 index 000000000..4007923da --- /dev/null +++ b/node_modules/yaml/dist/cli.d.ts @@ -0,0 +1,8 @@ +export declare const help = "yaml: A command-line YAML processor and inspector\n\nReads stdin and writes output to stdout and errors & warnings to stderr.\n\nUsage:\n yaml Process a YAML stream, outputting it as YAML\n yaml cst Parse the CST of a YAML stream\n yaml lex Parse the lexical tokens of a YAML stream\n yaml valid Validate a YAML stream, returning 0 on success\n\nOptions:\n --help, -h Show this message.\n --json, -j Output JSON.\n --indent 2 Output pretty-printed data, indented by the given number of spaces.\n --merge, -m Enable support for \"<<\" merge keys.\n\nAdditional options for bare \"yaml\" command:\n --doc, -d Output pretty-printed JS Document objects.\n --single, -1 Require the input to consist of a single YAML document.\n --strict, -s Stop on errors.\n --visit, -v Apply a visitor to each document (requires a path to import)\n --yaml 1.1 Set the YAML version. (default: 1.2)"; +export declare class UserError extends Error { + static ARGS: number; + static SINGLE: number; + code: number; + constructor(code: number, message: string); +} +export declare function cli(stdin: NodeJS.ReadableStream, done: (error?: Error) => void, argv?: string[]): Promise; diff --git a/node_modules/yaml/dist/cli.mjs b/node_modules/yaml/dist/cli.mjs new file mode 100644 index 000000000..639cca4b6 --- /dev/null +++ b/node_modules/yaml/dist/cli.mjs @@ -0,0 +1,201 @@ +import { resolve } from 'path'; +import { parseArgs } from 'util'; +import { prettyToken } from './parse/cst.js'; +import { Lexer } from './parse/lexer.js'; +import { Parser } from './parse/parser.js'; +import { Composer } from './compose/composer.js'; +import { LineCounter } from './parse/line-counter.js'; +import { prettifyError } from './errors.js'; +import { visit } from './visit.js'; + +const help = `\ +yaml: A command-line YAML processor and inspector + +Reads stdin and writes output to stdout and errors & warnings to stderr. + +Usage: + yaml Process a YAML stream, outputting it as YAML + yaml cst Parse the CST of a YAML stream + yaml lex Parse the lexical tokens of a YAML stream + yaml valid Validate a YAML stream, returning 0 on success + +Options: + --help, -h Show this message. + --json, -j Output JSON. + --indent 2 Output pretty-printed data, indented by the given number of spaces. + --merge, -m Enable support for "<<" merge keys. + +Additional options for bare "yaml" command: + --doc, -d Output pretty-printed JS Document objects. + --single, -1 Require the input to consist of a single YAML document. + --strict, -s Stop on errors. + --visit, -v Apply a visitor to each document (requires a path to import) + --yaml 1.1 Set the YAML version. (default: 1.2)`; +class UserError extends Error { + constructor(code, message) { + super(`Error: ${message}`); + this.code = code; + } +} +UserError.ARGS = 2; +UserError.SINGLE = 3; +async function cli(stdin, done, argv) { + let args; + try { + args = parseArgs({ + args: argv, + allowPositionals: true, + options: { + doc: { type: 'boolean', short: 'd' }, + help: { type: 'boolean', short: 'h' }, + indent: { type: 'string', short: 'i' }, + merge: { type: 'boolean', short: 'm' }, + json: { type: 'boolean', short: 'j' }, + single: { type: 'boolean', short: '1' }, + strict: { type: 'boolean', short: 's' }, + visit: { type: 'string', short: 'v' }, + yaml: { type: 'string', default: '1.2' } + } + }); + } + catch (error) { + return done(new UserError(UserError.ARGS, error.message)); + } + const { positionals: [mode], values: opt } = args; + let indent = Number(opt.indent); + stdin.setEncoding('utf-8'); + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + switch (opt.help || mode) { + /* istanbul ignore next */ + case true: // --help + console.log(help); + break; + case 'lex': { + const lexer = new Lexer(); + const data = []; + const add = (tok) => { + if (opt.json) + data.push(tok); + else + console.log(prettyToken(tok)); + }; + stdin.on('data', (chunk) => { + for (const tok of lexer.lex(chunk, true)) + add(tok); + }); + stdin.on('end', () => { + for (const tok of lexer.lex('', false)) + add(tok); + if (opt.json) + console.log(JSON.stringify(data, null, indent)); + done(); + }); + break; + } + case 'cst': { + const parser = new Parser(); + const data = []; + const add = (tok) => { + if (opt.json) + data.push(tok); + else + console.dir(tok, { depth: null }); + }; + stdin.on('data', (chunk) => { + for (const tok of parser.parse(chunk, true)) + add(tok); + }); + stdin.on('end', () => { + for (const tok of parser.parse('', false)) + add(tok); + if (opt.json) + console.log(JSON.stringify(data, null, indent)); + done(); + }); + break; + } + case undefined: + case 'valid': { + const lineCounter = new LineCounter(); + const parser = new Parser(lineCounter.addNewLine); + // @ts-expect-error Version is validated at runtime + const composer = new Composer({ version: opt.yaml, merge: opt.merge }); + const visitor = opt.visit + ? (await import(resolve(opt.visit))).default + : null; + let source = ''; + let hasDoc = false; + let reqDocEnd = false; + const data = []; + const add = (doc) => { + if (hasDoc && opt.single) { + return done(new UserError(UserError.SINGLE, 'Input stream contains multiple documents')); + } + for (const error of doc.errors) { + prettifyError(source, lineCounter)(error); + if (opt.strict || mode === 'valid') + return done(error); + console.error(error); + } + for (const warning of doc.warnings) { + prettifyError(source, lineCounter)(warning); + console.error(warning); + } + if (visitor) + visit(doc, visitor); + if (mode === 'valid') + doc.toJS(); + else if (opt.json) + data.push(doc); + else if (opt.doc) { + Object.defineProperties(doc, { + options: { enumerable: false }, + schema: { enumerable: false } + }); + console.dir(doc, { depth: null }); + } + else { + if (reqDocEnd) + console.log('...'); + try { + indent || (indent = 2); + const str = doc.toString({ indent }); + console.log(str.endsWith('\n') ? str.slice(0, -1) : str); + } + catch (error) { + done(error); + } + } + hasDoc = true; + reqDocEnd = !doc.directives?.docEnd; + }; + stdin.on('data', (chunk) => { + source += chunk; + for (const tok of parser.parse(chunk, true)) { + for (const doc of composer.next(tok)) + add(doc); + } + }); + stdin.on('end', () => { + for (const tok of parser.parse('', false)) { + for (const doc of composer.next(tok)) + add(doc); + } + for (const doc of composer.end(false)) + add(doc); + if (opt.single && !hasDoc) { + return done(new UserError(UserError.SINGLE, 'Input stream contained no documents')); + } + if (mode !== 'valid' && opt.json) { + console.log(JSON.stringify(opt.single ? data[0] : data, null, indent)); + } + done(); + }); + break; + } + default: + done(new UserError(UserError.ARGS, `Unknown command: ${JSON.stringify(mode)}`)); + } +} + +export { UserError, cli, help }; diff --git a/node_modules/yaml/dist/compose/compose-collection.d.ts b/node_modules/yaml/dist/compose/compose-collection.d.ts new file mode 100644 index 000000000..ecbd9e0f9 --- /dev/null +++ b/node_modules/yaml/dist/compose/compose-collection.d.ts @@ -0,0 +1,11 @@ +import type { ParsedNode } from '../nodes/Node'; +import type { BlockMap, BlockSequence, FlowCollection, SourceToken } from '../parse/cst'; +import type { ComposeContext, ComposeNode } from './compose-node'; +import type { ComposeErrorHandler } from './composer'; +interface Props { + anchor: SourceToken | null; + tag: SourceToken | null; + newlineAfterProp: SourceToken | null; +} +export declare function composeCollection(CN: ComposeNode, ctx: ComposeContext, token: BlockMap | BlockSequence | FlowCollection, props: Props, onError: ComposeErrorHandler): ParsedNode; +export {}; diff --git a/node_modules/yaml/dist/compose/compose-collection.js b/node_modules/yaml/dist/compose/compose-collection.js new file mode 100644 index 000000000..852efe2a4 --- /dev/null +++ b/node_modules/yaml/dist/compose/compose-collection.js @@ -0,0 +1,90 @@ +'use strict'; + +var identity = require('../nodes/identity.js'); +var Scalar = require('../nodes/Scalar.js'); +var YAMLMap = require('../nodes/YAMLMap.js'); +var YAMLSeq = require('../nodes/YAMLSeq.js'); +var resolveBlockMap = require('./resolve-block-map.js'); +var resolveBlockSeq = require('./resolve-block-seq.js'); +var resolveFlowCollection = require('./resolve-flow-collection.js'); + +function resolveCollection(CN, ctx, token, onError, tagName, tag) { + const coll = token.type === 'block-map' + ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag) + : token.type === 'block-seq' + ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag) + : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag); + const Coll = coll.constructor; + // If we got a tagName matching the class, or the tag name is '!', + // then use the tagName from the node class used to create it. + if (tagName === '!' || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken + ? null + : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg)); + if (token.type === 'block-seq') { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken + ? anchor.offset > tagToken.offset + ? anchor + : tagToken + : (anchor ?? tagToken); + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = 'Missing newline after block sequence props'; + onError(lastProp, 'MISSING_CHAR', message); + } + } + const expType = token.type === 'block-map' + ? 'map' + : token.type === 'block-seq' + ? 'seq' + : token.start.source === '{' + ? 'map' + : 'seq'; + // shortcut: check if it's a generic YAMLMap or YAMLSeq + // before jumping into the custom tag logic. + if (!tagToken || + !tagName || + tagName === '!' || + (tagName === YAMLMap.YAMLMap.tagName && expType === 'map') || + (tagName === YAMLSeq.YAMLSeq.tagName && expType === 'seq')) { + return resolveCollection(CN, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } + else { + if (kt) { + onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? 'scalar'}`, true); + } + else { + onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll; + const node = identity.isNode(res) + ? res + : new Scalar.Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +exports.composeCollection = composeCollection; diff --git a/node_modules/yaml/dist/compose/compose-doc.d.ts b/node_modules/yaml/dist/compose/compose-doc.d.ts new file mode 100644 index 000000000..5ffcc38b8 --- /dev/null +++ b/node_modules/yaml/dist/compose/compose-doc.d.ts @@ -0,0 +1,7 @@ +import type { Directives } from '../doc/directives'; +import { Document } from '../doc/Document'; +import type { ParsedNode } from '../nodes/Node'; +import type { DocumentOptions, ParseOptions, SchemaOptions } from '../options'; +import type * as CST from '../parse/cst'; +import type { ComposeErrorHandler } from './composer'; +export declare function composeDoc(options: ParseOptions & DocumentOptions & SchemaOptions, directives: Directives, { offset, start, value, end }: CST.Document, onError: ComposeErrorHandler): Document.Parsed; diff --git a/node_modules/yaml/dist/compose/compose-doc.js b/node_modules/yaml/dist/compose/compose-doc.js new file mode 100644 index 000000000..63c949518 --- /dev/null +++ b/node_modules/yaml/dist/compose/compose-doc.js @@ -0,0 +1,45 @@ +'use strict'; + +var Document = require('../doc/Document.js'); +var composeNode = require('./compose-node.js'); +var resolveEnd = require('./resolve-end.js'); +var resolveProps = require('./resolve-props.js'); + +function composeDoc(options, directives, { offset, start, value, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document.Document(undefined, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps.resolveProps(start, { + indicator: 'doc-start', + next: value ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value && + (value.type === 'block-map' || value.type === 'block-seq') && + !props.hasNewline) + onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker'); + } + // @ts-expect-error If Contents is set, let's trust the user + doc.contents = value + ? composeNode.composeNode(ctx, value, props, onError) + : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd.resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +exports.composeDoc = composeDoc; diff --git a/node_modules/yaml/dist/compose/compose-node.d.ts b/node_modules/yaml/dist/compose/compose-node.d.ts new file mode 100644 index 000000000..fa5085de6 --- /dev/null +++ b/node_modules/yaml/dist/compose/compose-node.d.ts @@ -0,0 +1,29 @@ +import type { Directives } from '../doc/directives'; +import type { ParsedNode } from '../nodes/Node'; +import type { ParseOptions } from '../options'; +import type { SourceToken, Token } from '../parse/cst'; +import type { Schema } from '../schema/Schema'; +import type { ComposeErrorHandler } from './composer'; +export interface ComposeContext { + atKey: boolean; + atRoot: boolean; + directives: Directives; + options: Readonly>>; + schema: Readonly; +} +interface Props { + spaceBefore: boolean; + comment: string; + anchor: SourceToken | null; + tag: SourceToken | null; + newlineAfterProp: SourceToken | null; + end: number; +} +declare const CN: { + composeNode: typeof composeNode; + composeEmptyNode: typeof composeEmptyNode; +}; +export type ComposeNode = typeof CN; +export declare function composeNode(ctx: ComposeContext, token: Token, props: Props, onError: ComposeErrorHandler): ParsedNode; +export declare function composeEmptyNode(ctx: ComposeContext, offset: number, before: Token[] | undefined, pos: number | null, { spaceBefore, comment, anchor, tag, end }: Props, onError: ComposeErrorHandler): import('../index').Scalar.Parsed; +export {}; diff --git a/node_modules/yaml/dist/compose/compose-node.js b/node_modules/yaml/dist/compose/compose-node.js new file mode 100644 index 000000000..c5f4d8bdd --- /dev/null +++ b/node_modules/yaml/dist/compose/compose-node.js @@ -0,0 +1,105 @@ +'use strict'; + +var Alias = require('../nodes/Alias.js'); +var identity = require('../nodes/identity.js'); +var composeCollection = require('./compose-collection.js'); +var composeScalar = require('./compose-scalar.js'); +var resolveEnd = require('./resolve-end.js'); +var utilEmptyScalarPosition = require('./util-empty-scalar-position.js'); + +const CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case 'alias': + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties'); + break; + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + case 'block-scalar': + node = composeScalar.composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case 'block-map': + case 'block-seq': + case 'flow-collection': + node = composeCollection.composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + default: { + const message = token.type === 'error' + ? token.message + : `Unsupported token (type: ${token.type})`; + onError(token, 'UNEXPECTED_TOKEN', message); + node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError); + isSrcToken = false; + } + } + if (anchor && node.anchor === '') + onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string'); + if (atKey && + ctx.options.stringKeys && + (!identity.isScalar(node) || + typeof node.value !== 'string' || + (node.tag && node.tag !== 'tag:yaml.org,2002:str'))) { + const msg = 'With stringKeys, all keys must be strings'; + onError(tag ?? token, 'NON_STRING_KEY', msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === 'scalar' && token.source === '') + node.comment = comment; + else + node.commentBefore = comment; + } + // @ts-expect-error Type checking misses meaning of isSrcToken + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: 'scalar', + offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos), + indent: -1, + source: '' + }; + const node = composeScalar.composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === '') + onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string'); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias.Alias(source.substring(1)); + if (alias.source === '') + onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string'); + if (alias.source.endsWith(':')) + onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true); + const valueEnd = offset + source.length; + const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +exports.composeEmptyNode = composeEmptyNode; +exports.composeNode = composeNode; diff --git a/node_modules/yaml/dist/compose/compose-scalar.d.ts b/node_modules/yaml/dist/compose/compose-scalar.d.ts new file mode 100644 index 000000000..f2b5ffa3c --- /dev/null +++ b/node_modules/yaml/dist/compose/compose-scalar.d.ts @@ -0,0 +1,5 @@ +import { Scalar } from '../nodes/Scalar'; +import type { BlockScalar, FlowScalar, SourceToken } from '../parse/cst'; +import type { ComposeContext } from './compose-node'; +import type { ComposeErrorHandler } from './composer'; +export declare function composeScalar(ctx: ComposeContext, token: FlowScalar | BlockScalar, tagToken: SourceToken | null, onError: ComposeErrorHandler): Scalar.Parsed; diff --git a/node_modules/yaml/dist/compose/compose-scalar.js b/node_modules/yaml/dist/compose/compose-scalar.js new file mode 100644 index 000000000..7fc7ed4d8 --- /dev/null +++ b/node_modules/yaml/dist/compose/compose-scalar.js @@ -0,0 +1,88 @@ +'use strict'; + +var identity = require('../nodes/identity.js'); +var Scalar = require('../nodes/Scalar.js'); +var resolveBlockScalar = require('./resolve-block-scalar.js'); +var resolveFlowScalar = require('./resolve-flow-scalar.js'); + +function composeScalar(ctx, token, tagToken, onError) { + const { value, type, comment, range } = token.type === 'block-scalar' + ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) + : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken + ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg)) + : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[identity.SCALAR]; + } + else if (tagName) + tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError); + else if (token.type === 'scalar') + tag = findScalarTagByTest(ctx, value, token, onError); + else + tag = ctx.schema[identity.SCALAR]; + let scalar; + try { + const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options); + scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res); + } + catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg); + scalar = new Scalar.Scalar(value); + } + scalar.range = range; + scalar.source = value; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema, value, tagName, tagToken, onError) { + if (tagName === '!') + return schema[identity.SCALAR]; // non-specific tag + const matchWithTest = []; + for (const tag of schema.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value)) + return tag; + const kt = schema.knownTags[tagName]; + if (kt && !kt.collection) { + // Ensure that the known tag is available for stringifying, + // but does not get used by default. + schema.tags.push(Object.assign({}, kt, { default: false, test: undefined })); + return kt; + } + onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str'); + return schema[identity.SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) { + const tag = schema.tags.find(tag => (tag.default === true || (atKey && tag.default === 'key')) && + tag.test?.test(value)) || schema[identity.SCALAR]; + if (schema.compat) { + const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ?? + schema[identity.SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, 'TAG_RESOLVE_FAILED', msg, true); + } + } + return tag; +} + +exports.composeScalar = composeScalar; diff --git a/node_modules/yaml/dist/compose/composer.d.ts b/node_modules/yaml/dist/compose/composer.d.ts new file mode 100644 index 000000000..94c28c704 --- /dev/null +++ b/node_modules/yaml/dist/compose/composer.d.ts @@ -0,0 +1,63 @@ +import { Directives } from '../doc/directives'; +import { Document } from '../doc/Document'; +import type { ErrorCode } from '../errors'; +import { YAMLParseError, YAMLWarning } from '../errors'; +import type { ParsedNode, Range } from '../nodes/Node'; +import type { DocumentOptions, ParseOptions, SchemaOptions } from '../options'; +import type { Token } from '../parse/cst'; +type ErrorSource = number | [number, number] | Range | { + offset: number; + source?: string; +}; +export type ComposeErrorHandler = (source: ErrorSource, code: ErrorCode, message: string, warning?: boolean) => void; +/** + * Compose a stream of CST nodes into a stream of YAML Documents. + * + * ```ts + * import { Composer, Parser } from 'yaml' + * + * const src: string = ... + * const tokens = new Parser().parse(src) + * const docs = new Composer().compose(tokens) + * ``` + */ +export declare class Composer { + private directives; + private doc; + private options; + private atDirectives; + private prelude; + private errors; + private warnings; + constructor(options?: ParseOptions & DocumentOptions & SchemaOptions); + private onError; + private decorate; + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo(): { + comment: string; + directives: Directives; + errors: YAMLParseError[]; + warnings: YAMLWarning[]; + }; + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + compose(tokens: Iterable, forceDoc?: boolean, endOffset?: number): Generator, void, unknown>; + /** Advance the composer by one CST token. */ + next(token: Token): Generator, void, unknown>; + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + end(forceDoc?: boolean, endOffset?: number): Generator, void, unknown>; +} +export {}; diff --git a/node_modules/yaml/dist/compose/composer.js b/node_modules/yaml/dist/compose/composer.js new file mode 100644 index 000000000..df60391f6 --- /dev/null +++ b/node_modules/yaml/dist/compose/composer.js @@ -0,0 +1,222 @@ +'use strict'; + +var node_process = require('process'); +var directives = require('../doc/directives.js'); +var Document = require('../doc/Document.js'); +var errors = require('../errors.js'); +var identity = require('../nodes/identity.js'); +var composeDoc = require('./compose-doc.js'); +var resolveEnd = require('./resolve-end.js'); + +function getErrorPos(src) { + if (typeof src === 'number') + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === 'string' ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ''; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case '#': + comment += + (comment === '' ? '' : afterEmptyLine ? '\n\n' : '\n') + + (source.substring(1) || ' '); + atComment = true; + afterEmptyLine = false; + break; + case '%': + if (prelude[i + 1]?.[0] !== '#') + i += 1; + atComment = false; + break; + default: + // This may be wrong after doc-end, but in that case it doesn't matter + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +/** + * Compose a stream of CST nodes into a stream of YAML Documents. + * + * ```ts + * import { Composer, Parser } from 'yaml' + * + * const src: string = ... + * const tokens = new Parser().parse(src) + * const docs = new Composer().compose(tokens) + * ``` + */ +class Composer { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new errors.YAMLWarning(pos, code, message)); + else + this.errors.push(new errors.YAMLParseError(pos, code, message)); + }; + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + this.directives = new directives.Directives({ version: options.version || '1.2' }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + //console.log({ dc: doc.comment, prelude, comment }) + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment}\n${comment}` : comment; + } + else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } + else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (identity.isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment}\n${cb}` : comment; + } + else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment}\n${cb}` : comment; + } + } + if (afterDoc) { + Array.prototype.push.apply(doc.errors, this.errors); + Array.prototype.push.apply(doc.warnings, this.warnings); + } + else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + if (node_process.env.LOG_STREAM) + console.dir(token, { depth: null }); + switch (token.type) { + case 'directive': + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, 'BAD_DIRECTIVE', message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case 'document': { + const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line'); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case 'byte-order-mark': + case 'space': + break; + case 'comment': + case 'newline': + this.prelude.push(token.source); + break; + case 'error': { + const msg = token.source + ? `${token.message}: ${JSON.stringify(token.source)}` + : token.message; + const error = new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case 'doc-end': { + if (!this.doc) { + const msg = 'Unexpected doc-end without preceding document'; + this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc}\n${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } + else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document.Document(undefined, opts); + if (this.atDirectives) + this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line'); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +} + +exports.Composer = Composer; diff --git a/node_modules/yaml/dist/compose/resolve-block-map.d.ts b/node_modules/yaml/dist/compose/resolve-block-map.d.ts new file mode 100644 index 000000000..0e33a1111 --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-block-map.d.ts @@ -0,0 +1,6 @@ +import { YAMLMap } from '../nodes/YAMLMap'; +import type { BlockMap } from '../parse/cst'; +import type { CollectionTag } from '../schema/types'; +import type { ComposeContext, ComposeNode } from './compose-node'; +import type { ComposeErrorHandler } from './composer'; +export declare function resolveBlockMap({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, bm: BlockMap, onError: ComposeErrorHandler, tag?: CollectionTag): YAMLMap.Parsed; diff --git a/node_modules/yaml/dist/compose/resolve-block-map.js b/node_modules/yaml/dist/compose/resolve-block-map.js new file mode 100644 index 000000000..f0d97272f --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-block-map.js @@ -0,0 +1,117 @@ +'use strict'; + +var Pair = require('../nodes/Pair.js'); +var YAMLMap = require('../nodes/YAMLMap.js'); +var resolveProps = require('./resolve-props.js'); +var utilContainsNewline = require('./util-contains-newline.js'); +var utilFlowIndentCheck = require('./util-flow-indent-check.js'); +var utilMapIncludes = require('./util-map-includes.js'); + +const startColMsg = 'All mapping items must start at the same column'; +function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap; + const map = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value } = collItem; + // key properties + const keyProps = resolveProps.resolveProps(start, { + indicator: 'explicit-key-ind', + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === 'block-seq') + onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key'); + else if ('indent' in key && key.indent !== bm.indent) + onError(offset, 'BAD_INDENT', startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map.comment) + map.comment += '\n' + keyProps.comment; + else + map.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) { + onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line'); + } + } + else if (keyProps.found?.indent !== bm.indent) { + onError(offset, 'BAD_INDENT', startColMsg); + } + // key value + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key + ? composeNode(ctx, key, keyProps, onError) + : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode)) + onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique'); + // value properties + const valueProps = resolveProps.resolveProps(sep ?? [], { + indicator: 'map-value-ind', + next: value, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === 'block-scalar' + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value?.type === 'block-map' && !valueProps.hasNewline) + onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings'); + if (ctx.options.strict && + keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key'); + } + // value value + const valueNode = value + ? composeNode(ctx, value, valueProps, onError) + : composeEmptyNode(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError); + offset = valueNode.range[2]; + const pair = new Pair.Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map.items.push(pair); + } + else { + // key with no value + if (implicitKey) + onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values'); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += '\n' + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair.Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content'); + map.range = [bm.offset, offset, commentEnd ?? offset]; + return map; +} + +exports.resolveBlockMap = resolveBlockMap; diff --git a/node_modules/yaml/dist/compose/resolve-block-scalar.d.ts b/node_modules/yaml/dist/compose/resolve-block-scalar.d.ts new file mode 100644 index 000000000..06346305f --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-block-scalar.d.ts @@ -0,0 +1,11 @@ +import type { Range } from '../nodes/Node'; +import { Scalar } from '../nodes/Scalar'; +import type { BlockScalar } from '../parse/cst'; +import type { ComposeContext } from './compose-node'; +import type { ComposeErrorHandler } from './composer'; +export declare function resolveBlockScalar(ctx: ComposeContext, scalar: BlockScalar, onError: ComposeErrorHandler): { + value: string; + type: Scalar.BLOCK_FOLDED | Scalar.BLOCK_LITERAL | null; + comment: string; + range: Range; +}; diff --git a/node_modules/yaml/dist/compose/resolve-block-scalar.js b/node_modules/yaml/dist/compose/resolve-block-scalar.js new file mode 100644 index 000000000..97eaf2b59 --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-block-scalar.js @@ -0,0 +1,200 @@ +'use strict'; + +var Scalar = require('../nodes/Scalar.js'); + +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: '', type: null, comment: '', range: [start, start, start] }; + const type = header.mode === '>' ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL; + const lines = scalar.source ? splitLines(scalar.source) : []; + // determine the end of content & start of chomping + let chompStart = lines.length; + for (let i = lines.length - 1; i >= 0; --i) { + const content = lines[i][1]; + if (content === '' || content === '\r') + chompStart = i; + else + break; + } + // shortcut for empty contents + if (chompStart === 0) { + const value = header.chomp === '+' && lines.length > 0 + ? '\n'.repeat(Math.max(1, lines.length - 1)) + : ''; + let end = start + header.length; + if (scalar.source) + end += scalar.source.length; + return { value, type, comment: header.comment, range: [start, end, end] }; + } + // find the indentation level to trim from start + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines[i]; + if (content === '' || content === '\r') { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } + else { + if (indent.length < trimIndent) { + const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator'; + onError(offset + indent.length, 'MISSING_CHAR', message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = 'Block scalar values in collections must be indented'; + onError(offset, 'BAD_INDENT', message); + } + break; + } + offset += indent.length + content.length + 1; + } + // include trailing more-indented empty lines in content + for (let i = lines.length - 1; i >= chompStart; --i) { + if (lines[i][0].length > trimIndent) + chompStart = i + 1; + } + let value = ''; + let sep = ''; + let prevMoreIndented = false; + // leading whitespace is kept intact + for (let i = 0; i < contentStart; ++i) + value += lines[i][0].slice(trimIndent) + '\n'; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === '\r'; + if (crlf) + content = content.slice(0, -1); + /* istanbul ignore if already caught in lexer */ + if (content && indent.length < trimIndent) { + const src = header.indent + ? 'explicit indentation indicator' + : 'first line'; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message); + indent = ''; + } + if (type === Scalar.Scalar.BLOCK_LITERAL) { + value += sep + indent.slice(trimIndent) + content; + sep = '\n'; + } + else if (indent.length > trimIndent || content[0] === '\t') { + // more-indented content within a folded block + if (sep === ' ') + sep = '\n'; + else if (!prevMoreIndented && sep === '\n') + sep = '\n\n'; + value += sep + indent.slice(trimIndent) + content; + sep = '\n'; + prevMoreIndented = true; + } + else if (content === '') { + // empty line + if (sep === '\n') + value += '\n'; + else + sep = '\n'; + } + else { + value += sep + content; + sep = ' '; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case '-': + break; + case '+': + for (let i = chompStart; i < lines.length; ++i) + value += '\n' + lines[i][0].slice(trimIndent); + if (value[value.length - 1] !== '\n') + value += '\n'; + break; + default: + value += '\n'; + } + const end = start + header.length + scalar.source.length; + return { value, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + /* istanbul ignore if should not happen */ + if (props[0].type !== 'block-scalar-header') { + onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found'); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ''; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === '-' || ch === '+')) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ''; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case 'space': + hasSpace = true; + // fallthrough + case 'newline': + length += token.source.length; + break; + case 'comment': + if (strict && !hasSpace) { + const message = 'Comments must be separated from other tokens by white space characters'; + onError(token, 'MISSING_CHAR', message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case 'error': + onError(token, 'UNEXPECTED_TOKEN', token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, 'UNEXPECTED_TOKEN', message); + const ts = token.source; + if (ts && typeof ts === 'string') + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +/** @returns Array of lines split up as `[indent, content]` */ +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] + ? [m[1], first.slice(m[1].length)] + : ['', first]; + const lines = [line0]; + for (let i = 1; i < split.length; i += 2) + lines.push([split[i], split[i + 1]]); + return lines; +} + +exports.resolveBlockScalar = resolveBlockScalar; diff --git a/node_modules/yaml/dist/compose/resolve-block-seq.d.ts b/node_modules/yaml/dist/compose/resolve-block-seq.d.ts new file mode 100644 index 000000000..38d539996 --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-block-seq.d.ts @@ -0,0 +1,6 @@ +import { YAMLSeq } from '../nodes/YAMLSeq'; +import type { BlockSequence } from '../parse/cst'; +import type { CollectionTag } from '../schema/types'; +import type { ComposeContext, ComposeNode } from './compose-node'; +import type { ComposeErrorHandler } from './composer'; +export declare function resolveBlockSeq({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, bs: BlockSequence, onError: ComposeErrorHandler, tag?: CollectionTag): YAMLSeq.Parsed; diff --git a/node_modules/yaml/dist/compose/resolve-block-seq.js b/node_modules/yaml/dist/compose/resolve-block-seq.js new file mode 100644 index 000000000..9c834fc4e --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-block-seq.js @@ -0,0 +1,51 @@ +'use strict'; + +var YAMLSeq = require('../nodes/YAMLSeq.js'); +var resolveProps = require('./resolve-props.js'); +var utilFlowIndentCheck = require('./util-flow-indent-check.js'); + +function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq; + const seq = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value } of bs.items) { + const props = resolveProps.resolveProps(start, { + indicator: 'seq-item-ind', + next: value, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value) { + if (value?.type === 'block-seq') + onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column'); + else + onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator'); + } + else { + commentEnd = props.end; + if (props.comment) + seq.comment = props.comment; + continue; + } + } + const node = value + ? composeNode(ctx, value, props, onError) + : composeEmptyNode(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError); + offset = node.range[2]; + seq.items.push(node); + } + seq.range = [bs.offset, offset, commentEnd ?? offset]; + return seq; +} + +exports.resolveBlockSeq = resolveBlockSeq; diff --git a/node_modules/yaml/dist/compose/resolve-end.d.ts b/node_modules/yaml/dist/compose/resolve-end.d.ts new file mode 100644 index 000000000..c9d27c214 --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-end.d.ts @@ -0,0 +1,6 @@ +import type { SourceToken } from '../parse/cst'; +import type { ComposeErrorHandler } from './composer'; +export declare function resolveEnd(end: SourceToken[] | undefined, offset: number, reqSpace: boolean, onError: ComposeErrorHandler): { + comment: string; + offset: number; +}; diff --git a/node_modules/yaml/dist/compose/resolve-end.js b/node_modules/yaml/dist/compose/resolve-end.js new file mode 100644 index 000000000..3a583477a --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-end.js @@ -0,0 +1,39 @@ +'use strict'; + +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ''; + if (end) { + let hasSpace = false; + let sep = ''; + for (const token of end) { + const { source, type } = token; + switch (type) { + case 'space': + hasSpace = true; + break; + case 'comment': { + if (reqSpace && !hasSpace) + onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters'); + const cb = source.substring(1) || ' '; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ''; + break; + } + case 'newline': + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +exports.resolveEnd = resolveEnd; diff --git a/node_modules/yaml/dist/compose/resolve-flow-collection.d.ts b/node_modules/yaml/dist/compose/resolve-flow-collection.d.ts new file mode 100644 index 000000000..86ffd0931 --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-flow-collection.d.ts @@ -0,0 +1,7 @@ +import { YAMLMap } from '../nodes/YAMLMap'; +import { YAMLSeq } from '../nodes/YAMLSeq'; +import type { FlowCollection } from '../parse/cst'; +import type { CollectionTag } from '../schema/types'; +import type { ComposeContext, ComposeNode } from './compose-node'; +import type { ComposeErrorHandler } from './composer'; +export declare function resolveFlowCollection({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, fc: FlowCollection, onError: ComposeErrorHandler, tag?: CollectionTag): YAMLMap.Parsed | YAMLSeq.Parsed; diff --git a/node_modules/yaml/dist/compose/resolve-flow-collection.js b/node_modules/yaml/dist/compose/resolve-flow-collection.js new file mode 100644 index 000000000..960ad31fa --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-flow-collection.js @@ -0,0 +1,209 @@ +'use strict'; + +var identity = require('../nodes/identity.js'); +var Pair = require('../nodes/Pair.js'); +var YAMLMap = require('../nodes/YAMLMap.js'); +var YAMLSeq = require('../nodes/YAMLSeq.js'); +var resolveEnd = require('./resolve-end.js'); +var resolveProps = require('./resolve-props.js'); +var utilContainsNewline = require('./util-contains-newline.js'); +var utilMapIncludes = require('./util-map-includes.js'); + +const blockMsg = 'Block collections are not allowed within flow collections'; +const isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq'); +function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) { + const isMap = fc.start.source === '{'; + const fcName = isMap ? 'flow map' : 'flow sequence'; + const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq)); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value } = collItem; + const props = resolveProps.resolveProps(start, { + flow: fcName, + indicator: 'explicit-key-ind', + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value) { + if (i === 0 && props.comma) + onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += '\n' + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key)) + onError(key, // checked by containsNewline() + 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line'); + } + if (i === 0) { + if (props.comma) + onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`); + } + else { + if (!props.comma) + onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ''; + loop: for (const st of start) { + switch (st.type) { + case 'comma': + case 'space': + break; + case 'comment': + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (identity.isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += '\n' + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap && !sep && !props.found) { + // item is a value in a seq + // → key & sep are empty, start does not include ? or : + const valueNode = value + ? composeNode(ctx, value, props, onError) + : composeEmptyNode(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value)) + onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg); + } + else { + // item is a key+value pair + // key value + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key + ? composeNode(ctx, key, props, onError) + : composeEmptyNode(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg); + ctx.atKey = false; + // value properties + const valueProps = resolveProps.resolveProps(sep ?? [], { + flow: fcName, + indicator: 'map-value-ind', + next: value, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === 'newline') { + onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line'); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key'); + } + } + else if (value) { + if ('source' in value && value.source?.[0] === ':') + onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`); + else + onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`); + } + // value value + const valueNode = value + ? composeNode(ctx, value, valueProps, onError) + : valueProps.found + ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) + : null; + if (valueNode) { + if (isBlock(value)) + onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg); + } + else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += '\n' + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair.Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap) { + const map = coll; + if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode)) + onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique'); + map.items.push(pair); + } + else { + const map = new YAMLMap.YAMLMap(ctx.schema); + map.flow = true; + map.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap ? '}' : ']'; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot + ? `${name} must end with a ${expectedEnd}` + : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += '\n' + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } + else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +exports.resolveFlowCollection = resolveFlowCollection; diff --git a/node_modules/yaml/dist/compose/resolve-flow-scalar.d.ts b/node_modules/yaml/dist/compose/resolve-flow-scalar.d.ts new file mode 100644 index 000000000..ee24cd7f2 --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-flow-scalar.d.ts @@ -0,0 +1,10 @@ +import type { Range } from '../nodes/Node'; +import { Scalar } from '../nodes/Scalar'; +import type { FlowScalar } from '../parse/cst'; +import type { ComposeErrorHandler } from './composer'; +export declare function resolveFlowScalar(scalar: FlowScalar, strict: boolean, onError: ComposeErrorHandler): { + value: string; + type: Scalar.PLAIN | Scalar.QUOTE_DOUBLE | Scalar.QUOTE_SINGLE | null; + comment: string; + range: Range; +}; diff --git a/node_modules/yaml/dist/compose/resolve-flow-scalar.js b/node_modules/yaml/dist/compose/resolve-flow-scalar.js new file mode 100644 index 000000000..45aad9955 --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-flow-scalar.js @@ -0,0 +1,225 @@ +'use strict'; + +var Scalar = require('../nodes/Scalar.js'); +var resolveEnd = require('./resolve-end.js'); + +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case 'scalar': + _type = Scalar.Scalar.PLAIN; + value = plainValue(source, _onError); + break; + case 'single-quoted-scalar': + _type = Scalar.Scalar.QUOTE_SINGLE; + value = singleQuotedValue(source, _onError); + break; + case 'double-quoted-scalar': + _type = Scalar.Scalar.QUOTE_DOUBLE; + value = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`); + return { + value: '', + type: null, + comment: '', + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError); + return { + value, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ''; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case '\t': + badChar = 'a tab character'; + break; + case ',': + badChar = 'flow indicator character ,'; + break; + case '%': + badChar = 'directive indicator character %'; + break; + case '|': + case '>': { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case '@': + case '`': { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`); + return foldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, 'MISSING_CHAR', "Missing closing 'quote"); + return foldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function foldLines(source) { + /** + * The negative lookbehind here and in the `re` RegExp is to + * prevent causing a polynomial search time in certain cases. + * + * The try-catch is for Safari, which doesn't support this yet: + * https://caniuse.com/js-regexp-lookbehind + */ + let first, line; + try { + first = new RegExp('(.*?)(? wsStart ? source.slice(wsStart, i + 1) : ch; + } + else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, 'MISSING_CHAR', 'Missing closing "quote'); + return res; +} +/** + * Fold a single newline into a space, multiple newlines to N - 1 newlines. + * Presumes `source[offset] === '\n'` + */ +function foldNewline(source, offset) { + let fold = ''; + let ch = source[offset + 1]; + while (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') { + if (ch === '\r' && source[offset + 2] !== '\n') + break; + if (ch === '\n') + fold += '\n'; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = ' '; + return { fold, offset }; +} +const escapeCodes = { + '0': '\0', // null character + a: '\x07', // bell character + b: '\b', // backspace + e: '\x1b', // escape character + f: '\f', // form feed + n: '\n', // line feed + r: '\r', // carriage return + t: '\t', // horizontal tab + v: '\v', // vertical tab + N: '\u0085', // Unicode next line + _: '\u00a0', // Unicode non-breaking space + L: '\u2028', // Unicode line separator + P: '\u2029', // Unicode paragraph separator + ' ': ' ', + '"': '"', + '/': '/', + '\\': '\\', + '\t': '\t' +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + if (isNaN(code)) { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`); + return raw; + } + return String.fromCodePoint(code); +} + +exports.resolveFlowScalar = resolveFlowScalar; diff --git a/node_modules/yaml/dist/compose/resolve-props.d.ts b/node_modules/yaml/dist/compose/resolve-props.d.ts new file mode 100644 index 000000000..d9ee38196 --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-props.d.ts @@ -0,0 +1,23 @@ +import type { SourceToken, Token } from '../parse/cst'; +import type { ComposeErrorHandler } from './composer'; +export interface ResolvePropsArg { + flow?: 'flow map' | 'flow sequence'; + indicator: 'doc-start' | 'explicit-key-ind' | 'map-value-ind' | 'seq-item-ind'; + next: Token | null | undefined; + offset: number; + onError: ComposeErrorHandler; + parentIndent: number; + startOnNewline: boolean; +} +export declare function resolveProps(tokens: SourceToken[], { flow, indicator, next, offset, onError, parentIndent, startOnNewline }: ResolvePropsArg): { + comma: SourceToken | null; + found: SourceToken | null; + spaceBefore: boolean; + comment: string; + hasNewline: boolean; + anchor: SourceToken | null; + tag: SourceToken | null; + newlineAfterProp: SourceToken | null; + end: number; + start: number; +}; diff --git a/node_modules/yaml/dist/compose/resolve-props.js b/node_modules/yaml/dist/compose/resolve-props.js new file mode 100644 index 000000000..a3598c892 --- /dev/null +++ b/node_modules/yaml/dist/compose/resolve-props.js @@ -0,0 +1,148 @@ +'use strict'; + +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ''; + let commentSep = ''; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== 'space' && + token.type !== 'newline' && + token.type !== 'comma') + onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space'); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== 'comment' && token.type !== 'newline') { + onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation'); + } + tab = null; + } + switch (token.type) { + case 'space': + // At the doc level, tabs at line start may be parsed + // as leading white space rather than indentation. + // In a flow collection, only the parser handles indent. + if (!flow && + (indicator !== 'doc-start' || next?.type !== 'flow-collection') && + token.source.includes('\t')) { + tab = token; + } + hasSpace = true; + break; + case 'comment': { + if (!hasSpace) + onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters'); + const cb = token.source.substring(1) || ' '; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ''; + atNewline = false; + break; + } + case 'newline': + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== 'seq-item-ind') + spaceBefore = true; + } + else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case 'anchor': + if (anchor) + onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor'); + if (token.source.endsWith(':')) + onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case 'tag': { + if (tag) + onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag'); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + // Could here handle preceding comments differently + if (anchor || tag) + onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`); + found = token; + atNewline = + indicator === 'seq-item-ind' || indicator === 'explicit-key-ind'; + hasSpace = false; + break; + case 'comma': + if (flow) { + if (comma) + onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && + next && + next.type !== 'space' && + next.type !== 'newline' && + next.type !== 'comma' && + (next.type !== 'scalar' || next.source !== '')) { + onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space'); + } + if (tab && + ((atNewline && tab.indent <= parentIndent) || + next?.type === 'block-map' || + next?.type === 'block-seq')) + onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation'); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +exports.resolveProps = resolveProps; diff --git a/node_modules/yaml/dist/compose/util-contains-newline.d.ts b/node_modules/yaml/dist/compose/util-contains-newline.d.ts new file mode 100644 index 000000000..ca3df4846 --- /dev/null +++ b/node_modules/yaml/dist/compose/util-contains-newline.d.ts @@ -0,0 +1,2 @@ +import type { Token } from '../parse/cst'; +export declare function containsNewline(key: Token | null | undefined): boolean | null; diff --git a/node_modules/yaml/dist/compose/util-contains-newline.js b/node_modules/yaml/dist/compose/util-contains-newline.js new file mode 100644 index 000000000..e7aa82d87 --- /dev/null +++ b/node_modules/yaml/dist/compose/util-contains-newline.js @@ -0,0 +1,36 @@ +'use strict'; + +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case 'alias': + case 'scalar': + case 'double-quoted-scalar': + case 'single-quoted-scalar': + if (key.source.includes('\n')) + return true; + if (key.end) + for (const st of key.end) + if (st.type === 'newline') + return true; + return false; + case 'flow-collection': + for (const it of key.items) { + for (const st of it.start) + if (st.type === 'newline') + return true; + if (it.sep) + for (const st of it.sep) + if (st.type === 'newline') + return true; + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +exports.containsNewline = containsNewline; diff --git a/node_modules/yaml/dist/compose/util-empty-scalar-position.d.ts b/node_modules/yaml/dist/compose/util-empty-scalar-position.d.ts new file mode 100644 index 000000000..a555fe382 --- /dev/null +++ b/node_modules/yaml/dist/compose/util-empty-scalar-position.d.ts @@ -0,0 +1,2 @@ +import type { Token } from '../parse/cst'; +export declare function emptyScalarPosition(offset: number, before: Token[] | undefined, pos: number | null): number; diff --git a/node_modules/yaml/dist/compose/util-empty-scalar-position.js b/node_modules/yaml/dist/compose/util-empty-scalar-position.js new file mode 100644 index 000000000..50fedb179 --- /dev/null +++ b/node_modules/yaml/dist/compose/util-empty-scalar-position.js @@ -0,0 +1,28 @@ +'use strict'; + +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case 'space': + case 'comment': + case 'newline': + offset -= st.source.length; + continue; + } + // Technically, an empty scalar is immediately after the last non-empty + // node, but it's more useful to place it after any whitespace. + st = before[++i]; + while (st?.type === 'space') { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +exports.emptyScalarPosition = emptyScalarPosition; diff --git a/node_modules/yaml/dist/compose/util-flow-indent-check.d.ts b/node_modules/yaml/dist/compose/util-flow-indent-check.d.ts new file mode 100644 index 000000000..7186397bc --- /dev/null +++ b/node_modules/yaml/dist/compose/util-flow-indent-check.d.ts @@ -0,0 +1,3 @@ +import type { Token } from '../parse/cst'; +import type { ComposeErrorHandler } from './composer'; +export declare function flowIndentCheck(indent: number, fc: Token | null | undefined, onError: ComposeErrorHandler): void; diff --git a/node_modules/yaml/dist/compose/util-flow-indent-check.js b/node_modules/yaml/dist/compose/util-flow-indent-check.js new file mode 100644 index 000000000..1e6b06f8e --- /dev/null +++ b/node_modules/yaml/dist/compose/util-flow-indent-check.js @@ -0,0 +1,17 @@ +'use strict'; + +var utilContainsNewline = require('./util-contains-newline.js'); + +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === 'flow-collection') { + const end = fc.end[0]; + if (end.indent === indent && + (end.source === ']' || end.source === '}') && + utilContainsNewline.containsNewline(fc)) { + const msg = 'Flow end indicator should be more indented than parent'; + onError(end, 'BAD_INDENT', msg, true); + } + } +} + +exports.flowIndentCheck = flowIndentCheck; diff --git a/node_modules/yaml/dist/compose/util-map-includes.d.ts b/node_modules/yaml/dist/compose/util-map-includes.d.ts new file mode 100644 index 000000000..838b6bc7d --- /dev/null +++ b/node_modules/yaml/dist/compose/util-map-includes.d.ts @@ -0,0 +1,4 @@ +import type { ParsedNode } from '../nodes/Node'; +import type { Pair } from '../nodes/Pair'; +import type { ComposeContext } from './compose-node'; +export declare function mapIncludes(ctx: ComposeContext, items: Pair[], search: ParsedNode): boolean; diff --git a/node_modules/yaml/dist/compose/util-map-includes.js b/node_modules/yaml/dist/compose/util-map-includes.js new file mode 100644 index 000000000..ebd7a2daa --- /dev/null +++ b/node_modules/yaml/dist/compose/util-map-includes.js @@ -0,0 +1,15 @@ +'use strict'; + +var identity = require('../nodes/identity.js'); + +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === 'function' + ? uniqueKeys + : (a, b) => a === b || (identity.isScalar(a) && identity.isScalar(b) && a.value === b.value); + return items.some(pair => isEqual(pair.key, search)); +} + +exports.mapIncludes = mapIncludes; diff --git a/node_modules/yaml/dist/doc/Document.d.ts b/node_modules/yaml/dist/doc/Document.d.ts new file mode 100644 index 000000000..7cfd686a4 --- /dev/null +++ b/node_modules/yaml/dist/doc/Document.d.ts @@ -0,0 +1,141 @@ +import type { YAMLError, YAMLWarning } from '../errors'; +import { Alias } from '../nodes/Alias'; +import { NODE_TYPE } from '../nodes/identity'; +import type { Node, NodeType, ParsedNode, Range } from '../nodes/Node'; +import { Pair } from '../nodes/Pair'; +import type { Scalar } from '../nodes/Scalar'; +import type { YAMLMap } from '../nodes/YAMLMap'; +import type { YAMLSeq } from '../nodes/YAMLSeq'; +import type { CreateNodeOptions, DocumentOptions, ParseOptions, SchemaOptions, ToJSOptions, ToStringOptions } from '../options'; +import { Schema } from '../schema/Schema'; +import { Directives } from './directives'; +export type Replacer = any[] | ((key: any, value: any) => unknown); +export declare namespace Document { + /** @ts-ignore The typing of directives fails in TS <= 4.2 */ + interface Parsed extends Document { + directives: Directives; + range: Range; + } +} +export declare class Document { + readonly [NODE_TYPE]: symbol; + /** A comment before this Document */ + commentBefore: string | null; + /** A comment immediately after this Document */ + comment: string | null; + /** The document contents. */ + contents: Strict extends true ? Contents | null : Contents; + directives: Strict extends true ? Directives | undefined : Directives; + /** Errors encountered during parsing. */ + errors: YAMLError[]; + options: Required>; + /** + * The `[start, value-end, node-end]` character offsets for the part of the + * source parsed into this document (undefined if not parsed). The `value-end` + * and `node-end` positions are themselves not included in their respective + * ranges. + */ + range?: Range; + /** The schema used with the document. Use `setSchema()` to change. */ + schema: Schema; + /** Warnings encountered during parsing. */ + warnings: YAMLWarning[]; + /** + * @param value - The initial value for the document, which will be wrapped + * in a Node container. + */ + constructor(value?: any, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions); + constructor(value: any, replacer: null | Replacer, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions); + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone(): Document; + /** Adds a value to the document. */ + add(value: any): void; + /** Adds a value to the document. */ + addIn(path: Iterable, value: unknown): void; + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node: Strict extends true ? Scalar | YAMLMap | YAMLSeq : Node, name?: string): Alias; + /** + * Convert any value into a `Node` using the current schema, recursively + * turning objects into collections. + */ + createNode(value: T, options?: CreateNodeOptions): NodeType; + createNode(value: T, replacer: Replacer | CreateNodeOptions | null, options?: CreateNodeOptions): NodeType; + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key: unknown, value: unknown, options?: CreateNodeOptions): Pair; + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key: unknown): boolean; + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path: Iterable | null): boolean; + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key: unknown, keepScalar?: boolean): Strict extends true ? unknown : any; + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path: Iterable | null, keepScalar?: boolean): Strict extends true ? unknown : any; + /** + * Checks if the document includes a value with the key `key`. + */ + has(key: unknown): boolean; + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path: Iterable | null): boolean; + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key: any, value: unknown): void; + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path: Iterable | null, value: unknown): void; + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version: '1.1' | '1.2' | 'next' | null, options?: SchemaOptions): void; + /** A plain JavaScript representation of the document `contents`. */ + toJS(opt?: ToJSOptions & { + [ignored: string]: unknown; + }): any; + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions['onAnchor']): any; + /** A YAML representation of the document. */ + toString(options?: ToStringOptions): string; +} diff --git a/node_modules/yaml/dist/doc/Document.js b/node_modules/yaml/dist/doc/Document.js new file mode 100644 index 000000000..a95308835 --- /dev/null +++ b/node_modules/yaml/dist/doc/Document.js @@ -0,0 +1,337 @@ +'use strict'; + +var Alias = require('../nodes/Alias.js'); +var Collection = require('../nodes/Collection.js'); +var identity = require('../nodes/identity.js'); +var Pair = require('../nodes/Pair.js'); +var toJS = require('../nodes/toJS.js'); +var Schema = require('../schema/Schema.js'); +var stringifyDocument = require('../stringify/stringifyDocument.js'); +var anchors = require('./anchors.js'); +var applyReviver = require('./applyReviver.js'); +var createNode = require('./createNode.js'); +var directives = require('./directives.js'); + +class Document { + constructor(value, replacer, options) { + /** A comment before this Document */ + this.commentBefore = null; + /** A comment immediately after this Document */ + this.comment = null; + /** Errors encountered during parsing. */ + this.errors = []; + /** Warnings encountered during parsing. */ + this.warnings = []; + Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC }); + let _replacer = null; + if (typeof replacer === 'function' || Array.isArray(replacer)) { + _replacer = replacer; + } + else if (options === undefined && replacer) { + options = replacer; + replacer = undefined; + } + const opt = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: 'warn', + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: '1.2' + }, options); + this.options = opt; + let { version } = opt; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } + else + this.directives = new directives.Directives({ version }); + this.setSchema(version, options); + // @ts-expect-error We can't really know that this matches Contents. + this.contents = + value === undefined ? null : this.createNode(value, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy = Object.create(Document.prototype, { + [identity.NODE_TYPE]: { value: identity.DOC } + }); + copy.commentBefore = this.commentBefore; + copy.comment = this.comment; + copy.errors = this.errors.slice(); + copy.warnings = this.warnings.slice(); + copy.options = Object.assign({}, this.options); + if (this.directives) + copy.directives = this.directives.clone(); + copy.schema = this.schema.clone(); + // @ts-expect-error We can't really know that this matches Contents. + copy.contents = identity.isNode(this.contents) + ? this.contents.clone(copy.schema) + : this.contents; + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** Adds a value to the document. */ + add(value) { + if (assertCollection(this.contents)) + this.contents.add(value); + } + /** Adds a value to the document. */ + addIn(path, value) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchors.anchorNames(this); + node.anchor = + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? anchors.findNewAnchor(name || 'a', prev) : name; + } + return new Alias.Alias(node.anchor); + } + createNode(value, replacer, options) { + let _replacer = undefined; + if (typeof replacer === 'function') { + value = replacer.call({ '': value }, '', value); + _replacer = replacer; + } + else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } + else if (options === undefined && replacer) { + options = replacer; + replacer = undefined; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || 'a'); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode.createNode(value, tag, ctx); + if (flow && identity.isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value, null, options); + return new Pair.Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (Collection.isEmptyPath(path)) { + if (this.contents == null) + return false; + // @ts-expect-error Presumed impossible if Strict extends false + this.contents = null; + return true; + } + return assertCollection(this.contents) + ? this.contents.deleteIn(path) + : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return identity.isCollection(this.contents) + ? this.contents.get(key, keepScalar) + : undefined; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (Collection.isEmptyPath(path)) + return !keepScalar && identity.isScalar(this.contents) + ? this.contents.value + : this.contents; + return identity.isCollection(this.contents) + ? this.contents.getIn(path, keepScalar) + : undefined; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return identity.isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (Collection.isEmptyPath(path)) + return this.contents !== undefined; + return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value) { + if (this.contents == null) { + // @ts-expect-error We can't really know that this matches Contents. + this.contents = Collection.collectionFromPath(this.schema, [key], value); + } + else if (assertCollection(this.contents)) { + this.contents.set(key, value); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + if (Collection.isEmptyPath(path)) { + // @ts-expect-error We can't really know that this matches Contents. + this.contents = value; + } + else if (this.contents == null) { + // @ts-expect-error We can't really know that this matches Contents. + this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value); + } + else if (assertCollection(this.contents)) { + this.contents.setIn(path, value); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === 'number') + version = String(version); + let opt; + switch (version) { + case '1.1': + if (this.directives) + this.directives.yaml.version = '1.1'; + else + this.directives = new directives.Directives({ version: '1.1' }); + opt = { resolveKnownTags: false, schema: 'yaml-1.1' }; + break; + case '1.2': + case 'next': + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new directives.Directives({ version }); + opt = { resolveKnownTags: true, schema: 'core' }; + break; + case null: + if (this.directives) + delete this.directives; + opt = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + // Not using `instanceof Schema` to allow for duck typing + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt) + this.schema = new Schema.Schema(Object.assign(opt, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100 + }; + const res = toJS.toJS(this.contents, jsonArg ?? '', ctx); + if (typeof onAnchor === 'function') + for (const { count, res } of ctx.anchors.values()) + onAnchor(res, count); + return typeof reviver === 'function' + ? applyReviver.applyReviver(reviver, { '': res }, '', res) + : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error('Document with errors cannot be stringified'); + if ('indent' in options && + (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument.stringifyDocument(this, options); + } +} +function assertCollection(contents) { + if (identity.isCollection(contents)) + return true; + throw new Error('Expected a YAML collection as document contents'); +} + +exports.Document = Document; diff --git a/node_modules/yaml/dist/doc/anchors.d.ts b/node_modules/yaml/dist/doc/anchors.d.ts new file mode 100644 index 000000000..feea5e4bc --- /dev/null +++ b/node_modules/yaml/dist/doc/anchors.d.ts @@ -0,0 +1,24 @@ +import type { Node } from '../nodes/Node'; +import type { Document } from './Document'; +/** + * Verify that the input string is a valid anchor. + * + * Will throw on errors. + */ +export declare function anchorIsValid(anchor: string): true; +export declare function anchorNames(root: Document | Node): Set; +/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */ +export declare function findNewAnchor(prefix: string, exclude: Set): string; +export declare function createNodeAnchors(doc: Document, prefix: string): { + onAnchor: (source: unknown) => string; + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => void; + sourceObjects: Map; +}; diff --git a/node_modules/yaml/dist/doc/anchors.js b/node_modules/yaml/dist/doc/anchors.js new file mode 100644 index 000000000..68613fa72 --- /dev/null +++ b/node_modules/yaml/dist/doc/anchors.js @@ -0,0 +1,76 @@ +'use strict'; + +var identity = require('../nodes/identity.js'); +var visit = require('../visit.js'); + +/** + * Verify that the input string is a valid anchor. + * + * Will throw on errors. + */ +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root) { + const anchors = new Set(); + visit.visit(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */ +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === 'object' && + ref.anchor && + (identity.isScalar(ref.node) || identity.isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } + else { + const error = new Error('Failed to resolve repeated object (this should not happen)'); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +exports.anchorIsValid = anchorIsValid; +exports.anchorNames = anchorNames; +exports.createNodeAnchors = createNodeAnchors; +exports.findNewAnchor = findNewAnchor; diff --git a/node_modules/yaml/dist/doc/applyReviver.d.ts b/node_modules/yaml/dist/doc/applyReviver.d.ts new file mode 100644 index 000000000..e125b0870 --- /dev/null +++ b/node_modules/yaml/dist/doc/applyReviver.d.ts @@ -0,0 +1,9 @@ +export type Reviver = (key: unknown, value: unknown) => unknown; +/** + * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec, + * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the + * 2021 edition: https://tc39.es/ecma262/#sec-json.parse + * + * Includes extensions for handling Map and Set objects. + */ +export declare function applyReviver(reviver: Reviver, obj: unknown, key: unknown, val: any): unknown; diff --git a/node_modules/yaml/dist/doc/applyReviver.js b/node_modules/yaml/dist/doc/applyReviver.js new file mode 100644 index 000000000..bfd0ba860 --- /dev/null +++ b/node_modules/yaml/dist/doc/applyReviver.js @@ -0,0 +1,57 @@ +'use strict'; + +/** + * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec, + * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the + * 2021 edition: https://tc39.es/ecma262/#sec-json.parse + * + * Includes extensions for handling Map and Set objects. + */ +function applyReviver(reviver, obj, key, val) { + if (val && typeof val === 'object') { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + // eslint-disable-next-line @typescript-eslint/no-array-delete + if (v1 === undefined) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } + else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === undefined) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } + else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === undefined) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } + else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === undefined) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj, key, val); +} + +exports.applyReviver = applyReviver; diff --git a/node_modules/yaml/dist/doc/createNode.d.ts b/node_modules/yaml/dist/doc/createNode.d.ts new file mode 100644 index 000000000..1488ff6e7 --- /dev/null +++ b/node_modules/yaml/dist/doc/createNode.d.ts @@ -0,0 +1,17 @@ +import type { Node } from '../nodes/Node'; +import type { Schema } from '../schema/Schema'; +import type { CollectionTag, ScalarTag } from '../schema/types'; +import type { Replacer } from './Document'; +export interface CreateNodeContext { + aliasDuplicateObjects: boolean; + keepUndefined: boolean; + onAnchor: (source: unknown) => string; + onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; + sourceObjects: Map; + replacer?: Replacer; + schema: Schema; +} +export declare function createNode(value: unknown, tagName: string | undefined, ctx: CreateNodeContext): Node; diff --git a/node_modules/yaml/dist/doc/createNode.js b/node_modules/yaml/dist/doc/createNode.js new file mode 100644 index 000000000..53522c6b1 --- /dev/null +++ b/node_modules/yaml/dist/doc/createNode.js @@ -0,0 +1,90 @@ +'use strict'; + +var Alias = require('../nodes/Alias.js'); +var identity = require('../nodes/identity.js'); +var Scalar = require('../nodes/Scalar.js'); + +const defaultTagPrefix = 'tag:yaml.org,2002:'; +function findTagObject(value, tagName, tags) { + if (tagName) { + const match = tags.filter(t => t.tag === tagName); + const tagObj = match.find(t => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find(t => t.identify?.(value) && !t.format); +} +function createNode(value, tagName, ctx) { + if (identity.isDocument(value)) + value = value.contents; + if (identity.isNode(value)) + return value; + if (identity.isPair(value)) { + const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx); + map.items.push(value); + return map; + } + if (value instanceof String || + value instanceof Number || + value instanceof Boolean || + (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere + ) { + // https://tc39.es/ecma262/#sec-serializejsonproperty + value = value.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx; + // Detect duplicate references to the same object & use Alias nodes for all + // after first. The `ref` wrapper allows for circular references to resolve. + let ref = undefined; + if (aliasDuplicateObjects && value && typeof value === 'object') { + ref = sourceObjects.get(value); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value)); + return new Alias.Alias(ref.anchor); + } + else { + ref = { anchor: null, node: null }; + sourceObjects.set(value, ref); + } + } + if (tagName?.startsWith('!!')) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema.tags); + if (!tagObj) { + if (value && typeof value.toJSON === 'function') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + value = value.toJSON(); + } + if (!value || typeof value !== 'object') { + const node = new Scalar.Scalar(value); + if (ref) + ref.node = node; + return node; + } + tagObj = + value instanceof Map + ? schema[identity.MAP] + : Symbol.iterator in Object(value) + ? schema[identity.SEQ] + : schema[identity.MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode + ? tagObj.createNode(ctx.schema, value, ctx) + : typeof tagObj?.nodeClass?.from === 'function' + ? tagObj.nodeClass.from(ctx.schema, value, ctx) + : new Scalar.Scalar(value); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +exports.createNode = createNode; diff --git a/node_modules/yaml/dist/doc/directives.d.ts b/node_modules/yaml/dist/doc/directives.d.ts new file mode 100644 index 000000000..ead29113b --- /dev/null +++ b/node_modules/yaml/dist/doc/directives.d.ts @@ -0,0 +1,49 @@ +import type { Document } from './Document'; +export declare class Directives { + static defaultYaml: Directives['yaml']; + static defaultTags: Directives['tags']; + yaml: { + version: '1.1' | '1.2' | 'next'; + explicit?: boolean; + }; + tags: Record; + /** + * The directives-end/doc-start marker `---`. If `null`, a marker may still be + * included in the document's stringified representation. + */ + docStart: true | null; + /** The doc-end marker `...`. */ + docEnd: boolean; + /** + * Used when parsing YAML 1.1, where: + * > If the document specifies no directives, it is parsed using the same + * > settings as the previous document. If the document does specify any + * > directives, all directives of previous documents, if any, are ignored. + */ + private atNextDocument?; + constructor(yaml?: Directives['yaml'], tags?: Directives['tags']); + clone(): Directives; + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument(): Directives; + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line: string, onError: (offset: number, message: string, warning?: boolean) => void): boolean; + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source: string, onError: (message: string) => void): string | null; + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag: string): string; + toString(doc?: Document): string; +} diff --git a/node_modules/yaml/dist/doc/directives.js b/node_modules/yaml/dist/doc/directives.js new file mode 100644 index 000000000..e13b10e3c --- /dev/null +++ b/node_modules/yaml/dist/doc/directives.js @@ -0,0 +1,178 @@ +'use strict'; + +var identity = require('../nodes/identity.js'); +var visit = require('../visit.js'); + +const escapeChars = { + '!': '%21', + ',': '%2C', + '[': '%5B', + ']': '%5D', + '{': '%7B', + '}': '%7D' +}; +const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, ch => escapeChars[ch]); +class Directives { + constructor(yaml, tags) { + /** + * The directives-end/doc-start marker `---`. If `null`, a marker may still be + * included in the document's stringified representation. + */ + this.docStart = null; + /** The doc-end marker `...`. */ + this.docEnd = false; + this.yaml = Object.assign({}, Directives.defaultYaml, yaml); + this.tags = Object.assign({}, Directives.defaultTags, tags); + } + clone() { + const copy = new Directives(this.yaml, this.tags); + copy.docStart = this.docStart; + return copy; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case '1.1': + this.atNextDocument = true; + break; + case '1.2': + this.atNextDocument = false; + this.yaml = { + explicit: Directives.defaultYaml.explicit, + version: '1.2' + }; + this.tags = Object.assign({}, Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' }; + this.tags = Object.assign({}, Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case '%TAG': { + if (parts.length !== 2) { + onError(0, '%TAG directive should contain exactly two parts'); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case '%YAML': { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, '%YAML directive should contain exactly one part'); + return false; + } + const [version] = parts; + if (version === '1.1' || version === '1.2') { + this.yaml.version = version; + return true; + } + else { + const isValid = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === '!') + return '!'; // non-specific tag + if (source[0] !== '!') { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === '<') { + const verbatim = source.slice(2, -1); + if (verbatim === '!' || verbatim === '!!') { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== '>') + onError('Verbatim tags must end with a >'); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } + catch (error) { + onError(String(error)); + return null; + } + } + if (handle === '!') + return source; // local tag + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === '!' ? tag : `!<${tag}>`; + } + toString(doc) { + const lines = this.yaml.explicit + ? [`%YAML ${this.yaml.version || '1.2'}`] + : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) { + const tags = {}; + visit.visit(doc.contents, (_key, node) => { + if (identity.isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } + else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === '!!' && prefix === 'tag:yaml.org,2002:') + continue; + if (!doc || tagNames.some(tn => tn.startsWith(prefix))) + lines.push(`%TAG ${handle} ${prefix}`); + } + return lines.join('\n'); + } +} +Directives.defaultYaml = { explicit: false, version: '1.2' }; +Directives.defaultTags = { '!!': 'tag:yaml.org,2002:' }; + +exports.Directives = Directives; diff --git a/node_modules/yaml/dist/errors.d.ts b/node_modules/yaml/dist/errors.d.ts new file mode 100644 index 000000000..e5ee857ba --- /dev/null +++ b/node_modules/yaml/dist/errors.d.ts @@ -0,0 +1,21 @@ +import type { LineCounter } from './parse/line-counter'; +export type ErrorCode = 'ALIAS_PROPS' | 'BAD_ALIAS' | 'BAD_DIRECTIVE' | 'BAD_DQ_ESCAPE' | 'BAD_INDENT' | 'BAD_PROP_ORDER' | 'BAD_SCALAR_START' | 'BLOCK_AS_IMPLICIT_KEY' | 'BLOCK_IN_FLOW' | 'DUPLICATE_KEY' | 'IMPOSSIBLE' | 'KEY_OVER_1024_CHARS' | 'MISSING_CHAR' | 'MULTILINE_IMPLICIT_KEY' | 'MULTIPLE_ANCHORS' | 'MULTIPLE_DOCS' | 'MULTIPLE_TAGS' | 'NON_STRING_KEY' | 'TAB_AS_INDENT' | 'TAG_RESOLVE_FAILED' | 'UNEXPECTED_TOKEN' | 'BAD_COLLECTION_TYPE'; +export type LinePos = { + line: number; + col: number; +}; +export declare class YAMLError extends Error { + name: 'YAMLParseError' | 'YAMLWarning'; + code: ErrorCode; + message: string; + pos: [number, number]; + linePos?: [LinePos] | [LinePos, LinePos]; + constructor(name: YAMLError['name'], pos: [number, number], code: ErrorCode, message: string); +} +export declare class YAMLParseError extends YAMLError { + constructor(pos: [number, number], code: ErrorCode, message: string); +} +export declare class YAMLWarning extends YAMLError { + constructor(pos: [number, number], code: ErrorCode, message: string); +} +export declare const prettifyError: (src: string, lc: LineCounter) => (error: YAMLError) => void; diff --git a/node_modules/yaml/dist/errors.js b/node_modules/yaml/dist/errors.js new file mode 100644 index 000000000..358c7ed48 --- /dev/null +++ b/node_modules/yaml/dist/errors.js @@ -0,0 +1,62 @@ +'use strict'; + +class YAMLError extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +} +class YAMLParseError extends YAMLError { + constructor(pos, code, message) { + super('YAMLParseError', pos, code, message); + } +} +class YAMLWarning extends YAMLError { + constructor(pos, code, message) { + super('YAMLWarning', pos, code, message); + } +} +const prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map(pos => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src + .substring(lc.lineStarts[line - 1], lc.lineStarts[line]) + .replace(/[\n\r]+$/, ''); + // Trim to max 80 chars, keeping col position near the middle + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = '…' + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + '…'; + // Include previous line in context if pointing at line start + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + // Regexp won't match if start is trimmed + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + '…\n'; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer = ' '.repeat(ci) + '^'.repeat(count); + error.message += `:\n\n${lineStr}\n${pointer}\n`; + } +}; + +exports.YAMLError = YAMLError; +exports.YAMLParseError = YAMLParseError; +exports.YAMLWarning = YAMLWarning; +exports.prettifyError = prettifyError; diff --git a/node_modules/yaml/dist/index.d.ts b/node_modules/yaml/dist/index.d.ts new file mode 100644 index 000000000..075c612b7 --- /dev/null +++ b/node_modules/yaml/dist/index.d.ts @@ -0,0 +1,25 @@ +export { Composer } from './compose/composer'; +export { Document } from './doc/Document'; +export { Schema } from './schema/Schema'; +export type { ErrorCode } from './errors'; +export { YAMLError, YAMLParseError, YAMLWarning } from './errors'; +export { Alias } from './nodes/Alias'; +export { isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq } from './nodes/identity'; +export type { Node, ParsedNode, Range } from './nodes/Node'; +export { Pair } from './nodes/Pair'; +export { Scalar } from './nodes/Scalar'; +export { YAMLMap } from './nodes/YAMLMap'; +export { YAMLSeq } from './nodes/YAMLSeq'; +export type { CreateNodeOptions, DocumentOptions, ParseOptions, SchemaOptions, ToJSOptions, ToStringOptions } from './options'; +export * as CST from './parse/cst'; +export { Lexer } from './parse/lexer'; +export { LineCounter } from './parse/line-counter'; +export { Parser } from './parse/parser'; +export type { EmptyStream } from './public-api'; +export { parse, parseAllDocuments, parseDocument, stringify } from './public-api'; +export type { TagId, Tags } from './schema/tags'; +export type { CollectionTag, ScalarTag } from './schema/types'; +export type { YAMLOMap } from './schema/yaml-1.1/omap'; +export type { YAMLSet } from './schema/yaml-1.1/set'; +export type { asyncVisitor, asyncVisitorFn, visitor, visitorFn } from './visit'; +export { visit, visitAsync } from './visit'; diff --git a/node_modules/yaml/dist/index.js b/node_modules/yaml/dist/index.js new file mode 100644 index 000000000..18c0cb612 --- /dev/null +++ b/node_modules/yaml/dist/index.js @@ -0,0 +1,50 @@ +'use strict'; + +var composer = require('./compose/composer.js'); +var Document = require('./doc/Document.js'); +var Schema = require('./schema/Schema.js'); +var errors = require('./errors.js'); +var Alias = require('./nodes/Alias.js'); +var identity = require('./nodes/identity.js'); +var Pair = require('./nodes/Pair.js'); +var Scalar = require('./nodes/Scalar.js'); +var YAMLMap = require('./nodes/YAMLMap.js'); +var YAMLSeq = require('./nodes/YAMLSeq.js'); +var cst = require('./parse/cst.js'); +var lexer = require('./parse/lexer.js'); +var lineCounter = require('./parse/line-counter.js'); +var parser = require('./parse/parser.js'); +var publicApi = require('./public-api.js'); +var visit = require('./visit.js'); + + + +exports.Composer = composer.Composer; +exports.Document = Document.Document; +exports.Schema = Schema.Schema; +exports.YAMLError = errors.YAMLError; +exports.YAMLParseError = errors.YAMLParseError; +exports.YAMLWarning = errors.YAMLWarning; +exports.Alias = Alias.Alias; +exports.isAlias = identity.isAlias; +exports.isCollection = identity.isCollection; +exports.isDocument = identity.isDocument; +exports.isMap = identity.isMap; +exports.isNode = identity.isNode; +exports.isPair = identity.isPair; +exports.isScalar = identity.isScalar; +exports.isSeq = identity.isSeq; +exports.Pair = Pair.Pair; +exports.Scalar = Scalar.Scalar; +exports.YAMLMap = YAMLMap.YAMLMap; +exports.YAMLSeq = YAMLSeq.YAMLSeq; +exports.CST = cst; +exports.Lexer = lexer.Lexer; +exports.LineCounter = lineCounter.LineCounter; +exports.Parser = parser.Parser; +exports.parse = publicApi.parse; +exports.parseAllDocuments = publicApi.parseAllDocuments; +exports.parseDocument = publicApi.parseDocument; +exports.stringify = publicApi.stringify; +exports.visit = visit.visit; +exports.visitAsync = visit.visitAsync; diff --git a/node_modules/yaml/dist/log.d.ts b/node_modules/yaml/dist/log.d.ts new file mode 100644 index 000000000..5e216121a --- /dev/null +++ b/node_modules/yaml/dist/log.d.ts @@ -0,0 +1,3 @@ +export type LogLevelId = 'silent' | 'error' | 'warn' | 'debug'; +export declare function debug(logLevel: LogLevelId, ...messages: any[]): void; +export declare function warn(logLevel: LogLevelId, warning: string | Error): void; diff --git a/node_modules/yaml/dist/log.js b/node_modules/yaml/dist/log.js new file mode 100644 index 000000000..65f99508f --- /dev/null +++ b/node_modules/yaml/dist/log.js @@ -0,0 +1,19 @@ +'use strict'; + +var node_process = require('process'); + +function debug(logLevel, ...messages) { + if (logLevel === 'debug') + console.log(...messages); +} +function warn(logLevel, warning) { + if (logLevel === 'debug' || logLevel === 'warn') { + if (typeof node_process.emitWarning === 'function') + node_process.emitWarning(warning); + else + console.warn(warning); + } +} + +exports.debug = debug; +exports.warn = warn; diff --git a/node_modules/yaml/dist/nodes/Alias.d.ts b/node_modules/yaml/dist/nodes/Alias.d.ts new file mode 100644 index 000000000..c48f40e45 --- /dev/null +++ b/node_modules/yaml/dist/nodes/Alias.d.ts @@ -0,0 +1,29 @@ +import type { Document } from '../doc/Document'; +import type { FlowScalar } from '../parse/cst'; +import type { StringifyContext } from '../stringify/stringify'; +import type { Range } from './Node'; +import { NodeBase } from './Node'; +import type { Scalar } from './Scalar'; +import type { ToJSContext } from './toJS'; +import type { YAMLMap } from './YAMLMap'; +import type { YAMLSeq } from './YAMLSeq'; +export declare namespace Alias { + interface Parsed extends Alias { + range: Range; + srcToken?: FlowScalar & { + type: 'alias'; + }; + } +} +export declare class Alias extends NodeBase { + source: string; + anchor?: never; + constructor(source: string); + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc: Document, ctx?: ToJSContext): Scalar | YAMLMap | YAMLSeq | undefined; + toJSON(_arg?: unknown, ctx?: ToJSContext): unknown; + toString(ctx?: StringifyContext, _onComment?: () => void, _onChompKeep?: () => void): string; +} diff --git a/node_modules/yaml/dist/nodes/Alias.js b/node_modules/yaml/dist/nodes/Alias.js new file mode 100644 index 000000000..e0c57a519 --- /dev/null +++ b/node_modules/yaml/dist/nodes/Alias.js @@ -0,0 +1,116 @@ +'use strict'; + +var anchors = require('../doc/anchors.js'); +var visit = require('../visit.js'); +var identity = require('./identity.js'); +var Node = require('./Node.js'); +var toJS = require('./toJS.js'); + +class Alias extends Node.NodeBase { + constructor(source) { + super(identity.ALIAS); + this.source = source; + Object.defineProperty(this, 'tag', { + set() { + throw new Error('Alias nodes cannot have tags'); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } + else { + nodes = []; + visit.visit(doc, { + Node: (_key, node) => { + if (identity.isAlias(node) || identity.hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = undefined; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const { anchors, doc, maxAliasCount } = ctx; + const source = this.resolve(doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + let data = anchors.get(source); + if (!data) { + // Resolve anchors for Node.prototype.toJS() + toJS.toJS(source, null, ctx); + data = anchors.get(source); + } + /* istanbul ignore if */ + if (data?.res === undefined) { + const msg = 'This should not happen: Alias anchor was not resolved?'; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc, source, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = 'Excessive alias count indicates a resource exhaustion attack'; + throw new ReferenceError(msg); + } + } + return data.res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchors.anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +} +function getAliasCount(doc, node, anchors) { + if (identity.isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } + else if (identity.isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } + else if (identity.isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +exports.Alias = Alias; diff --git a/node_modules/yaml/dist/nodes/Collection.d.ts b/node_modules/yaml/dist/nodes/Collection.d.ts new file mode 100644 index 000000000..ffbacfcc4 --- /dev/null +++ b/node_modules/yaml/dist/nodes/Collection.d.ts @@ -0,0 +1,73 @@ +import type { Schema } from '../schema/Schema'; +import { NODE_TYPE } from './identity'; +import { NodeBase } from './Node'; +export declare function collectionFromPath(schema: Schema, path: unknown[], value: unknown): import('./Node').Node; +export declare const isEmptyPath: (path: Iterable | null | undefined) => path is null | undefined; +export declare abstract class Collection extends NodeBase { + schema: Schema | undefined; + [NODE_TYPE]: symbol; + items: unknown[]; + /** An optional anchor on this node. Used by alias nodes. */ + anchor?: string; + /** + * If true, stringify this and all child nodes using flow rather than + * block styles. + */ + flow?: boolean; + constructor(type: symbol, schema?: Schema); + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema?: Schema): Collection; + /** Adds a value to the collection. */ + abstract add(value: unknown): void; + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + abstract delete(key: unknown): boolean; + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + abstract get(key: unknown, keepScalar?: boolean): unknown; + /** + * Checks if the collection includes a value with the key `key`. + */ + abstract has(key: unknown): boolean; + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + abstract set(key: unknown, value: unknown): void; + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path: Iterable, value: unknown): void; + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path: Iterable): boolean; + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path: Iterable, keepScalar?: boolean): unknown; + hasAllNullValues(allowScalar?: boolean): boolean; + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path: Iterable): boolean; + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path: Iterable, value: unknown): void; +} diff --git a/node_modules/yaml/dist/nodes/Collection.js b/node_modules/yaml/dist/nodes/Collection.js new file mode 100644 index 000000000..bdf8cb4fa --- /dev/null +++ b/node_modules/yaml/dist/nodes/Collection.js @@ -0,0 +1,151 @@ +'use strict'; + +var createNode = require('../doc/createNode.js'); +var identity = require('./identity.js'); +var Node = require('./Node.js'); + +function collectionFromPath(schema, path, value) { + let v = value; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === 'number' && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } + else { + v = new Map([[k, v]]); + } + } + return createNode.createNode(v, undefined, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error('This should not happen, please report a bug.'); + }, + schema, + sourceObjects: new Map() + }); +} +// Type guard is intentionally a little wrong so as to be more useful, +// as it does not cover untypable empty non-string iterables (e.g. []). +const isEmptyPath = (path) => path == null || + (typeof path === 'object' && !!path[Symbol.iterator]().next().done); +class Collection extends Node.NodeBase { + constructor(type, schema) { + super(type); + Object.defineProperty(this, 'schema', { + value: schema, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema) { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema) + copy.schema = schema; + copy.items = copy.items.map(it => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value) { + if (isEmptyPath(path)) + this.add(value); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (identity.isCollection(node)) + node.addIn(rest, value); + else if (node === undefined && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (identity.isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && identity.isScalar(node) ? node.value : node; + else + return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined; + } + hasAllNullValues(allowScalar) { + return this.items.every(node => { + if (!identity.isPair(node)) + return false; + const n = node.value; + return (n == null || + (allowScalar && + identity.isScalar(n) && + n.value == null && + !n.commentBefore && + !n.comment && + !n.tag)); + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return identity.isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value); + } + else { + const node = this.get(key, true); + if (identity.isCollection(node)) + node.setIn(rest, value); + else if (node === undefined && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +} + +exports.Collection = Collection; +exports.collectionFromPath = collectionFromPath; +exports.isEmptyPath = isEmptyPath; diff --git a/node_modules/yaml/dist/nodes/Node.d.ts b/node_modules/yaml/dist/nodes/Node.d.ts new file mode 100644 index 000000000..5fde1d879 --- /dev/null +++ b/node_modules/yaml/dist/nodes/Node.d.ts @@ -0,0 +1,53 @@ +import type { Document } from '../doc/Document'; +import type { ToJSOptions } from '../options'; +import type { Token } from '../parse/cst'; +import type { StringifyContext } from '../stringify/stringify'; +import type { Alias } from './Alias'; +import { NODE_TYPE } from './identity'; +import type { Scalar } from './Scalar'; +import type { ToJSContext } from './toJS'; +import type { MapLike, YAMLMap } from './YAMLMap'; +import type { YAMLSeq } from './YAMLSeq'; +export type Node = Alias | Scalar | YAMLMap | YAMLSeq; +/** Utility type mapper */ +export type NodeType = T extends string | number | bigint | boolean | null | undefined ? Scalar : T extends Date ? Scalar : T extends Array ? YAMLSeq> : T extends { + [key: string]: any; +} ? YAMLMap, NodeType> : T extends { + [key: number]: any; +} ? YAMLMap, NodeType> : Node; +export type ParsedNode = Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed; +/** `[start, value-end, node-end]` */ +export type Range = [number, number, number]; +export declare abstract class NodeBase { + readonly [NODE_TYPE]: symbol; + /** A comment on or immediately after this */ + comment?: string | null; + /** A comment before this */ + commentBefore?: string | null; + /** + * The `[start, value-end, node-end]` character offsets for the part of the + * source parsed into this node (undefined if not parsed). The `value-end` + * and `node-end` positions are themselves not included in their respective + * ranges. + */ + range?: Range | null; + /** A blank line before this node and its commentBefore */ + spaceBefore?: boolean; + /** The CST token that was composed into this node. */ + srcToken?: Token; + /** A fully qualified tag, if required */ + tag?: string; + /** + * Customize the way that a key-value pair is resolved. + * Used for YAML 1.1 !!merge << handling. + */ + addToJSMap?: (ctx: ToJSContext | undefined, map: MapLike, value: unknown) => void; + /** A plain JS representation of this node */ + abstract toJSON(): any; + abstract toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; + constructor(type: symbol); + /** Create a copy of this node. */ + clone(): NodeBase; + /** A plain JavaScript representation of this node. */ + toJS(doc: Document, { mapAsMap, maxAliasCount, onAnchor, reviver }?: ToJSOptions): any; +} diff --git a/node_modules/yaml/dist/nodes/Node.js b/node_modules/yaml/dist/nodes/Node.js new file mode 100644 index 000000000..d384e1cd0 --- /dev/null +++ b/node_modules/yaml/dist/nodes/Node.js @@ -0,0 +1,40 @@ +'use strict'; + +var applyReviver = require('../doc/applyReviver.js'); +var identity = require('./identity.js'); +var toJS = require('./toJS.js'); + +class NodeBase { + constructor(type) { + Object.defineProperty(this, identity.NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!identity.isDocument(doc)) + throw new TypeError('A document argument is required'); + const ctx = { + anchors: new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100 + }; + const res = toJS.toJS(this, '', ctx); + if (typeof onAnchor === 'function') + for (const { count, res } of ctx.anchors.values()) + onAnchor(res, count); + return typeof reviver === 'function' + ? applyReviver.applyReviver(reviver, { '': res }, '', res) + : res; + } +} + +exports.NodeBase = NodeBase; diff --git a/node_modules/yaml/dist/nodes/Pair.d.ts b/node_modules/yaml/dist/nodes/Pair.d.ts new file mode 100644 index 000000000..0fa082d71 --- /dev/null +++ b/node_modules/yaml/dist/nodes/Pair.d.ts @@ -0,0 +1,22 @@ +import type { CreateNodeContext } from '../doc/createNode'; +import type { CollectionItem } from '../parse/cst'; +import type { Schema } from '../schema/Schema'; +import type { StringifyContext } from '../stringify/stringify'; +import { addPairToJSMap } from './addPairToJSMap'; +import { NODE_TYPE } from './identity'; +import type { Node } from './Node'; +import type { ToJSContext } from './toJS'; +export declare function createPair(key: unknown, value: unknown, ctx: CreateNodeContext): Pair; +export declare class Pair { + readonly [NODE_TYPE]: symbol; + /** Always Node or null when parsed, but can be set to anything. */ + key: K; + /** Always Node or null when parsed, but can be set to anything. */ + value: V | null; + /** The CST token that was composed into this pair. */ + srcToken?: CollectionItem; + constructor(key: K, value?: V | null); + clone(schema?: Schema): Pair; + toJSON(_?: unknown, ctx?: ToJSContext): ReturnType; + toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; +} diff --git a/node_modules/yaml/dist/nodes/Pair.js b/node_modules/yaml/dist/nodes/Pair.js new file mode 100644 index 000000000..ae4c7727d --- /dev/null +++ b/node_modules/yaml/dist/nodes/Pair.js @@ -0,0 +1,39 @@ +'use strict'; + +var createNode = require('../doc/createNode.js'); +var stringifyPair = require('../stringify/stringifyPair.js'); +var addPairToJSMap = require('./addPairToJSMap.js'); +var identity = require('./identity.js'); + +function createPair(key, value, ctx) { + const k = createNode.createNode(key, undefined, ctx); + const v = createNode.createNode(value, undefined, ctx); + return new Pair(k, v); +} +class Pair { + constructor(key, value = null) { + Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR }); + this.key = key; + this.value = value; + } + clone(schema) { + let { key, value } = this; + if (identity.isNode(key)) + key = key.clone(schema); + if (identity.isNode(value)) + value = value.clone(schema); + return new Pair(key, value); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? new Map() : {}; + return addPairToJSMap.addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc + ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) + : JSON.stringify(this); + } +} + +exports.Pair = Pair; +exports.createPair = createPair; diff --git a/node_modules/yaml/dist/nodes/Scalar.d.ts b/node_modules/yaml/dist/nodes/Scalar.d.ts new file mode 100644 index 000000000..d3db56766 --- /dev/null +++ b/node_modules/yaml/dist/nodes/Scalar.d.ts @@ -0,0 +1,43 @@ +import type { BlockScalar, FlowScalar } from '../parse/cst'; +import type { Range } from './Node'; +import { NodeBase } from './Node'; +import type { ToJSContext } from './toJS'; +export declare const isScalarValue: (value: unknown) => boolean; +export declare namespace Scalar { + interface Parsed extends Scalar { + range: Range; + source: string; + srcToken?: FlowScalar | BlockScalar; + } + type BLOCK_FOLDED = 'BLOCK_FOLDED'; + type BLOCK_LITERAL = 'BLOCK_LITERAL'; + type PLAIN = 'PLAIN'; + type QUOTE_DOUBLE = 'QUOTE_DOUBLE'; + type QUOTE_SINGLE = 'QUOTE_SINGLE'; + type Type = BLOCK_FOLDED | BLOCK_LITERAL | PLAIN | QUOTE_DOUBLE | QUOTE_SINGLE; +} +export declare class Scalar extends NodeBase { + static readonly BLOCK_FOLDED = "BLOCK_FOLDED"; + static readonly BLOCK_LITERAL = "BLOCK_LITERAL"; + static readonly PLAIN = "PLAIN"; + static readonly QUOTE_DOUBLE = "QUOTE_DOUBLE"; + static readonly QUOTE_SINGLE = "QUOTE_SINGLE"; + value: T; + /** An optional anchor on this node. Used by alias nodes. */ + anchor?: string; + /** + * By default (undefined), numbers use decimal notation. + * The YAML 1.2 core schema only supports 'HEX' and 'OCT'. + * The YAML 1.1 schema also supports 'BIN' and 'TIME' + */ + format?: string; + /** If `value` is a number, use this value when stringifying this node. */ + minFractionDigits?: number; + /** Set during parsing to the source string value */ + source?: string; + /** The scalar style used for the node's string representation */ + type?: Scalar.Type; + constructor(value: T); + toJSON(arg?: any, ctx?: ToJSContext): any; + toString(): string; +} diff --git a/node_modules/yaml/dist/nodes/Scalar.js b/node_modules/yaml/dist/nodes/Scalar.js new file mode 100644 index 000000000..bd7d4d22c --- /dev/null +++ b/node_modules/yaml/dist/nodes/Scalar.js @@ -0,0 +1,27 @@ +'use strict'; + +var identity = require('./identity.js'); +var Node = require('./Node.js'); +var toJS = require('./toJS.js'); + +const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object'); +class Scalar extends Node.NodeBase { + constructor(value) { + super(identity.SCALAR); + this.value = value; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +} +Scalar.BLOCK_FOLDED = 'BLOCK_FOLDED'; +Scalar.BLOCK_LITERAL = 'BLOCK_LITERAL'; +Scalar.PLAIN = 'PLAIN'; +Scalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE'; +Scalar.QUOTE_SINGLE = 'QUOTE_SINGLE'; + +exports.Scalar = Scalar; +exports.isScalarValue = isScalarValue; diff --git a/node_modules/yaml/dist/nodes/YAMLMap.d.ts b/node_modules/yaml/dist/nodes/YAMLMap.d.ts new file mode 100644 index 000000000..8a6aa869e --- /dev/null +++ b/node_modules/yaml/dist/nodes/YAMLMap.d.ts @@ -0,0 +1,53 @@ +import type { BlockMap, FlowCollection } from '../parse/cst'; +import type { Schema } from '../schema/Schema'; +import type { StringifyContext } from '../stringify/stringify'; +import type { CreateNodeContext } from '../util'; +import { Collection } from './Collection'; +import type { ParsedNode, Range } from './Node'; +import { Pair } from './Pair'; +import type { Scalar } from './Scalar'; +import type { ToJSContext } from './toJS'; +export type MapLike = Map | Set | Record; +export declare function findPair(items: Iterable>, key: unknown): Pair | undefined; +export declare namespace YAMLMap { + interface Parsed extends YAMLMap { + items: Pair[]; + range: Range; + srcToken?: BlockMap | FlowCollection; + } +} +export declare class YAMLMap extends Collection { + static get tagName(): 'tag:yaml.org,2002:map'; + items: Pair[]; + constructor(schema?: Schema); + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap; + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair: Pair | { + key: K; + value: V; + }, overwrite?: boolean): void; + delete(key: unknown): boolean; + get(key: unknown, keepScalar: true): Scalar | undefined; + get(key: unknown, keepScalar?: false): V | undefined; + get(key: unknown, keepScalar?: boolean): V | Scalar | undefined; + has(key: unknown): boolean; + set(key: K, value: V): void; + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON>(_?: unknown, ctx?: ToJSContext, Type?: { + new (): T; + }): any; + toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; +} diff --git a/node_modules/yaml/dist/nodes/YAMLMap.js b/node_modules/yaml/dist/nodes/YAMLMap.js new file mode 100644 index 000000000..210abbfcd --- /dev/null +++ b/node_modules/yaml/dist/nodes/YAMLMap.js @@ -0,0 +1,147 @@ +'use strict'; + +var stringifyCollection = require('../stringify/stringifyCollection.js'); +var addPairToJSMap = require('./addPairToJSMap.js'); +var Collection = require('./Collection.js'); +var identity = require('./identity.js'); +var Pair = require('./Pair.js'); +var Scalar = require('./Scalar.js'); + +function findPair(items, key) { + const k = identity.isScalar(key) ? key.value : key; + for (const it of items) { + if (identity.isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (identity.isScalar(it.key) && it.key.value === k) + return it; + } + } + return undefined; +} +class YAMLMap extends Collection.Collection { + static get tagName() { + return 'tag:yaml.org,2002:map'; + } + constructor(schema) { + super(identity.MAP, schema); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema, obj, ctx) { + const { keepUndefined, replacer } = ctx; + const map = new this(schema); + const add = (key, value) => { + if (typeof replacer === 'function') + value = replacer.call(obj, key, value); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value !== undefined || keepUndefined) + map.items.push(Pair.createPair(key, value, ctx)); + }; + if (obj instanceof Map) { + for (const [key, value] of obj) + add(key, value); + } + else if (obj && typeof obj === 'object') { + for (const key of Object.keys(obj)) + add(key, obj[key]); + } + if (typeof schema.sortMapEntries === 'function') { + map.items.sort(schema.sortMapEntries); + } + return map; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (identity.isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== 'object' || !('key' in pair)) { + // In TypeScript, this never happens. + _pair = new Pair.Pair(pair, pair?.value); + } + else + _pair = new Pair.Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + // For scalars, keep the old node & its comments and anchors + if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } + else if (sortEntries) { + const i = this.items.findIndex(item => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } + else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value) { + this.add(new Pair.Pair(key, value), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map); + for (const item of this.items) + addPairToJSMap.addPairToJSMap(ctx, map, item); + return map; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!identity.isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection.stringifyCollection(this, ctx, { + blockItemPrefix: '', + flowChars: { start: '{', end: '}' }, + itemIndent: ctx.indent || '', + onChompKeep, + onComment + }); + } +} + +exports.YAMLMap = YAMLMap; +exports.findPair = findPair; diff --git a/node_modules/yaml/dist/nodes/YAMLSeq.d.ts b/node_modules/yaml/dist/nodes/YAMLSeq.d.ts new file mode 100644 index 000000000..23baf2b86 --- /dev/null +++ b/node_modules/yaml/dist/nodes/YAMLSeq.d.ts @@ -0,0 +1,60 @@ +import type { CreateNodeContext } from '../doc/createNode'; +import type { BlockSequence, FlowCollection } from '../parse/cst'; +import type { Schema } from '../schema/Schema'; +import type { StringifyContext } from '../stringify/stringify'; +import { Collection } from './Collection'; +import type { ParsedNode, Range } from './Node'; +import type { Pair } from './Pair'; +import type { Scalar } from './Scalar'; +import type { ToJSContext } from './toJS'; +export declare namespace YAMLSeq { + interface Parsed = ParsedNode> extends YAMLSeq { + items: T[]; + range: Range; + srcToken?: BlockSequence | FlowCollection; + } +} +export declare class YAMLSeq extends Collection { + static get tagName(): 'tag:yaml.org,2002:seq'; + items: T[]; + constructor(schema?: Schema); + add(value: T): void; + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key: unknown): boolean; + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + get(key: unknown, keepScalar: true): Scalar | undefined; + get(key: unknown, keepScalar?: false): T | undefined; + get(key: unknown, keepScalar?: boolean): T | Scalar | undefined; + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key: unknown): boolean; + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key: unknown, value: T): void; + toJSON(_?: unknown, ctx?: ToJSContext): unknown[]; + toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; + static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq; +} diff --git a/node_modules/yaml/dist/nodes/YAMLSeq.js b/node_modules/yaml/dist/nodes/YAMLSeq.js new file mode 100644 index 000000000..a2af086d8 --- /dev/null +++ b/node_modules/yaml/dist/nodes/YAMLSeq.js @@ -0,0 +1,115 @@ +'use strict'; + +var createNode = require('../doc/createNode.js'); +var stringifyCollection = require('../stringify/stringifyCollection.js'); +var Collection = require('./Collection.js'); +var identity = require('./identity.js'); +var Scalar = require('./Scalar.js'); +var toJS = require('./toJS.js'); + +class YAMLSeq extends Collection.Collection { + static get tagName() { + return 'tag:yaml.org,2002:seq'; + } + constructor(schema) { + super(identity.SEQ, schema); + this.items = []; + } + add(value) { + this.items.push(value); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') + return undefined; + const it = this.items[idx]; + return !keepScalar && identity.isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === 'number' && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (identity.isScalar(prev) && Scalar.isScalarValue(value)) + prev.value = value; + else + this.items[idx] = value; + } + toJSON(_, ctx) { + const seq = []; + if (ctx?.onCreate) + ctx.onCreate(seq); + let i = 0; + for (const item of this.items) + seq.push(toJS.toJS(item, String(i++), ctx)); + return seq; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection.stringifyCollection(this, ctx, { + blockItemPrefix: '- ', + flowChars: { start: '[', end: ']' }, + itemIndent: (ctx.indent || '') + ' ', + onChompKeep, + onComment + }); + } + static from(schema, obj, ctx) { + const { replacer } = ctx; + const seq = new this(schema); + if (obj && Symbol.iterator in Object(obj)) { + let i = 0; + for (let it of obj) { + if (typeof replacer === 'function') { + const key = obj instanceof Set ? it : String(i++); + it = replacer.call(obj, key, it); + } + seq.items.push(createNode.createNode(it, undefined, ctx)); + } + } + return seq; + } +} +function asItemIndex(key) { + let idx = identity.isScalar(key) ? key.value : key; + if (idx && typeof idx === 'string') + idx = Number(idx); + return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0 + ? idx + : null; +} + +exports.YAMLSeq = YAMLSeq; diff --git a/node_modules/yaml/dist/nodes/addPairToJSMap.d.ts b/node_modules/yaml/dist/nodes/addPairToJSMap.d.ts new file mode 100644 index 000000000..58e931c39 --- /dev/null +++ b/node_modules/yaml/dist/nodes/addPairToJSMap.d.ts @@ -0,0 +1,4 @@ +import type { Pair } from './Pair'; +import type { ToJSContext } from './toJS'; +import type { MapLike } from './YAMLMap'; +export declare function addPairToJSMap(ctx: ToJSContext | undefined, map: MapLike, { key, value }: Pair): MapLike; diff --git a/node_modules/yaml/dist/nodes/addPairToJSMap.js b/node_modules/yaml/dist/nodes/addPairToJSMap.js new file mode 100644 index 000000000..a8faa2904 --- /dev/null +++ b/node_modules/yaml/dist/nodes/addPairToJSMap.js @@ -0,0 +1,65 @@ +'use strict'; + +var log = require('../log.js'); +var merge = require('../schema/yaml-1.1/merge.js'); +var stringify = require('../stringify/stringify.js'); +var identity = require('./identity.js'); +var toJS = require('./toJS.js'); + +function addPairToJSMap(ctx, map, { key, value }) { + if (identity.isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map, value); + // TODO: Should drop this special case for bare << handling + else if (merge.isMergeKey(ctx, key)) + merge.addMergeToJSMap(ctx, map, value); + else { + const jsKey = toJS.toJS(key, '', ctx); + if (map instanceof Map) { + map.set(jsKey, toJS.toJS(value, jsKey, ctx)); + } + else if (map instanceof Set) { + map.add(jsKey); + } + else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS.toJS(value, stringKey, ctx); + if (stringKey in map) + Object.defineProperty(map, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map[stringKey] = jsValue; + } + } + return map; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ''; + // eslint-disable-next-line @typescript-eslint/no-base-to-string + if (typeof jsKey !== 'object') + return String(jsKey); + if (identity.isNode(key) && ctx?.doc) { + const strCtx = stringify.createStringifyContext(ctx.doc, {}); + strCtx.anchors = new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +exports.addPairToJSMap = addPairToJSMap; diff --git a/node_modules/yaml/dist/nodes/identity.d.ts b/node_modules/yaml/dist/nodes/identity.d.ts new file mode 100644 index 000000000..15fc2960a --- /dev/null +++ b/node_modules/yaml/dist/nodes/identity.d.ts @@ -0,0 +1,23 @@ +import type { Document } from '../doc/Document'; +import type { Alias } from './Alias'; +import type { Node } from './Node'; +import type { Pair } from './Pair'; +import type { Scalar } from './Scalar'; +import type { YAMLMap } from './YAMLMap'; +import type { YAMLSeq } from './YAMLSeq'; +export declare const ALIAS: unique symbol; +export declare const DOC: unique symbol; +export declare const MAP: unique symbol; +export declare const PAIR: unique symbol; +export declare const SCALAR: unique symbol; +export declare const SEQ: unique symbol; +export declare const NODE_TYPE: unique symbol; +export declare const isAlias: (node: any) => node is Alias; +export declare const isDocument: (node: any) => node is Document; +export declare const isMap: (node: any) => node is YAMLMap; +export declare const isPair: (node: any) => node is Pair; +export declare const isScalar: (node: any) => node is Scalar; +export declare const isSeq: (node: any) => node is YAMLSeq; +export declare function isCollection(node: any): node is YAMLMap | YAMLSeq; +export declare function isNode(node: any): node is Node; +export declare const hasAnchor: (node: unknown) => node is Scalar | YAMLMap | YAMLSeq; diff --git a/node_modules/yaml/dist/nodes/identity.js b/node_modules/yaml/dist/nodes/identity.js new file mode 100644 index 000000000..5794aa3f8 --- /dev/null +++ b/node_modules/yaml/dist/nodes/identity.js @@ -0,0 +1,53 @@ +'use strict'; + +const ALIAS = Symbol.for('yaml.alias'); +const DOC = Symbol.for('yaml.document'); +const MAP = Symbol.for('yaml.map'); +const PAIR = Symbol.for('yaml.pair'); +const SCALAR = Symbol.for('yaml.scalar'); +const SEQ = Symbol.for('yaml.seq'); +const NODE_TYPE = Symbol.for('yaml.node.type'); +const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS; +const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC; +const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP; +const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR; +const isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR; +const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === 'object') + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === 'object') + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +exports.ALIAS = ALIAS; +exports.DOC = DOC; +exports.MAP = MAP; +exports.NODE_TYPE = NODE_TYPE; +exports.PAIR = PAIR; +exports.SCALAR = SCALAR; +exports.SEQ = SEQ; +exports.hasAnchor = hasAnchor; +exports.isAlias = isAlias; +exports.isCollection = isCollection; +exports.isDocument = isDocument; +exports.isMap = isMap; +exports.isNode = isNode; +exports.isPair = isPair; +exports.isScalar = isScalar; +exports.isSeq = isSeq; diff --git a/node_modules/yaml/dist/nodes/toJS.d.ts b/node_modules/yaml/dist/nodes/toJS.d.ts new file mode 100644 index 000000000..d7e129e14 --- /dev/null +++ b/node_modules/yaml/dist/nodes/toJS.d.ts @@ -0,0 +1,29 @@ +import type { Document } from '../doc/Document'; +import type { Node } from './Node'; +export interface AnchorData { + aliasCount: number; + count: number; + res: unknown; +} +export interface ToJSContext { + anchors: Map; + /** Cached anchor and alias nodes in the order they occur in the document */ + aliasResolveCache?: Node[]; + doc: Document; + keep: boolean; + mapAsMap: boolean; + mapKeyWarned: boolean; + maxAliasCount: number; + onCreate?: (res: unknown) => void; +} +/** + * Recursively convert any node or its contents to native JavaScript + * + * @param value - The input value + * @param arg - If `value` defines a `toJSON()` method, use this + * as its first argument + * @param ctx - Conversion context, originally set in Document#toJS(). If + * `{ keep: true }` is not set, output should be suitable for JSON + * stringification. + */ +export declare function toJS(value: any, arg: string | null, ctx?: ToJSContext): any; diff --git a/node_modules/yaml/dist/nodes/toJS.js b/node_modules/yaml/dist/nodes/toJS.js new file mode 100644 index 000000000..a012823bf --- /dev/null +++ b/node_modules/yaml/dist/nodes/toJS.js @@ -0,0 +1,39 @@ +'use strict'; + +var identity = require('./identity.js'); + +/** + * Recursively convert any node or its contents to native JavaScript + * + * @param value - The input value + * @param arg - If `value` defines a `toJSON()` method, use this + * as its first argument + * @param ctx - Conversion context, originally set in Document#toJS(). If + * `{ keep: true }` is not set, output should be suitable for JSON + * stringification. + */ +function toJS(value, arg, ctx) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + if (Array.isArray(value)) + return value.map((v, i) => toJS(v, String(i), ctx)); + if (value && typeof value.toJSON === 'function') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + if (!ctx || !identity.hasAnchor(value)) + return value.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: undefined }; + ctx.anchors.set(value, data); + ctx.onCreate = res => { + data.res = res; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value === 'bigint' && !ctx?.keep) + return Number(value); + return value; +} + +exports.toJS = toJS; diff --git a/node_modules/yaml/dist/options.d.ts b/node_modules/yaml/dist/options.d.ts new file mode 100644 index 000000000..7771e2a09 --- /dev/null +++ b/node_modules/yaml/dist/options.d.ts @@ -0,0 +1,344 @@ +import type { Reviver } from './doc/applyReviver'; +import type { Directives } from './doc/directives'; +import type { LogLevelId } from './log'; +import type { ParsedNode } from './nodes/Node'; +import type { Pair } from './nodes/Pair'; +import type { Scalar } from './nodes/Scalar'; +import type { LineCounter } from './parse/line-counter'; +import type { Schema } from './schema/Schema'; +import type { Tags } from './schema/tags'; +import type { CollectionTag, ScalarTag } from './schema/types'; +export type ParseOptions = { + /** + * Whether integers should be parsed into BigInt rather than number values. + * + * Default: `false` + * + * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/BigInt + */ + intAsBigInt?: boolean; + /** + * Include a `srcToken` value on each parsed `Node`, containing the CST token + * that was composed into this node. + * + * Default: `false` + */ + keepSourceTokens?: boolean; + /** + * If set, newlines will be tracked, to allow for `lineCounter.linePos(offset)` + * to provide the `{ line, col }` positions within the input. + */ + lineCounter?: LineCounter; + /** + * Include line/col position & node type directly in parse errors. + * + * Default: `true` + */ + prettyErrors?: boolean; + /** + * Detect and report errors that are required by the YAML 1.2 spec, + * but are caused by unambiguous content. + * + * Default: `true` + */ + strict?: boolean; + /** + * Parse all mapping keys as strings. Treat all non-scalar keys as errors. + * + * Default: `false` + */ + stringKeys?: boolean; + /** + * YAML requires map keys to be unique. By default, this is checked by + * comparing scalar values with `===`; deep equality is not checked for + * aliases or collections. If merge keys are enabled by the schema, + * multiple `<<` keys are allowed. + * + * Set `false` to disable, or provide your own comparator function to + * customise. The comparator will be passed two `ParsedNode` values, and + * is expected to return a `boolean` indicating their equality. + * + * Default: `true` + */ + uniqueKeys?: boolean | ((a: ParsedNode, b: ParsedNode) => boolean); +}; +export type DocumentOptions = { + /** + * @internal + * Used internally by Composer. If set and includes an explicit version, + * that overrides the `version` option. + */ + _directives?: Directives; + /** + * Control the logging level during parsing + * + * Default: `'warn'` + */ + logLevel?: LogLevelId; + /** + * The YAML version used by documents without a `%YAML` directive. + * + * Default: `"1.2"` + */ + version?: '1.1' | '1.2' | 'next'; +}; +export type SchemaOptions = { + /** + * When parsing, warn about compatibility issues with the given schema. + * When stringifying, use scalar styles that are parsed correctly + * by the `compat` schema as well as the actual schema. + * + * Default: `null` + */ + compat?: string | Tags | null; + /** + * Array of additional tags to include in the schema, or a function that may + * modify the schema's base tag array. + */ + customTags?: Tags | ((tags: Tags) => Tags) | null; + /** + * Enable support for `<<` merge keys. + * + * Default: `false` for YAML 1.2, `true` for earlier versions + */ + merge?: boolean; + /** + * When using the `'core'` schema, support parsing values with these + * explicit YAML 1.1 tags: + * + * `!!binary`, `!!omap`, `!!pairs`, `!!set`, `!!timestamp`. + * + * Default `true` + */ + resolveKnownTags?: boolean; + /** + * The base schema to use. + * + * The core library has built-in support for the following: + * - `'failsafe'`: A minimal schema that parses all scalars as strings + * - `'core'`: The YAML 1.2 core schema + * - `'json'`: The YAML 1.2 JSON schema, with minimal rules for JSON compatibility + * - `'yaml-1.1'`: The YAML 1.1 schema + * + * If using another (custom) schema, the `customTags` array needs to + * fully define the schema's tags. + * + * Default: `'core'` for YAML 1.2, `'yaml-1.1'` for earlier versions + */ + schema?: string | Schema; + /** + * When adding to or stringifying a map, sort the entries. + * If `true`, sort by comparing key values with `<`. + * Does not affect item order when parsing. + * + * Default: `false` + */ + sortMapEntries?: boolean | ((a: Pair, b: Pair) => number); + /** + * Override default values for `toString()` options. + */ + toStringDefaults?: ToStringOptions; +}; +export type CreateNodeOptions = { + /** + * During node construction, use anchors and aliases to keep strictly equal + * non-null objects as equivalent in YAML. + * + * Default: `true` + */ + aliasDuplicateObjects?: boolean; + /** + * Default prefix for anchors. + * + * Default: `'a'`, resulting in anchors `a1`, `a2`, etc. + */ + anchorPrefix?: string; + /** Force the top-level collection node to use flow style. */ + flow?: boolean; + /** + * Keep `undefined` object values when creating mappings, rather than + * discarding them. + * + * Default: `false` + */ + keepUndefined?: boolean | null; + onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; + /** + * Specify the top-level collection type, e.g. `"!!omap"`. Note that this + * requires the corresponding tag to be available in this document's schema. + */ + tag?: string; +}; +export type ToJSOptions = { + /** + * Use Map rather than Object to represent mappings. + * + * Default: `false` + */ + mapAsMap?: boolean; + /** + * Prevent exponential entity expansion attacks by limiting data aliasing count; + * set to `-1` to disable checks; `0` disallows all alias nodes. + * + * Default: `100` + */ + maxAliasCount?: number; + /** + * If defined, called with the resolved `value` and reference `count` for + * each anchor in the document. + */ + onAnchor?: (value: unknown, count: number) => void; + /** + * Optional function that may filter or modify the output JS value + * + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter + */ + reviver?: Reviver; +}; +export type ToStringOptions = { + /** + * Use block quote styles for scalar values where applicable. + * Set to `false` to disable block quotes completely. + * + * Default: `true` + */ + blockQuote?: boolean | 'folded' | 'literal'; + /** + * Enforce `'block'` or `'flow'` style on maps and sequences. + * Empty collections will always be stringified as `{}` or `[]`. + * + * Default: `'any'`, allowing each node to set its style separately + * with its `flow: boolean` (default `false`) property. + */ + collectionStyle?: 'any' | 'block' | 'flow'; + /** + * Comment stringifier. + * Output should be valid for the current schema. + * + * By default, empty comment lines are left empty, + * lines consisting of a single space are replaced by `#`, + * and all other lines are prefixed with a `#`. + */ + commentString?: (comment: string) => string; + /** + * The default type of string literal used to stringify implicit key values. + * Output may use other types if required to fully represent the value. + * + * If `null`, the value of `defaultStringType` is used. + * + * Default: `null` + */ + defaultKeyType?: Scalar.Type | null; + /** + * The default type of string literal used to stringify values in general. + * Output may use other types if required to fully represent the value. + * + * Default: `'PLAIN'` + */ + defaultStringType?: Scalar.Type; + /** + * Include directives in the output. + * + * - If `true`, at least the document-start marker `---` is always included. + * This does not force the `%YAML` directive to be included. To do that, + * set `doc.directives.yaml.explicit = true`. + * - If `false`, no directives or marker is ever included. If using the `%TAG` + * directive, you are expected to include it manually in the stream before + * its use. + * - If `null`, directives and marker may be included if required. + * + * Default: `null` + */ + directives?: boolean | null; + /** + * Restrict double-quoted strings to use JSON-compatible syntax. + * + * Default: `false` + */ + doubleQuotedAsJSON?: boolean; + /** + * Minimum length for double-quoted strings to use multiple lines to + * represent the value. Ignored if `doubleQuotedAsJSON` is set. + * + * Default: `40` + */ + doubleQuotedMinMultiLineLength?: number; + /** + * String representation for `false`. + * With the core schema, use `'false'`, `'False'`, or `'FALSE'`. + * + * Default: `'false'` + */ + falseStr?: string; + /** + * When true, a single space of padding will be added inside the delimiters + * of non-empty single-line flow collections. + * + * Default: `true` + */ + flowCollectionPadding?: boolean; + /** + * The number of spaces to use when indenting code. + * + * Default: `2` + */ + indent?: number; + /** + * Whether block sequences should be indented. + * + * Default: `true` + */ + indentSeq?: boolean; + /** + * Maximum line width (set to `0` to disable folding). + * + * This is a soft limit, as only double-quoted semantics allow for inserting + * a line break in the middle of a word, as well as being influenced by the + * `minContentWidth` option. + * + * Default: `80` + */ + lineWidth?: number; + /** + * Minimum line width for highly-indented content (set to `0` to disable). + * + * Default: `20` + */ + minContentWidth?: number; + /** + * String representation for `null`. + * With the core schema, use `'null'`, `'Null'`, `'NULL'`, `'~'`, or an empty + * string `''`. + * + * Default: `'null'` + */ + nullStr?: string; + /** + * Require keys to be scalars and to use implicit rather than explicit notation. + * + * Default: `false` + */ + simpleKeys?: boolean; + /** + * Use 'single quote' rather than "double quote" where applicable. + * Set to `false` to disable single quotes completely. + * + * Default: `null` + */ + singleQuote?: boolean | null; + /** + * String representation for `true`. + * With the core schema, use `'true'`, `'True'`, or `'TRUE'`. + * + * Default: `'true'` + */ + trueStr?: string; + /** + * The anchor used by an alias must be defined before the alias node. As it's + * possible for the document to be modified manually, the order may be + * verified during stringification. + * + * Default: `'true'` + */ + verifyAliasOrder?: boolean; +}; diff --git a/node_modules/yaml/dist/parse/cst-scalar.d.ts b/node_modules/yaml/dist/parse/cst-scalar.d.ts new file mode 100644 index 000000000..6064ed892 --- /dev/null +++ b/node_modules/yaml/dist/parse/cst-scalar.d.ts @@ -0,0 +1,64 @@ +import type { ErrorCode } from '../errors'; +import type { Range } from '../nodes/Node'; +import type { Scalar } from '../nodes/Scalar'; +import type { BlockScalar, FlowScalar, SourceToken, Token } from './cst'; +/** + * If `token` is a CST flow or block scalar, determine its string value and a few other attributes. + * Otherwise, return `null`. + */ +export declare function resolveAsScalar(token: FlowScalar | BlockScalar, strict?: boolean, onError?: (offset: number, code: ErrorCode, message: string) => void): { + value: string; + type: Scalar.Type | null; + comment: string; + range: Range; +}; +export declare function resolveAsScalar(token: Token | null | undefined, strict?: boolean, onError?: (offset: number, code: ErrorCode, message: string) => void): { + value: string; + type: Scalar.Type | null; + comment: string; + range: Range; +} | null; +/** + * Create a new scalar token with `value` + * + * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`, + * as this function does not support any schema operations and won't check for such conflicts. + * + * @param value The string representation of the value, which will have its content properly indented. + * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added. + * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value. + * @param context.indent The indent level of the token. + * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value. + * @param context.offset The offset position of the token. + * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`. + */ +export declare function createScalarToken(value: string, context: { + end?: SourceToken[]; + implicitKey?: boolean; + indent: number; + inFlow?: boolean; + offset?: number; + type?: Scalar.Type; +}): BlockScalar | FlowScalar; +/** + * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have. + * + * Best efforts are made to retain any comments previously associated with the `token`, + * though all contents within a collection's `items` will be overwritten. + * + * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`, + * as this function does not support any schema operations and won't check for such conflicts. + * + * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key. + * @param value The string representation of the value, which will have its content properly indented. + * @param context.afterKey In most cases, values after a key should have an additional level of indentation. + * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value. + * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value. + * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`. + */ +export declare function setScalarValue(token: Token, value: string, context?: { + afterKey?: boolean; + implicitKey?: boolean; + inFlow?: boolean; + type?: Scalar.Type; +}): void; diff --git a/node_modules/yaml/dist/parse/cst-scalar.js b/node_modules/yaml/dist/parse/cst-scalar.js new file mode 100644 index 000000000..81b8463f8 --- /dev/null +++ b/node_modules/yaml/dist/parse/cst-scalar.js @@ -0,0 +1,218 @@ +'use strict'; + +var resolveBlockScalar = require('../compose/resolve-block-scalar.js'); +var resolveFlowScalar = require('../compose/resolve-flow-scalar.js'); +var errors = require('../errors.js'); +var stringifyString = require('../stringify/stringifyString.js'); + +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new errors.YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + return resolveFlowScalar.resolveFlowScalar(token, strict, _onError); + case 'block-scalar': + return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +/** + * Create a new scalar token with `value` + * + * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`, + * as this function does not support any schema operations and won't check for such conflicts. + * + * @param value The string representation of the value, which will have its content properly indented. + * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added. + * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value. + * @param context.indent The indent level of the token. + * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value. + * @param context.offset The offset position of the token. + * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`. + */ +function createScalarToken(value, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context; + const source = stringifyString.stringifyString({ type, value }, { + implicitKey, + indent: indent > 0 ? ' '.repeat(indent) : '', + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: 'newline', offset: -1, indent, source: '\n' } + ]; + switch (source[0]) { + case '|': + case '>': { + const he = source.indexOf('\n'); + const head = source.substring(0, he); + const body = source.substring(he + 1) + '\n'; + const props = [ + { type: 'block-scalar-header', offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: 'newline', offset: -1, indent, source: '\n' }); + return { type: 'block-scalar', offset, indent, props, source: body }; + } + case '"': + return { type: 'double-quoted-scalar', offset, indent, source, end }; + case "'": + return { type: 'single-quoted-scalar', offset, indent, source, end }; + default: + return { type: 'scalar', offset, indent, source, end }; + } +} +/** + * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have. + * + * Best efforts are made to retain any comments previously associated with the `token`, + * though all contents within a collection's `items` will be overwritten. + * + * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`, + * as this function does not support any schema operations and won't check for such conflicts. + * + * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key. + * @param value The string representation of the value, which will have its content properly indented. + * @param context.afterKey In most cases, values after a key should have an additional level of indentation. + * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value. + * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value. + * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`. + */ +function setScalarValue(token, value, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = 'indent' in token ? token.indent : null; + if (afterKey && typeof indent === 'number') + indent += 2; + if (!type) + switch (token.type) { + case 'single-quoted-scalar': + type = 'QUOTE_SINGLE'; + break; + case 'double-quoted-scalar': + type = 'QUOTE_DOUBLE'; + break; + case 'block-scalar': { + const header = token.props[0]; + if (header.type !== 'block-scalar-header') + throw new Error('Invalid block scalar header'); + type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL'; + break; + } + default: + type = 'PLAIN'; + } + const source = stringifyString.stringifyString({ type, value }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '', + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case '|': + case '>': + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, 'double-quoted-scalar'); + break; + case "'": + setFlowScalarValue(token, source, 'single-quoted-scalar'); + break; + default: + setFlowScalarValue(token, source, 'scalar'); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf('\n'); + const head = source.substring(0, he); + const body = source.substring(he + 1) + '\n'; + if (token.type === 'block-scalar') { + const header = token.props[0]; + if (header.type !== 'block-scalar-header') + throw new Error('Invalid block scalar header'); + header.source = head; + token.source = body; + } + else { + const { offset } = token; + const indent = 'indent' in token ? token.indent : -1; + const props = [ + { type: 'block-scalar-header', offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined)) + props.push({ type: 'newline', offset: -1, indent, source: '\n' }); + for (const key of Object.keys(token)) + if (key !== 'type' && key !== 'offset') + delete token[key]; + Object.assign(token, { type: 'block-scalar', indent, props, source: body }); + } +} +/** @returns `true` if last token is a newline */ +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case 'space': + case 'comment': + props.push(st); + break; + case 'newline': + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case 'scalar': + case 'double-quoted-scalar': + case 'single-quoted-scalar': + token.type = type; + token.source = source; + break; + case 'block-scalar': { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === 'block-scalar-header') + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case 'block-map': + case 'block-seq': { + const offset = token.offset + source.length; + const nl = { type: 'newline', offset, indent: token.indent, source: '\n' }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = 'indent' in token ? token.indent : -1; + const end = 'end' in token && Array.isArray(token.end) + ? token.end.filter(st => st.type === 'space' || + st.type === 'comment' || + st.type === 'newline') + : []; + for (const key of Object.keys(token)) + if (key !== 'type' && key !== 'offset') + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +exports.createScalarToken = createScalarToken; +exports.resolveAsScalar = resolveAsScalar; +exports.setScalarValue = setScalarValue; diff --git a/node_modules/yaml/dist/parse/cst-stringify.d.ts b/node_modules/yaml/dist/parse/cst-stringify.d.ts new file mode 100644 index 000000000..312bf6c26 --- /dev/null +++ b/node_modules/yaml/dist/parse/cst-stringify.d.ts @@ -0,0 +1,8 @@ +import type { CollectionItem, Token } from './cst'; +/** + * Stringify a CST document, token, or collection item + * + * Fair warning: This applies no validation whatsoever, and + * simply concatenates the sources in their logical order. + */ +export declare const stringify: (cst: Token | CollectionItem) => string; diff --git a/node_modules/yaml/dist/parse/cst-stringify.js b/node_modules/yaml/dist/parse/cst-stringify.js new file mode 100644 index 000000000..78e8c3722 --- /dev/null +++ b/node_modules/yaml/dist/parse/cst-stringify.js @@ -0,0 +1,63 @@ +'use strict'; + +/** + * Stringify a CST document, token, or collection item + * + * Fair warning: This applies no validation whatsoever, and + * simply concatenates the sources in their logical order. + */ +const stringify = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case 'block-scalar': { + let res = ''; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case 'block-map': + case 'block-seq': { + let res = ''; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case 'flow-collection': { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case 'document': { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ('end' in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value }) { + let res = ''; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value) + res += stringifyToken(value); + return res; +} + +exports.stringify = stringify; diff --git a/node_modules/yaml/dist/parse/cst-visit.d.ts b/node_modules/yaml/dist/parse/cst-visit.d.ts new file mode 100644 index 000000000..edac14072 --- /dev/null +++ b/node_modules/yaml/dist/parse/cst-visit.d.ts @@ -0,0 +1,39 @@ +import type { BlockMap, BlockSequence, CollectionItem, Document, FlowCollection } from './cst'; +export type VisitPath = readonly ['key' | 'value', number][]; +export type Visitor = (item: CollectionItem, path: VisitPath) => number | symbol | Visitor | void; +/** + * Apply a visitor to a CST document or item. + * + * Walks through the tree (depth-first) starting from the root, calling a + * `visitor` function with two arguments when entering each item: + * - `item`: The current item, which included the following members: + * - `start: SourceToken[]` – Source tokens before the key or value, + * possibly including its anchor or tag. + * - `key?: Token | null` – Set for pair values. May then be `null`, if + * the key before the `:` separator is empty. + * - `sep?: SourceToken[]` – Source tokens between the key and the value, + * which should include the `:` map value indicator if `value` is set. + * - `value?: Token` – The value of a sequence item, or of a map pair. + * - `path`: The steps from the root to the current node, as an array of + * `['key' | 'value', number]` tuples. + * + * The return value of the visitor may be used to control the traversal: + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this token, continue with + * next sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current item, then continue with the next one + * - `number`: Set the index of the next step. This is useful especially if + * the index of the current token has changed. + * - `function`: Define the next visitor for this item. After the original + * visitor is called on item entry, next visitors are called after handling + * a non-empty `key` and when exiting the item. + */ +export declare function visit(cst: Document | CollectionItem, visitor: Visitor): void; +export declare namespace visit { + var BREAK: symbol; + var SKIP: symbol; + var REMOVE: symbol; + var itemAtPath: (cst: Document | CollectionItem, path: VisitPath) => CollectionItem | undefined; + var parentCollection: (cst: Document | CollectionItem, path: VisitPath) => BlockMap | BlockSequence | FlowCollection; +} diff --git a/node_modules/yaml/dist/parse/cst-visit.js b/node_modules/yaml/dist/parse/cst-visit.js new file mode 100644 index 000000000..9ceee936b --- /dev/null +++ b/node_modules/yaml/dist/parse/cst-visit.js @@ -0,0 +1,99 @@ +'use strict'; + +const BREAK = Symbol('break visit'); +const SKIP = Symbol('skip children'); +const REMOVE = Symbol('remove item'); +/** + * Apply a visitor to a CST document or item. + * + * Walks through the tree (depth-first) starting from the root, calling a + * `visitor` function with two arguments when entering each item: + * - `item`: The current item, which included the following members: + * - `start: SourceToken[]` – Source tokens before the key or value, + * possibly including its anchor or tag. + * - `key?: Token | null` – Set for pair values. May then be `null`, if + * the key before the `:` separator is empty. + * - `sep?: SourceToken[]` – Source tokens between the key and the value, + * which should include the `:` map value indicator if `value` is set. + * - `value?: Token` – The value of a sequence item, or of a map pair. + * - `path`: The steps from the root to the current node, as an array of + * `['key' | 'value', number]` tuples. + * + * The return value of the visitor may be used to control the traversal: + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this token, continue with + * next sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current item, then continue with the next one + * - `number`: Set the index of the next step. This is useful especially if + * the index of the current token has changed. + * - `function`: Define the next visitor for this item. After the original + * visitor is called on item entry, next visitors are called after handling + * a non-empty `key` and when exiting the item. + */ +function visit(cst, visitor) { + if ('type' in cst && cst.type === 'document') + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +// Without the `as symbol` casts, TS declares these in the `visit` +// namespace using `var`, but then complains about that because +// `unique symbol` must be `const`. +/** Terminate visit traversal completely */ +visit.BREAK = BREAK; +/** Do not visit the children of the current item */ +visit.SKIP = SKIP; +/** Remove the current item */ +visit.REMOVE = REMOVE; +/** Find the item at `path` from `cst` as the root */ +visit.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && 'items' in tok) { + item = tok.items[index]; + } + else + return undefined; + } + return item; +}; +/** + * Get the immediate parent collection of the item at `path` from `cst` as the root. + * + * Throws an error if the collection is not found, which should never happen if the item itself exists. + */ +visit.parentCollection = (cst, path) => { + const parent = visit.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && 'items' in coll) + return coll; + throw new Error('Parent collection not found'); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === 'symbol') + return ctrl; + for (const field of ['key', 'value']) { + const token = item[field]; + if (token && 'items' in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === 'number') + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === 'function' && field === 'key') + ctrl = ctrl(item, path); + } + } + return typeof ctrl === 'function' ? ctrl(item, path) : ctrl; +} + +exports.visit = visit; diff --git a/node_modules/yaml/dist/parse/cst.d.ts b/node_modules/yaml/dist/parse/cst.d.ts new file mode 100644 index 000000000..3606c0cf3 --- /dev/null +++ b/node_modules/yaml/dist/parse/cst.d.ts @@ -0,0 +1,109 @@ +export { createScalarToken, resolveAsScalar, setScalarValue } from './cst-scalar'; +export { stringify } from './cst-stringify'; +export type { Visitor, VisitPath } from './cst-visit'; +export { visit } from './cst-visit'; +export interface SourceToken { + type: 'byte-order-mark' | 'doc-mode' | 'doc-start' | 'space' | 'comment' | 'newline' | 'directive-line' | 'anchor' | 'tag' | 'seq-item-ind' | 'explicit-key-ind' | 'map-value-ind' | 'flow-map-start' | 'flow-map-end' | 'flow-seq-start' | 'flow-seq-end' | 'flow-error-end' | 'comma' | 'block-scalar-header'; + offset: number; + indent: number; + source: string; +} +export interface ErrorToken { + type: 'error'; + offset: number; + source: string; + message: string; +} +export interface Directive { + type: 'directive'; + offset: number; + source: string; +} +export interface Document { + type: 'document'; + offset: number; + start: SourceToken[]; + value?: Token; + end?: SourceToken[]; +} +export interface DocumentEnd { + type: 'doc-end'; + offset: number; + source: string; + end?: SourceToken[]; +} +export interface FlowScalar { + type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar'; + offset: number; + indent: number; + source: string; + end?: SourceToken[]; +} +export interface BlockScalar { + type: 'block-scalar'; + offset: number; + indent: number; + props: Token[]; + source: string; +} +export interface BlockMap { + type: 'block-map'; + offset: number; + indent: number; + items: Array<{ + start: SourceToken[]; + explicitKey?: true; + key?: never; + sep?: never; + value?: never; + } | { + start: SourceToken[]; + explicitKey?: true; + key: Token | null; + sep: SourceToken[]; + value?: Token; + }>; +} +export interface BlockSequence { + type: 'block-seq'; + offset: number; + indent: number; + items: Array<{ + start: SourceToken[]; + key?: never; + sep?: never; + value?: Token; + }>; +} +export type CollectionItem = { + start: SourceToken[]; + key?: Token | null; + sep?: SourceToken[]; + value?: Token; +}; +export interface FlowCollection { + type: 'flow-collection'; + offset: number; + indent: number; + start: SourceToken; + items: CollectionItem[]; + end: SourceToken[]; +} +export type Token = SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection; +export type TokenType = SourceToken['type'] | DocumentEnd['type'] | FlowScalar['type']; +/** The byte order mark */ +export declare const BOM = "\uFEFF"; +/** Start of doc-mode */ +export declare const DOCUMENT = "\u0002"; +/** Unexpected end of flow-mode */ +export declare const FLOW_END = "\u0018"; +/** Next token is a scalar value */ +export declare const SCALAR = "\u001F"; +/** @returns `true` if `token` is a flow or block collection */ +export declare const isCollection: (token: Token | null | undefined) => token is BlockMap | BlockSequence | FlowCollection; +/** @returns `true` if `token` is a flow or block scalar; not an alias */ +export declare const isScalar: (token: Token | null | undefined) => token is FlowScalar | BlockScalar; +/** Get a printable representation of a lexer token */ +export declare function prettyToken(token: string): string; +/** Identify the type of a lexer token. May return `null` for unknown tokens. */ +export declare function tokenType(source: string): TokenType | null; diff --git a/node_modules/yaml/dist/parse/cst.js b/node_modules/yaml/dist/parse/cst.js new file mode 100644 index 000000000..613c229b2 --- /dev/null +++ b/node_modules/yaml/dist/parse/cst.js @@ -0,0 +1,112 @@ +'use strict'; + +var cstScalar = require('./cst-scalar.js'); +var cstStringify = require('./cst-stringify.js'); +var cstVisit = require('./cst-visit.js'); + +/** The byte order mark */ +const BOM = '\u{FEFF}'; +/** Start of doc-mode */ +const DOCUMENT = '\x02'; // C0: Start of Text +/** Unexpected end of flow-mode */ +const FLOW_END = '\x18'; // C0: Cancel +/** Next token is a scalar value */ +const SCALAR = '\x1f'; // C0: Unit Separator +/** @returns `true` if `token` is a flow or block collection */ +const isCollection = (token) => !!token && 'items' in token; +/** @returns `true` if `token` is a flow or block scalar; not an alias */ +const isScalar = (token) => !!token && + (token.type === 'scalar' || + token.type === 'single-quoted-scalar' || + token.type === 'double-quoted-scalar' || + token.type === 'block-scalar'); +/* istanbul ignore next */ +/** Get a printable representation of a lexer token */ +function prettyToken(token) { + switch (token) { + case BOM: + return ''; + case DOCUMENT: + return ''; + case FLOW_END: + return ''; + case SCALAR: + return ''; + default: + return JSON.stringify(token); + } +} +/** Identify the type of a lexer token. May return `null` for unknown tokens. */ +function tokenType(source) { + switch (source) { + case BOM: + return 'byte-order-mark'; + case DOCUMENT: + return 'doc-mode'; + case FLOW_END: + return 'flow-error-end'; + case SCALAR: + return 'scalar'; + case '---': + return 'doc-start'; + case '...': + return 'doc-end'; + case '': + case '\n': + case '\r\n': + return 'newline'; + case '-': + return 'seq-item-ind'; + case '?': + return 'explicit-key-ind'; + case ':': + return 'map-value-ind'; + case '{': + return 'flow-map-start'; + case '}': + return 'flow-map-end'; + case '[': + return 'flow-seq-start'; + case ']': + return 'flow-seq-end'; + case ',': + return 'comma'; + } + switch (source[0]) { + case ' ': + case '\t': + return 'space'; + case '#': + return 'comment'; + case '%': + return 'directive-line'; + case '*': + return 'alias'; + case '&': + return 'anchor'; + case '!': + return 'tag'; + case "'": + return 'single-quoted-scalar'; + case '"': + return 'double-quoted-scalar'; + case '|': + case '>': + return 'block-scalar-header'; + } + return null; +} + +exports.createScalarToken = cstScalar.createScalarToken; +exports.resolveAsScalar = cstScalar.resolveAsScalar; +exports.setScalarValue = cstScalar.setScalarValue; +exports.stringify = cstStringify.stringify; +exports.visit = cstVisit.visit; +exports.BOM = BOM; +exports.DOCUMENT = DOCUMENT; +exports.FLOW_END = FLOW_END; +exports.SCALAR = SCALAR; +exports.isCollection = isCollection; +exports.isScalar = isScalar; +exports.prettyToken = prettyToken; +exports.tokenType = tokenType; diff --git a/node_modules/yaml/dist/parse/lexer.d.ts b/node_modules/yaml/dist/parse/lexer.d.ts new file mode 100644 index 000000000..4c01430d7 --- /dev/null +++ b/node_modules/yaml/dist/parse/lexer.d.ts @@ -0,0 +1,87 @@ +/** + * Splits an input string into lexical tokens, i.e. smaller strings that are + * easily identifiable by `tokens.tokenType()`. + * + * Lexing starts always in a "stream" context. Incomplete input may be buffered + * until a complete token can be emitted. + * + * In addition to slices of the original input, the following control characters + * may also be emitted: + * + * - `\x02` (Start of Text): A document starts with the next token + * - `\x18` (Cancel): Unexpected end of flow-mode (indicates an error) + * - `\x1f` (Unit Separator): Next token is a scalar value + * - `\u{FEFF}` (Byte order mark): Emitted separately outside documents + */ +export declare class Lexer { + /** + * Flag indicating whether the end of the current buffer marks the end of + * all input + */ + private atEnd; + /** + * Explicit indent set in block scalar header, as an offset from the current + * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not + * explicitly set. + */ + private blockScalarIndent; + /** + * Block scalars that include a + (keep) chomping indicator in their header + * include trailing empty lines, which are otherwise excluded from the + * scalar's contents. + */ + private blockScalarKeep; + /** Current input */ + private buffer; + /** + * Flag noting whether the map value indicator : can immediately follow this + * node within a flow context. + */ + private flowKey; + /** Count of surrounding flow collection levels. */ + private flowLevel; + /** + * Minimum level of indentation required for next lines to be parsed as a + * part of the current scalar value. + */ + private indentNext; + /** Indentation level of the current line. */ + private indentValue; + /** Position of the next \n character. */ + private lineEndPos; + /** Stores the state of the lexer if reaching the end of incpomplete input */ + private next; + /** A pointer to `buffer`; the current position of the lexer. */ + private pos; + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + lex(source: string, incomplete?: boolean): Generator; + private atLineEnd; + private charAt; + private continueScalar; + private getLine; + private hasChars; + private setNext; + private peek; + private parseNext; + private parseStream; + private parseLineStart; + private parseBlockStart; + private parseDocument; + private parseFlowCollection; + private parseQuotedScalar; + private parseBlockScalarHeader; + private parseBlockScalar; + private parsePlainScalar; + private pushCount; + private pushToIndex; + private pushIndicators; + private pushTag; + private pushNewline; + private pushSpaces; + private pushUntil; +} diff --git a/node_modules/yaml/dist/parse/lexer.js b/node_modules/yaml/dist/parse/lexer.js new file mode 100644 index 000000000..9ac766e9b --- /dev/null +++ b/node_modules/yaml/dist/parse/lexer.js @@ -0,0 +1,719 @@ +'use strict'; + +var cst = require('./cst.js'); + +/* +START -> stream + +stream + directive -> line-end -> stream + indent + line-end -> stream + [else] -> line-start + +line-end + comment -> line-end + newline -> . + input-end -> END + +line-start + doc-start -> doc + doc-end -> stream + [else] -> indent -> block-start + +block-start + seq-item-start -> block-start + explicit-key-start -> block-start + map-value-start -> block-start + [else] -> doc + +doc + line-end -> line-start + spaces -> doc + anchor -> doc + tag -> doc + flow-start -> flow -> doc + flow-end -> error -> doc + seq-item-start -> error -> doc + explicit-key-start -> error -> doc + map-value-start -> doc + alias -> doc + quote-start -> quoted-scalar -> doc + block-scalar-header -> line-end -> block-scalar(min) -> line-start + [else] -> plain-scalar(false, min) -> doc + +flow + line-end -> flow + spaces -> flow + anchor -> flow + tag -> flow + flow-start -> flow -> flow + flow-end -> . + seq-item-start -> error -> flow + explicit-key-start -> flow + map-value-start -> flow + alias -> flow + quote-start -> quoted-scalar -> flow + comma -> flow + [else] -> plain-scalar(true, 0) -> flow + +quoted-scalar + quote-end -> . + [else] -> quoted-scalar + +block-scalar(min) + newline + peek(indent < min) -> . + [else] -> block-scalar(min) + +plain-scalar(is-flow, min) + scalar-end(is-flow) -> . + peek(newline + (indent < min)) -> . + [else] -> plain-scalar(min) +*/ +function isEmpty(ch) { + switch (ch) { + case undefined: + case ' ': + case '\n': + case '\r': + case '\t': + return true; + default: + return false; + } +} +const hexDigits = new Set('0123456789ABCDEFabcdef'); +const tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +const flowIndicatorChars = new Set(',[]{}'); +const invalidAnchorChars = new Set(' ,[]{}\n\r\t'); +const isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +/** + * Splits an input string into lexical tokens, i.e. smaller strings that are + * easily identifiable by `tokens.tokenType()`. + * + * Lexing starts always in a "stream" context. Incomplete input may be buffered + * until a complete token can be emitted. + * + * In addition to slices of the original input, the following control characters + * may also be emitted: + * + * - `\x02` (Start of Text): A document starts with the next token + * - `\x18` (Cancel): Unexpected end of flow-mode (indicates an error) + * - `\x1f` (Unit Separator): Next token is a scalar value + * - `\u{FEFF}` (Byte order mark): Emitted separately outside documents + */ +class Lexer { + constructor() { + /** + * Flag indicating whether the end of the current buffer marks the end of + * all input + */ + this.atEnd = false; + /** + * Explicit indent set in block scalar header, as an offset from the current + * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not + * explicitly set. + */ + this.blockScalarIndent = -1; + /** + * Block scalars that include a + (keep) chomping indicator in their header + * include trailing empty lines, which are otherwise excluded from the + * scalar's contents. + */ + this.blockScalarKeep = false; + /** Current input */ + this.buffer = ''; + /** + * Flag noting whether the map value indicator : can immediately follow this + * node within a flow context. + */ + this.flowKey = false; + /** Count of surrounding flow collection levels. */ + this.flowLevel = 0; + /** + * Minimum level of indentation required for next lines to be parsed as a + * part of the current scalar value. + */ + this.indentNext = 0; + /** Indentation level of the current line. */ + this.indentValue = 0; + /** Position of the next \n character. */ + this.lineEndPos = null; + /** Stores the state of the lexer if reaching the end of incpomplete input */ + this.next = null; + /** A pointer to `buffer`; the current position of the lexer. */ + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== 'string') + throw TypeError('source is not a string'); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? 'stream'; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === ' ' || ch === '\t') + ch = this.buffer[++i]; + if (!ch || ch === '#' || ch === '\n') + return true; + if (ch === '\r') + return this.buffer[i + 1] === '\n'; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === ' ') + ch = this.buffer[++indent + offset]; + if (ch === '\r') { + const next = this.buffer[indent + offset + 1]; + if (next === '\n' || (!next && !this.atEnd)) + return offset + indent + 1; + } + return ch === '\n' || indent >= this.indentNext || (!ch && !this.atEnd) + ? offset + indent + : -1; + } + if (ch === '-' || ch === '.') { + const dt = this.buffer.substr(offset, 3); + if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== 'number' || (end !== -1 && end < this.pos)) { + end = this.buffer.indexOf('\n', this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === '\r') + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case 'stream': + return yield* this.parseStream(); + case 'line-start': + return yield* this.parseLineStart(); + case 'block-start': + return yield* this.parseBlockStart(); + case 'doc': + return yield* this.parseDocument(); + case 'flow': + return yield* this.parseFlowCollection(); + case 'quoted-scalar': + return yield* this.parseQuotedScalar(); + case 'block-scalar': + return yield* this.parseBlockScalar(); + case 'plain-scalar': + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext('stream'); + if (line[0] === cst.BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === '%') { + let dirEnd = line.length; + let cs = line.indexOf('#'); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === ' ' || ch === '\t') { + dirEnd = cs - 1; + break; + } + else { + cs = line.indexOf('#', cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === ' ' || ch === '\t') + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); // possible comment + this.pushNewline(); + return 'stream'; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return 'stream'; + } + yield cst.DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext('line-start'); + if (ch === '-' || ch === '.') { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext('line-start'); + const s = this.peek(3); + if ((s === '---' || s === '...') && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === '---' ? 'doc' : 'stream'; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext('block-start'); + if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return yield* this.parseBlockStart(); + } + return 'doc'; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext('doc'); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case '#': + yield* this.pushCount(line.length - n); + // fallthrough + case undefined: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case '{': + case '[': + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return 'flow'; + case '}': + case ']': + // this is an error + yield* this.pushCount(1); + return 'doc'; + case '*': + yield* this.pushUntil(isNotAnchorChar); + return 'doc'; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case '|': + case '>': + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } + else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext('flow'); + if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') || + (indent === 0 && + (line.startsWith('---') || line.startsWith('...')) && + isEmpty(line[3]))) { + // Allowing for the terminal ] or } at the same (rather than greater) + // indent level as the initial [ or { is technically invalid, but + // failing here would be surprising to users. + const atFlowEndMarker = indent === this.indentNext - 1 && + this.flowLevel === 1 && + (line[0] === ']' || line[0] === '}'); + if (!atFlowEndMarker) { + // this is an error + this.flowLevel = 0; + yield cst.FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ',') { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case undefined: + return 'flow'; + case '#': + yield* this.pushCount(line.length - n); + return 'flow'; + case '{': + case '[': + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return 'flow'; + case '}': + case ']': + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? 'flow' : 'doc'; + case '*': + yield* this.pushUntil(isNotAnchorChar); + return 'flow'; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ':': { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ',') { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return 'flow'; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } + else { + // double-quote + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === '\\') + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + // Only looking for newlines within the quotes + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf('\n', this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf('\n', cs); + } + if (nl !== -1) { + // this is an error caused by an unexpected unindent + end = nl - (qb[nl - 1] === '\r' ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext('quoted-scalar'); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? 'flow' : 'doc'; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === '+') + this.blockScalarKeep = true; + else if (ch > '0' && ch <= '9') + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== '-') + break; + } + return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#'); + } + *parseBlockScalar() { + let nl = this.pos - 1; // may be -1 if this.pos === 0 + let indent = 0; + let ch; + loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) { + switch (ch) { + case ' ': + indent += 1; + break; + case '\n': + nl = i; + indent = 0; + break; + case '\r': { + const next = this.buffer[i + 1]; + if (!next && !this.atEnd) + return this.setNext('block-scalar'); + if (next === '\n') + break; + } // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext('block-scalar'); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = + this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf('\n', cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext('block-scalar'); + nl = this.buffer.length; + } + } + // Trailing insufficiently indented tabs are invalid. + // To catch that during parsing, we include them in the block scalar value. + let i = nl + 1; + ch = this.buffer[i]; + while (ch === ' ') + ch = this.buffer[++i]; + if (ch === '\t') { + while (ch === '\t' || ch === ' ' || ch === '\r' || ch === '\n') + ch = this.buffer[++i]; + nl = i - 1; + } + else if (!this.blockScalarKeep) { + do { + let i = nl - 1; + let ch = this.buffer[i]; + if (ch === '\r') + ch = this.buffer[--i]; + const lastChar = i; // Drop the line if last char not more indented + while (ch === ' ') + ch = this.buffer[--i]; + if (ch === '\n' && i >= this.pos && i + 1 + indent > lastChar) + nl = i; + else + break; + } while (true); + } + yield cst.SCALAR; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while ((ch = this.buffer[++i])) { + if (ch === ':') { + const next = this.buffer[i + 1]; + if (isEmpty(next) || (inFlow && flowIndicatorChars.has(next))) + break; + end = i; + } + else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === '\r') { + if (next === '\n') { + i += 1; + ch = '\n'; + next = this.buffer[i + 1]; + } + else + end = i; + } + if (next === '#' || (inFlow && flowIndicatorChars.has(next))) + break; + if (ch === '\n') { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); // to advance, but still account for ' #' + } + } + else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext('plain-scalar'); + yield cst.SCALAR; + yield* this.pushToIndex(end + 1, true); + return inFlow ? 'flow' : 'doc'; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } + else if (allowEmpty) + yield ''; + return 0; + } + *pushIndicators() { + switch (this.charAt(0)) { + case '!': + return ((yield* this.pushTag()) + + (yield* this.pushSpaces(true)) + + (yield* this.pushIndicators())); + case '&': + return ((yield* this.pushUntil(isNotAnchorChar)) + + (yield* this.pushSpaces(true)) + + (yield* this.pushIndicators())); + case '-': // this is an error + case '?': // this is an error outside flow collections + case ':': { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || (inFlow && flowIndicatorChars.has(ch1))) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + return ((yield* this.pushCount(1)) + + (yield* this.pushSpaces(true)) + + (yield* this.pushIndicators())); + } + } + } + return 0; + } + *pushTag() { + if (this.charAt(1) === '<') { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== '>') + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false); + } + else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === '%' && + hexDigits.has(this.buffer[i + 1]) && + hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[(i += 3)]; + } + else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === '\n') + return yield* this.pushCount(1); + else if (ch === '\r' && this.charAt(1) === '\n') + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === ' ' || (allowTabs && ch === '\t')); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +} + +exports.Lexer = Lexer; diff --git a/node_modules/yaml/dist/parse/line-counter.d.ts b/node_modules/yaml/dist/parse/line-counter.d.ts new file mode 100644 index 000000000..b4690958a --- /dev/null +++ b/node_modules/yaml/dist/parse/line-counter.d.ts @@ -0,0 +1,22 @@ +/** + * Tracks newlines during parsing in order to provide an efficient API for + * determining the one-indexed `{ line, col }` position for any offset + * within the input. + */ +export declare class LineCounter { + lineStarts: number[]; + /** + * Should be called in ascending order. Otherwise, call + * `lineCounter.lineStarts.sort()` before calling `linePos()`. + */ + addNewLine: (offset: number) => number; + /** + * Performs a binary search and returns the 1-indexed { line, col } + * position of `offset`. If `line === 0`, `addNewLine` has never been + * called or `offset` is before the first known newline. + */ + linePos: (offset: number) => { + line: number; + col: number; + }; +} diff --git a/node_modules/yaml/dist/parse/line-counter.js b/node_modules/yaml/dist/parse/line-counter.js new file mode 100644 index 000000000..0e7383bde --- /dev/null +++ b/node_modules/yaml/dist/parse/line-counter.js @@ -0,0 +1,41 @@ +'use strict'; + +/** + * Tracks newlines during parsing in order to provide an efficient API for + * determining the one-indexed `{ line, col }` position for any offset + * within the input. + */ +class LineCounter { + constructor() { + this.lineStarts = []; + /** + * Should be called in ascending order. Otherwise, call + * `lineCounter.lineStarts.sort()` before calling `linePos()`. + */ + this.addNewLine = (offset) => this.lineStarts.push(offset); + /** + * Performs a binary search and returns the 1-indexed { line, col } + * position of `offset`. If `line === 0`, `addNewLine` has never been + * called or `offset` is before the first known newline. + */ + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = (low + high) >> 1; // Math.floor((low + high) / 2) + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +} + +exports.LineCounter = LineCounter; diff --git a/node_modules/yaml/dist/parse/parser.d.ts b/node_modules/yaml/dist/parse/parser.d.ts new file mode 100644 index 000000000..b7ab54511 --- /dev/null +++ b/node_modules/yaml/dist/parse/parser.d.ts @@ -0,0 +1,84 @@ +import type { Token } from './cst'; +/** + * A YAML concrete syntax tree (CST) parser + * + * ```ts + * const src: string = ... + * for (const token of new Parser().parse(src)) { + * // token: Token + * } + * ``` + * + * To use the parser with a user-provided lexer: + * + * ```ts + * function* parse(source: string, lexer: Lexer) { + * const parser = new Parser() + * for (const lexeme of lexer.lex(source)) + * yield* parser.next(lexeme) + * yield* parser.end() + * } + * + * const src: string = ... + * const lexer = new Lexer() + * for (const token of parse(src, lexer)) { + * // token: Token + * } + * ``` + */ +export declare class Parser { + private onNewLine?; + /** If true, space and sequence indicators count as indentation */ + private atNewLine; + /** If true, next token is a scalar value */ + private atScalar; + /** Current indentation level */ + private indent; + /** Current offset since the start of parsing */ + offset: number; + /** On the same line with a block map key */ + private onKeyLine; + /** Top indicates the node that's currently being built */ + stack: Token[]; + /** The source of the current token, set in parse() */ + private source; + /** The type of the current token, set in parse() */ + private type; + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine?: (offset: number) => void); + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + parse(source: string, incomplete?: boolean): Generator; + /** + * Advance the parser by the `source` of one lexical token. + */ + next(source: string): Generator; + private lexer; + /** Call at end of input to push out any remaining constructions */ + end(): Generator; + private get sourceToken(); + private step; + private peek; + private pop; + private stream; + private document; + private scalar; + private blockScalar; + private blockMap; + private blockSequence; + private flowCollection; + private flowScalar; + private startBlockValue; + private atIndentedComment; + private documentEnd; + private lineEnd; +} diff --git a/node_modules/yaml/dist/parse/parser.js b/node_modules/yaml/dist/parse/parser.js new file mode 100644 index 000000000..b794303fc --- /dev/null +++ b/node_modules/yaml/dist/parse/parser.js @@ -0,0 +1,972 @@ +'use strict'; + +var node_process = require('process'); +var cst = require('./cst.js'); +var lexer = require('./lexer.js'); + +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case 'space': + case 'comment': + case 'newline': + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + case 'flow-collection': + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case 'document': + return parent.start; + case 'block-map': { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case 'block-seq': + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +/** Note: May modify input array */ +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case 'doc-start': + case 'explicit-key-ind': + case 'map-value-ind': + case 'seq-item-ind': + case 'newline': + break loop; + } + } + while (prev[++i]?.type === 'space') { + /* loop */ + } + return prev.splice(i, prev.length); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === 'flow-seq-start') { + for (const it of fc.items) { + if (it.sep && + !it.value && + !includesToken(it.start, 'explicit-key-ind') && + !includesToken(it.sep, 'map-value-ind')) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + Array.prototype.push.apply(it.value.end, it.sep); + else + it.value.end = it.sep; + } + else + Array.prototype.push.apply(it.start, it.sep); + delete it.sep; + } + } + } +} +/** + * A YAML concrete syntax tree (CST) parser + * + * ```ts + * const src: string = ... + * for (const token of new Parser().parse(src)) { + * // token: Token + * } + * ``` + * + * To use the parser with a user-provided lexer: + * + * ```ts + * function* parse(source: string, lexer: Lexer) { + * const parser = new Parser() + * for (const lexeme of lexer.lex(source)) + * yield* parser.next(lexeme) + * yield* parser.end() + * } + * + * const src: string = ... + * const lexer = new Lexer() + * for (const token of parse(src, lexer)) { + * // token: Token + * } + * ``` + */ +class Parser { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + /** If true, space and sequence indicators count as indentation */ + this.atNewLine = true; + /** If true, next token is a scalar value */ + this.atScalar = false; + /** Current indentation level */ + this.indent = 0; + /** Current offset since the start of parsing */ + this.offset = 0; + /** On the same line with a block map key */ + this.onKeyLine = false; + /** Top indicates the node that's currently being built */ + this.stack = []; + /** The source of the current token, set in parse() */ + this.source = ''; + /** The type of the current token, set in parse() */ + this.type = ''; + // Must be defined after `next()` + this.lexer = new lexer.Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (node_process.env.LOG_TOKENS) + console.log('|', cst.prettyToken(source)); + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = cst.tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: 'error', offset: this.offset, message, source }); + this.offset += source.length; + } + else if (type === 'scalar') { + this.atNewLine = false; + this.atScalar = true; + this.type = 'scalar'; + } + else { + this.type = type; + yield* this.step(); + switch (type) { + case 'newline': + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case 'space': + if (this.atNewLine && source[0] === ' ') + this.indent += source.length; + break; + case 'explicit-key-ind': + case 'map-value-ind': + case 'seq-item-ind': + if (this.atNewLine) + this.indent += source.length; + break; + case 'doc-mode': + case 'flow-error-end': + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === 'doc-end' && top?.type !== 'doc-end') { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: 'doc-end', + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case 'document': + return yield* this.document(top); + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + return yield* this.scalar(top); + case 'block-scalar': + return yield* this.blockScalar(top); + case 'block-map': + return yield* this.blockMap(top); + case 'block-seq': + return yield* this.blockSequence(top); + case 'flow-collection': + return yield* this.flowCollection(top); + case 'doc-end': + return yield* this.documentEnd(top); + } + /* istanbul ignore next should not happen */ + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + /* istanbul ignore if should not happen */ + if (!token) { + const message = 'Tried to pop an empty stack'; + yield { type: 'error', offset: this.offset, source: '', message }; + } + else if (this.stack.length === 0) { + yield token; + } + else { + const top = this.peek(1); + if (token.type === 'block-scalar') { + // Block scalars use their parent rather than header indent + token.indent = 'indent' in top ? top.indent : 0; + } + else if (token.type === 'flow-collection' && top.type === 'document') { + // Ignore all indent for top-level flow collections + token.indent = 0; + } + if (token.type === 'flow-collection') + fixFlowSeqItems(token); + switch (top.type) { + case 'document': + top.value = token; + break; + case 'block-scalar': + top.props.push(token); // error + break; + case 'block-map': { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } + else if (it.sep) { + it.value = token; + } + else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case 'block-seq': { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case 'flow-collection': { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === 'document' || + top.type === 'block-map' || + top.type === 'block-seq') && + (token.type === 'block-map' || token.type === 'block-seq')) { + const last = token.items[token.items.length - 1]; + if (last && + !last.sep && + !last.value && + last.start.length > 0 && + findNonEmptyIndex(last.start) === -1 && + (token.indent === 0 || + last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) { + if (top.type === 'document') + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case 'directive-line': + yield { type: 'directive', offset: this.offset, source: this.source }; + return; + case 'byte-order-mark': + case 'space': + case 'comment': + case 'newline': + yield this.sourceToken; + return; + case 'doc-mode': + case 'doc-start': { + const doc = { + type: 'document', + offset: this.offset, + start: [] + }; + if (this.type === 'doc-start') + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: 'error', + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case 'doc-start': { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } + else + doc.start.push(this.sourceToken); + return; + } + case 'anchor': + case 'tag': + case 'space': + case 'comment': + case 'newline': + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: 'error', + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === 'map-value-ind') { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } + else + sep = [this.sourceToken]; + const map = { + type: 'block-map', + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map; + } + else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case 'space': + case 'comment': + case 'newline': + scalar.props.push(this.sourceToken); + return; + case 'scalar': + scalar.source = this.source; + // block-scalar source includes trailing newline + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf('\n') + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf('\n', nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map) { + const it = map.items[map.items.length - 1]; + // it.sep is true-ish if pair already has key or : separator + switch (this.type) { + case 'newline': + this.onKeyLine = false; + if (it.value) { + const end = 'end' in it.value ? it.value.end : undefined; + const last = Array.isArray(end) ? end[end.length - 1] : undefined; + if (last?.type === 'comment') + end?.push(this.sourceToken); + else + map.items.push({ start: [this.sourceToken] }); + } + else if (it.sep) { + it.sep.push(this.sourceToken); + } + else { + it.start.push(this.sourceToken); + } + return; + case 'space': + case 'comment': + if (it.value) { + map.items.push({ start: [this.sourceToken] }); + } + else if (it.sep) { + it.sep.push(this.sourceToken); + } + else { + if (this.atIndentedComment(it.start, map.indent)) { + const prev = map.items[map.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + map.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map.indent; + const atNextItem = atMapIndent && + (it.sep || it.explicitKey) && + this.type !== 'seq-item-ind'; + // For empty nodes, assign newline-separated not indented empty tokens to following node + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case 'newline': + nl.push(i); + break; + case 'space': + break; + case 'comment': + if (st.indent > map.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case 'anchor': + case 'tag': + if (atNextItem || it.value) { + start.push(this.sourceToken); + map.items.push({ start }); + this.onKeyLine = true; + } + else if (it.sep) { + it.sep.push(this.sourceToken); + } + else { + it.start.push(this.sourceToken); + } + return; + case 'explicit-key-ind': + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } + else if (atNextItem || it.value) { + start.push(this.sourceToken); + map.items.push({ start, explicitKey: true }); + } + else { + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case 'map-value-ind': + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, 'newline')) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } + else { + const start = getFirstKeyStartProps(it.start); + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } + } + else if (it.value) { + map.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } + else if (includesToken(it.sep, 'map-value-ind')) { + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } + else if (isFlowToken(it.key) && + !includesToken(it.sep, 'newline')) { + const start = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + // @ts-expect-error type guard is wrong here + delete it.key; + // @ts-expect-error type guard is wrong here + delete it.sep; + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, key, sep }] + }); + } + else if (start.length > 0) { + // Not actually at next item + it.sep = it.sep.concat(start, this.sourceToken); + } + else { + it.sep.push(this.sourceToken); + } + } + else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } + else if (it.value || atNextItem) { + map.items.push({ start, key: null, sep: [this.sourceToken] }); + } + else if (includesToken(it.sep, 'map-value-ind')) { + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } + else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': { + const fs = this.flowScalar(this.type); + if (atNextItem || it.value) { + map.items.push({ start, key: fs, sep: [] }); + this.onKeyLine = true; + } + else if (it.sep) { + this.stack.push(fs); + } + else { + Object.assign(it, { key: fs, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map); + if (bv) { + if (bv.type === 'block-seq') { + if (!it.explicitKey && + it.sep && + !includesToken(it.sep, 'newline')) { + yield* this.pop({ + type: 'error', + offset: this.offset, + message: 'Unexpected block-seq-ind on same line with key', + source: this.source + }); + return; + } + } + else if (atMapIndent) { + map.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq) { + const it = seq.items[seq.items.length - 1]; + switch (this.type) { + case 'newline': + if (it.value) { + const end = 'end' in it.value ? it.value.end : undefined; + const last = Array.isArray(end) ? end[end.length - 1] : undefined; + if (last?.type === 'comment') + end?.push(this.sourceToken); + else + seq.items.push({ start: [this.sourceToken] }); + } + else + it.start.push(this.sourceToken); + return; + case 'space': + case 'comment': + if (it.value) + seq.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq.indent)) { + const prev = seq.items[seq.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + seq.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case 'anchor': + case 'tag': + if (it.value || this.indent <= seq.indent) + break; + it.start.push(this.sourceToken); + return; + case 'seq-item-ind': + if (this.indent !== seq.indent) + break; + if (it.value || includesToken(it.start, 'seq-item-ind')) + seq.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq.indent) { + const bv = this.startBlockValue(seq); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === 'flow-error-end') { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === 'flow-collection'); + } + else if (fc.end.length === 0) { + switch (this.type) { + case 'comma': + case 'explicit-key-ind': + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case 'map-value-ind': + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case 'space': + case 'comment': + case 'newline': + case 'anchor': + case 'tag': + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': { + const fs = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs, sep: [] }); + else if (it.sep) + this.stack.push(fs); + else + Object.assign(it, { key: fs, sep: [] }); + return; + } + case 'flow-map-end': + case 'flow-seq-end': + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + /* istanbul ignore else should not happen */ + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } + else { + const parent = this.peek(2); + if (parent.type === 'block-map' && + ((this.type === 'map-value-ind' && parent.indent === fc.indent) || + (this.type === 'newline' && + !parent.items[parent.items.length - 1].sep))) { + yield* this.pop(); + yield* this.step(); + } + else if (this.type === 'map-value-ind' && + parent.type !== 'flow-collection') { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map = { + type: 'block-map', + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map; + } + else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf('\n') + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf('\n', nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + return this.flowScalar(this.type); + case 'block-scalar-header': + return { + type: 'block-scalar', + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: '' + }; + case 'flow-map-start': + case 'flow-seq-start': + return { + type: 'flow-collection', + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case 'seq-item-ind': + return { + type: 'block-seq', + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case 'explicit-key-ind': { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case 'map-value-ind': { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== 'comment') + return false; + if (this.indent <= indent) + return false; + return start.every(st => st.type === 'newline' || st.type === 'space'); + } + *documentEnd(docEnd) { + if (this.type !== 'doc-mode') { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === 'newline') + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case 'comma': + case 'doc-start': + case 'doc-end': + case 'flow-seq-end': + case 'flow-map-end': + case 'map-value-ind': + yield* this.pop(); + yield* this.step(); + break; + case 'newline': + this.onKeyLine = false; + // fallthrough + case 'space': + case 'comment': + default: + // all other values are errors + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === 'newline') + yield* this.pop(); + } + } +} + +exports.Parser = Parser; diff --git a/node_modules/yaml/dist/public-api.d.ts b/node_modules/yaml/dist/public-api.d.ts new file mode 100644 index 000000000..fd6dd4590 --- /dev/null +++ b/node_modules/yaml/dist/public-api.d.ts @@ -0,0 +1,44 @@ +import { Composer } from './compose/composer'; +import type { Reviver } from './doc/applyReviver'; +import type { Replacer } from './doc/Document'; +import { Document } from './doc/Document'; +import type { Node, ParsedNode } from './nodes/Node'; +import type { CreateNodeOptions, DocumentOptions, ParseOptions, SchemaOptions, ToJSOptions, ToStringOptions } from './options'; +export interface EmptyStream extends Array, ReturnType { + empty: true; +} +/** + * Parse the input as a stream of YAML documents. + * + * Documents should be separated from each other by `...` or `---` marker lines. + * + * @returns If an empty `docs` array is returned, it will be of type + * EmptyStream and contain additional stream information. In + * TypeScript, you should use `'empty' in docs` as a type guard for it. + */ +export declare function parseAllDocuments(source: string, options?: ParseOptions & DocumentOptions & SchemaOptions): Array : Document> | EmptyStream; +/** Parse an input string into a single YAML.Document */ +export declare function parseDocument(source: string, options?: ParseOptions & DocumentOptions & SchemaOptions): Contents extends ParsedNode ? Document.Parsed : Document; +/** + * Parse an input string into JavaScript. + * + * Only supports input consisting of a single YAML document; for multi-document + * support you should use `YAML.parseAllDocuments`. May throw on error, and may + * log warnings using `console.warn`. + * + * @param str - A string with YAML formatting. + * @param reviver - A reviver function, as in `JSON.parse()` + * @returns The value will match the type of the root value of the parsed YAML + * document, so Maps become objects, Sequences arrays, and scalars result in + * nulls, booleans, numbers and strings. + */ +export declare function parse(src: string, options?: ParseOptions & DocumentOptions & SchemaOptions & ToJSOptions): any; +export declare function parse(src: string, reviver: Reviver, options?: ParseOptions & DocumentOptions & SchemaOptions & ToJSOptions): any; +/** + * Stringify a value as a YAML document. + * + * @param replacer - A replacer array or function, as in `JSON.stringify()` + * @returns Will always include `\n` as the last character, as is expected of YAML documents. + */ +export declare function stringify(value: any, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions & ToStringOptions): string; +export declare function stringify(value: any, replacer?: Replacer | null, options?: string | number | (DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions & ToStringOptions)): string; diff --git a/node_modules/yaml/dist/public-api.js b/node_modules/yaml/dist/public-api.js new file mode 100644 index 000000000..db76cefdc --- /dev/null +++ b/node_modules/yaml/dist/public-api.js @@ -0,0 +1,107 @@ +'use strict'; + +var composer = require('./compose/composer.js'); +var Document = require('./doc/Document.js'); +var errors = require('./errors.js'); +var log = require('./log.js'); +var identity = require('./nodes/identity.js'); +var lineCounter = require('./parse/line-counter.js'); +var parser = require('./parse/parser.js'); + +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter$1 = options.lineCounter || (prettyErrors && new lineCounter.LineCounter()) || null; + return { lineCounter: lineCounter$1, prettyErrors }; +} +/** + * Parse the input as a stream of YAML documents. + * + * Documents should be separated from each other by `...` or `---` marker lines. + * + * @returns If an empty `docs` array is returned, it will be of type + * EmptyStream and contain additional stream information. In + * TypeScript, you should use `'empty' in docs` as a type guard for it. + */ +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser$1 = new parser.Parser(lineCounter?.addNewLine); + const composer$1 = new composer.Composer(options); + const docs = Array.from(composer$1.compose(parser$1.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(errors.prettifyError(source, lineCounter)); + doc.warnings.forEach(errors.prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer$1.streamInfo()); +} +/** Parse an input string into a single YAML.Document */ +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser$1 = new parser.Parser(lineCounter?.addNewLine); + const composer$1 = new composer.Composer(options); + // `doc` is always set by compose.end(true) at the very latest + let doc = null; + for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== 'silent') { + doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()')); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(errors.prettifyError(source, lineCounter)); + doc.warnings.forEach(errors.prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = undefined; + if (typeof reviver === 'function') { + _reviver = reviver; + } + else if (options === undefined && reviver && typeof reviver === 'object') { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach(warning => log.warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== 'silent') + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify(value, replacer, options) { + let _replacer = null; + if (typeof replacer === 'function' || Array.isArray(replacer)) { + _replacer = replacer; + } + else if (options === undefined && replacer) { + options = replacer; + } + if (typeof options === 'string') + options = options.length; + if (typeof options === 'number') { + const indent = Math.round(options); + options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent }; + } + if (value === undefined) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return undefined; + } + if (identity.isDocument(value) && !_replacer) + return value.toString(options); + return new Document.Document(value, _replacer, options).toString(options); +} + +exports.parse = parse; +exports.parseAllDocuments = parseAllDocuments; +exports.parseDocument = parseDocument; +exports.stringify = stringify; diff --git a/node_modules/yaml/dist/schema/Schema.d.ts b/node_modules/yaml/dist/schema/Schema.d.ts new file mode 100644 index 000000000..cb6c3ed61 --- /dev/null +++ b/node_modules/yaml/dist/schema/Schema.d.ts @@ -0,0 +1,17 @@ +import { MAP, SCALAR, SEQ } from '../nodes/identity'; +import type { Pair } from '../nodes/Pair'; +import type { SchemaOptions, ToStringOptions } from '../options'; +import type { CollectionTag, ScalarTag } from './types'; +export declare class Schema { + compat: Array | null; + knownTags: Record; + name: string; + sortMapEntries: ((a: Pair, b: Pair) => number) | null; + tags: Array; + toStringOptions: Readonly | null; + readonly [MAP]: CollectionTag; + readonly [SCALAR]: ScalarTag; + readonly [SEQ]: CollectionTag; + constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions); + clone(): Schema; +} diff --git a/node_modules/yaml/dist/schema/Schema.js b/node_modules/yaml/dist/schema/Schema.js new file mode 100644 index 000000000..392654702 --- /dev/null +++ b/node_modules/yaml/dist/schema/Schema.js @@ -0,0 +1,39 @@ +'use strict'; + +var identity = require('../nodes/identity.js'); +var map = require('./common/map.js'); +var seq = require('./common/seq.js'); +var string = require('./common/string.js'); +var tags = require('./tags.js'); + +const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +class Schema { + constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) + ? tags.getTags(compat, 'compat') + : compat + ? tags.getTags(null, compat) + : null; + this.name = (typeof schema === 'string' && schema) || 'core'; + this.knownTags = resolveKnownTags ? tags.coreKnownTags : {}; + this.tags = tags.getTags(customTags, this.name, merge); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, identity.MAP, { value: map.map }); + Object.defineProperty(this, identity.SCALAR, { value: string.string }); + Object.defineProperty(this, identity.SEQ, { value: seq.seq }); + // Used by createMap() + this.sortMapEntries = + typeof sortMapEntries === 'function' + ? sortMapEntries + : sortMapEntries === true + ? sortMapEntriesByKey + : null; + } + clone() { + const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy.tags = this.tags.slice(); + return copy; + } +} + +exports.Schema = Schema; diff --git a/node_modules/yaml/dist/schema/common/map.d.ts b/node_modules/yaml/dist/schema/common/map.d.ts new file mode 100644 index 000000000..5db47c559 --- /dev/null +++ b/node_modules/yaml/dist/schema/common/map.d.ts @@ -0,0 +1,2 @@ +import type { CollectionTag } from '../types'; +export declare const map: CollectionTag; diff --git a/node_modules/yaml/dist/schema/common/map.js b/node_modules/yaml/dist/schema/common/map.js new file mode 100644 index 000000000..649c3b973 --- /dev/null +++ b/node_modules/yaml/dist/schema/common/map.js @@ -0,0 +1,19 @@ +'use strict'; + +var identity = require('../../nodes/identity.js'); +var YAMLMap = require('../../nodes/YAMLMap.js'); + +const map = { + collection: 'map', + default: true, + nodeClass: YAMLMap.YAMLMap, + tag: 'tag:yaml.org,2002:map', + resolve(map, onError) { + if (!identity.isMap(map)) + onError('Expected a mapping for this tag'); + return map; + }, + createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx) +}; + +exports.map = map; diff --git a/node_modules/yaml/dist/schema/common/null.d.ts b/node_modules/yaml/dist/schema/common/null.d.ts new file mode 100644 index 000000000..66f9f8393 --- /dev/null +++ b/node_modules/yaml/dist/schema/common/null.d.ts @@ -0,0 +1,4 @@ +import type { ScalarTag } from '../types'; +export declare const nullTag: ScalarTag & { + test: RegExp; +}; diff --git a/node_modules/yaml/dist/schema/common/null.js b/node_modules/yaml/dist/schema/common/null.js new file mode 100644 index 000000000..cb353a7a7 --- /dev/null +++ b/node_modules/yaml/dist/schema/common/null.js @@ -0,0 +1,17 @@ +'use strict'; + +var Scalar = require('../../nodes/Scalar.js'); + +const nullTag = { + identify: value => value == null, + createNode: () => new Scalar.Scalar(null), + default: true, + tag: 'tag:yaml.org,2002:null', + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar.Scalar(null), + stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source) + ? source + : ctx.options.nullStr +}; + +exports.nullTag = nullTag; diff --git a/node_modules/yaml/dist/schema/common/seq.d.ts b/node_modules/yaml/dist/schema/common/seq.d.ts new file mode 100644 index 000000000..fc8f562d1 --- /dev/null +++ b/node_modules/yaml/dist/schema/common/seq.d.ts @@ -0,0 +1,2 @@ +import type { CollectionTag } from '../types'; +export declare const seq: CollectionTag; diff --git a/node_modules/yaml/dist/schema/common/seq.js b/node_modules/yaml/dist/schema/common/seq.js new file mode 100644 index 000000000..9c54bc96a --- /dev/null +++ b/node_modules/yaml/dist/schema/common/seq.js @@ -0,0 +1,19 @@ +'use strict'; + +var identity = require('../../nodes/identity.js'); +var YAMLSeq = require('../../nodes/YAMLSeq.js'); + +const seq = { + collection: 'seq', + default: true, + nodeClass: YAMLSeq.YAMLSeq, + tag: 'tag:yaml.org,2002:seq', + resolve(seq, onError) { + if (!identity.isSeq(seq)) + onError('Expected a sequence for this tag'); + return seq; + }, + createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx) +}; + +exports.seq = seq; diff --git a/node_modules/yaml/dist/schema/common/string.d.ts b/node_modules/yaml/dist/schema/common/string.d.ts new file mode 100644 index 000000000..d03dc8999 --- /dev/null +++ b/node_modules/yaml/dist/schema/common/string.d.ts @@ -0,0 +1,2 @@ +import type { ScalarTag } from '../types'; +export declare const string: ScalarTag; diff --git a/node_modules/yaml/dist/schema/common/string.js b/node_modules/yaml/dist/schema/common/string.js new file mode 100644 index 000000000..760142009 --- /dev/null +++ b/node_modules/yaml/dist/schema/common/string.js @@ -0,0 +1,16 @@ +'use strict'; + +var stringifyString = require('../../stringify/stringifyString.js'); + +const string = { + identify: value => typeof value === 'string', + default: true, + tag: 'tag:yaml.org,2002:str', + resolve: str => str, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString.stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +exports.string = string; diff --git a/node_modules/yaml/dist/schema/core/bool.d.ts b/node_modules/yaml/dist/schema/core/bool.d.ts new file mode 100644 index 000000000..36c614985 --- /dev/null +++ b/node_modules/yaml/dist/schema/core/bool.d.ts @@ -0,0 +1,4 @@ +import type { ScalarTag } from '../types'; +export declare const boolTag: ScalarTag & { + test: RegExp; +}; diff --git a/node_modules/yaml/dist/schema/core/bool.js b/node_modules/yaml/dist/schema/core/bool.js new file mode 100644 index 000000000..4def73c7f --- /dev/null +++ b/node_modules/yaml/dist/schema/core/bool.js @@ -0,0 +1,21 @@ +'use strict'; + +var Scalar = require('../../nodes/Scalar.js'); + +const boolTag = { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: str => new Scalar.Scalar(str[0] === 't' || str[0] === 'T'), + stringify({ source, value }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === 't' || source[0] === 'T'; + if (value === sv) + return source; + } + return value ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +exports.boolTag = boolTag; diff --git a/node_modules/yaml/dist/schema/core/float.d.ts b/node_modules/yaml/dist/schema/core/float.d.ts new file mode 100644 index 000000000..6e5412b84 --- /dev/null +++ b/node_modules/yaml/dist/schema/core/float.d.ts @@ -0,0 +1,4 @@ +import type { ScalarTag } from '../types'; +export declare const floatNaN: ScalarTag; +export declare const floatExp: ScalarTag; +export declare const float: ScalarTag; diff --git a/node_modules/yaml/dist/schema/core/float.js b/node_modules/yaml/dist/schema/core/float.js new file mode 100644 index 000000000..8756446e4 --- /dev/null +++ b/node_modules/yaml/dist/schema/core/float.js @@ -0,0 +1,47 @@ +'use strict'; + +var Scalar = require('../../nodes/Scalar.js'); +var stringifyNumber = require('../../stringify/stringifyNumber.js'); + +const floatNaN = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: str => str.slice(-3).toLowerCase() === 'nan' + ? NaN + : str[0] === '-' + ? Number.NEGATIVE_INFINITY + : Number.POSITIVE_INFINITY, + stringify: stringifyNumber.stringifyNumber +}; +const floatExp = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'EXP', + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: str => parseFloat(str), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); + } +}; +const float = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str) { + const node = new Scalar.Scalar(parseFloat(str)); + const dot = str.indexOf('.'); + if (dot !== -1 && str[str.length - 1] === '0') + node.minFractionDigits = str.length - dot - 1; + return node; + }, + stringify: stringifyNumber.stringifyNumber +}; + +exports.float = float; +exports.floatExp = floatExp; +exports.floatNaN = floatNaN; diff --git a/node_modules/yaml/dist/schema/core/int.d.ts b/node_modules/yaml/dist/schema/core/int.d.ts new file mode 100644 index 000000000..fb884bb8b --- /dev/null +++ b/node_modules/yaml/dist/schema/core/int.d.ts @@ -0,0 +1,4 @@ +import type { ScalarTag } from '../types'; +export declare const intOct: ScalarTag; +export declare const int: ScalarTag; +export declare const intHex: ScalarTag; diff --git a/node_modules/yaml/dist/schema/core/int.js b/node_modules/yaml/dist/schema/core/int.js new file mode 100644 index 000000000..fe4c9ca1a --- /dev/null +++ b/node_modules/yaml/dist/schema/core/int.js @@ -0,0 +1,42 @@ +'use strict'; + +var stringifyNumber = require('../../stringify/stringifyNumber.js'); + +const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value); +const intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix)); +function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value) && value >= 0) + return prefix + value.toString(radix); + return stringifyNumber.stringifyNumber(node); +} +const intOct = { + identify: value => intIdentify(value) && value >= 0, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'OCT', + test: /^0o[0-7]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt), + stringify: node => intStringify(node, 8, '0o') +}; +const int = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^[-+]?[0-9]+$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber.stringifyNumber +}; +const intHex = { + identify: value => intIdentify(value) && value >= 0, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'HEX', + test: /^0x[0-9a-fA-F]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: node => intStringify(node, 16, '0x') +}; + +exports.int = int; +exports.intHex = intHex; +exports.intOct = intOct; diff --git a/node_modules/yaml/dist/schema/core/schema.d.ts b/node_modules/yaml/dist/schema/core/schema.d.ts new file mode 100644 index 000000000..0d21e5690 --- /dev/null +++ b/node_modules/yaml/dist/schema/core/schema.d.ts @@ -0,0 +1 @@ +export declare const schema: (import('../types').CollectionTag | import('../types').ScalarTag)[]; diff --git a/node_modules/yaml/dist/schema/core/schema.js b/node_modules/yaml/dist/schema/core/schema.js new file mode 100644 index 000000000..6ab87f2cc --- /dev/null +++ b/node_modules/yaml/dist/schema/core/schema.js @@ -0,0 +1,25 @@ +'use strict'; + +var map = require('../common/map.js'); +var _null = require('../common/null.js'); +var seq = require('../common/seq.js'); +var string = require('../common/string.js'); +var bool = require('./bool.js'); +var float = require('./float.js'); +var int = require('./int.js'); + +const schema = [ + map.map, + seq.seq, + string.string, + _null.nullTag, + bool.boolTag, + int.intOct, + int.int, + int.intHex, + float.floatNaN, + float.floatExp, + float.float +]; + +exports.schema = schema; diff --git a/node_modules/yaml/dist/schema/json-schema.d.ts b/node_modules/yaml/dist/schema/json-schema.d.ts new file mode 100644 index 000000000..6d51f40b5 --- /dev/null +++ b/node_modules/yaml/dist/schema/json-schema.d.ts @@ -0,0 +1,69 @@ +type JsonSchema = boolean | ArraySchema | ObjectSchema | NumberSchema | StringSchema; +type JsonType = 'array' | 'object' | 'string' | 'number' | 'integer' | 'boolean' | 'null'; +interface CommonSchema { + type?: JsonType | JsonType[]; + const?: unknown; + enum?: unknown[]; + format?: string; + allOf?: JsonSchema[]; + anyOf?: JsonSchema[]; + oneOf?: JsonSchema[]; + not?: JsonSchema; + if?: JsonSchema; + then?: JsonSchema; + else?: JsonSchema; + $id?: string; + $defs?: Record; + $anchor?: string; + $dynamicAnchor?: string; + $ref?: string; + $dynamicRef?: string; + $schema?: string; + $vocabulary?: Record; + $comment?: string; + default?: unknown; + deprecated?: boolean; + readOnly?: boolean; + writeOnly?: boolean; + title?: string; + description?: string; + examples?: unknown[]; +} +interface ArraySchema extends CommonSchema { + prefixItems?: JsonSchema[]; + items?: JsonSchema; + contains?: JsonSchema; + unevaluatedItems?: JsonSchema; + maxItems?: number; + minItems?: number; + uniqueItems?: boolean; + maxContains?: number; + minContains?: number; +} +interface ObjectSchema extends CommonSchema { + properties?: Record; + patternProperties?: Record; + additionalProperties?: JsonSchema; + propertyNames?: JsonSchema; + unevaluatedProperties?: JsonSchema; + maxProperties?: number; + minProperties?: number; + required?: string[]; + dependentRequired?: Record; + dependentSchemas?: Record; +} +interface StringSchema extends CommonSchema { + maxLength?: number; + minLength?: number; + patter?: string; + contentEncoding?: string; + contentMediaType?: string; + contentSchema?: JsonSchema; +} +interface NumberSchema extends CommonSchema { + multipleOf?: number; + maximum?: number; + exclusiveMaximum?: number; + minimum?: number; + exclusiveMinimum?: number; +} diff --git a/node_modules/yaml/dist/schema/json/schema.d.ts b/node_modules/yaml/dist/schema/json/schema.d.ts new file mode 100644 index 000000000..5c18c611d --- /dev/null +++ b/node_modules/yaml/dist/schema/json/schema.d.ts @@ -0,0 +1,2 @@ +import type { CollectionTag, ScalarTag } from '../types'; +export declare const schema: (CollectionTag | ScalarTag)[]; diff --git a/node_modules/yaml/dist/schema/json/schema.js b/node_modules/yaml/dist/schema/json/schema.js new file mode 100644 index 000000000..ccb871afb --- /dev/null +++ b/node_modules/yaml/dist/schema/json/schema.js @@ -0,0 +1,64 @@ +'use strict'; + +var Scalar = require('../../nodes/Scalar.js'); +var map = require('../common/map.js'); +var seq = require('../common/seq.js'); + +function intIdentify(value) { + return typeof value === 'bigint' || Number.isInteger(value); +} +const stringifyJSON = ({ value }) => JSON.stringify(value); +const jsonScalars = [ + { + identify: value => typeof value === 'string', + default: true, + tag: 'tag:yaml.org,2002:str', + resolve: str => str, + stringify: stringifyJSON + }, + { + identify: value => value == null, + createNode: () => new Scalar.Scalar(null), + default: true, + tag: 'tag:yaml.org,2002:null', + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^true$|^false$/, + resolve: str => str === 'true', + stringify: stringifyJSON + }, + { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value) + }, + { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: str => parseFloat(str), + stringify: stringifyJSON + } +]; +const jsonError = { + default: true, + tag: '', + test: /^/, + resolve(str, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str)}`); + return str; + } +}; +const schema = [map.map, seq.seq].concat(jsonScalars, jsonError); + +exports.schema = schema; diff --git a/node_modules/yaml/dist/schema/tags.d.ts b/node_modules/yaml/dist/schema/tags.d.ts new file mode 100644 index 000000000..01cf33f4d --- /dev/null +++ b/node_modules/yaml/dist/schema/tags.d.ts @@ -0,0 +1,48 @@ +import type { SchemaOptions } from '../options'; +import type { CollectionTag, ScalarTag } from './types'; +declare const tagsByName: { + binary: ScalarTag; + bool: ScalarTag & { + test: RegExp; + }; + float: ScalarTag; + floatExp: ScalarTag; + floatNaN: ScalarTag; + floatTime: ScalarTag; + int: ScalarTag; + intHex: ScalarTag; + intOct: ScalarTag; + intTime: ScalarTag; + map: CollectionTag; + merge: ScalarTag & { + identify(value: unknown): boolean; + test: RegExp; + }; + null: ScalarTag & { + test: RegExp; + }; + omap: CollectionTag; + pairs: CollectionTag; + seq: CollectionTag; + set: CollectionTag; + timestamp: ScalarTag & { + test: RegExp; + }; +}; +export type TagId = keyof typeof tagsByName; +export type Tags = Array; +export declare const coreKnownTags: { + 'tag:yaml.org,2002:binary': ScalarTag; + 'tag:yaml.org,2002:merge': ScalarTag & { + identify(value: unknown): boolean; + test: RegExp; + }; + 'tag:yaml.org,2002:omap': CollectionTag; + 'tag:yaml.org,2002:pairs': CollectionTag; + 'tag:yaml.org,2002:set': CollectionTag; + 'tag:yaml.org,2002:timestamp': ScalarTag & { + test: RegExp; + }; +}; +export declare function getTags(customTags: SchemaOptions['customTags'] | undefined, schemaName: string, addMergeTag?: boolean): (CollectionTag | ScalarTag)[]; +export {}; diff --git a/node_modules/yaml/dist/schema/tags.js b/node_modules/yaml/dist/schema/tags.js new file mode 100644 index 000000000..bd67d864f --- /dev/null +++ b/node_modules/yaml/dist/schema/tags.js @@ -0,0 +1,99 @@ +'use strict'; + +var map = require('./common/map.js'); +var _null = require('./common/null.js'); +var seq = require('./common/seq.js'); +var string = require('./common/string.js'); +var bool = require('./core/bool.js'); +var float = require('./core/float.js'); +var int = require('./core/int.js'); +var schema = require('./core/schema.js'); +var schema$1 = require('./json/schema.js'); +var binary = require('./yaml-1.1/binary.js'); +var merge = require('./yaml-1.1/merge.js'); +var omap = require('./yaml-1.1/omap.js'); +var pairs = require('./yaml-1.1/pairs.js'); +var schema$2 = require('./yaml-1.1/schema.js'); +var set = require('./yaml-1.1/set.js'); +var timestamp = require('./yaml-1.1/timestamp.js'); + +const schemas = new Map([ + ['core', schema.schema], + ['failsafe', [map.map, seq.seq, string.string]], + ['json', schema$1.schema], + ['yaml11', schema$2.schema], + ['yaml-1.1', schema$2.schema] +]); +const tagsByName = { + binary: binary.binary, + bool: bool.boolTag, + float: float.float, + floatExp: float.floatExp, + floatNaN: float.floatNaN, + floatTime: timestamp.floatTime, + int: int.int, + intHex: int.intHex, + intOct: int.intOct, + intTime: timestamp.intTime, + map: map.map, + merge: merge.merge, + null: _null.nullTag, + omap: omap.omap, + pairs: pairs.pairs, + seq: seq.seq, + set: set.set, + timestamp: timestamp.timestamp +}; +const coreKnownTags = { + 'tag:yaml.org,2002:binary': binary.binary, + 'tag:yaml.org,2002:merge': merge.merge, + 'tag:yaml.org,2002:omap': omap.omap, + 'tag:yaml.org,2002:pairs': pairs.pairs, + 'tag:yaml.org,2002:set': set.set, + 'tag:yaml.org,2002:timestamp': timestamp.timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge.merge) + ? schemaTags.concat(merge.merge) + : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()) + .filter(key => key !== 'yaml11') + .map(key => JSON.stringify(key)) + .join(', '); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } + else if (typeof customTags === 'function') { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge.merge); + return tags.reduce((tags, tag) => { + const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName) + .map(key => JSON.stringify(key)) + .join(', '); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags.includes(tagObj)) + tags.push(tagObj); + return tags; + }, []); +} + +exports.coreKnownTags = coreKnownTags; +exports.getTags = getTags; diff --git a/node_modules/yaml/dist/schema/types.d.ts b/node_modules/yaml/dist/schema/types.d.ts new file mode 100644 index 000000000..631cc53fc --- /dev/null +++ b/node_modules/yaml/dist/schema/types.d.ts @@ -0,0 +1,92 @@ +import type { CreateNodeContext } from '../doc/createNode'; +import type { Node } from '../nodes/Node'; +import type { Scalar } from '../nodes/Scalar'; +import type { YAMLMap } from '../nodes/YAMLMap'; +import type { YAMLSeq } from '../nodes/YAMLSeq'; +import type { ParseOptions } from '../options'; +import type { StringifyContext } from '../stringify/stringify'; +import type { Schema } from './Schema'; +interface TagBase { + /** + * An optional factory function, used e.g. by collections when wrapping JS objects as AST nodes. + */ + createNode?: (schema: Schema, value: unknown, ctx: CreateNodeContext) => Node; + /** + * If `true`, allows for values to be stringified without + * an explicit tag together with `test`. + * If `'key'`, this only applies if the value is used as a mapping key. + * For most cases, it's unlikely that you'll actually want to use this, + * even if you first think you do. + */ + default?: boolean | 'key'; + /** + * If a tag has multiple forms that should be parsed and/or stringified + * differently, use `format` to identify them. + */ + format?: string; + /** + * Used by `YAML.createNode` to detect your data type, e.g. using `typeof` or + * `instanceof`. + */ + identify?: (value: unknown) => boolean; + /** + * The identifier for your data type, with which its stringified form will be + * prefixed. Should either be a !-prefixed local `!tag`, or a fully qualified + * `tag:domain,date:foo`. + */ + tag: string; +} +export interface ScalarTag extends TagBase { + collection?: never; + nodeClass?: never; + /** + * Turns a value into an AST node. + * If returning a non-`Node` value, the output will be wrapped as a `Scalar`. + */ + resolve(value: string, onError: (message: string) => void, options: ParseOptions): unknown; + /** + * Optional function stringifying a Scalar node. If your data includes a + * suitable `.toString()` method, you can probably leave this undefined and + * use the default stringifier. + * + * @param item The node being stringified. + * @param ctx Contains the stringifying context variables. + * @param onComment Callback to signal that the stringifier includes the + * item's comment in its output. + * @param onChompKeep Callback to signal that the output uses a block scalar + * type with the `+` chomping indicator. + */ + stringify?: (item: Scalar, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void) => string; + /** + * Together with `default` allows for values to be stringified without an + * explicit tag and detected using a regular expression. For most cases, it's + * unlikely that you'll actually want to use these, even if you first think + * you do. + */ + test?: RegExp; +} +export interface CollectionTag extends TagBase { + stringify?: never; + test?: never; + /** The source collection type supported by this tag. */ + collection: 'map' | 'seq'; + /** + * The `Node` child class that implements this tag. + * If set, used to select this tag when stringifying. + * + * If the class provides a static `from` method, then that + * will be used if the tag object doesn't have a `createNode` method. + */ + nodeClass?: { + new (schema?: Schema): Node; + from?: (schema: Schema, obj: unknown, ctx: CreateNodeContext) => Node; + }; + /** + * Turns a value into an AST node. + * If returning a non-`Node` value, the output will be wrapped as a `Scalar`. + * + * Note: this is required if nodeClass is not provided. + */ + resolve?: (value: YAMLMap.Parsed | YAMLSeq.Parsed, onError: (message: string) => void, options: ParseOptions) => unknown; +} +export {}; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/binary.d.ts b/node_modules/yaml/dist/schema/yaml-1.1/binary.d.ts new file mode 100644 index 000000000..6a7e60b52 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/binary.d.ts @@ -0,0 +1,2 @@ +import type { ScalarTag } from '../types'; +export declare const binary: ScalarTag; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/binary.js b/node_modules/yaml/dist/schema/yaml-1.1/binary.js new file mode 100644 index 000000000..e529d7493 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/binary.js @@ -0,0 +1,70 @@ +'use strict'; + +var node_buffer = require('buffer'); +var Scalar = require('../../nodes/Scalar.js'); +var stringifyString = require('../../stringify/stringifyString.js'); + +const binary = { + identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array + default: false, + tag: 'tag:yaml.org,2002:binary', + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof node_buffer.Buffer === 'function') { + return node_buffer.Buffer.from(src, 'base64'); + } + else if (typeof atob === 'function') { + // On IE 11, atob() can't handle newlines + const str = atob(src.replace(/[\n\r]/g, '')); + const buffer = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) + buffer[i] = str.charCodeAt(i); + return buffer; + } + else { + onError('This environment does not support reading binary tags; either Buffer or atob is required'); + return src; + } + }, + stringify({ comment, type, value }, ctx, onComment, onChompKeep) { + if (!value) + return ''; + const buf = value; // checked earlier by binary.identify() + let str; + if (typeof node_buffer.Buffer === 'function') { + str = + buf instanceof node_buffer.Buffer + ? buf.toString('base64') + : node_buffer.Buffer.from(buf.buffer).toString('base64'); + } + else if (typeof btoa === 'function') { + let s = ''; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str = btoa(s); + } + else { + throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required'); + } + type ?? (type = Scalar.Scalar.BLOCK_LITERAL); + if (type !== Scalar.Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str.length / lineWidth); + const lines = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines[i] = str.substr(o, lineWidth); + } + str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? '\n' : ' '); + } + return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep); + } +}; + +exports.binary = binary; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/bool.d.ts b/node_modules/yaml/dist/schema/yaml-1.1/bool.d.ts new file mode 100644 index 000000000..5208456c1 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/bool.d.ts @@ -0,0 +1,7 @@ +import type { ScalarTag } from '../types'; +export declare const trueTag: ScalarTag & { + test: RegExp; +}; +export declare const falseTag: ScalarTag & { + test: RegExp; +}; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/bool.js b/node_modules/yaml/dist/schema/yaml-1.1/bool.js new file mode 100644 index 000000000..d98795263 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/bool.js @@ -0,0 +1,29 @@ +'use strict'; + +var Scalar = require('../../nodes/Scalar.js'); + +function boolStringify({ value, source }, ctx) { + const boolObj = value ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value ? ctx.options.trueStr : ctx.options.falseStr; +} +const trueTag = { + identify: value => value === true, + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar.Scalar(true), + stringify: boolStringify +}; +const falseTag = { + identify: value => value === false, + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar.Scalar(false), + stringify: boolStringify +}; + +exports.falseTag = falseTag; +exports.trueTag = trueTag; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/float.d.ts b/node_modules/yaml/dist/schema/yaml-1.1/float.d.ts new file mode 100644 index 000000000..6e5412b84 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/float.d.ts @@ -0,0 +1,4 @@ +import type { ScalarTag } from '../types'; +export declare const floatNaN: ScalarTag; +export declare const floatExp: ScalarTag; +export declare const float: ScalarTag; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/float.js b/node_modules/yaml/dist/schema/yaml-1.1/float.js new file mode 100644 index 000000000..39f1eb0c9 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/float.js @@ -0,0 +1,50 @@ +'use strict'; + +var Scalar = require('../../nodes/Scalar.js'); +var stringifyNumber = require('../../stringify/stringifyNumber.js'); + +const floatNaN = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === 'nan' + ? NaN + : str[0] === '-' + ? Number.NEGATIVE_INFINITY + : Number.POSITIVE_INFINITY, + stringify: stringifyNumber.stringifyNumber +}; +const floatExp = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'EXP', + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str.replace(/_/g, '')), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); + } +}; +const float = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str) { + const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, ''))); + const dot = str.indexOf('.'); + if (dot !== -1) { + const f = str.substring(dot + 1).replace(/_/g, ''); + if (f[f.length - 1] === '0') + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber.stringifyNumber +}; + +exports.float = float; +exports.floatExp = floatExp; +exports.floatNaN = floatNaN; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/int.d.ts b/node_modules/yaml/dist/schema/yaml-1.1/int.d.ts new file mode 100644 index 000000000..22461ed67 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/int.d.ts @@ -0,0 +1,5 @@ +import type { ScalarTag } from '../types'; +export declare const intBin: ScalarTag; +export declare const intOct: ScalarTag; +export declare const int: ScalarTag; +export declare const intHex: ScalarTag; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/int.js b/node_modules/yaml/dist/schema/yaml-1.1/int.js new file mode 100644 index 000000000..fdf47ca68 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/int.js @@ -0,0 +1,76 @@ +'use strict'; + +var stringifyNumber = require('../../stringify/stringifyNumber.js'); + +const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value); +function intResolve(str, offset, radix, { intAsBigInt }) { + const sign = str[0]; + if (sign === '-' || sign === '+') + offset += 1; + str = str.substring(offset).replace(/_/g, ''); + if (intAsBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + case 8: + str = `0o${str}`; + break; + case 16: + str = `0x${str}`; + break; + } + const n = BigInt(str); + return sign === '-' ? BigInt(-1) * n : n; + } + const n = parseInt(str, radix); + return sign === '-' ? -1 * n : n; +} +function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? '-' + prefix + str.substr(1) : prefix + str; + } + return stringifyNumber.stringifyNumber(node); +} +const intBin = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'BIN', + test: /^[-+]?0b[0-1_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt), + stringify: node => intStringify(node, 2, '0b') +}; +const intOct = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'OCT', + test: /^[-+]?0[0-7_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt), + stringify: node => intStringify(node, 8, '0') +}; +const int = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber.stringifyNumber +}; +const intHex = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'HEX', + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: node => intStringify(node, 16, '0x') +}; + +exports.int = int; +exports.intBin = intBin; +exports.intHex = intHex; +exports.intOct = intOct; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/merge.d.ts b/node_modules/yaml/dist/schema/yaml-1.1/merge.d.ts new file mode 100644 index 000000000..8ade17125 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/merge.d.ts @@ -0,0 +1,9 @@ +import type { ToJSContext } from '../../nodes/toJS'; +import type { MapLike } from '../../nodes/YAMLMap'; +import type { ScalarTag } from '../types'; +export declare const merge: ScalarTag & { + identify(value: unknown): boolean; + test: RegExp; +}; +export declare const isMergeKey: (ctx: ToJSContext | undefined, key: unknown) => boolean | undefined; +export declare function addMergeToJSMap(ctx: ToJSContext | undefined, map: MapLike, value: unknown): void; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/merge.js b/node_modules/yaml/dist/schema/yaml-1.1/merge.js new file mode 100644 index 000000000..ef2ff3247 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/merge.js @@ -0,0 +1,68 @@ +'use strict'; + +var identity = require('../../nodes/identity.js'); +var Scalar = require('../../nodes/Scalar.js'); + +// If the value associated with a merge key is a single mapping node, each of +// its key/value pairs is inserted into the current mapping, unless the key +// already exists in it. If the value associated with the merge key is a +// sequence, then this sequence is expected to contain mapping nodes and each +// of these nodes is merged in turn according to its order in the sequence. +// Keys in mapping nodes earlier in the sequence override keys specified in +// later mapping nodes. -- http://yaml.org/type/merge.html +const MERGE_KEY = '<<'; +const merge = { + identify: value => value === MERGE_KEY || + (typeof value === 'symbol' && value.description === MERGE_KEY), + default: 'key', + tag: 'tag:yaml.org,2002:merge', + test: /^<<$/, + resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +const isMergeKey = (ctx, key) => (merge.identify(key) || + (identity.isScalar(key) && + (!key.type || key.type === Scalar.Scalar.PLAIN) && + merge.identify(key.value))) && + ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default); +function addMergeToJSMap(ctx, map, value) { + value = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value; + if (identity.isSeq(value)) + for (const it of value.items) + mergeValue(ctx, map, it); + else if (Array.isArray(value)) + for (const it of value) + mergeValue(ctx, map, it); + else + mergeValue(ctx, map, value); +} +function mergeValue(ctx, map, value) { + const source = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value; + if (!identity.isMap(source)) + throw new Error('Merge sources must be maps or map aliases'); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value] of srcMap) { + if (map instanceof Map) { + if (!map.has(key)) + map.set(key, value); + } + else if (map instanceof Set) { + map.add(key); + } + else if (!Object.prototype.hasOwnProperty.call(map, key)) { + Object.defineProperty(map, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map; +} + +exports.addMergeToJSMap = addMergeToJSMap; +exports.isMergeKey = isMergeKey; +exports.merge = merge; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/omap.d.ts b/node_modules/yaml/dist/schema/yaml-1.1/omap.d.ts new file mode 100644 index 000000000..33425afcb --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/omap.d.ts @@ -0,0 +1,22 @@ +import type { ToJSContext } from '../../nodes/toJS'; +import { YAMLMap } from '../../nodes/YAMLMap'; +import { YAMLSeq } from '../../nodes/YAMLSeq'; +import type { CreateNodeContext } from '../../util'; +import type { Schema } from '../Schema'; +import type { CollectionTag } from '../types'; +export declare class YAMLOMap extends YAMLSeq { + static tag: string; + constructor(); + add: typeof YAMLMap.prototype.add; + delete: typeof YAMLMap.prototype.delete; + get: typeof YAMLMap.prototype.get; + has: typeof YAMLMap.prototype.has; + set: typeof YAMLMap.prototype.set; + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_?: unknown, ctx?: ToJSContext): unknown[]; + static from(schema: Schema, iterable: unknown, ctx: CreateNodeContext): YAMLOMap; +} +export declare const omap: CollectionTag; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/omap.js b/node_modules/yaml/dist/schema/yaml-1.1/omap.js new file mode 100644 index 000000000..3ca141dee --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/omap.js @@ -0,0 +1,77 @@ +'use strict'; + +var identity = require('../../nodes/identity.js'); +var toJS = require('../../nodes/toJS.js'); +var YAMLMap = require('../../nodes/YAMLMap.js'); +var YAMLSeq = require('../../nodes/YAMLSeq.js'); +var pairs = require('./pairs.js'); + +class YAMLOMap extends YAMLSeq.YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.YAMLMap.prototype.set.bind(this); + this.tag = YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map = new Map(); + if (ctx?.onCreate) + ctx.onCreate(map); + for (const pair of this.items) { + let key, value; + if (identity.isPair(pair)) { + key = toJS.toJS(pair.key, '', ctx); + value = toJS.toJS(pair.value, key, ctx); + } + else { + key = toJS.toJS(pair, '', ctx); + } + if (map.has(key)) + throw new Error('Ordered maps must not include duplicate keys'); + map.set(key, value); + } + return map; + } + static from(schema, iterable, ctx) { + const pairs$1 = pairs.createPairs(schema, iterable, ctx); + const omap = new this(); + omap.items = pairs$1.items; + return omap; + } +} +YAMLOMap.tag = 'tag:yaml.org,2002:omap'; +const omap = { + collection: 'seq', + identify: value => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: 'tag:yaml.org,2002:omap', + resolve(seq, onError) { + const pairs$1 = pairs.resolvePairs(seq, onError); + const seenKeys = []; + for (const { key } of pairs$1.items) { + if (identity.isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } + else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs$1); + }, + createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx) +}; + +exports.YAMLOMap = YAMLOMap; +exports.omap = omap; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/pairs.d.ts b/node_modules/yaml/dist/schema/yaml-1.1/pairs.d.ts new file mode 100644 index 000000000..3bb7d0c0d --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/pairs.d.ts @@ -0,0 +1,10 @@ +import type { CreateNodeContext } from '../../doc/createNode'; +import type { ParsedNode } from '../../nodes/Node'; +import { Pair } from '../../nodes/Pair'; +import type { YAMLMap } from '../../nodes/YAMLMap'; +import { YAMLSeq } from '../../nodes/YAMLSeq'; +import type { Schema } from '../../schema/Schema'; +import type { CollectionTag } from '../types'; +export declare function resolvePairs(seq: YAMLSeq.Parsed> | YAMLMap.Parsed, onError: (message: string) => void): YAMLSeq.Parsed>; +export declare function createPairs(schema: Schema, iterable: unknown, ctx: CreateNodeContext): YAMLSeq; +export declare const pairs: CollectionTag; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/pairs.js b/node_modules/yaml/dist/schema/yaml-1.1/pairs.js new file mode 100644 index 000000000..aa32e0fa2 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/pairs.js @@ -0,0 +1,82 @@ +'use strict'; + +var identity = require('../../nodes/identity.js'); +var Pair = require('../../nodes/Pair.js'); +var Scalar = require('../../nodes/Scalar.js'); +var YAMLSeq = require('../../nodes/YAMLSeq.js'); + +function resolvePairs(seq, onError) { + if (identity.isSeq(seq)) { + for (let i = 0; i < seq.items.length; ++i) { + let item = seq.items[i]; + if (identity.isPair(item)) + continue; + else if (identity.isMap(item)) { + if (item.items.length > 1) + onError('Each pair must have its own sequence indicator'); + const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore + ? `${item.commentBefore}\n${pair.key.commentBefore}` + : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment + ? `${item.comment}\n${cn.comment}` + : item.comment; + } + item = pair; + } + seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item); + } + } + else + onError('Expected a sequence for this tag'); + return seq; +} +function createPairs(schema, iterable, ctx) { + const { replacer } = ctx; + const pairs = new YAMLSeq.YAMLSeq(schema); + pairs.tag = 'tag:yaml.org,2002:pairs'; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === 'function') + it = replacer.call(iterable, String(i++), it); + let key, value; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value = it[1]; + } + else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } + else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } + else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } + else { + key = it; + } + pairs.items.push(Pair.createPair(key, value, ctx)); + } + return pairs; +} +const pairs = { + collection: 'seq', + default: false, + tag: 'tag:yaml.org,2002:pairs', + resolve: resolvePairs, + createNode: createPairs +}; + +exports.createPairs = createPairs; +exports.pairs = pairs; +exports.resolvePairs = resolvePairs; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/schema.d.ts b/node_modules/yaml/dist/schema/yaml-1.1/schema.d.ts new file mode 100644 index 000000000..0d21e5690 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/schema.d.ts @@ -0,0 +1 @@ +export declare const schema: (import('../types').CollectionTag | import('../types').ScalarTag)[]; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/schema.js b/node_modules/yaml/dist/schema/yaml-1.1/schema.js new file mode 100644 index 000000000..2ea4b730e --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/schema.js @@ -0,0 +1,41 @@ +'use strict'; + +var map = require('../common/map.js'); +var _null = require('../common/null.js'); +var seq = require('../common/seq.js'); +var string = require('../common/string.js'); +var binary = require('./binary.js'); +var bool = require('./bool.js'); +var float = require('./float.js'); +var int = require('./int.js'); +var merge = require('./merge.js'); +var omap = require('./omap.js'); +var pairs = require('./pairs.js'); +var set = require('./set.js'); +var timestamp = require('./timestamp.js'); + +const schema = [ + map.map, + seq.seq, + string.string, + _null.nullTag, + bool.trueTag, + bool.falseTag, + int.intBin, + int.intOct, + int.int, + int.intHex, + float.floatNaN, + float.floatExp, + float.float, + binary.binary, + merge.merge, + omap.omap, + pairs.pairs, + set.set, + timestamp.intTime, + timestamp.floatTime, + timestamp.timestamp +]; + +exports.schema = schema; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/set.d.ts b/node_modules/yaml/dist/schema/yaml-1.1/set.d.ts new file mode 100644 index 000000000..ddf43aa03 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/set.d.ts @@ -0,0 +1,28 @@ +import { Pair } from '../../nodes/Pair'; +import type { Scalar } from '../../nodes/Scalar'; +import type { ToJSContext } from '../../nodes/toJS'; +import { YAMLMap } from '../../nodes/YAMLMap'; +import type { Schema } from '../../schema/Schema'; +import type { StringifyContext } from '../../stringify/stringify'; +import type { CreateNodeContext } from '../../util'; +import type { CollectionTag } from '../types'; +export declare class YAMLSet extends YAMLMap | null> { + static tag: string; + constructor(schema?: Schema); + add(key: T | Pair | null> | { + key: T; + value: Scalar | null; + }): void; + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key: unknown, keepPair?: boolean): any; + set(key: T, value: boolean): void; + /** @deprecated Will throw; `value` must be boolean */ + set(key: T, value: null): void; + toJSON(_?: unknown, ctx?: ToJSContext): any; + toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; + static from(schema: Schema, iterable: unknown, ctx: CreateNodeContext): YAMLSet; +} +export declare const set: CollectionTag; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/set.js b/node_modules/yaml/dist/schema/yaml-1.1/set.js new file mode 100644 index 000000000..650c2508b --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/set.js @@ -0,0 +1,96 @@ +'use strict'; + +var identity = require('../../nodes/identity.js'); +var Pair = require('../../nodes/Pair.js'); +var YAMLMap = require('../../nodes/YAMLMap.js'); + +class YAMLSet extends YAMLMap.YAMLMap { + constructor(schema) { + super(schema); + this.tag = YAMLSet.tag; + } + add(key) { + let pair; + if (identity.isPair(key)) + pair = key; + else if (key && + typeof key === 'object' && + 'key' in key && + 'value' in key && + key.value === null) + pair = new Pair.Pair(key.key, null); + else + pair = new Pair.Pair(key, null); + const prev = YAMLMap.findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = YAMLMap.findPair(this.items, key); + return !keepPair && identity.isPair(pair) + ? identity.isScalar(pair.key) + ? pair.key.value + : pair.key + : pair; + } + set(key, value) { + if (typeof value !== 'boolean') + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = YAMLMap.findPair(this.items, key); + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } + else if (!prev && value) { + this.items.push(new Pair.Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error('Set items must all have null values'); + } + static from(schema, iterable, ctx) { + const { replacer } = ctx; + const set = new this(schema); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value of iterable) { + if (typeof replacer === 'function') + value = replacer.call(iterable, value, value); + set.items.push(Pair.createPair(value, null, ctx)); + } + return set; + } +} +YAMLSet.tag = 'tag:yaml.org,2002:set'; +const set = { + collection: 'map', + identify: value => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: 'tag:yaml.org,2002:set', + createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx), + resolve(map, onError) { + if (identity.isMap(map)) { + if (map.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map); + else + onError('Set items must all have null values'); + } + else + onError('Expected a mapping for this tag'); + return map; + } +}; + +exports.YAMLSet = YAMLSet; +exports.set = set; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/timestamp.d.ts b/node_modules/yaml/dist/schema/yaml-1.1/timestamp.d.ts new file mode 100644 index 000000000..851346688 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/timestamp.d.ts @@ -0,0 +1,6 @@ +import type { ScalarTag } from '../types'; +export declare const intTime: ScalarTag; +export declare const floatTime: ScalarTag; +export declare const timestamp: ScalarTag & { + test: RegExp; +}; diff --git a/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js b/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js new file mode 100644 index 000000000..982fd0637 --- /dev/null +++ b/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js @@ -0,0 +1,105 @@ +'use strict'; + +var stringifyNumber = require('../../stringify/stringifyNumber.js'); + +/** Internal types handle bigint as number, because TS can't figure it out. */ +function parseSexagesimal(str, asBigInt) { + const sign = str[0]; + const parts = sign === '-' || sign === '+' ? str.substring(1) : str; + const num = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts + .replace(/_/g, '') + .split(':') + .reduce((res, p) => res * num(60) + num(p), num(0)); + return (sign === '-' ? num(-1) * res : res); +} +/** + * hhhh:mm:ss.sss + * + * Internal types handle bigint as number, because TS can't figure it out. + */ +function stringifySexagesimal(node) { + let { value } = node; + let num = (n) => n; + if (typeof value === 'bigint') + num = n => BigInt(n); + else if (isNaN(value) || !isFinite(value)) + return stringifyNumber.stringifyNumber(node); + let sign = ''; + if (value < 0) { + sign = '-'; + value *= num(-1); + } + const _60 = num(60); + const parts = [value % _60]; // seconds, including ms + if (value < 60) { + parts.unshift(0); // at least one : is required + } + else { + value = (value - parts[0]) / _60; + parts.unshift(value % _60); // minutes + if (value >= 60) { + value = (value - parts[0]) / _60; + parts.unshift(value); // hours + } + } + return (sign + + parts + .map(n => String(n).padStart(2, '0')) + .join(':') + .replace(/000000\d*$/, '') // % 60 may introduce error + ); +} +const intTime = { + identify: value => typeof value === 'bigint' || Number.isInteger(value), + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'TIME', + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), + stringify: stringifySexagesimal +}; +const floatTime = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'TIME', + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: str => parseSexagesimal(str, false), + stringify: stringifySexagesimal +}; +const timestamp = { + identify: value => value instanceof Date, + default: true, + tag: 'tag:yaml.org,2002:timestamp', + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd + '(?:' + // time is optional + '(?:t|T|[ \\t]+)' + // t | T | whitespace + '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)? + '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30 + ')?$'), + resolve(str) { + const match = str.match(timestamp.test); + if (!match) + throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd'); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== 'Z') { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 60000 * d; + } + return new Date(date); + }, + stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, '') ?? '' +}; + +exports.floatTime = floatTime; +exports.intTime = intTime; +exports.timestamp = timestamp; diff --git a/node_modules/yaml/dist/stringify/foldFlowLines.d.ts b/node_modules/yaml/dist/stringify/foldFlowLines.d.ts new file mode 100644 index 000000000..aac3cac60 --- /dev/null +++ b/node_modules/yaml/dist/stringify/foldFlowLines.d.ts @@ -0,0 +1,34 @@ +export declare const FOLD_FLOW = "flow"; +export declare const FOLD_BLOCK = "block"; +export declare const FOLD_QUOTED = "quoted"; +/** + * `'block'` prevents more-indented lines from being folded; + * `'quoted'` allows for `\` escapes, including escaped newlines + */ +export type FoldMode = 'flow' | 'block' | 'quoted'; +export interface FoldOptions { + /** + * Accounts for leading contents on the first line, defaulting to + * `indent.length` + */ + indentAtStart?: number; + /** Default: `80` */ + lineWidth?: number; + /** + * Allow highly indented lines to stretch the line width or indent content + * from the start. + * + * Default: `20` + */ + minContentWidth?: number; + /** Called once if the text is folded */ + onFold?: () => void; + /** Called once if any line of text exceeds lineWidth characters */ + onOverflow?: () => void; +} +/** + * Tries to keep input at up to `lineWidth` characters, splitting only on spaces + * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are + * terminated with `\n` and started with `indent`. + */ +export declare function foldFlowLines(text: string, indent: string, mode?: FoldMode, { indentAtStart, lineWidth, minContentWidth, onFold, onOverflow }?: FoldOptions): string; diff --git a/node_modules/yaml/dist/stringify/foldFlowLines.js b/node_modules/yaml/dist/stringify/foldFlowLines.js new file mode 100644 index 000000000..9c610589e --- /dev/null +++ b/node_modules/yaml/dist/stringify/foldFlowLines.js @@ -0,0 +1,151 @@ +'use strict'; + +const FOLD_FLOW = 'flow'; +const FOLD_BLOCK = 'block'; +const FOLD_QUOTED = 'quoted'; +/** + * Tries to keep input at up to `lineWidth` characters, splitting only on spaces + * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are + * terminated with `\n` and started with `indent`. + */ +function foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === 'number') { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = undefined; + let prev = undefined; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; (ch = text[(i += 1)]);) { + if (mode === FOLD_QUOTED && ch === '\\') { + escStart = i; + switch (text[i + 1]) { + case 'x': + i += 3; + break; + case 'u': + i += 5; + break; + case 'U': + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === '\n') { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = undefined; + } + else { + if (ch === ' ' && + prev && + prev !== ' ' && + prev !== '\n' && + prev !== '\t') { + // space surrounded by non-space can be replaced with newline + indent + const next = text[i + 1]; + if (next && next !== ' ' && next !== '\n' && next !== '\t') + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = undefined; + } + else if (mode === FOLD_QUOTED) { + // white-space collected at end may stretch past lineWidth + while (prev === ' ' || prev === '\t') { + prev = ch; + ch = text[(i += 1)]; + overflow = true; + } + // Account for newline escape, but don't break preceding escape + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + // Bail out if lineWidth & minContentWidth are shorter than an escape string + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = undefined; + } + else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i = 0; i < folds.length; ++i) { + const fold = folds[i]; + const end = folds[i + 1] || text.length; + if (fold === 0) + res = `\n${indent}${text.slice(0, end)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += `\n${indent}${text.slice(fold + 1, end)}`; + } + } + return res; +} +/** + * Presumes `i + 1` is at the start of a line + * @returns index of last newline in more-indented block + */ +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === ' ' || ch === '\t') { + if (i < start + indent) { + ch = text[++i]; + } + else { + do { + ch = text[++i]; + } while (ch && ch !== '\n'); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +exports.FOLD_BLOCK = FOLD_BLOCK; +exports.FOLD_FLOW = FOLD_FLOW; +exports.FOLD_QUOTED = FOLD_QUOTED; +exports.foldFlowLines = foldFlowLines; diff --git a/node_modules/yaml/dist/stringify/stringify.d.ts b/node_modules/yaml/dist/stringify/stringify.d.ts new file mode 100644 index 000000000..b693d457a --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringify.d.ts @@ -0,0 +1,21 @@ +import type { Document } from '../doc/Document'; +import type { Alias } from '../nodes/Alias'; +import type { ToStringOptions } from '../options'; +export type StringifyContext = { + actualString?: boolean; + allNullValues?: boolean; + anchors: Set; + doc: Document; + forceBlockIndent?: boolean; + implicitKey?: boolean; + indent: string; + indentStep: string; + indentAtStart?: number; + inFlow: boolean | null; + inStringifyKey?: boolean; + flowCollectionPadding: string; + options: Readonly>>; + resolvedAliases?: Set; +}; +export declare function createStringifyContext(doc: Document, options: ToStringOptions): StringifyContext; +export declare function stringify(item: unknown, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; diff --git a/node_modules/yaml/dist/stringify/stringify.js b/node_modules/yaml/dist/stringify/stringify.js new file mode 100644 index 000000000..e6cc402c4 --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringify.js @@ -0,0 +1,131 @@ +'use strict'; + +var anchors = require('../doc/anchors.js'); +var identity = require('../nodes/identity.js'); +var stringifyComment = require('./stringifyComment.js'); +var stringifyString = require('./stringifyString.js'); + +function createStringifyContext(doc, options) { + const opt = Object.assign({ + blockQuote: true, + commentString: stringifyComment.stringifyComment, + defaultKeyType: null, + defaultStringType: 'PLAIN', + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: 'false', + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: 'null', + simpleKeys: false, + singleQuote: null, + trueStr: 'true', + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt.collectionStyle) { + case 'block': + inFlow = false; + break; + case 'flow': + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: new Set(), + doc, + flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '', + indent: '', + indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ', + inFlow, + options: opt + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter(t => t.tag === item.tag); + if (match.length > 0) + return match.find(t => t.format === item.format) ?? match[0]; + } + let tagObj = undefined; + let obj; + if (identity.isScalar(item)) { + obj = item.value; + let match = tags.filter(t => t.identify?.(obj)); + if (match.length > 1) { + const testMatch = match.filter(t => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = + match.find(t => t.format === item.format) ?? match.find(t => !t.format); + } + else { + obj = item; + tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj?.constructor?.name ?? (obj === null ? 'null' : typeof obj); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +// needs to be called before value stringifier to allow for circular anchor refs +function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) { + if (!doc.directives) + return ''; + const props = []; + const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor; + if (anchor && anchors.anchorIsValid(anchor)) { + anchors$1.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(' '); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (identity.isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (identity.isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } + else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = undefined; + const node = identity.isNode(item) + ? item + : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str = typeof tagObj.stringify === 'function' + ? tagObj.stringify(node, ctx, onComment, onChompKeep) + : identity.isScalar(node) + ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) + : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str; + return identity.isScalar(node) || str[0] === '{' || str[0] === '[' + ? `${props} ${str}` + : `${props}\n${ctx.indent}${str}`; +} + +exports.createStringifyContext = createStringifyContext; +exports.stringify = stringify; diff --git a/node_modules/yaml/dist/stringify/stringifyCollection.d.ts b/node_modules/yaml/dist/stringify/stringifyCollection.d.ts new file mode 100644 index 000000000..c5e8ffa55 --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringifyCollection.d.ts @@ -0,0 +1,17 @@ +import type { Collection } from '../nodes/Collection'; +import type { StringifyContext } from './stringify'; +interface StringifyCollectionOptions { + blockItemPrefix: string; + flowChars: { + start: '{'; + end: '}'; + } | { + start: '['; + end: ']'; + }; + itemIndent: string; + onChompKeep?: () => void; + onComment?: () => void; +} +export declare function stringifyCollection(collection: Readonly, ctx: StringifyContext, options: StringifyCollectionOptions): string; +export {}; diff --git a/node_modules/yaml/dist/stringify/stringifyCollection.js b/node_modules/yaml/dist/stringify/stringifyCollection.js new file mode 100644 index 000000000..6efffc519 --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringifyCollection.js @@ -0,0 +1,145 @@ +'use strict'; + +var identity = require('../nodes/identity.js'); +var stringify = require('./stringify.js'); +var stringifyComment = require('./stringifyComment.js'); + +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; // flag for the preceding node's status + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (identity.isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines.push(''); + addCommentBefore(ctx, lines, item.commentBefore, chompKeep); + if (item.comment) + comment = item.comment; + } + else if (identity.isPair(item)) { + const ik = identity.isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines.push(''); + addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str = stringify.stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true)); + if (comment) + str += stringifyComment.lineComment(str, itemIndent, commentString(comment)); + if (chompKeep && comment) + chompKeep = false; + lines.push(blockItemPrefix + str); + } + let str; + if (lines.length === 0) { + str = flowChars.start + flowChars.end; + } + else { + str = lines[0]; + for (let i = 1; i < lines.length; ++i) { + const line = lines[i]; + str += line ? `\n${indent}${line}` : '\n'; + } + } + if (comment) { + str += '\n' + stringifyComment.indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } + else if (chompKeep && onChompKeep) + onChompKeep(); + return str; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (identity.isNode(item)) { + if (item.spaceBefore) + lines.push(''); + addCommentBefore(ctx, lines, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } + else if (identity.isPair(item)) { + const ik = identity.isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines.push(''); + addCommentBefore(ctx, lines, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = identity.isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } + else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str = stringify.stringify(item, itemCtx, () => (comment = null)); + if (i < items.length - 1) + str += ','; + if (comment) + str += stringifyComment.lineComment(str, itemIndent, commentString(comment)); + if (!reqNewline && (lines.length > linesAtValue || str.includes('\n'))) + reqNewline = true; + lines.push(str); + linesAtValue = lines.length; + } + const { start, end } = flowChars; + if (lines.length === 0) { + return start + end; + } + else { + if (!reqNewline) { + const len = lines.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str = start; + for (const line of lines) + str += line ? `\n${indentStep}${indent}${line}` : '\n'; + return `${str}\n${indent}${end}`; + } + else { + return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ''); + if (comment) { + const ic = stringifyComment.indentComment(commentString(comment), indent); + lines.push(ic.trimStart()); // Avoid double indent on first line + } +} + +exports.stringifyCollection = stringifyCollection; diff --git a/node_modules/yaml/dist/stringify/stringifyComment.d.ts b/node_modules/yaml/dist/stringify/stringifyComment.d.ts new file mode 100644 index 000000000..9fcf48d76 --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringifyComment.d.ts @@ -0,0 +1,10 @@ +/** + * Stringifies a comment. + * + * Empty comment lines are left empty, + * lines consisting of a single space are replaced by `#`, + * and all other lines are prefixed with a `#`. + */ +export declare const stringifyComment: (str: string) => string; +export declare function indentComment(comment: string, indent: string): string; +export declare const lineComment: (str: string, indent: string, comment: string) => string; diff --git a/node_modules/yaml/dist/stringify/stringifyComment.js b/node_modules/yaml/dist/stringify/stringifyComment.js new file mode 100644 index 000000000..26bf361a9 --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringifyComment.js @@ -0,0 +1,24 @@ +'use strict'; + +/** + * Stringifies a comment. + * + * Empty comment lines are left empty, + * lines consisting of a single space are replaced by `#`, + * and all other lines are prefixed with a `#`. + */ +const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#'); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +const lineComment = (str, indent, comment) => str.endsWith('\n') + ? indentComment(comment, indent) + : comment.includes('\n') + ? '\n' + indentComment(comment, indent) + : (str.endsWith(' ') ? '' : ' ') + comment; + +exports.indentComment = indentComment; +exports.lineComment = lineComment; +exports.stringifyComment = stringifyComment; diff --git a/node_modules/yaml/dist/stringify/stringifyDocument.d.ts b/node_modules/yaml/dist/stringify/stringifyDocument.d.ts new file mode 100644 index 000000000..6b37acca8 --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringifyDocument.d.ts @@ -0,0 +1,4 @@ +import type { Document } from '../doc/Document'; +import type { Node } from '../nodes/Node'; +import type { ToStringOptions } from '../options'; +export declare function stringifyDocument(doc: Readonly>, options: ToStringOptions): string; diff --git a/node_modules/yaml/dist/stringify/stringifyDocument.js b/node_modules/yaml/dist/stringify/stringifyDocument.js new file mode 100644 index 000000000..fb9d73cb2 --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringifyDocument.js @@ -0,0 +1,87 @@ +'use strict'; + +var identity = require('../nodes/identity.js'); +var stringify = require('./stringify.js'); +var stringifyComment = require('./stringifyComment.js'); + +function stringifyDocument(doc, options) { + const lines = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines.push(dir); + hasDirectives = true; + } + else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines.push('---'); + const ctx = stringify.createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines.length !== 1) + lines.unshift(''); + const cs = commentString(doc.commentBefore); + lines.unshift(stringifyComment.indentComment(cs, '')); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (identity.isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines.push(''); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines.push(stringifyComment.indentComment(cs, '')); + } + // top-level block scalars need to be indented if followed by a comment + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? undefined : () => (chompKeep = true); + let body = stringify.stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep); + if (contentComment) + body += stringifyComment.lineComment(body, '', commentString(contentComment)); + if ((body[0] === '|' || body[0] === '>') && + lines[lines.length - 1] === '---') { + // Top-level block scalars with a preceding doc marker ought to use the + // same line for their header. + lines[lines.length - 1] = `--- ${body}`; + } + else + lines.push(body); + } + else { + lines.push(stringify.stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes('\n')) { + lines.push('...'); + lines.push(stringifyComment.indentComment(cs, '')); + } + else { + lines.push(`... ${cs}`); + } + } + else { + lines.push('...'); + } + } + else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ''); + if (dc) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') + lines.push(''); + lines.push(stringifyComment.indentComment(commentString(dc), '')); + } + } + return lines.join('\n') + '\n'; +} + +exports.stringifyDocument = stringifyDocument; diff --git a/node_modules/yaml/dist/stringify/stringifyNumber.d.ts b/node_modules/yaml/dist/stringify/stringifyNumber.d.ts new file mode 100644 index 000000000..743b4244a --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringifyNumber.d.ts @@ -0,0 +1,2 @@ +import type { Scalar } from '../nodes/Scalar'; +export declare function stringifyNumber({ format, minFractionDigits, tag, value }: Scalar): string; diff --git a/node_modules/yaml/dist/stringify/stringifyNumber.js b/node_modules/yaml/dist/stringify/stringifyNumber.js new file mode 100644 index 000000000..49c3f0694 --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringifyNumber.js @@ -0,0 +1,26 @@ +'use strict'; + +function stringifyNumber({ format, minFractionDigits, tag, value }) { + if (typeof value === 'bigint') + return String(value); + const num = typeof value === 'number' ? value : Number(value); + if (!isFinite(num)) + return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf'; + let n = Object.is(value, -0) ? '-0' : JSON.stringify(value); + if (!format && + minFractionDigits && + (!tag || tag === 'tag:yaml.org,2002:float') && + /^\d/.test(n)) { + let i = n.indexOf('.'); + if (i < 0) { + i = n.length; + n += '.'; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += '0'; + } + return n; +} + +exports.stringifyNumber = stringifyNumber; diff --git a/node_modules/yaml/dist/stringify/stringifyPair.d.ts b/node_modules/yaml/dist/stringify/stringifyPair.d.ts new file mode 100644 index 000000000..2126beebe --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringifyPair.d.ts @@ -0,0 +1,3 @@ +import type { Pair } from '../nodes/Pair'; +import type { StringifyContext } from './stringify'; +export declare function stringifyPair({ key, value }: Readonly, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; diff --git a/node_modules/yaml/dist/stringify/stringifyPair.js b/node_modules/yaml/dist/stringify/stringifyPair.js new file mode 100644 index 000000000..25f974b2d --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringifyPair.js @@ -0,0 +1,152 @@ +'use strict'; + +var identity = require('../nodes/identity.js'); +var Scalar = require('../nodes/Scalar.js'); +var stringify = require('./stringify.js'); +var stringifyComment = require('./stringifyComment.js'); + +function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = (identity.isNode(key) && key.comment) || null; + if (simpleKeys) { + if (keyComment) { + throw new Error('With simple keys, key nodes cannot have comments'); + } + if (identity.isCollection(key) || (!identity.isNode(key) && typeof key === 'object')) { + const msg = 'With simple keys, collection cannot be used as a key value'; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && + (!key || + (keyComment && value == null && !ctx.inFlow) || + identity.isCollection(key) || + (identity.isScalar(key) + ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL + : typeof key === 'object')); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str = stringify.stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true)); + if (!explicitKey && !ctx.inFlow && str.length > 1024) { + if (simpleKeys) + throw new Error('With simple keys, single line scalar must not span more than 1024 characters'); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value == null) { + if (keyCommentDone && onComment) + onComment(); + return str === '' ? '?' : explicitKey ? `? ${str}` : str; + } + } + else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) { + str = `? ${str}`; + if (keyComment && !keyCommentDone) { + str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + } + else if (chompKeep && onChompKeep) + onChompKeep(); + return str; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + str = `? ${str}\n${indent}:`; + } + else { + str = `${str}:`; + if (keyComment) + str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (identity.isNode(value)) { + vsb = !!value.spaceBefore; + vcb = value.commentBefore; + valueComment = value.comment; + } + else { + vsb = false; + vcb = null; + valueComment = null; + if (value && typeof value === 'object') + value = doc.createNode(value); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && identity.isScalar(value)) + ctx.indentAtStart = str.length + 1; + chompKeep = false; + if (!indentSeq && + indentStep.length >= 2 && + !ctx.inFlow && + !explicitKey && + identity.isSeq(value) && + !value.flow && + !value.tag && + !value.anchor) { + // If indentSeq === false, consider '- ' as part of indentation where possible + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify.stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true)); + let ws = ' '; + if (keyComment || vsb || vcb) { + ws = vsb ? '\n' : ''; + if (vcb) { + const cs = commentString(vcb); + ws += `\n${stringifyComment.indentComment(cs, ctx.indent)}`; + } + if (valueStr === '' && !ctx.inFlow) { + if (ws === '\n' && valueComment) + ws = '\n\n'; + } + else { + ws += `\n${ctx.indent}`; + } + } + else if (!explicitKey && identity.isCollection(value)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf('\n'); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === '&' || vs0 === '!')) { + let sp0 = valueStr.indexOf(' '); + if (vs0 === '&' && + sp0 !== -1 && + sp0 < nl0 && + valueStr[sp0 + 1] === '!') { + sp0 = valueStr.indexOf(' ', sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = `\n${ctx.indent}`; + } + } + else if (valueStr === '' || valueStr[0] === '\n') { + ws = ''; + } + str += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } + else if (valueComment && !valueCommentDone) { + str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment)); + } + else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str; +} + +exports.stringifyPair = stringifyPair; diff --git a/node_modules/yaml/dist/stringify/stringifyString.d.ts b/node_modules/yaml/dist/stringify/stringifyString.d.ts new file mode 100644 index 000000000..df109307d --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringifyString.d.ts @@ -0,0 +1,9 @@ +import { Scalar } from '../nodes/Scalar'; +import type { StringifyContext } from './stringify'; +interface StringifyScalar { + value: string; + comment?: string | null; + type?: string; +} +export declare function stringifyString(item: Scalar | StringifyScalar, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string; +export {}; diff --git a/node_modules/yaml/dist/stringify/stringifyString.js b/node_modules/yaml/dist/stringify/stringifyString.js new file mode 100644 index 000000000..2caadc633 --- /dev/null +++ b/node_modules/yaml/dist/stringify/stringifyString.js @@ -0,0 +1,338 @@ +'use strict'; + +var Scalar = require('../nodes/Scalar.js'); +var foldFlowLines = require('./foldFlowLines.js'); + +const getFoldOptions = (ctx, isBlock) => ({ + indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +// Also checks for lines starting with %, as parsing the output as YAML 1.1 will +// presume that's starting a new document. +const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); +function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str[i] === '\n') { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value, ctx) { + const json = JSON.stringify(value); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); + let str = ''; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') { + // space before newline needs to be escaped to not be folded + str += json.slice(start, i) + '\\ '; + i += 1; + start = i; + ch = '\\'; + } + if (ch === '\\') + switch (json[i + 1]) { + case 'u': + { + str += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case '0000': + str += '\\0'; + break; + case '0007': + str += '\\a'; + break; + case '000b': + str += '\\v'; + break; + case '001b': + str += '\\e'; + break; + case '0085': + str += '\\N'; + break; + case '00a0': + str += '\\_'; + break; + case '2028': + str += '\\L'; + break; + case '2029': + str += '\\P'; + break; + default: + if (code.substr(0, 2) === '00') + str += '\\x' + code.substr(2); + else + str += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case 'n': + if (implicitKey || + json[i + 2] === '"' || + json.length < minMultiLineLength) { + i += 1; + } + else { + // folding will eat first newline + str += json.slice(start, i) + '\n\n'; + while (json[i + 2] === '\\' && + json[i + 3] === 'n' && + json[i + 4] !== '"') { + str += '\n'; + i += 2; + } + str += indent; + // space after newline needs to be escaped to not be folded + if (json[i + 2] === ' ') + str += '\\'; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str = start ? str + json.slice(start) : json; + return implicitKey + ? str + : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value, ctx) { + if (ctx.options.singleQuote === false || + (ctx.implicitKey && value.includes('\n')) || + /[ \t]\n|\n[ \t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline + ) + return doubleQuotedString(value, ctx); + const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'"; + return ctx.implicitKey + ? res + : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value.includes('"'); + const hasSingle = value.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value, ctx); +} +// The negative lookbehind avoids a polynomial search, +// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind +let blockEndNewlines; +try { + blockEndNewlines = new RegExp('(^|(?\n'; + // determine chomping from whitespace at value end + let chomp; + let endStart; + for (endStart = value.length; endStart > 0; --endStart) { + const ch = value[endStart - 1]; + if (ch !== '\n' && ch !== '\t' && ch !== ' ') + break; + } + let end = value.substring(endStart); + const endNlPos = end.indexOf('\n'); + if (endNlPos === -1) { + chomp = '-'; // strip + } + else if (value === end || endNlPos !== end.length - 1) { + chomp = '+'; // keep + if (onChompKeep) + onChompKeep(); + } + else { + chomp = ''; // clip + } + if (end) { + value = value.slice(0, -end.length); + if (end[end.length - 1] === '\n') + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + // determine indent indicator from whitespace at value start + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value.length; ++startEnd) { + const ch = value[startEnd]; + if (ch === ' ') + startWithSpace = true; + else if (ch === '\n') + startNlPos = startEnd; + else + break; + } + let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value = value.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? '2' : '1'; // root is at -1 + // Leading | or > is added later + let header = (startWithSpace ? indentSize : '') + chomp; + if (comment) { + header += ' ' + commentString(comment.replace(/ ?[\r\n]+/g, ' ')); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value + .replace(/\n+/g, '\n$&') + .replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded + // ^ more-ind. ^ empty ^ capture next empty lines only at end of indent + .replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== 'folded' && type !== Scalar.Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header}\n${indent}${body}`; + } + value = value.replace(/\n+/g, `$&${indent}`); + return `|${header}\n${indent}${start}${value}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if ((implicitKey && value.includes('\n')) || + (inFlow && /[[\]{},]/.test(value))) { + return quotedString(value, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + // not allowed: + // - '-' or '?' + // - start with an indicator character (except [?:-]) or /[?-] / + // - '\n ', ': ' or ' \n' anywhere + // - '#' not preceded by a non-space char + // - end with ' ' or ':' + return implicitKey || inFlow || !value.includes('\n') + ? quotedString(value, ctx) + : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && + !inFlow && + type !== Scalar.Scalar.PLAIN && + value.includes('\n')) { + // Where allowed & type not set explicitly, prefer block style for multiline strings + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value)) { + if (indent === '') { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } + else if (implicitKey && indent === indentStep) { + return quotedString(value, ctx); + } + } + const str = value.replace(/\n+/g, `$&\n${indent}`); + // Verify that output will be parsed as a string, as e.g. plain numbers and + // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'), + // and others in v1.1. + if (actualString) { + const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value, ctx); + } + return implicitKey + ? str + : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === 'string' + ? item + : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.Scalar.QUOTE_DOUBLE) { + // force double quotes on control characters & unpaired surrogates + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.Scalar.BLOCK_FOLDED: + case Scalar.Scalar.BLOCK_LITERAL: + return implicitKey || inFlow + ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers + : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = (implicitKey && defaultKeyType) || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +exports.stringifyString = stringifyString; diff --git a/node_modules/yaml/dist/test-events.d.ts b/node_modules/yaml/dist/test-events.d.ts new file mode 100644 index 000000000..d1a234835 --- /dev/null +++ b/node_modules/yaml/dist/test-events.d.ts @@ -0,0 +1,4 @@ +export declare function testEvents(src: string): { + events: string[]; + error: unknown; +}; diff --git a/node_modules/yaml/dist/test-events.js b/node_modules/yaml/dist/test-events.js new file mode 100644 index 000000000..f38d3365f --- /dev/null +++ b/node_modules/yaml/dist/test-events.js @@ -0,0 +1,134 @@ +'use strict'; + +var identity = require('./nodes/identity.js'); +var publicApi = require('./public-api.js'); +var visit = require('./visit.js'); + +const scalarChar = { + BLOCK_FOLDED: '>', + BLOCK_LITERAL: '|', + PLAIN: ':', + QUOTE_DOUBLE: '"', + QUOTE_SINGLE: "'" +}; +function anchorExists(doc, anchor) { + let found = false; + visit.visit(doc, { + Value(_key, node) { + if (node.anchor === anchor) { + found = true; + return visit.visit.BREAK; + } + } + }); + return found; +} +// test harness for yaml-test-suite event tests +function testEvents(src) { + const docs = publicApi.parseAllDocuments(src); + const errDoc = docs.find(doc => doc.errors.length > 0); + const error = errDoc ? errDoc.errors[0].message : null; + const events = ['+STR']; + try { + for (let i = 0; i < docs.length; ++i) { + const doc = docs[i]; + let root = doc.contents; + if (Array.isArray(root)) + root = root[0]; + const [rootStart] = doc.range || [0]; + const error = doc.errors[0]; + if (error && (!error.pos || error.pos[0] < rootStart)) + throw new Error(); + let docStart = '+DOC'; + if (doc.directives.docStart) + docStart += ' ---'; + else if (doc.contents && + doc.contents.range[2] === doc.contents.range[0] && + !doc.contents.anchor && + !doc.contents.tag) + continue; + events.push(docStart); + addEvents(events, doc, error?.pos[0] ?? -1, root); + let docEnd = '-DOC'; + if (doc.directives.docEnd) + docEnd += ' ...'; + events.push(docEnd); + } + } + catch (e) { + return { events, error: error ?? e }; + } + events.push('-STR'); + return { events, error }; +} +function addEvents(events, doc, errPos, node) { + if (!node) { + events.push('=VAL :'); + return; + } + if (errPos !== -1 && identity.isNode(node) && node.range[0] >= errPos) + throw new Error(); + let props = ''; + let anchor = identity.isScalar(node) || identity.isCollection(node) ? node.anchor : undefined; + if (anchor) { + if (/\d$/.test(anchor)) { + const alt = anchor.replace(/\d$/, ''); + if (anchorExists(doc, alt)) + anchor = alt; + } + props = ` &${anchor}`; + } + if (identity.isNode(node) && node.tag) + props += ` <${node.tag}>`; + if (identity.isMap(node)) { + const ev = node.flow ? '+MAP {}' : '+MAP'; + events.push(`${ev}${props}`); + node.items.forEach(({ key, value }) => { + addEvents(events, doc, errPos, key); + addEvents(events, doc, errPos, value); + }); + events.push('-MAP'); + } + else if (identity.isSeq(node)) { + const ev = node.flow ? '+SEQ []' : '+SEQ'; + events.push(`${ev}${props}`); + node.items.forEach(item => { + addEvents(events, doc, errPos, item); + }); + events.push('-SEQ'); + } + else if (identity.isPair(node)) { + events.push(`+MAP${props}`); + addEvents(events, doc, errPos, node.key); + addEvents(events, doc, errPos, node.value); + events.push('-MAP'); + } + else if (identity.isAlias(node)) { + let alias = node.source; + if (alias && /\d$/.test(alias)) { + const alt = alias.replace(/\d$/, ''); + if (anchorExists(doc, alt)) + alias = alt; + } + events.push(`=ALI${props} *${alias}`); + } + else { + const scalar = scalarChar[String(node.type)]; + if (!scalar) + throw new Error(`Unexpected node type ${node.type}`); + const value = node.source + .replace(/\\/g, '\\\\') + .replace(/\0/g, '\\0') + .replace(/\x07/g, '\\a') + .replace(/\x08/g, '\\b') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\v/g, '\\v') + .replace(/\f/g, '\\f') + .replace(/\r/g, '\\r') + .replace(/\x1b/g, '\\e'); + events.push(`=VAL${props} ${scalar}${value}`); + } +} + +exports.testEvents = testEvents; diff --git a/node_modules/yaml/dist/util.d.ts b/node_modules/yaml/dist/util.d.ts new file mode 100644 index 000000000..176130e68 --- /dev/null +++ b/node_modules/yaml/dist/util.d.ts @@ -0,0 +1,16 @@ +export { createNode } from './doc/createNode'; +export type { CreateNodeContext } from './doc/createNode'; +export { debug, warn } from './log'; +export type { LogLevelId } from './log'; +export { createPair } from './nodes/Pair'; +export { toJS } from './nodes/toJS'; +export type { ToJSContext } from './nodes/toJS'; +export { findPair } from './nodes/YAMLMap'; +export { map as mapTag } from './schema/common/map'; +export { seq as seqTag } from './schema/common/seq'; +export { string as stringTag } from './schema/common/string'; +export { foldFlowLines } from './stringify/foldFlowLines'; +export type { FoldOptions } from './stringify/foldFlowLines'; +export type { StringifyContext } from './stringify/stringify'; +export { stringifyNumber } from './stringify/stringifyNumber'; +export { stringifyString } from './stringify/stringifyString'; diff --git a/node_modules/yaml/dist/util.js b/node_modules/yaml/dist/util.js new file mode 100644 index 000000000..ae3c4abc5 --- /dev/null +++ b/node_modules/yaml/dist/util.js @@ -0,0 +1,28 @@ +'use strict'; + +var createNode = require('./doc/createNode.js'); +var log = require('./log.js'); +var Pair = require('./nodes/Pair.js'); +var toJS = require('./nodes/toJS.js'); +var YAMLMap = require('./nodes/YAMLMap.js'); +var map = require('./schema/common/map.js'); +var seq = require('./schema/common/seq.js'); +var string = require('./schema/common/string.js'); +var foldFlowLines = require('./stringify/foldFlowLines.js'); +var stringifyNumber = require('./stringify/stringifyNumber.js'); +var stringifyString = require('./stringify/stringifyString.js'); + + + +exports.createNode = createNode.createNode; +exports.debug = log.debug; +exports.warn = log.warn; +exports.createPair = Pair.createPair; +exports.toJS = toJS.toJS; +exports.findPair = YAMLMap.findPair; +exports.mapTag = map.map; +exports.seqTag = seq.seq; +exports.stringTag = string.string; +exports.foldFlowLines = foldFlowLines.foldFlowLines; +exports.stringifyNumber = stringifyNumber.stringifyNumber; +exports.stringifyString = stringifyString.stringifyString; diff --git a/node_modules/yaml/dist/visit.d.ts b/node_modules/yaml/dist/visit.d.ts new file mode 100644 index 000000000..8af36313f --- /dev/null +++ b/node_modules/yaml/dist/visit.d.ts @@ -0,0 +1,102 @@ +import type { Document } from './doc/Document'; +import type { Alias } from './nodes/Alias'; +import type { Node } from './nodes/Node'; +import type { Pair } from './nodes/Pair'; +import type { Scalar } from './nodes/Scalar'; +import type { YAMLMap } from './nodes/YAMLMap'; +import type { YAMLSeq } from './nodes/YAMLSeq'; +export type visitorFn = (key: number | 'key' | 'value' | null, node: T, path: readonly (Document | Node | Pair)[]) => void | symbol | number | Node | Pair; +export type visitor = visitorFn | { + Alias?: visitorFn; + Collection?: visitorFn; + Map?: visitorFn; + Node?: visitorFn; + Pair?: visitorFn; + Scalar?: visitorFn; + Seq?: visitorFn; + Value?: visitorFn; +}; +export type asyncVisitorFn = (key: number | 'key' | 'value' | null, node: T, path: readonly (Document | Node | Pair)[]) => void | symbol | number | Node | Pair | Promise; +export type asyncVisitor = asyncVisitorFn | { + Alias?: asyncVisitorFn; + Collection?: asyncVisitorFn; + Map?: asyncVisitorFn; + Node?: asyncVisitorFn; + Pair?: asyncVisitorFn; + Scalar?: asyncVisitorFn; + Seq?: asyncVisitorFn; + Value?: asyncVisitorFn; +}; +/** + * Apply a visitor to an AST node or document. + * + * Walks through the tree (depth-first) starting from `node`, calling a + * `visitor` function with three arguments: + * - `key`: For sequence values and map `Pair`, the node's index in the + * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. + * `null` for the root node. + * - `node`: The current node. + * - `path`: The ancestry of the current node. + * + * The return value of the visitor may be used to control the traversal: + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this node, continue with next + * sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current node, then continue with the next one + * - `Node`: Replace the current node, then continue by visiting it + * - `number`: While iterating the items of a sequence or map, set the index + * of the next step. This is useful especially if the index of the current + * node has changed. + * + * If `visitor` is a single function, it will be called with all values + * encountered in the tree, including e.g. `null` values. Alternatively, + * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, + * `Alias` and `Scalar` node. To define the same visitor function for more than + * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) + * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most + * specific defined one will be used for each node. + */ +export declare function visit(node: Node | Document | null, visitor: visitor): void; +export declare namespace visit { + var BREAK: symbol; + var SKIP: symbol; + var REMOVE: symbol; +} +/** + * Apply an async visitor to an AST node or document. + * + * Walks through the tree (depth-first) starting from `node`, calling a + * `visitor` function with three arguments: + * - `key`: For sequence values and map `Pair`, the node's index in the + * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. + * `null` for the root node. + * - `node`: The current node. + * - `path`: The ancestry of the current node. + * + * The return value of the visitor may be used to control the traversal: + * - `Promise`: Must resolve to one of the following values + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this node, continue with next + * sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current node, then continue with the next one + * - `Node`: Replace the current node, then continue by visiting it + * - `number`: While iterating the items of a sequence or map, set the index + * of the next step. This is useful especially if the index of the current + * node has changed. + * + * If `visitor` is a single function, it will be called with all values + * encountered in the tree, including e.g. `null` values. Alternatively, + * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, + * `Alias` and `Scalar` node. To define the same visitor function for more than + * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) + * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most + * specific defined one will be used for each node. + */ +export declare function visitAsync(node: Node | Document | null, visitor: asyncVisitor): Promise; +export declare namespace visitAsync { + var BREAK: symbol; + var SKIP: symbol; + var REMOVE: symbol; +} diff --git a/node_modules/yaml/dist/visit.js b/node_modules/yaml/dist/visit.js new file mode 100644 index 000000000..f126e54f7 --- /dev/null +++ b/node_modules/yaml/dist/visit.js @@ -0,0 +1,236 @@ +'use strict'; + +var identity = require('./nodes/identity.js'); + +const BREAK = Symbol('break visit'); +const SKIP = Symbol('skip children'); +const REMOVE = Symbol('remove node'); +/** + * Apply a visitor to an AST node or document. + * + * Walks through the tree (depth-first) starting from `node`, calling a + * `visitor` function with three arguments: + * - `key`: For sequence values and map `Pair`, the node's index in the + * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. + * `null` for the root node. + * - `node`: The current node. + * - `path`: The ancestry of the current node. + * + * The return value of the visitor may be used to control the traversal: + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this node, continue with next + * sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current node, then continue with the next one + * - `Node`: Replace the current node, then continue by visiting it + * - `number`: While iterating the items of a sequence or map, set the index + * of the next step. This is useful especially if the index of the current + * node has changed. + * + * If `visitor` is a single function, it will be called with all values + * encountered in the tree, including e.g. `null` values. Alternatively, + * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, + * `Alias` and `Scalar` node. To define the same visitor function for more than + * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) + * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most + * specific defined one will be used for each node. + */ +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (identity.isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } + else + visit_(null, node, visitor_, Object.freeze([])); +} +// Without the `as symbol` casts, TS declares these in the `visit` +// namespace using `var`, but then complains about that because +// `unique symbol` must be `const`. +/** Terminate visit traversal completely */ +visit.BREAK = BREAK; +/** Do not visit the children of the current node */ +visit.SKIP = SKIP; +/** Remove the current node */ +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (identity.isNode(ctrl) || identity.isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== 'symbol') { + if (identity.isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === 'number') + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } + else if (identity.isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_('key', node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_('value', node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +/** + * Apply an async visitor to an AST node or document. + * + * Walks through the tree (depth-first) starting from `node`, calling a + * `visitor` function with three arguments: + * - `key`: For sequence values and map `Pair`, the node's index in the + * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. + * `null` for the root node. + * - `node`: The current node. + * - `path`: The ancestry of the current node. + * + * The return value of the visitor may be used to control the traversal: + * - `Promise`: Must resolve to one of the following values + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this node, continue with next + * sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current node, then continue with the next one + * - `Node`: Replace the current node, then continue by visiting it + * - `number`: While iterating the items of a sequence or map, set the index + * of the next step. This is useful especially if the index of the current + * node has changed. + * + * If `visitor` is a single function, it will be called with all values + * encountered in the tree, including e.g. `null` values. Alternatively, + * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, + * `Alias` and `Scalar` node. To define the same visitor function for more than + * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) + * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most + * specific defined one will be used for each node. + */ +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (identity.isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } + else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +// Without the `as symbol` casts, TS declares these in the `visit` +// namespace using `var`, but then complains about that because +// `unique symbol` must be `const`. +/** Terminate visit traversal completely */ +visitAsync.BREAK = BREAK; +/** Do not visit the children of the current node */ +visitAsync.SKIP = SKIP; +/** Remove the current node */ +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (identity.isNode(ctrl) || identity.isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== 'symbol') { + if (identity.isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === 'number') + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } + else if (identity.isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_('key', node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_('value', node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === 'object' && + (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === 'function') + return visitor(key, node, path); + if (identity.isMap(node)) + return visitor.Map?.(key, node, path); + if (identity.isSeq(node)) + return visitor.Seq?.(key, node, path); + if (identity.isPair(node)) + return visitor.Pair?.(key, node, path); + if (identity.isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (identity.isAlias(node)) + return visitor.Alias?.(key, node, path); + return undefined; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (identity.isCollection(parent)) { + parent.items[key] = node; + } + else if (identity.isPair(parent)) { + if (key === 'key') + parent.key = node; + else + parent.value = node; + } + else if (identity.isDocument(parent)) { + parent.contents = node; + } + else { + const pt = identity.isAlias(parent) ? 'alias' : 'scalar'; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +exports.visit = visit; +exports.visitAsync = visitAsync; diff --git a/node_modules/yaml/package.json b/node_modules/yaml/package.json new file mode 100644 index 000000000..7afcb8a5e --- /dev/null +++ b/node_modules/yaml/package.json @@ -0,0 +1,97 @@ +{ + "name": "yaml", + "version": "2.8.2", + "license": "ISC", + "author": "Eemeli Aro ", + "funding": "https://github.com/sponsors/eemeli", + "repository": "github:eemeli/yaml", + "description": "JavaScript parser and stringifier for YAML", + "keywords": [ + "YAML", + "parser", + "stringifier" + ], + "homepage": "https://eemeli.org/yaml/", + "files": [ + "browser/", + "dist/", + "util.js" + ], + "type": "commonjs", + "main": "./dist/index.js", + "bin": "./bin.mjs", + "browser": { + "./dist/index.js": "./browser/index.js", + "./dist/util.js": "./browser/dist/util.js", + "./util.js": "./browser/dist/util.js" + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "node": "./dist/index.js", + "default": "./browser/index.js" + }, + "./package.json": "./package.json", + "./util": { + "types": "./dist/util.d.ts", + "node": "./dist/util.js", + "default": "./browser/dist/util.js" + } + }, + "scripts": { + "build": "npm run build:node && npm run build:browser", + "build:browser": "rollup -c config/rollup.browser-config.mjs", + "build:node": "rollup -c config/rollup.node-config.mjs", + "clean": "git clean -fdxe node_modules", + "lint": "eslint config/ src/", + "prettier": "prettier --write .", + "prestart": "rollup --sourcemap -c config/rollup.node-config.mjs", + "start": "node --enable-source-maps -i -e 'YAML=require(\"./dist/index.js\");const{parse,parseDocument,parseAllDocuments}=YAML'", + "test": "jest --config config/jest.config.js", + "test:all": "npm test && npm run test:types && npm run test:dist && npm run test:dist:types", + "test:browsers": "cd playground && npm test", + "test:dist": "npm run build:node && jest --config config/jest.config.js", + "test:dist:types": "tsc --allowJs --moduleResolution node --noEmit --target es5 dist/index.js", + "test:types": "tsc --noEmit && tsc --noEmit -p tests/tsconfig.json", + "docs:install": "cd docs-slate && bundle install", + "predocs:deploy": "node docs/prepare-docs.mjs", + "docs:deploy": "cd docs-slate && ./deploy.sh", + "predocs": "node docs/prepare-docs.mjs", + "docs": "cd docs-slate && bundle exec middleman server", + "preversion": "npm test && npm run build", + "prepublishOnly": "npm run clean && npm test && npm run build" + }, + "browserslist": "defaults, not ie 11", + "prettier": { + "arrowParens": "avoid", + "semi": false, + "singleQuote": true, + "trailingComma": "none" + }, + "devDependencies": { + "@babel/core": "^7.12.10", + "@babel/plugin-transform-typescript": "^7.12.17", + "@babel/preset-env": "^7.12.11", + "@eslint/js": "^9.9.1", + "@rollup/plugin-babel": "^6.0.3", + "@rollup/plugin-replace": "^6.0.3", + "@rollup/plugin-typescript": "^12.1.1", + "@types/jest": "^29.2.4", + "@types/node": "^20.11.20", + "babel-jest": "^29.0.1", + "eslint": "^9.9.1", + "eslint-config-prettier": "^10.1.8", + "fast-check": "^2.12.0", + "jest": "^29.0.1", + "jest-resolve": "^29.7.0", + "jest-ts-webcompat-resolver": "^1.0.0", + "prettier": "^3.0.2", + "rollup": "^4.12.0", + "tslib": "^2.8.1", + "typescript": "^5.7.2", + "typescript-eslint": "^8.4.0" + }, + "engines": { + "node": ">= 14.6" + } +} diff --git a/node_modules/yaml/util.js b/node_modules/yaml/util.js new file mode 100644 index 000000000..070103f91 --- /dev/null +++ b/node_modules/yaml/util.js @@ -0,0 +1,2 @@ +// Re-exporter for Node.js < 12.16.0 +module.exports = require('./dist/util.js') diff --git a/node_modules/zod-to-json-schema/.github/CR_logotype-full-color.png b/node_modules/zod-to-json-schema/.github/CR_logotype-full-color.png new file mode 100644 index 000000000..c6bd7efd3 Binary files /dev/null and b/node_modules/zod-to-json-schema/.github/CR_logotype-full-color.png differ diff --git a/node_modules/zod-to-json-schema/.github/FUNDING.yml b/node_modules/zod-to-json-schema/.github/FUNDING.yml new file mode 100644 index 000000000..cce355c09 --- /dev/null +++ b/node_modules/zod-to-json-schema/.github/FUNDING.yml @@ -0,0 +1 @@ +github: [StefanTerdell] diff --git a/node_modules/zod-to-json-schema/.prettierrc.json b/node_modules/zod-to-json-schema/.prettierrc.json new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/node_modules/zod-to-json-schema/.prettierrc.json @@ -0,0 +1 @@ +{} diff --git a/node_modules/zod-to-json-schema/LICENSE b/node_modules/zod-to-json-schema/LICENSE new file mode 100644 index 000000000..406daaf2d --- /dev/null +++ b/node_modules/zod-to-json-schema/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2020, Stefan Terdell + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/node_modules/zod-to-json-schema/README.md b/node_modules/zod-to-json-schema/README.md new file mode 100644 index 000000000..ff4a54a18 --- /dev/null +++ b/node_modules/zod-to-json-schema/README.md @@ -0,0 +1,390 @@ +# Zod to Json Schema + +[![NPM Version](https://img.shields.io/npm/v/zod-to-json-schema.svg)](https://npmjs.org/package/zod-to-json-schema) +[![NPM Downloads](https://img.shields.io/npm/dw/zod-to-json-schema.svg)](https://npmjs.org/package/zod-to-json-schema) + +## Notice of deprecation + +As of November 2025, this project will no longer be receiving updates. Zod v4 natively supports generating JSON schemas, so I recommend you switch to the new major, or better yet, a [decent language](https://rust-lang.org/) ;) + +Thank you to all the contributors and sponsors throughout the years! So long, and thanks for all the fish. + +## Summary + +Does what it says on the tin; converts [Zod schemas](https://github.com/colinhacks/zod) into [JSON schemas](https://json-schema.org/)! + +- Supports all relevant schema types, basic string, number and array length validations and string patterns. +- Resolves recursive and recurring schemas with internal `$ref`s. +- Supports targeting legacy Open API 3.0 specification (3.1 supports regular Json Schema). +- Supports Open AI strict mode schemas (Optional object properties are replaced with required but nullable ones). +- As of v3.25 you can use Zod v4 as a peer-dependency, so long as you still provide v3-schemas. + +_Looking for the exact opposite? Check out [json-schema-to-zod](https://npmjs.org/package/json-schema-to-zod)_ + +## Sponsors + +As this project will no longer be receiving updates I am no longer accepting new partnerships. Huge shout-out to CodeRabbit for keeping it real to the end <3 + + + + + +
+

+

+

+
+ Cut code review time & bugs in half +
+ coderabbit.ai +

+

+
+ +## Usage + +### Basic example + +```typescript +import { z } from "zod"; // Or, using v3.25 or v4, "zod/v3" +import { zodToJsonSchema } from "zod-to-json-schema"; + +const mySchema = z + .object({ + myString: z.string().min(5), + myUnion: z.union([z.number(), z.boolean()]), + }) + .describe("My neat object schema"); + +const jsonSchema = zodToJsonSchema(mySchema, "mySchema"); +``` + +#### Expected output + +```json +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$ref": "#/definitions/mySchema", + "definitions": { + "mySchema": { + "description": "My neat object schema", + "type": "object", + "properties": { + "myString": { + "type": "string", + "minLength": 5 + }, + "myUnion": { + "type": ["number", "boolean"] + } + }, + "additionalProperties": false, + "required": ["myString", "myUnion"] + } + } +} +``` + +## Options + +### Schema name + +You can pass a string as the second parameter of the main zodToJsonSchema function. If you do, your schema will end up inside a definitions object property on the root and referenced from there. Alternatively, you can pass the name as the `name` property of the options object (see below). + +### Options object + +Instead of the schema name (or nothing), you can pass an options object as the second parameter. The following options are available: + +| Option | Effect | +| ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **name**?: _string_ | As described above. | +| **nameStrategy**?: "ref" \| "title" | Adds name as "title" meta instead of as a ref as described above | +| **basePath**?: string[] | The base path of the root reference builder. Defaults to ["#"]. | +| **$refStrategy**?: "root" \| "relative" \| "seen" \| "none" | The reference builder strategy;
  • **"root"** resolves $refs from the root up, ie: "#/definitions/mySchema".
  • **"relative"** uses [relative JSON pointers](https://tools.ietf.org/id/draft-handrews-relative-json-pointer-00.html). _See known issues!_
  • **"seen"** reuses the output of any "seen" Zod schema. In theory it's a more performant version of "none", but in practice this behaviour can cause issues with nested schemas and has now gotten its own option.
  • **"none"** ignores referencing all together, creating a new schema branch even on "seen" schemas. Recursive references defaults to "any", ie `{}`.
Defaults to "root". | +| **effectStrategy**?: "input" \| "any" | The effects output strategy. Defaults to "input". _See known issues!_ | +| **dateStrategy**?: "format:date" \| "format:date-time" \| "string" \| "integer" | Date strategy, integer allow to specify in unix-time min and max values. "format:date" creates a string schema with format: "date". "format:date-time" creates a string schema with format: "date-time". "string" is intepreted as "format:date-time". "integer" creates an integer schema with format "unix-time" (unless target "openApi3" is used min max checks are also respected) | +| | +| **emailStrategy**?: "format:email" \| "format:idn-email" \| "pattern:zod" | Choose how to handle the email string check. Defaults to "format:email". | +| **base64Strategy**?: "format:binary" \| "contentEnconding:base64" \| "pattern:zod" | Choose how to handle the base64 string check. Defaults to "contentEncoding:base64" as described [here](https://json-schema.org/understanding-json-schema/reference/non_json_data#contentencoding). Note that "format:binary" is not represented in the output type as it's not part of the JSON Schema spec and only intended to be used when targeting OpenAPI 3.0. Later versions of OpenAPI support contentEncoding. | +| **definitionPath**?: "definitions" \| "$defs" | The name of the definitions property when name is passed. Defaults to "definitions". | +| **target**?: "jsonSchema7" \| "jsonSchema2019-09" \| "openApi3" \| "openAi" | Which spec to target. Defaults to "jsonSchema7" | +| **strictUnions**?: boolean | Scrubs unions of any-like json schemas, like `{}` or `true`. Multiple zod types may result in these out of necessity, such as z.instanceof() | +| **definitions**?: Record | See separate section below | +| **errorMessages**?: boolean | Include custom error messages created via chained function checks for supported zod types. See section below | +| **markdownDescription**?: boolean | Copies the `description` meta to `markdownDescription` | +| **patternStrategy**?: "escape" \| "preserve" | The Zod string validations `.includes()`, `.startsWith()`, and `.endsWith()` must be converted to regex to be compatible with JSON Schema's `pattern`. For safety, all non-alphanumeric characters are `escape`d by default (consider `z.string().includes(".")`), but this can occasionally cause problems with Unicode-flagged regex parsers. Use `preserve` to prevent this escaping behaviour and preserve the exact string written, even if it results in an inaccurate regex. | +| **applyRegexFlags**?: boolean | JSON Schema's `pattern` doesn't support RegExp flags, but Zod's `z.string().regex()` does. When this option is true (default false), a best-effort is made to transform regexes into a flag-independent form (e.g. `/x/i => /[xX]/` ). Supported flags: `i` (basic Latin only), `m`, `s`. | +| **pipeStrategy**?: "all" \| "input" \| "output" | Decide which types should be included when using `z.pipe`, for example `z.string().pipe(z.number())` would return both `string` and `number` by default, only `string` for "input" and only `number` for "output". | +| **removeAdditionalStrategy**?: "passthrough" \| "strict" | Decide when `additionalProperties` should be allowed. See the section on additional properties for details. | +| **allowedAdditionalProperties**?: `true` \| `undefined` | What value to give `additionalProperties` when allowed. See the section on additional properties for details. | +| **rejectedAdditionalProperties**?: `false` \| `undefined` | What value to give `additionalProperties` when rejected. See the section on additional properties for details. | +| **override**?: callback | See section | +| **postProcess**?: callback | See section | +| **openAiAnyTypeName**?: string | Decides the name of a Json schema used to allow semi-arbitrary values in Open AI structured output. If any value in the Zod-schema resolves to any "any"-type schema it will reference a definition of this name. If no such definition is provided a default Json schema will be used. Defaults to "OpenAiAnyType" | + +### Definitions + +The definitions option lets you manually add recurring schemas into definitions for cleaner outputs. It's fully compatible with named schemas, changed definitions path and base path. Here's a simple example: + +```typescript +const myRecurringSchema = z.string(); +const myObjectSchema = z.object({ a: myRecurringSchema, b: myRecurringSchema }); + +const myJsonSchema = zodToJsonSchema(myObjectSchema, { + definitions: { myRecurringSchema }, +}); +``` + +#### Result + +```json +{ + "type": "object", + "properties": { + "a": { + "$ref": "#/definitions/myRecurringSchema" + }, + "b": { + "$ref": "#/definitions/myRecurringSchema" + } + }, + "definitions": { + "myRecurringSchema": { + "type": "string" + } + } +} +``` + +### Error Messages + +This feature allows optionally including error messages created via chained function calls for supported zod types: + +```ts +// string schema with additional chained function call checks +const EmailSchema = z.string().email("Invalid email").min(5, "Too short"); + +const jsonSchema = zodToJsonSchema(EmailSchema, { errorMessages: true }); +``` + +#### Result + +```json +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "string", + "format": "email", + "minLength": 5, + "errorMessage": { + "format": "Invalid email", + "minLength": "Too short" + } +} +``` + +This allows for field specific, validation step specific error messages which can be useful for building forms and such. This format is accepted by `react-hook-form`'s ajv resolver (and therefor `ajv-errors` which it uses under the hood). Note that if using AJV with this format will require [enabling `ajv-errors`](https://ajv.js.org/packages/ajv-errors.html#usage) as vanilla AJV does not accept this format by default. + +#### Custom Error Message Support + +- ZodString + - regex + - min, max + - email, cuid, uuid, url + - endsWith, startsWith +- ZodNumber + - min, max, lt, lte, gt, gte, + - int + - multipleOf +- ZodSet + - min, max +- ZodArray + - min, max + +### Additional properties + +By default, Zod removes undeclared properties when parsing object schemas. In order to replicate the expected output of this behaviour, the default for behaviour of zodToJsonSchema is to set `"additionalProperties"` to `false` (although the correctness of this can be debated). If you wish to allow undeclared properties you can either: + +- Set `removeAdditionalStrategy` to `"strict"`. This will allow additional properties for any object schema that is not declared with `.strict()`. +- Leave `removeAdditionalStrategy` set to its default value of `"passthrough"`, and add `.passtrough()` to your object schema. + +#### Removing the `additionalProperties` keyword using the `allowedAdditionalProperties` and/or `rejectedAdditionalProperties` options. + +Some schema definitions (like Googles Gen AI API for instance) does not allow the `additionalProperties` keyword at all. Luckily the JSON Schema spec allows for this: leaving the keyword undefined _should_ have the same effect as setting it to true (as per usual YMMV). To enable this behaviour, set the option `allowedAdditionalProperties` to `undefined`. + +To exclude the keyword even when additional properties are _not_ allowed, set the `rejectedAdditionalProperties` to `undefined` as well. + +_Heads up ⚠️: Both of these options will be ignored if your schema is declared with `.catchall(...)` as the provided schema will be used instead (if valid)._ + +#### Expected outputs + +| `z.object({})` + option | `"additionalProperties"` value | +| ------------------------- | ----------------------------------------------------------- | +| `.strip()` (default) | `false` if strategy is `"passtrough"`, `true` if `"strict"` | +| `.passtrough()` | `true` | +| `.strict()` | `false` | +| `.catchall(z.string())` | `{ "type": "string" }` | +| `.catchall(z.function())` | `undefined` (function schemas are not currently parseable) | + +Substitute `true` and `false` for `undefined` according to `allowedAdditionalProperties` and/or `rejectedAdditionalProperties` respectively. + +### `override` + +This options takes a callback receiving a Zod schema definition, the current reference object (containing the current ref path and other options), an argument containing inforation about wether or not the schema has been encountered before, and a forceResolution argument. + +Important: if you don't want to override the current item you have to return the `ignoreOverride` symbol exported from the index. This is because `undefined` is a valid option to return when you want the property to be excluded from the resulting JSON schema. + +```typescript +import zodToJsonSchema, { ignoreOverride } from "zod-to-json-schema"; + +zodToJsonSchema( + z.object({ + ignoreThis: z.string(), + overrideThis: z.string(), + removeThis: z.string(), + }), + { + override: (def, refs) => { + const path = refs.currentPath.join("/"); + + if (path === "#/properties/overrideThis") { + return { + type: "integer", + }; + } + + if (path === "#/properties/removeThis") { + return undefined; + } + + // Important! Do not return `undefined` or void unless you want to remove the property from the resulting schema completely. + return ignoreOverride; + }, + }, +); +``` + +Expected output: + +```json +{ + "type": "object", + "required": ["ignoreThis", "overrideThis"], + "properties": { + "ignoreThis": { + "type": "string" + }, + "overrideThis": { + "type": "integer" + } + }, + "additionalProperties": false +} +``` + +### `postProcess` + +Besided receiving all arguments of the `override` callback, the `postProcess` callback also receives the generated schema. It should always return a JSON Schema, or `undefined` if you wish to filter it out. Unlike the `override` callback you do not have to return `ignoreOverride` if you are happy with the produced schema; simply return it unchanged. + +```typescript +import zodToJsonSchema, { PostProcessCallback } from "zod-to-json-schema"; + +// Define the callback to be used to process the output using the PostProcessCallback type: +const postProcess: PostProcessCallback = ( + // The original output produced by the package itself: + jsonSchema, + // The ZodSchema def used to produce the original schema: + def, + // The refs object containing the current path, passed options, etc. + refs, +) => { + if (!jsonSchema) { + return jsonSchema; + } + + // Try to expand description as JSON meta: + if (jsonSchema.description) { + try { + jsonSchema = { + ...jsonSchema, + ...JSON.parse(jsonSchema.description), + }; + } catch {} + } + + // Make all numbers nullable: + if ("type" in jsonSchema! && jsonSchema.type === "number") { + jsonSchema.type = ["number", "null"]; + } + + // Add the refs path, just because + (jsonSchema as any).path = refs.currentPath; + + return jsonSchema; +}; + +const jsonSchema = zodToJsonSchema(zodSchema, { postProcess }); +``` + +#### Using `postProcess` for including examples and other meta + +Adding support for examples and other JSON Schema meta keys are among the most commonly requested features for this project. Unfortunately the current Zod major (3) has pretty anemic support for this, so some userland hacking is required. Since this is such a common usecase I've included a helper function that simply tries to parse any description as JSON and expand it into the resulting schema. + +Simply stringify whatever you want added to the output schema as the description, then import and use `jsonDescription` as the postProcess option: + +```typescript +import zodToJsonSchema, { jsonDescription } from "zod-to-json-schema"; + +const zodSchema = z.string().describe( + JSON.stringify({ + title: "My string", + description: "My description", + examples: ["Foo", "Bar"], + whatever: 123, + }), +); + +const jsonSchema = zodToJsonSchema(zodSchema, { + postProcess: jsonDescription, +}); +``` + +Expected output: + +```json +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "string", + "title": "My string", + "description": "My description", + "examples": ["Foo", "Bar"], + "whatever": 123 +} +``` + +## Known issues + +- The OpenAI target should be considered experimental for now, as some combination of options may break the compatibility. +- When using `.transform`, the return type is inferred from the supplied function. In other words, there is no schema for the return type, and there is no way to convert it in runtime. Currently the JSON schema will therefore reflect the input side of the Zod schema and not necessarily the output (the latter aka. `z.infer`). If this causes problems with your schema, consider using the effectStrategy "any", which will allow any type of output. +- JSON Schemas does not support any other key type than strings for objects. When using `z.record` with any other key type, this will be ignored. An exception to this rule is `z.enum` as is supported since 3.11.3 +- Relative JSON pointers, while published alongside [JSON schema draft 2020-12](https://json-schema.org/specification.html), is not technically a part of it. Currently, most resolvers do not handle them at all. +- Since v3, the Object parser uses `.isOptional()` to check if a property should be included in `required` or not. This has the potentially dangerous behavior of calling `.safeParse` with `undefined`. To work around this, make sure your `preprocess` and other effects callbacks are pure and not liable to throw errors. An issue has been logged in the Zod repo and can be [tracked here](https://github.com/colinhacks/zod/issues/1460). +- JSON Schema version 2020-12 is not yet officially supported. However, you should be able to use this library to obtain a compatible schema for the 2020-12 format just by changing the returned schema's `$schema` field to: "https://json-schema.org/draft/2020-12/schema#" + +## Versioning + +This package _does not_ follow semantic versioning. The major and minor versions of this package instead reflects feature parity with the [Zod package](http://npmjs.com/package/zod). + +I will do my best to keep API-breaking changes to an absolute minimum, but new features may appear as "patches", such as introducing the options pattern in 3.9.1. + +While v3.25 supports Zod v4 as a peer-dependency, it does _not_ mean it supports v4 schemas. Use `import { z } from "zod/v3"` and refer to the Zod documentation. + +## Changelog + +https://github.com/StefanTerdell/zod-to-json-schema/blob/master/changelog.md diff --git a/node_modules/zod-to-json-schema/changelog.md b/node_modules/zod-to-json-schema/changelog.md new file mode 100644 index 000000000..4c0af24c8 --- /dev/null +++ b/node_modules/zod-to-json-schema/changelog.md @@ -0,0 +1,82 @@ +# Changelog + +| Version | Change | +| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 3.25.1 | Fixes large install size due to accidental inclusion of test files. Thanks, [Felix Mosheev](https://github.com/felixmosh)! | +| 3.25.0 | Adds support for v3.25 and v3 through v4 (`import { z } from "zod/v3"`). Big thank you to both [Andrey Gubanovs](https://github.com/finom) and especially to [Faïz Hernawan Abdillah](https://github.com/Abdillah), whose more minimal implementation was merged. This will likely be the final release of `zod-to-json-schema`, as v4 now supports JSON schema natively. | +| 3.24.6 | Removed use of instanceOf to check for optional properties as differing package versions could produce intermittent bugs. Added OpenAiAnyType to work around their schema restrictions. | +| 3.24.5 | Update .npmignore to drop 2 mb of test files. Thanks [Misha Kaletsky](https://github.com/mmkal)! | +| 3.24.4 | Added options to set the value of additionalProperties in objects and record | +| 3.24.3 | Adds postProcess callback option | +| 3.24.2 | Restructured internals to remove circular dependencies which apparently might cause some build systems to whine a bit. Big thanks to [Víctor Hernández](https://github.com/NanezX) for the fix. | +| 3.24.1 | Adds OpenAI target | +| 3.24.0 | Implements new string checks (jwt, base64url, cidr ipv4/v6), matching the new Zod version | +| 3.23.5 | Module import hotfix by [Enzo Monjardín](https://github.com/enzomonjardin). Thanks! | +| 3.23.4 | Fixes branded regex property names and a weird edgecase in arrays. Thanks to [Isaiah Marc Sanchez](https://github.com/imsanchez) and [Mitchell Merry](https://github.com/mitchell-merry)! | +| 3.23.3 | More tests (Thanks [Brett Zamir!](https://github.com/brettz9)), removed dead code | +| 3.23.2 | Lazily loads Emoji regex to avoid incompatibility with some environments. Thanks [Jacob Lee](https://github.com/jacoblee93)! | +| 3.23.1 | Best-effort RegEx flag support by [Spappz](https://github.com/Spappz)! Some minor fixes and additions, such as the title option. | +| 3.23.0 | Adds support for base64, date, time, duration and nanoid string validations. A warm welcome and a big thanks to [Colin](https://www.github.com/colinhacks), the creator of Zod, joining in as a contributor :) | +| 3.22.5 | Adds new z.date() parsing options and override callback | +| 3.22.4 | Adds fix for nullable references in OpenAPI mode | +| 3.22.3 | Adjust root path from "#/" to "#" according to RFC 6901 | +| 3.22.2 | Adds "output" pipe strategy | +| 3.22.1 | Fixes broken imports when using some bundlers | +| 3.22.0 | Support readonly. Export both CJS and ESM. Export everything from index. Alternative map parser. Improved pattern handling and updated sources. | +| 3.21.4 | Fixes missing support for exact array length | +| 3.21.3 | Fixes issue #77 (Reference path to nullable schemas in Open-API mode) | +| 3.21.2 | Adds "integer" type Date output to support min/max checks, markdownDescription option, fixes "none" refStrategy by adding "seen" and adds an option to use "pattern" with Zods' email enum instead of "format". | +| 3.21.1 | New target (2019-09) along with improved intersection schemas, improved mutual recursion references in definitions, descriptions respected in union parser and not removed in collapsed | +| 3.21.0 | Added new string validations (ip, emoji, etc) and BigInt checks to support Zod 3.21 | +| 3.20.5 | Added uniqueItems to Set and an option to disregard pipe schemas | +| 3.20.4 | Bugfixes and improved record parsing for openApi3 | +| 3.20.3 | Added Cuid2 support introduced in Zod 3.20.3 | +| 3.20.2 | Reintroduced conditional simplified return-type for when target is OpenAPI 3 | +| 3.20.1 | Fixed inconsistent casing in imports | +| 3.20.0 | Adds support for Zod 3.20 with catch and pipe parser as well as new string validations. Refactored Ref handling; adding definitions no longer considered experimental. Main API function refactored and simplified; output type less defined but a lot easier to maintain. Doubt anyone will miss it.
Narrator: Someone did in fact miss it | +| 3.19.4 | Adds custom error message support | +| 3.19.3 | Mark `definitions` as experimental in the readme | +| 3.19.2 | Added `definitions` option | +| 3.19.1 | Strict unions fix | +| 3.19.0 | No new features added in Zod, parity bump | +| 3.18.2 | Fixes support for native enums | +| 3.18.1 | Add strictUnions options | +| 3.18.0 | Added support for branded types | +| 3.17.2 | Fix for reference paths when supplying name option string. | +| 3.17.1 | Added startsWith and endsWith string checks. Merge multiple pattern checks into allOf array. | +| 3.17.0 | Added switch case handler for new trim "check". No changes to functionality. | +| 3.15.x - 3.16.x | Skipped: Did not change the Zod API in any way relevant for this package. | +| 3.14.1 | Dependabot security updates | +| 3.14.0 | Moves Zod into peerDependencies. Supports checks for sets, NaN-type (sort of), discriminated union type and standalone optional properties (as unions with undefined) | +| 3.12.x - 3.13.x | Skipped | +| 3.11.3 | Joins unions of enums into single enum and allows enums as keys of records | +| 3.11.2 | Adds option to target Open API 3 spec (paths) instead of Json Schema 7. | +| 3.11.1 | Performance boost when using $refStrategy `none` and internal improvements. | +| 3.11.0 | Added description support introduced in Zod 3.11.5 | +| 3.10.x | Skipped: Minor 10 did not change the Zod API | +| 3.9.5 | Type bug fix: used dev dependency types in package | +| 3.9.4 | Path bug fix and test case when using optional definitions path | +| 3.9.3 | Added option to change definition property name to $defs | +| 3.9.2 | Added option to handle transform results as any instead of relying on their input schema. | +| 3.9.1 | Refactored the way reference pointers are passed around and added options pattern to main function without braking backwards compatibility! You can now add a base path, change the reference strategy (or opt out), and still set the schema name inside the options object or outside as before. | +| 3.9.0 | Added support for multipleOf number validaion, .rest() schemas for tuples and key validation for records (only compatible with string keys due to JSON Schema limitation). | +| 3.7.x - 3.8.x | Skipped to reach functional parity with Zod versioning. | +| 3.6.1 | Realised intersection had another potential ref pathing bug. Fixed. | +| 3.6.0 | Added support for default & effects (refine). Broke out changelog.md | +| 3.5.0 | Added support for CUID string validation | +| 3.4.3 | Fixed $ref pathing for catchall and intersection. Additional tests and code structure fixes. | +| 3.4.2 | Fixed broken intersection parser (Thanks [Noah2610](https://github.com/Noah2610)!) | +| 3.4.1 | Fixed pathing bug for nullable items. | +| 3.4.0 | Added support for z.lazy() | +| 3.3.0 | Added support for catchall (additionalProperties schema on objects). Rebuilt object parser. | +| 3.2.0 | Added support for Map and Set as seen by their most common JSON definitions. Beware no standardized definition seem to exist and JSON.parse doesn't handle either natively. Their implementations here are based on the spread approach. Also further simplified intersection definition to just allOf. | +| 3.1.0 | String patterns finally supported! Fixed bugs include broken external type, unsafe nullable parsing, bad intersection implementation, and missing support for passthrough keys in objects. | +| 3.0.3 | Fixed array deep pathing bug (path contained `array` instead of `items`) | +| 3.0.2 | Fixed broken type usage (NonEmptyArrayDefinition was removed from Zod) | +| 3.0.1 | Fixed a typo in the readme | +| 3.0.0 | Compatible with Zod 3.2.0. Huge props to [Mr Hammad Asif](https://github.com/mrhammadasif) for his work on this. | +| 0.6.2 | Hotfix for undefined object properties. Could crash the parser when using Pick | +| 0.6.1 | Fixed bug in union pathing. `$Ref` was missing `/anyOf` | +| 0.6.0 | Moved `@types/json-schema` and `typescript` to dev dependencies. `@types/json-schema` is now only used for the test suites. Using `strict: true` in ts config. | +| 0.5.1 | First working release with all relevant Zod types present with most validations (except for string patterns due to Zod not exposing the source regexp pattern for those). | +| < 0.5.1 | Deprecated due to broken package structure. Please be patient, I eat crayons. | diff --git a/node_modules/zod-to-json-schema/contributing.md b/node_modules/zod-to-json-schema/contributing.md new file mode 100644 index 000000000..c8b4717f8 --- /dev/null +++ b/node_modules/zod-to-json-schema/contributing.md @@ -0,0 +1,9 @@ +# Contributing + +Hey, thanks for wanting to contribute. + +Before you open a PR, make sure to open an issue and discuss the problem you want to solve. I will not consider PRs without issues. + +I use [gitmoji](https://gitmoji.dev/) for my commit messages because I think it's fun. I encourage you to do the same, but won't enforce it. + +I check PRs and issues very rarely so please be patient. diff --git a/node_modules/zod-to-json-schema/createIndex.ts b/node_modules/zod-to-json-schema/createIndex.ts new file mode 100644 index 000000000..d126fcae5 --- /dev/null +++ b/node_modules/zod-to-json-schema/createIndex.ts @@ -0,0 +1,32 @@ +import { readdirSync, writeFileSync, statSync } from "fs"; + +const ignore = ["src/index.ts"]; + +function checkSrcDir(path: string): string[] { + const lines: string[] = []; + + for (const item of readdirSync(path)) { + const itemPath = path + "/" + item; + + if (ignore.includes(itemPath)) { + continue; + } + + if (statSync(itemPath).isDirectory()) { + lines.push(...checkSrcDir(itemPath)); + } else if (item.endsWith(".ts")) { + lines.push('export * from "./' + itemPath.slice(4, -2) + 'js"'); + } + } + + return lines; +} + +const lines = checkSrcDir("src"); + +lines.push( + 'import { zodToJsonSchema } from "./zodToJsonSchema.js"', + "export default zodToJsonSchema;", +); + +writeFileSync("./src/index.ts", lines.join(";\n")); diff --git a/node_modules/zod-to-json-schema/dist/cjs/Options.js b/node_modules/zod-to-json-schema/dist/cjs/Options.js new file mode 100644 index 000000000..63970bee5 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/Options.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getDefaultOptions = exports.defaultOptions = exports.jsonDescription = exports.ignoreOverride = void 0; +exports.ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); +const jsonDescription = (jsonSchema, def) => { + if (def.description) { + try { + return { + ...jsonSchema, + ...JSON.parse(def.description), + }; + } + catch { } + } + return jsonSchema; +}; +exports.jsonDescription = jsonDescription; +exports.defaultOptions = { + name: undefined, + $refStrategy: "root", + basePath: ["#"], + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "format:date-time", + mapStrategy: "entries", + removeAdditionalStrategy: "passthrough", + allowedAdditionalProperties: true, + rejectedAdditionalProperties: false, + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + definitions: {}, + errorMessages: false, + markdownDescription: false, + patternStrategy: "escape", + applyRegexFlags: false, + emailStrategy: "format:email", + base64Strategy: "contentEncoding:base64", + nameStrategy: "ref", + openAiAnyTypeName: "OpenAiAnyType" +}; +const getDefaultOptions = (options) => (typeof options === "string" + ? { + ...exports.defaultOptions, + name: options, + } + : { + ...exports.defaultOptions, + ...options, + }); +exports.getDefaultOptions = getDefaultOptions; diff --git a/node_modules/zod-to-json-schema/dist/cjs/Refs.js b/node_modules/zod-to-json-schema/dist/cjs/Refs.js new file mode 100644 index 000000000..04fd37b8b --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/Refs.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRefs = void 0; +const Options_js_1 = require("./Options.js"); +const getRefs = (options) => { + const _options = (0, Options_js_1.getDefaultOptions)(options); + const currentPath = _options.name !== undefined + ? [..._options.basePath, _options.definitionPath, _options.name] + : _options.basePath; + return { + ..._options, + flags: { hasReferencedOpenAiAnyType: false }, + currentPath: currentPath, + propertyPath: undefined, + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ + def._def, + { + def: def._def, + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: undefined, + }, + ])), + }; +}; +exports.getRefs = getRefs; diff --git a/node_modules/zod-to-json-schema/dist/cjs/errorMessages.js b/node_modules/zod-to-json-schema/dist/cjs/errorMessages.js new file mode 100644 index 000000000..a65eb082e --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/errorMessages.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setResponseValueAndErrors = exports.addErrorMessage = void 0; +function addErrorMessage(res, key, errorMessage, refs) { + if (!refs?.errorMessages) + return; + if (errorMessage) { + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage, + }; + } +} +exports.addErrorMessage = addErrorMessage; +function setResponseValueAndErrors(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage(res, key, errorMessage, refs); +} +exports.setResponseValueAndErrors = setResponseValueAndErrors; diff --git a/node_modules/zod-to-json-schema/dist/cjs/getRelativePath.js b/node_modules/zod-to-json-schema/dist/cjs/getRelativePath.js new file mode 100644 index 000000000..03f4d787a --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/getRelativePath.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRelativePath = void 0; +const getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) { + if (pathA[i] !== pathB[i]) + break; + } + return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); +}; +exports.getRelativePath = getRelativePath; diff --git a/node_modules/zod-to-json-schema/dist/cjs/index.js b/node_modules/zod-to-json-schema/dist/cjs/index.js new file mode 100644 index 000000000..c438d2cad --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/index.js @@ -0,0 +1,56 @@ +"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 }); +__exportStar(require("./Options.js"), exports); +__exportStar(require("./Refs.js"), exports); +__exportStar(require("./errorMessages.js"), exports); +__exportStar(require("./getRelativePath.js"), exports); +__exportStar(require("./parseDef.js"), exports); +__exportStar(require("./parseTypes.js"), exports); +__exportStar(require("./parsers/any.js"), exports); +__exportStar(require("./parsers/array.js"), exports); +__exportStar(require("./parsers/bigint.js"), exports); +__exportStar(require("./parsers/boolean.js"), exports); +__exportStar(require("./parsers/branded.js"), exports); +__exportStar(require("./parsers/catch.js"), exports); +__exportStar(require("./parsers/date.js"), exports); +__exportStar(require("./parsers/default.js"), exports); +__exportStar(require("./parsers/effects.js"), exports); +__exportStar(require("./parsers/enum.js"), exports); +__exportStar(require("./parsers/intersection.js"), exports); +__exportStar(require("./parsers/literal.js"), exports); +__exportStar(require("./parsers/map.js"), exports); +__exportStar(require("./parsers/nativeEnum.js"), exports); +__exportStar(require("./parsers/never.js"), exports); +__exportStar(require("./parsers/null.js"), exports); +__exportStar(require("./parsers/nullable.js"), exports); +__exportStar(require("./parsers/number.js"), exports); +__exportStar(require("./parsers/object.js"), exports); +__exportStar(require("./parsers/optional.js"), exports); +__exportStar(require("./parsers/pipeline.js"), exports); +__exportStar(require("./parsers/promise.js"), exports); +__exportStar(require("./parsers/readonly.js"), exports); +__exportStar(require("./parsers/record.js"), exports); +__exportStar(require("./parsers/set.js"), exports); +__exportStar(require("./parsers/string.js"), exports); +__exportStar(require("./parsers/tuple.js"), exports); +__exportStar(require("./parsers/undefined.js"), exports); +__exportStar(require("./parsers/union.js"), exports); +__exportStar(require("./parsers/unknown.js"), exports); +__exportStar(require("./selectParser.js"), exports); +__exportStar(require("./zodToJsonSchema.js"), exports); +const zodToJsonSchema_js_1 = require("./zodToJsonSchema.js"); +exports.default = zodToJsonSchema_js_1.zodToJsonSchema; diff --git a/node_modules/zod-to-json-schema/dist/cjs/package.json b/node_modules/zod-to-json-schema/dist/cjs/package.json new file mode 100644 index 000000000..0292b9956 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/package.json @@ -0,0 +1 @@ +{"type":"commonjs"} \ No newline at end of file diff --git a/node_modules/zod-to-json-schema/dist/cjs/parseDef.js b/node_modules/zod-to-json-schema/dist/cjs/parseDef.js new file mode 100644 index 000000000..1a4d35f6f --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parseDef.js @@ -0,0 +1,66 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseDef = void 0; +const Options_js_1 = require("./Options.js"); +const selectParser_js_1 = require("./selectParser.js"); +const getRelativePath_js_1 = require("./getRelativePath.js"); +const any_js_1 = require("./parsers/any.js"); +function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== Options_js_1.ignoreOverride) { + return overrideResult; + } + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== undefined) { + return seenSchema; + } + } + const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; + refs.seen.set(def, newItem); + const jsonSchemaOrGetter = (0, selectParser_js_1.selectParser)(def, def.typeName, refs); + // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive) + const jsonSchema = typeof jsonSchemaOrGetter === "function" + ? parseDef(jsonSchemaOrGetter(), refs) + : jsonSchemaOrGetter; + if (jsonSchema) { + addMeta(def, refs, jsonSchema); + } + if (refs.postProcess) { + const postProcessResult = refs.postProcess(jsonSchema, def, refs); + newItem.jsonSchema = jsonSchema; + return postProcessResult; + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +exports.parseDef = parseDef; +const get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case "root": + return { $ref: item.path.join("/") }; + case "relative": + return { $ref: (0, getRelativePath_js_1.getRelativePath)(refs.currentPath, item.path) }; + case "none": + case "seen": { + if (item.path.length < refs.currentPath.length && + item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return (0, any_js_1.parseAnyDef)(refs); + } + return refs.$refStrategy === "seen" ? (0, any_js_1.parseAnyDef)(refs) : undefined; + } + } +}; +const addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; + } + } + return jsonSchema; +}; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parseTypes.js b/node_modules/zod-to-json-schema/dist/cjs/parseTypes.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parseTypes.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/any.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/any.js new file mode 100644 index 000000000..d48e69dc8 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/any.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseAnyDef = void 0; +const getRelativePath_js_1 = require("../getRelativePath.js"); +function parseAnyDef(refs) { + if (refs.target !== "openAi") { + return {}; + } + const anyDefinitionPath = [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName, + ]; + refs.flags.hasReferencedOpenAiAnyType = true; + return { + $ref: refs.$refStrategy === "relative" + ? (0, getRelativePath_js_1.getRelativePath)(anyDefinitionPath, refs.currentPath) + : anyDefinitionPath.join("/"), + }; +} +exports.parseAnyDef = parseAnyDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/array.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/array.js new file mode 100644 index 000000000..4f7a3db61 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/array.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseArrayDef = void 0; +const v3_1 = require("zod/v3"); +const errorMessages_js_1 = require("../errorMessages.js"); +const parseDef_js_1 = require("../parseDef.js"); +function parseArrayDef(def, refs) { + const res = { + type: "array", + }; + if (def.type?._def && + def.type?._def?.typeName !== v3_1.ZodFirstPartyTypeKind.ZodAny) { + res.items = (0, parseDef_js_1.parseDef)(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, "items"], + }); + } + if (def.minLength) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minItems", def.minLength.value, def.minLength.message, refs); + } + if (def.maxLength) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); + } + if (def.exactLength) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minItems", def.exactLength.value, def.exactLength.message, refs); + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); + } + return res; +} +exports.parseArrayDef = parseArrayDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/bigint.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/bigint.js new file mode 100644 index 000000000..239dd3423 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/bigint.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseBigintDef = void 0; +const errorMessages_js_1 = require("../errorMessages.js"); +function parseBigintDef(def, refs) { + const res = { + type: "integer", + format: "int64", + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } + else { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } + else { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs); + break; + } + } + return res; +} +exports.parseBigintDef = parseBigintDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/boolean.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/boolean.js new file mode 100644 index 000000000..504cfa17b --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/boolean.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseBooleanDef = void 0; +function parseBooleanDef() { + return { + type: "boolean", + }; +} +exports.parseBooleanDef = parseBooleanDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/branded.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/branded.js new file mode 100644 index 000000000..db09a921c --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/branded.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseBrandedDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +function parseBrandedDef(_def, refs) { + return (0, parseDef_js_1.parseDef)(_def.type._def, refs); +} +exports.parseBrandedDef = parseBrandedDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/catch.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/catch.js new file mode 100644 index 000000000..75d86c10c --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/catch.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseCatchDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +const parseCatchDef = (def, refs) => { + return (0, parseDef_js_1.parseDef)(def.innerType._def, refs); +}; +exports.parseCatchDef = parseCatchDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/date.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/date.js new file mode 100644 index 000000000..5a5229f7e --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/date.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseDateDef = void 0; +const errorMessages_js_1 = require("../errorMessages.js"); +function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) { + return { + anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)), + }; + } + switch (strategy) { + case "string": + case "format:date-time": + return { + type: "string", + format: "date-time", + }; + case "format:date": + return { + type: "string", + format: "date", + }; + case "integer": + return integerDateParser(def, refs); + } +} +exports.parseDateDef = parseDateDef; +const integerDateParser = (def, refs) => { + const res = { + type: "integer", + format: "unix-time", + }; + if (refs.target === "openApi3") { + return res; + } + for (const check of def.checks) { + switch (check.kind) { + case "min": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, // This is in milliseconds + check.message, refs); + break; + case "max": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, // This is in milliseconds + check.message, refs); + break; + } + } + return res; +}; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/default.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/default.js new file mode 100644 index 000000000..f558d0348 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/default.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseDefaultDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +function parseDefaultDef(_def, refs) { + return { + ...(0, parseDef_js_1.parseDef)(_def.innerType._def, refs), + default: _def.defaultValue(), + }; +} +exports.parseDefaultDef = parseDefaultDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/effects.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/effects.js new file mode 100644 index 000000000..e862cb415 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/effects.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseEffectsDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +const any_js_1 = require("./any.js"); +function parseEffectsDef(_def, refs) { + return refs.effectStrategy === "input" + ? (0, parseDef_js_1.parseDef)(_def.schema._def, refs) + : (0, any_js_1.parseAnyDef)(refs); +} +exports.parseEffectsDef = parseEffectsDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/enum.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/enum.js new file mode 100644 index 000000000..63d599141 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/enum.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseEnumDef = void 0; +function parseEnumDef(def) { + return { + type: "string", + enum: Array.from(def.values), + }; +} +exports.parseEnumDef = parseEnumDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/intersection.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/intersection.js new file mode 100644 index 000000000..d68f73ef2 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/intersection.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseIntersectionDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +const isJsonSchema7AllOfType = (type) => { + if ("type" in type && type.type === "string") + return false; + return "allOf" in type; +}; +function parseIntersectionDef(def, refs) { + const allOf = [ + (0, parseDef_js_1.parseDef)(def.left._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"], + }), + (0, parseDef_js_1.parseDef)(def.right._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "1"], + }), + ].filter((x) => !!x); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" + ? { unevaluatedProperties: false } + : undefined; + const mergedAllOf = []; + // If either of the schemas is an allOf, merge them into a single allOf + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === undefined) { + // If one of the schemas has no unevaluatedProperties set, + // the merged schema should also have no unevaluatedProperties set + unevaluatedProperties = undefined; + } + } + else { + let nestedSchema = schema; + if ("additionalProperties" in schema && + schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } + else { + // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties + unevaluatedProperties = undefined; + } + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length + ? { + allOf: mergedAllOf, + ...unevaluatedProperties, + } + : undefined; +} +exports.parseIntersectionDef = parseIntersectionDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/literal.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/literal.js new file mode 100644 index 000000000..66c4ba063 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/literal.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseLiteralDef = void 0; +function parseLiteralDef(def, refs) { + const parsedType = typeof def.value; + if (parsedType !== "bigint" && + parsedType !== "number" && + parsedType !== "boolean" && + parsedType !== "string") { + return { + type: Array.isArray(def.value) ? "array" : "object", + }; + } + if (refs.target === "openApi3") { + return { + type: parsedType === "bigint" ? "integer" : parsedType, + enum: [def.value], + }; + } + return { + type: parsedType === "bigint" ? "integer" : parsedType, + const: def.value, + }; +} +exports.parseLiteralDef = parseLiteralDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/map.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/map.js new file mode 100644 index 000000000..9974688fa --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/map.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseMapDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +const record_js_1 = require("./record.js"); +const any_js_1 = require("./any.js"); +function parseMapDef(def, refs) { + if (refs.mapStrategy === "record") { + return (0, record_js_1.parseRecordDef)(def, refs); + } + const keys = (0, parseDef_js_1.parseDef)(def.keyType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "0"], + }) || (0, any_js_1.parseAnyDef)(refs); + const values = (0, parseDef_js_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "1"], + }) || (0, any_js_1.parseAnyDef)(refs); + return { + type: "array", + maxItems: 125, + items: { + type: "array", + items: [keys, values], + minItems: 2, + maxItems: 2, + }, + }; +} +exports.parseMapDef = parseMapDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/nativeEnum.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/nativeEnum.js new file mode 100644 index 000000000..a3b35724d --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/nativeEnum.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseNativeEnumDef = void 0; +function parseNativeEnumDef(def) { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== "number"; + }); + const actualValues = actualKeys.map((key) => object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); + return { + type: parsedTypes.length === 1 + ? parsedTypes[0] === "string" + ? "string" + : "number" + : ["string", "number"], + enum: actualValues, + }; +} +exports.parseNativeEnumDef = parseNativeEnumDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/never.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/never.js new file mode 100644 index 000000000..01f24f9e4 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/never.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseNeverDef = void 0; +const any_js_1 = require("./any.js"); +function parseNeverDef(refs) { + return refs.target === "openAi" + ? undefined + : { + not: (0, any_js_1.parseAnyDef)({ + ...refs, + currentPath: [...refs.currentPath, "not"], + }), + }; +} +exports.parseNeverDef = parseNeverDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/null.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/null.js new file mode 100644 index 000000000..1b4bfa8f8 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/null.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseNullDef = void 0; +function parseNullDef(refs) { + return refs.target === "openApi3" + ? { + enum: ["null"], + nullable: true, + } + : { + type: "null", + }; +} +exports.parseNullDef = parseNullDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/nullable.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/nullable.js new file mode 100644 index 000000000..8890795ab --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/nullable.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseNullableDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +const union_js_1 = require("./union.js"); +function parseNullableDef(def, refs) { + if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && + (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === "openApi3") { + return { + type: union_js_1.primitiveMappings[def.innerType._def.typeName], + nullable: true, + }; + } + return { + type: [ + union_js_1.primitiveMappings[def.innerType._def.typeName], + "null", + ], + }; + } + if (refs.target === "openApi3") { + const base = (0, parseDef_js_1.parseDef)(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath], + }); + if (base && "$ref" in base) + return { allOf: [base], nullable: true }; + return base && { ...base, nullable: true }; + } + const base = (0, parseDef_js_1.parseDef)(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "0"], + }); + return base && { anyOf: [base, { type: "null" }] }; +} +exports.parseNullableDef = parseNullableDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/number.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/number.js new file mode 100644 index 000000000..274014a94 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/number.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseNumberDef = void 0; +const errorMessages_js_1 = require("../errorMessages.js"); +function parseNumberDef(def, refs) { + const res = { + type: "number", + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "int": + res.type = "integer"; + (0, errorMessages_js_1.addErrorMessage)(res, "type", check.message, refs); + break; + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } + else { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } + else { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs); + break; + } + } + return res; +} +exports.parseNumberDef = parseNumberDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/object.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/object.js new file mode 100644 index 000000000..87c77e781 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/object.js @@ -0,0 +1,76 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseObjectDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +function parseObjectDef(def, refs) { + const forceOptionalIntoNullable = refs.target === "openAi"; + const result = { + type: "object", + properties: {}, + }; + const required = []; + const shape = def.shape(); + for (const propName in shape) { + let propDef = shape[propName]; + if (propDef === undefined || propDef._def === undefined) { + continue; + } + let propOptional = safeIsOptional(propDef); + if (propOptional && forceOptionalIntoNullable) { + if (propDef._def.typeName === "ZodOptional") { + propDef = propDef._def.innerType; + } + if (!propDef.isNullable()) { + propDef = propDef.nullable(); + } + propOptional = false; + } + const parsedDef = (0, parseDef_js_1.parseDef)(propDef._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", propName], + propertyPath: [...refs.currentPath, "properties", propName], + }); + if (parsedDef === undefined) { + continue; + } + result.properties[propName] = parsedDef; + if (!propOptional) { + required.push(propName); + } + } + if (required.length) { + result.required = required; + } + const additionalProperties = decideAdditionalProperties(def, refs); + if (additionalProperties !== undefined) { + result.additionalProperties = additionalProperties; + } + return result; +} +exports.parseObjectDef = parseObjectDef; +function decideAdditionalProperties(def, refs) { + if (def.catchall._def.typeName !== "ZodNever") { + return (0, parseDef_js_1.parseDef)(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"], + }); + } + switch (def.unknownKeys) { + case "passthrough": + return refs.allowedAdditionalProperties; + case "strict": + return refs.rejectedAdditionalProperties; + case "strip": + return refs.removeAdditionalStrategy === "strict" + ? refs.allowedAdditionalProperties + : refs.rejectedAdditionalProperties; + } +} +function safeIsOptional(schema) { + try { + return schema.isOptional(); + } + catch { + return true; + } +} diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/optional.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/optional.js new file mode 100644 index 000000000..234d81902 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/optional.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseOptionalDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +const any_js_1 = require("./any.js"); +const parseOptionalDef = (def, refs) => { + if (refs.currentPath.toString() === refs.propertyPath?.toString()) { + return (0, parseDef_js_1.parseDef)(def.innerType._def, refs); + } + const innerSchema = (0, parseDef_js_1.parseDef)(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "1"], + }); + return innerSchema + ? { + anyOf: [ + { + not: (0, any_js_1.parseAnyDef)(refs), + }, + innerSchema, + ], + } + : (0, any_js_1.parseAnyDef)(refs); +}; +exports.parseOptionalDef = parseOptionalDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/pipeline.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/pipeline.js new file mode 100644 index 000000000..c05d0ef6b --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/pipeline.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parsePipelineDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +const parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === "input") { + return (0, parseDef_js_1.parseDef)(def.in._def, refs); + } + else if (refs.pipeStrategy === "output") { + return (0, parseDef_js_1.parseDef)(def.out._def, refs); + } + const a = (0, parseDef_js_1.parseDef)(def.in._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"], + }); + const b = (0, parseDef_js_1.parseDef)(def.out._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"], + }); + return { + allOf: [a, b].filter((x) => x !== undefined), + }; +}; +exports.parsePipelineDef = parsePipelineDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/promise.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/promise.js new file mode 100644 index 000000000..9f917e7ae --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/promise.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parsePromiseDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +function parsePromiseDef(def, refs) { + return (0, parseDef_js_1.parseDef)(def.type._def, refs); +} +exports.parsePromiseDef = parsePromiseDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/readonly.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/readonly.js new file mode 100644 index 000000000..cdccec882 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/readonly.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseReadonlyDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +const parseReadonlyDef = (def, refs) => { + return (0, parseDef_js_1.parseDef)(def.innerType._def, refs); +}; +exports.parseReadonlyDef = parseReadonlyDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/record.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/record.js new file mode 100644 index 000000000..197f78f75 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/record.js @@ -0,0 +1,65 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseRecordDef = void 0; +const v3_1 = require("zod/v3"); +const parseDef_js_1 = require("../parseDef.js"); +const string_js_1 = require("./string.js"); +const branded_js_1 = require("./branded.js"); +const any_js_1 = require("./any.js"); +function parseRecordDef(def, refs) { + if (refs.target === "openAi") { + console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); + } + if (refs.target === "openApi3" && + def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodEnum) { + return { + type: "object", + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: (0, parseDef_js_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", key], + }) ?? (0, any_js_1.parseAnyDef)(refs), + }), {}), + additionalProperties: refs.rejectedAdditionalProperties, + }; + } + const schema = { + type: "object", + additionalProperties: (0, parseDef_js_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"], + }) ?? refs.allowedAdditionalProperties, + }; + if (refs.target === "openApi3") { + return schema; + } + if (def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodString && + def.keyType._def.checks?.length) { + const { type, ...keyType } = (0, string_js_1.parseStringDef)(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType, + }; + } + else if (def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodEnum) { + return { + ...schema, + propertyNames: { + enum: def.keyType._def.values, + }, + }; + } + else if (def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodBranded && + def.keyType._def.type._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodString && + def.keyType._def.type._def.checks?.length) { + const { type, ...keyType } = (0, branded_js_1.parseBrandedDef)(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType, + }; + } + return schema; +} +exports.parseRecordDef = parseRecordDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/set.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/set.js new file mode 100644 index 000000000..8a2dee03c --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/set.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseSetDef = void 0; +const errorMessages_js_1 = require("../errorMessages.js"); +const parseDef_js_1 = require("../parseDef.js"); +function parseSetDef(def, refs) { + const items = (0, parseDef_js_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items"], + }); + const schema = { + type: "array", + uniqueItems: true, + items, + }; + if (def.minSize) { + (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "minItems", def.minSize.value, def.minSize.message, refs); + } + if (def.maxSize) { + (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); + } + return schema; +} +exports.parseSetDef = parseSetDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/string.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/string.js new file mode 100644 index 000000000..fd2ba9ebf --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/string.js @@ -0,0 +1,356 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseStringDef = exports.zodPatterns = void 0; +const errorMessages_js_1 = require("../errorMessages.js"); +let emojiRegex = undefined; +/** + * Generated from the regular expressions found here as of 2024-05-22: + * https://github.com/colinhacks/zod/blob/master/src/types.ts. + * + * Expressions with /i flag have been changed accordingly. + */ +exports.zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (emojiRegex === undefined) { + emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); + } + return emojiRegex; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, + jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/, +}; +function parseStringDef(def, refs) { + const res = { + type: "string", + }; + if (def.checks) { + for (const check of def.checks) { + switch (check.kind) { + case "min": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" + ? Math.max(res.minLength, check.value) + : check.value, check.message, refs); + break; + case "max": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" + ? Math.min(res.maxLength, check.value) + : check.value, check.message, refs); + break; + case "email": + switch (refs.emailStrategy) { + case "format:email": + addFormat(res, "email", check.message, refs); + break; + case "format:idn-email": + addFormat(res, "idn-email", check.message, refs); + break; + case "pattern:zod": + addPattern(res, exports.zodPatterns.email, check.message, refs); + break; + } + break; + case "url": + addFormat(res, "uri", check.message, refs); + break; + case "uuid": + addFormat(res, "uuid", check.message, refs); + break; + case "regex": + addPattern(res, check.regex, check.message, refs); + break; + case "cuid": + addPattern(res, exports.zodPatterns.cuid, check.message, refs); + break; + case "cuid2": + addPattern(res, exports.zodPatterns.cuid2, check.message, refs); + break; + case "startsWith": + addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); + break; + case "endsWith": + addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); + break; + case "datetime": + addFormat(res, "date-time", check.message, refs); + break; + case "date": + addFormat(res, "date", check.message, refs); + break; + case "time": + addFormat(res, "time", check.message, refs); + break; + case "duration": + addFormat(res, "duration", check.message, refs); + break; + case "length": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" + ? Math.max(res.minLength, check.value) + : check.value, check.message, refs); + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" + ? Math.min(res.maxLength, check.value) + : check.value, check.message, refs); + break; + case "includes": { + addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); + break; + } + case "ip": { + if (check.version !== "v6") { + addFormat(res, "ipv4", check.message, refs); + } + if (check.version !== "v4") { + addFormat(res, "ipv6", check.message, refs); + } + break; + } + case "base64url": + addPattern(res, exports.zodPatterns.base64url, check.message, refs); + break; + case "jwt": + addPattern(res, exports.zodPatterns.jwt, check.message, refs); + break; + case "cidr": { + if (check.version !== "v6") { + addPattern(res, exports.zodPatterns.ipv4Cidr, check.message, refs); + } + if (check.version !== "v4") { + addPattern(res, exports.zodPatterns.ipv6Cidr, check.message, refs); + } + break; + } + case "emoji": + addPattern(res, exports.zodPatterns.emoji(), check.message, refs); + break; + case "ulid": { + addPattern(res, exports.zodPatterns.ulid, check.message, refs); + break; + } + case "base64": { + switch (refs.base64Strategy) { + case "format:binary": { + addFormat(res, "binary", check.message, refs); + break; + } + case "contentEncoding:base64": { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "contentEncoding", "base64", check.message, refs); + break; + } + case "pattern:zod": { + addPattern(res, exports.zodPatterns.base64, check.message, refs); + break; + } + } + break; + } + case "nanoid": { + addPattern(res, exports.zodPatterns.nanoid, check.message, refs); + } + case "toLowerCase": + case "toUpperCase": + case "trim": + break; + default: + ((_) => { })(check); + } + } + } + return res; +} +exports.parseStringDef = parseStringDef; +function escapeLiteralCheckValue(literal, refs) { + return refs.patternStrategy === "escape" + ? escapeNonAlphaNumeric(literal) + : literal; +} +const ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); +function escapeNonAlphaNumeric(source) { + let result = ""; + for (let i = 0; i < source.length; i++) { + if (!ALPHA_NUMERIC.has(source[i])) { + result += "\\"; + } + result += source[i]; + } + return result; +} +// Adds a "format" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones. +function addFormat(schema, value, message, refs) { + if (schema.format || schema.anyOf?.some((x) => x.format)) { + if (!schema.anyOf) { + schema.anyOf = []; + } + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { format: schema.errorMessage.format }, + }), + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.anyOf.push({ + format: value, + ...(message && + refs.errorMessages && { errorMessage: { format: message } }), + }); + } + else { + (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "format", value, message, refs); + } +} +// Adds a "pattern" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones. +function addPattern(schema, regex, message, refs) { + if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { + if (!schema.allOf) { + schema.allOf = []; + } + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { pattern: schema.errorMessage.pattern }, + }), + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.allOf.push({ + pattern: stringifyRegExpWithFlags(regex, refs), + ...(message && + refs.errorMessages && { errorMessage: { pattern: message } }), + }); + } + else { + (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); + } +} +// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true +function stringifyRegExpWithFlags(regex, refs) { + if (!refs.applyRegexFlags || !regex.flags) { + return regex.source; + } + // Currently handled flags + const flags = { + i: regex.flags.includes("i"), + m: regex.flags.includes("m"), + s: regex.flags.includes("s"), // `.` matches newlines + }; + // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ""; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i = 0; i < source.length; i++) { + if (isEscaped) { + pattern += source[i]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i]; + pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); + inCharRange = false; + } + else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { + pattern += source[i]; + inCharRange = true; + } + else { + pattern += `${source[i]}${source[i].toUpperCase()}`; + } + continue; + } + } + else if (source[i].match(/[a-z]/)) { + pattern += `[${source[i]}${source[i].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i] === "^") { + pattern += `(^|(?<=[\r\n]))`; + continue; + } + else if (source[i] === "$") { + pattern += `($|(?=[\r\n]))`; + continue; + } + } + if (flags.s && source[i] === ".") { + pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; + continue; + } + pattern += source[i]; + if (source[i] === "\\") { + isEscaped = true; + } + else if (inCharGroup && source[i] === "]") { + inCharGroup = false; + } + else if (!inCharGroup && source[i] === "[") { + inCharGroup = true; + } + } + try { + new RegExp(pattern); + } + catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; +} diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/tuple.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/tuple.js new file mode 100644 index 000000000..e8b9fc568 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/tuple.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseTupleDef = void 0; +const parseDef_js_1 = require("../parseDef.js"); +function parseTupleDef(def, refs) { + if (def.rest) { + return { + type: "array", + minItems: def.items.length, + items: def.items + .map((x, i) => (0, parseDef_js_1.parseDef)(x._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i}`], + })) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + additionalItems: (0, parseDef_js_1.parseDef)(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalItems"], + }), + }; + } + else { + return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items + .map((x, i) => (0, parseDef_js_1.parseDef)(x._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i}`], + })) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + }; + } +} +exports.parseTupleDef = parseTupleDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/undefined.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/undefined.js new file mode 100644 index 000000000..529d7ee20 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/undefined.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseUndefinedDef = void 0; +const any_js_1 = require("./any.js"); +function parseUndefinedDef(refs) { + return { + not: (0, any_js_1.parseAnyDef)(refs), + }; +} +exports.parseUndefinedDef = parseUndefinedDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/union.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/union.js new file mode 100644 index 000000000..808e57272 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/union.js @@ -0,0 +1,84 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseUnionDef = exports.primitiveMappings = void 0; +const parseDef_js_1 = require("../parseDef.js"); +exports.primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null", +}; +function parseUnionDef(def, refs) { + if (refs.target === "openApi3") + return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. + if (options.every((x) => x._def.typeName in exports.primitiveMappings && + (!x._def.checks || !x._def.checks.length))) { + // all types in union are primitive and lack checks, so might as well squash into {type: [...]} + const types = options.reduce((types, x) => { + const type = exports.primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43 + return type && !types.includes(type) ? [...types, type] : types; + }, []); + return { + type: types.length > 1 ? types : types[0], + }; + } + else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { + // all options literals + const types = options.reduce((acc, x) => { + const type = typeof x._def.value; + switch (type) { + case "string": + case "number": + case "boolean": + return [...acc, type]; + case "bigint": + return [...acc, "integer"]; + case "object": + if (x._def.value === null) + return [...acc, "null"]; + case "symbol": + case "undefined": + case "function": + default: + return acc; + } + }, []); + if (types.length === options.length) { + // all the literals are primitive, as far as null can be considered primitive + const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []), + }; + } + } + else if (options.every((x) => x._def.typeName === "ZodEnum")) { + return { + type: "string", + enum: options.reduce((acc, x) => [ + ...acc, + ...x._def.values.filter((x) => !acc.includes(x)), + ], []), + }; + } + return asAnyOf(def, refs); +} +exports.parseUnionDef = parseUnionDef; +const asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map + ? Array.from(def.options.values()) + : def.options) + .map((x, i) => (0, parseDef_js_1.parseDef)(x._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", `${i}`], + })) + .filter((x) => !!x && + (!refs.strictUnions || + (typeof x === "object" && Object.keys(x).length > 0))); + return anyOf.length ? { anyOf } : undefined; +}; diff --git a/node_modules/zod-to-json-schema/dist/cjs/parsers/unknown.js b/node_modules/zod-to-json-schema/dist/cjs/parsers/unknown.js new file mode 100644 index 000000000..22e55649f --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/parsers/unknown.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseUnknownDef = void 0; +const any_js_1 = require("./any.js"); +function parseUnknownDef(refs) { + return (0, any_js_1.parseAnyDef)(refs); +} +exports.parseUnknownDef = parseUnknownDef; diff --git a/node_modules/zod-to-json-schema/dist/cjs/selectParser.js b/node_modules/zod-to-json-schema/dist/cjs/selectParser.js new file mode 100644 index 000000000..fbe18d9ae --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/selectParser.js @@ -0,0 +1,109 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.selectParser = void 0; +const v3_1 = require("zod/v3"); +const any_js_1 = require("./parsers/any.js"); +const array_js_1 = require("./parsers/array.js"); +const bigint_js_1 = require("./parsers/bigint.js"); +const boolean_js_1 = require("./parsers/boolean.js"); +const branded_js_1 = require("./parsers/branded.js"); +const catch_js_1 = require("./parsers/catch.js"); +const date_js_1 = require("./parsers/date.js"); +const default_js_1 = require("./parsers/default.js"); +const effects_js_1 = require("./parsers/effects.js"); +const enum_js_1 = require("./parsers/enum.js"); +const intersection_js_1 = require("./parsers/intersection.js"); +const literal_js_1 = require("./parsers/literal.js"); +const map_js_1 = require("./parsers/map.js"); +const nativeEnum_js_1 = require("./parsers/nativeEnum.js"); +const never_js_1 = require("./parsers/never.js"); +const null_js_1 = require("./parsers/null.js"); +const nullable_js_1 = require("./parsers/nullable.js"); +const number_js_1 = require("./parsers/number.js"); +const object_js_1 = require("./parsers/object.js"); +const optional_js_1 = require("./parsers/optional.js"); +const pipeline_js_1 = require("./parsers/pipeline.js"); +const promise_js_1 = require("./parsers/promise.js"); +const record_js_1 = require("./parsers/record.js"); +const set_js_1 = require("./parsers/set.js"); +const string_js_1 = require("./parsers/string.js"); +const tuple_js_1 = require("./parsers/tuple.js"); +const undefined_js_1 = require("./parsers/undefined.js"); +const union_js_1 = require("./parsers/union.js"); +const unknown_js_1 = require("./parsers/unknown.js"); +const readonly_js_1 = require("./parsers/readonly.js"); +const selectParser = (def, typeName, refs) => { + switch (typeName) { + case v3_1.ZodFirstPartyTypeKind.ZodString: + return (0, string_js_1.parseStringDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodNumber: + return (0, number_js_1.parseNumberDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodObject: + return (0, object_js_1.parseObjectDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodBigInt: + return (0, bigint_js_1.parseBigintDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodBoolean: + return (0, boolean_js_1.parseBooleanDef)(); + case v3_1.ZodFirstPartyTypeKind.ZodDate: + return (0, date_js_1.parseDateDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodUndefined: + return (0, undefined_js_1.parseUndefinedDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodNull: + return (0, null_js_1.parseNullDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodArray: + return (0, array_js_1.parseArrayDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodUnion: + case v3_1.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return (0, union_js_1.parseUnionDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodIntersection: + return (0, intersection_js_1.parseIntersectionDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodTuple: + return (0, tuple_js_1.parseTupleDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodRecord: + return (0, record_js_1.parseRecordDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodLiteral: + return (0, literal_js_1.parseLiteralDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodEnum: + return (0, enum_js_1.parseEnumDef)(def); + case v3_1.ZodFirstPartyTypeKind.ZodNativeEnum: + return (0, nativeEnum_js_1.parseNativeEnumDef)(def); + case v3_1.ZodFirstPartyTypeKind.ZodNullable: + return (0, nullable_js_1.parseNullableDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodOptional: + return (0, optional_js_1.parseOptionalDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodMap: + return (0, map_js_1.parseMapDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodSet: + return (0, set_js_1.parseSetDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodLazy: + return () => def.getter()._def; + case v3_1.ZodFirstPartyTypeKind.ZodPromise: + return (0, promise_js_1.parsePromiseDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodNaN: + case v3_1.ZodFirstPartyTypeKind.ZodNever: + return (0, never_js_1.parseNeverDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodEffects: + return (0, effects_js_1.parseEffectsDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodAny: + return (0, any_js_1.parseAnyDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodUnknown: + return (0, unknown_js_1.parseUnknownDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodDefault: + return (0, default_js_1.parseDefaultDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodBranded: + return (0, branded_js_1.parseBrandedDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodReadonly: + return (0, readonly_js_1.parseReadonlyDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodCatch: + return (0, catch_js_1.parseCatchDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodPipeline: + return (0, pipeline_js_1.parsePipelineDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodFunction: + case v3_1.ZodFirstPartyTypeKind.ZodVoid: + case v3_1.ZodFirstPartyTypeKind.ZodSymbol: + return undefined; + default: + return ((_) => undefined)(typeName); + } +}; +exports.selectParser = selectParser; diff --git a/node_modules/zod-to-json-schema/dist/cjs/zodToJsonSchema.js b/node_modules/zod-to-json-schema/dist/cjs/zodToJsonSchema.js new file mode 100644 index 000000000..2673e3a2e --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/cjs/zodToJsonSchema.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.zodToJsonSchema = void 0; +const parseDef_js_1 = require("./parseDef.js"); +const Refs_js_1 = require("./Refs.js"); +const any_js_1 = require("./parsers/any.js"); +const zodToJsonSchema = (schema, options) => { + const refs = (0, Refs_js_1.getRefs)(options); + let definitions = typeof options === "object" && options.definitions + ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({ + ...acc, + [name]: (0, parseDef_js_1.parseDef)(schema._def, { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name], + }, true) ?? (0, any_js_1.parseAnyDef)(refs), + }), {}) + : undefined; + const name = typeof options === "string" + ? options + : options?.nameStrategy === "title" + ? undefined + : options?.name; + const main = (0, parseDef_js_1.parseDef)(schema._def, name === undefined + ? refs + : { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name], + }, false) ?? (0, any_js_1.parseAnyDef)(refs); + const title = typeof options === "object" && + options.name !== undefined && + options.nameStrategy === "title" + ? options.name + : undefined; + if (title !== undefined) { + main.title = title; + } + if (refs.flags.hasReferencedOpenAiAnyType) { + if (!definitions) { + definitions = {}; + } + if (!definitions[refs.openAiAnyTypeName]) { + definitions[refs.openAiAnyTypeName] = { + // Skipping "object" as no properties can be defined and additionalProperties must be "false" + type: ["string", "number", "integer", "boolean", "array", "null"], + items: { + $ref: refs.$refStrategy === "relative" + ? "1" + : [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName, + ].join("/"), + }, + }; + } + } + const combined = name === undefined + ? definitions + ? { + ...main, + [refs.definitionPath]: definitions, + } + : main + : { + $ref: [ + ...(refs.$refStrategy === "relative" ? [] : refs.basePath), + refs.definitionPath, + name, + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name]: main, + }, + }; + if (refs.target === "jsonSchema7") { + combined.$schema = "http://json-schema.org/draft-07/schema#"; + } + else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { + combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + } + if (refs.target === "openAi" && + ("anyOf" in combined || + "oneOf" in combined || + "allOf" in combined || + ("type" in combined && Array.isArray(combined.type)))) { + console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); + } + return combined; +}; +exports.zodToJsonSchema = zodToJsonSchema; diff --git a/node_modules/zod-to-json-schema/dist/esm/Options.js b/node_modules/zod-to-json-schema/dist/esm/Options.js new file mode 100644 index 000000000..e26d8cec2 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/Options.js @@ -0,0 +1,46 @@ +export const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); +export const jsonDescription = (jsonSchema, def) => { + if (def.description) { + try { + return { + ...jsonSchema, + ...JSON.parse(def.description), + }; + } + catch { } + } + return jsonSchema; +}; +export const defaultOptions = { + name: undefined, + $refStrategy: "root", + basePath: ["#"], + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "format:date-time", + mapStrategy: "entries", + removeAdditionalStrategy: "passthrough", + allowedAdditionalProperties: true, + rejectedAdditionalProperties: false, + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + definitions: {}, + errorMessages: false, + markdownDescription: false, + patternStrategy: "escape", + applyRegexFlags: false, + emailStrategy: "format:email", + base64Strategy: "contentEncoding:base64", + nameStrategy: "ref", + openAiAnyTypeName: "OpenAiAnyType" +}; +export const getDefaultOptions = (options) => (typeof options === "string" + ? { + ...defaultOptions, + name: options, + } + : { + ...defaultOptions, + ...options, + }); diff --git a/node_modules/zod-to-json-schema/dist/esm/Refs.js b/node_modules/zod-to-json-schema/dist/esm/Refs.js new file mode 100644 index 000000000..99a1e0b33 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/Refs.js @@ -0,0 +1,22 @@ +import { getDefaultOptions } from "./Options.js"; +export const getRefs = (options) => { + const _options = getDefaultOptions(options); + const currentPath = _options.name !== undefined + ? [..._options.basePath, _options.definitionPath, _options.name] + : _options.basePath; + return { + ..._options, + flags: { hasReferencedOpenAiAnyType: false }, + currentPath: currentPath, + propertyPath: undefined, + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ + def._def, + { + def: def._def, + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: undefined, + }, + ])), + }; +}; diff --git a/node_modules/zod-to-json-schema/dist/esm/errorMessages.js b/node_modules/zod-to-json-schema/dist/esm/errorMessages.js new file mode 100644 index 000000000..5a300a7f8 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/errorMessages.js @@ -0,0 +1,14 @@ +export function addErrorMessage(res, key, errorMessage, refs) { + if (!refs?.errorMessages) + return; + if (errorMessage) { + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage, + }; + } +} +export function setResponseValueAndErrors(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage(res, key, errorMessage, refs); +} diff --git a/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js b/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js new file mode 100644 index 000000000..63a005cb4 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js @@ -0,0 +1,8 @@ +export const getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) { + if (pathA[i] !== pathB[i]) + break; + } + return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); +}; diff --git a/node_modules/zod-to-json-schema/dist/esm/index.js b/node_modules/zod-to-json-schema/dist/esm/index.js new file mode 100644 index 000000000..cdfb5306e --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/index.js @@ -0,0 +1,40 @@ +export * from "./Options.js"; +export * from "./Refs.js"; +export * from "./errorMessages.js"; +export * from "./getRelativePath.js"; +export * from "./parseDef.js"; +export * from "./parseTypes.js"; +export * from "./parsers/any.js"; +export * from "./parsers/array.js"; +export * from "./parsers/bigint.js"; +export * from "./parsers/boolean.js"; +export * from "./parsers/branded.js"; +export * from "./parsers/catch.js"; +export * from "./parsers/date.js"; +export * from "./parsers/default.js"; +export * from "./parsers/effects.js"; +export * from "./parsers/enum.js"; +export * from "./parsers/intersection.js"; +export * from "./parsers/literal.js"; +export * from "./parsers/map.js"; +export * from "./parsers/nativeEnum.js"; +export * from "./parsers/never.js"; +export * from "./parsers/null.js"; +export * from "./parsers/nullable.js"; +export * from "./parsers/number.js"; +export * from "./parsers/object.js"; +export * from "./parsers/optional.js"; +export * from "./parsers/pipeline.js"; +export * from "./parsers/promise.js"; +export * from "./parsers/readonly.js"; +export * from "./parsers/record.js"; +export * from "./parsers/set.js"; +export * from "./parsers/string.js"; +export * from "./parsers/tuple.js"; +export * from "./parsers/undefined.js"; +export * from "./parsers/union.js"; +export * from "./parsers/unknown.js"; +export * from "./selectParser.js"; +export * from "./zodToJsonSchema.js"; +import { zodToJsonSchema } from "./zodToJsonSchema.js"; +export default zodToJsonSchema; diff --git a/node_modules/zod-to-json-schema/dist/esm/package.json b/node_modules/zod-to-json-schema/dist/esm/package.json new file mode 100644 index 000000000..7b3eae25b --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/package.json @@ -0,0 +1 @@ +{"type":"module","main":"index.js"} \ No newline at end of file diff --git a/node_modules/zod-to-json-schema/dist/esm/parseDef.js b/node_modules/zod-to-json-schema/dist/esm/parseDef.js new file mode 100644 index 000000000..87a615e4b --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parseDef.js @@ -0,0 +1,62 @@ +import { ignoreOverride } from "./Options.js"; +import { selectParser } from "./selectParser.js"; +import { getRelativePath } from "./getRelativePath.js"; +import { parseAnyDef } from "./parsers/any.js"; +export function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== ignoreOverride) { + return overrideResult; + } + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== undefined) { + return seenSchema; + } + } + const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; + refs.seen.set(def, newItem); + const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); + // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive) + const jsonSchema = typeof jsonSchemaOrGetter === "function" + ? parseDef(jsonSchemaOrGetter(), refs) + : jsonSchemaOrGetter; + if (jsonSchema) { + addMeta(def, refs, jsonSchema); + } + if (refs.postProcess) { + const postProcessResult = refs.postProcess(jsonSchema, def, refs); + newItem.jsonSchema = jsonSchema; + return postProcessResult; + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +const get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case "root": + return { $ref: item.path.join("/") }; + case "relative": + return { $ref: getRelativePath(refs.currentPath, item.path) }; + case "none": + case "seen": { + if (item.path.length < refs.currentPath.length && + item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return parseAnyDef(refs); + } + return refs.$refStrategy === "seen" ? parseAnyDef(refs) : undefined; + } + } +}; +const addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; + } + } + return jsonSchema; +}; diff --git a/node_modules/zod-to-json-schema/dist/esm/parseTypes.js b/node_modules/zod-to-json-schema/dist/esm/parseTypes.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parseTypes.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/any.js b/node_modules/zod-to-json-schema/dist/esm/parsers/any.js new file mode 100644 index 000000000..ec9ddfdc3 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/any.js @@ -0,0 +1,17 @@ +import { getRelativePath } from "../getRelativePath.js"; +export function parseAnyDef(refs) { + if (refs.target !== "openAi") { + return {}; + } + const anyDefinitionPath = [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName, + ]; + refs.flags.hasReferencedOpenAiAnyType = true; + return { + $ref: refs.$refStrategy === "relative" + ? getRelativePath(anyDefinitionPath, refs.currentPath) + : anyDefinitionPath.join("/"), + }; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/array.js b/node_modules/zod-to-json-schema/dist/esm/parsers/array.js new file mode 100644 index 000000000..6f275adb7 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/array.js @@ -0,0 +1,26 @@ +import { ZodFirstPartyTypeKind } from "zod/v3"; +import { setResponseValueAndErrors } from "../errorMessages.js"; +import { parseDef } from "../parseDef.js"; +export function parseArrayDef(def, refs) { + const res = { + type: "array", + }; + if (def.type?._def && + def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { + res.items = parseDef(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, "items"], + }); + } + if (def.minLength) { + setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); + } + if (def.maxLength) { + setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); + } + if (def.exactLength) { + setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); + setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); + } + return res; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js b/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js new file mode 100644 index 000000000..1298a70df --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js @@ -0,0 +1,49 @@ +import { setResponseValueAndErrors } from "../errorMessages.js"; +export function parseBigintDef(def, refs) { + const res = { + type: "integer", + format: "int64", + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } + else { + setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } + else { + setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); + break; + } + } + return res; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js b/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js new file mode 100644 index 000000000..a7d9e5c08 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js @@ -0,0 +1,5 @@ +export function parseBooleanDef() { + return { + type: "boolean", + }; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js b/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js new file mode 100644 index 000000000..fba4c9f02 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js @@ -0,0 +1,4 @@ +import { parseDef } from "../parseDef.js"; +export function parseBrandedDef(_def, refs) { + return parseDef(_def.type._def, refs); +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js b/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js new file mode 100644 index 000000000..c1833f238 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js @@ -0,0 +1,4 @@ +import { parseDef } from "../parseDef.js"; +export const parseCatchDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/date.js b/node_modules/zod-to-json-schema/dist/esm/parsers/date.js new file mode 100644 index 000000000..28408a52a --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/date.js @@ -0,0 +1,46 @@ +import { setResponseValueAndErrors } from "../errorMessages.js"; +export function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) { + return { + anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)), + }; + } + switch (strategy) { + case "string": + case "format:date-time": + return { + type: "string", + format: "date-time", + }; + case "format:date": + return { + type: "string", + format: "date", + }; + case "integer": + return integerDateParser(def, refs); + } +} +const integerDateParser = (def, refs) => { + const res = { + type: "integer", + format: "unix-time", + }; + if (refs.target === "openApi3") { + return res; + } + for (const check of def.checks) { + switch (check.kind) { + case "min": + setResponseValueAndErrors(res, "minimum", check.value, // This is in milliseconds + check.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maximum", check.value, // This is in milliseconds + check.message, refs); + break; + } + } + return res; +}; diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/default.js b/node_modules/zod-to-json-schema/dist/esm/parsers/default.js new file mode 100644 index 000000000..7f1c4dbc0 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/default.js @@ -0,0 +1,7 @@ +import { parseDef } from "../parseDef.js"; +export function parseDefaultDef(_def, refs) { + return { + ...parseDef(_def.innerType._def, refs), + default: _def.defaultValue(), + }; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js b/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js new file mode 100644 index 000000000..780413e50 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js @@ -0,0 +1,7 @@ +import { parseDef } from "../parseDef.js"; +import { parseAnyDef } from "./any.js"; +export function parseEffectsDef(_def, refs) { + return refs.effectStrategy === "input" + ? parseDef(_def.schema._def, refs) + : parseAnyDef(refs); +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js b/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js new file mode 100644 index 000000000..d6dbc0680 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js @@ -0,0 +1,6 @@ +export function parseEnumDef(def) { + return { + type: "string", + enum: Array.from(def.values), + }; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js b/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js new file mode 100644 index 000000000..945f5b3db --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js @@ -0,0 +1,52 @@ +import { parseDef } from "../parseDef.js"; +const isJsonSchema7AllOfType = (type) => { + if ("type" in type && type.type === "string") + return false; + return "allOf" in type; +}; +export function parseIntersectionDef(def, refs) { + const allOf = [ + parseDef(def.left._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"], + }), + parseDef(def.right._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "1"], + }), + ].filter((x) => !!x); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" + ? { unevaluatedProperties: false } + : undefined; + const mergedAllOf = []; + // If either of the schemas is an allOf, merge them into a single allOf + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === undefined) { + // If one of the schemas has no unevaluatedProperties set, + // the merged schema should also have no unevaluatedProperties set + unevaluatedProperties = undefined; + } + } + else { + let nestedSchema = schema; + if ("additionalProperties" in schema && + schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } + else { + // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties + unevaluatedProperties = undefined; + } + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length + ? { + allOf: mergedAllOf, + ...unevaluatedProperties, + } + : undefined; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js b/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js new file mode 100644 index 000000000..14cd677d1 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js @@ -0,0 +1,21 @@ +export function parseLiteralDef(def, refs) { + const parsedType = typeof def.value; + if (parsedType !== "bigint" && + parsedType !== "number" && + parsedType !== "boolean" && + parsedType !== "string") { + return { + type: Array.isArray(def.value) ? "array" : "object", + }; + } + if (refs.target === "openApi3") { + return { + type: parsedType === "bigint" ? "integer" : parsedType, + enum: [def.value], + }; + } + return { + type: parsedType === "bigint" ? "integer" : parsedType, + const: def.value, + }; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/map.js b/node_modules/zod-to-json-schema/dist/esm/parsers/map.js new file mode 100644 index 000000000..7b35b7807 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/map.js @@ -0,0 +1,26 @@ +import { parseDef } from "../parseDef.js"; +import { parseRecordDef } from "./record.js"; +import { parseAnyDef } from "./any.js"; +export function parseMapDef(def, refs) { + if (refs.mapStrategy === "record") { + return parseRecordDef(def, refs); + } + const keys = parseDef(def.keyType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "0"], + }) || parseAnyDef(refs); + const values = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "1"], + }) || parseAnyDef(refs); + return { + type: "array", + maxItems: 125, + items: { + type: "array", + items: [keys, values], + minItems: 2, + maxItems: 2, + }, + }; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js b/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js new file mode 100644 index 000000000..fc411ba57 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js @@ -0,0 +1,16 @@ +export function parseNativeEnumDef(def) { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== "number"; + }); + const actualValues = actualKeys.map((key) => object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); + return { + type: parsedTypes.length === 1 + ? parsedTypes[0] === "string" + ? "string" + : "number" + : ["string", "number"], + enum: actualValues, + }; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/never.js b/node_modules/zod-to-json-schema/dist/esm/parsers/never.js new file mode 100644 index 000000000..a9940cae3 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/never.js @@ -0,0 +1,11 @@ +import { parseAnyDef } from "./any.js"; +export function parseNeverDef(refs) { + return refs.target === "openAi" + ? undefined + : { + not: parseAnyDef({ + ...refs, + currentPath: [...refs.currentPath, "not"], + }), + }; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/null.js b/node_modules/zod-to-json-schema/dist/esm/parsers/null.js new file mode 100644 index 000000000..5b47a8a3d --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/null.js @@ -0,0 +1,10 @@ +export function parseNullDef(refs) { + return refs.target === "openApi3" + ? { + enum: ["null"], + nullable: true, + } + : { + type: "null", + }; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js b/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js new file mode 100644 index 000000000..b4038d076 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js @@ -0,0 +1,33 @@ +import { parseDef } from "../parseDef.js"; +import { primitiveMappings } from "./union.js"; +export function parseNullableDef(def, refs) { + if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && + (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === "openApi3") { + return { + type: primitiveMappings[def.innerType._def.typeName], + nullable: true, + }; + } + return { + type: [ + primitiveMappings[def.innerType._def.typeName], + "null", + ], + }; + } + if (refs.target === "openApi3") { + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath], + }); + if (base && "$ref" in base) + return { allOf: [base], nullable: true }; + return base && { ...base, nullable: true }; + } + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "0"], + }); + return base && { anyOf: [base, { type: "null" }] }; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/number.js b/node_modules/zod-to-json-schema/dist/esm/parsers/number.js new file mode 100644 index 000000000..2a0292c81 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/number.js @@ -0,0 +1,52 @@ +import { addErrorMessage, setResponseValueAndErrors, } from "../errorMessages.js"; +export function parseNumberDef(def, refs) { + const res = { + type: "number", + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "int": + res.type = "integer"; + addErrorMessage(res, "type", check.message, refs); + break; + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } + else { + setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } + else { + setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); + break; + } + } + return res; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/object.js b/node_modules/zod-to-json-schema/dist/esm/parsers/object.js new file mode 100644 index 000000000..cff67272a --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/object.js @@ -0,0 +1,72 @@ +import { parseDef } from "../parseDef.js"; +export function parseObjectDef(def, refs) { + const forceOptionalIntoNullable = refs.target === "openAi"; + const result = { + type: "object", + properties: {}, + }; + const required = []; + const shape = def.shape(); + for (const propName in shape) { + let propDef = shape[propName]; + if (propDef === undefined || propDef._def === undefined) { + continue; + } + let propOptional = safeIsOptional(propDef); + if (propOptional && forceOptionalIntoNullable) { + if (propDef._def.typeName === "ZodOptional") { + propDef = propDef._def.innerType; + } + if (!propDef.isNullable()) { + propDef = propDef.nullable(); + } + propOptional = false; + } + const parsedDef = parseDef(propDef._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", propName], + propertyPath: [...refs.currentPath, "properties", propName], + }); + if (parsedDef === undefined) { + continue; + } + result.properties[propName] = parsedDef; + if (!propOptional) { + required.push(propName); + } + } + if (required.length) { + result.required = required; + } + const additionalProperties = decideAdditionalProperties(def, refs); + if (additionalProperties !== undefined) { + result.additionalProperties = additionalProperties; + } + return result; +} +function decideAdditionalProperties(def, refs) { + if (def.catchall._def.typeName !== "ZodNever") { + return parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"], + }); + } + switch (def.unknownKeys) { + case "passthrough": + return refs.allowedAdditionalProperties; + case "strict": + return refs.rejectedAdditionalProperties; + case "strip": + return refs.removeAdditionalStrategy === "strict" + ? refs.allowedAdditionalProperties + : refs.rejectedAdditionalProperties; + } +} +function safeIsOptional(schema) { + try { + return schema.isOptional(); + } + catch { + return true; + } +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js b/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js new file mode 100644 index 000000000..2c5e53233 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js @@ -0,0 +1,21 @@ +import { parseDef } from "../parseDef.js"; +import { parseAnyDef } from "./any.js"; +export const parseOptionalDef = (def, refs) => { + if (refs.currentPath.toString() === refs.propertyPath?.toString()) { + return parseDef(def.innerType._def, refs); + } + const innerSchema = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "1"], + }); + return innerSchema + ? { + anyOf: [ + { + not: parseAnyDef(refs), + }, + innerSchema, + ], + } + : parseAnyDef(refs); +}; diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js b/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js new file mode 100644 index 000000000..e8edfe296 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js @@ -0,0 +1,20 @@ +import { parseDef } from "../parseDef.js"; +export const parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === "input") { + return parseDef(def.in._def, refs); + } + else if (refs.pipeStrategy === "output") { + return parseDef(def.out._def, refs); + } + const a = parseDef(def.in._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"], + }); + const b = parseDef(def.out._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"], + }); + return { + allOf: [a, b].filter((x) => x !== undefined), + }; +}; diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js b/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js new file mode 100644 index 000000000..bfb1f5d04 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js @@ -0,0 +1,4 @@ +import { parseDef } from "../parseDef.js"; +export function parsePromiseDef(def, refs) { + return parseDef(def.type._def, refs); +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js b/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js new file mode 100644 index 000000000..b36a73c96 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js @@ -0,0 +1,4 @@ +import { parseDef } from "../parseDef.js"; +export const parseReadonlyDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/record.js b/node_modules/zod-to-json-schema/dist/esm/parsers/record.js new file mode 100644 index 000000000..dd75a92f4 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/record.js @@ -0,0 +1,61 @@ +import { ZodFirstPartyTypeKind, } from "zod/v3"; +import { parseDef } from "../parseDef.js"; +import { parseStringDef } from "./string.js"; +import { parseBrandedDef } from "./branded.js"; +import { parseAnyDef } from "./any.js"; +export function parseRecordDef(def, refs) { + if (refs.target === "openAi") { + console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); + } + if (refs.target === "openApi3" && + def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + type: "object", + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", key], + }) ?? parseAnyDef(refs), + }), {}), + additionalProperties: refs.rejectedAdditionalProperties, + }; + } + const schema = { + type: "object", + additionalProperties: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"], + }) ?? refs.allowedAdditionalProperties, + }; + if (refs.target === "openApi3") { + return schema; + } + if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && + def.keyType._def.checks?.length) { + const { type, ...keyType } = parseStringDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType, + }; + } + else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + ...schema, + propertyNames: { + enum: def.keyType._def.values, + }, + }; + } + else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && + def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && + def.keyType._def.type._def.checks?.length) { + const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType, + }; + } + return schema; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/set.js b/node_modules/zod-to-json-schema/dist/esm/parsers/set.js new file mode 100644 index 000000000..88f0624bd --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/set.js @@ -0,0 +1,20 @@ +import { setResponseValueAndErrors } from "../errorMessages.js"; +import { parseDef } from "../parseDef.js"; +export function parseSetDef(def, refs) { + const items = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items"], + }); + const schema = { + type: "array", + uniqueItems: true, + items, + }; + if (def.minSize) { + setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); + } + if (def.maxSize) { + setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); + } + return schema; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/string.js b/node_modules/zod-to-json-schema/dist/esm/parsers/string.js new file mode 100644 index 000000000..bc224a306 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/string.js @@ -0,0 +1,352 @@ +import { setResponseValueAndErrors } from "../errorMessages.js"; +let emojiRegex = undefined; +/** + * Generated from the regular expressions found here as of 2024-05-22: + * https://github.com/colinhacks/zod/blob/master/src/types.ts. + * + * Expressions with /i flag have been changed accordingly. + */ +export const zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (emojiRegex === undefined) { + emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); + } + return emojiRegex; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, + jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/, +}; +export function parseStringDef(def, refs) { + const res = { + type: "string", + }; + if (def.checks) { + for (const check of def.checks) { + switch (check.kind) { + case "min": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" + ? Math.max(res.minLength, check.value) + : check.value, check.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" + ? Math.min(res.maxLength, check.value) + : check.value, check.message, refs); + break; + case "email": + switch (refs.emailStrategy) { + case "format:email": + addFormat(res, "email", check.message, refs); + break; + case "format:idn-email": + addFormat(res, "idn-email", check.message, refs); + break; + case "pattern:zod": + addPattern(res, zodPatterns.email, check.message, refs); + break; + } + break; + case "url": + addFormat(res, "uri", check.message, refs); + break; + case "uuid": + addFormat(res, "uuid", check.message, refs); + break; + case "regex": + addPattern(res, check.regex, check.message, refs); + break; + case "cuid": + addPattern(res, zodPatterns.cuid, check.message, refs); + break; + case "cuid2": + addPattern(res, zodPatterns.cuid2, check.message, refs); + break; + case "startsWith": + addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); + break; + case "endsWith": + addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); + break; + case "datetime": + addFormat(res, "date-time", check.message, refs); + break; + case "date": + addFormat(res, "date", check.message, refs); + break; + case "time": + addFormat(res, "time", check.message, refs); + break; + case "duration": + addFormat(res, "duration", check.message, refs); + break; + case "length": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" + ? Math.max(res.minLength, check.value) + : check.value, check.message, refs); + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" + ? Math.min(res.maxLength, check.value) + : check.value, check.message, refs); + break; + case "includes": { + addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); + break; + } + case "ip": { + if (check.version !== "v6") { + addFormat(res, "ipv4", check.message, refs); + } + if (check.version !== "v4") { + addFormat(res, "ipv6", check.message, refs); + } + break; + } + case "base64url": + addPattern(res, zodPatterns.base64url, check.message, refs); + break; + case "jwt": + addPattern(res, zodPatterns.jwt, check.message, refs); + break; + case "cidr": { + if (check.version !== "v6") { + addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); + } + if (check.version !== "v4") { + addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); + } + break; + } + case "emoji": + addPattern(res, zodPatterns.emoji(), check.message, refs); + break; + case "ulid": { + addPattern(res, zodPatterns.ulid, check.message, refs); + break; + } + case "base64": { + switch (refs.base64Strategy) { + case "format:binary": { + addFormat(res, "binary", check.message, refs); + break; + } + case "contentEncoding:base64": { + setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); + break; + } + case "pattern:zod": { + addPattern(res, zodPatterns.base64, check.message, refs); + break; + } + } + break; + } + case "nanoid": { + addPattern(res, zodPatterns.nanoid, check.message, refs); + } + case "toLowerCase": + case "toUpperCase": + case "trim": + break; + default: + ((_) => { })(check); + } + } + } + return res; +} +function escapeLiteralCheckValue(literal, refs) { + return refs.patternStrategy === "escape" + ? escapeNonAlphaNumeric(literal) + : literal; +} +const ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); +function escapeNonAlphaNumeric(source) { + let result = ""; + for (let i = 0; i < source.length; i++) { + if (!ALPHA_NUMERIC.has(source[i])) { + result += "\\"; + } + result += source[i]; + } + return result; +} +// Adds a "format" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones. +function addFormat(schema, value, message, refs) { + if (schema.format || schema.anyOf?.some((x) => x.format)) { + if (!schema.anyOf) { + schema.anyOf = []; + } + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { format: schema.errorMessage.format }, + }), + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.anyOf.push({ + format: value, + ...(message && + refs.errorMessages && { errorMessage: { format: message } }), + }); + } + else { + setResponseValueAndErrors(schema, "format", value, message, refs); + } +} +// Adds a "pattern" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones. +function addPattern(schema, regex, message, refs) { + if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { + if (!schema.allOf) { + schema.allOf = []; + } + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { pattern: schema.errorMessage.pattern }, + }), + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.allOf.push({ + pattern: stringifyRegExpWithFlags(regex, refs), + ...(message && + refs.errorMessages && { errorMessage: { pattern: message } }), + }); + } + else { + setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); + } +} +// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true +function stringifyRegExpWithFlags(regex, refs) { + if (!refs.applyRegexFlags || !regex.flags) { + return regex.source; + } + // Currently handled flags + const flags = { + i: regex.flags.includes("i"), + m: regex.flags.includes("m"), + s: regex.flags.includes("s"), // `.` matches newlines + }; + // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ""; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i = 0; i < source.length; i++) { + if (isEscaped) { + pattern += source[i]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i]; + pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); + inCharRange = false; + } + else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { + pattern += source[i]; + inCharRange = true; + } + else { + pattern += `${source[i]}${source[i].toUpperCase()}`; + } + continue; + } + } + else if (source[i].match(/[a-z]/)) { + pattern += `[${source[i]}${source[i].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i] === "^") { + pattern += `(^|(?<=[\r\n]))`; + continue; + } + else if (source[i] === "$") { + pattern += `($|(?=[\r\n]))`; + continue; + } + } + if (flags.s && source[i] === ".") { + pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; + continue; + } + pattern += source[i]; + if (source[i] === "\\") { + isEscaped = true; + } + else if (inCharGroup && source[i] === "]") { + inCharGroup = false; + } + else if (!inCharGroup && source[i] === "[") { + inCharGroup = true; + } + } + try { + new RegExp(pattern); + } + catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js b/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js new file mode 100644 index 000000000..538793621 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js @@ -0,0 +1,32 @@ +import { parseDef } from "../parseDef.js"; +export function parseTupleDef(def, refs) { + if (def.rest) { + return { + type: "array", + minItems: def.items.length, + items: def.items + .map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i}`], + })) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + additionalItems: parseDef(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalItems"], + }), + }; + } + else { + return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items + .map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i}`], + })) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + }; + } +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js b/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js new file mode 100644 index 000000000..2209eff2d --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js @@ -0,0 +1,6 @@ +import { parseAnyDef } from "./any.js"; +export function parseUndefinedDef(refs) { + return { + not: parseAnyDef(refs), + }; +} diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/union.js b/node_modules/zod-to-json-schema/dist/esm/parsers/union.js new file mode 100644 index 000000000..45a105fe4 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/union.js @@ -0,0 +1,80 @@ +import { parseDef } from "../parseDef.js"; +export const primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null", +}; +export function parseUnionDef(def, refs) { + if (refs.target === "openApi3") + return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. + if (options.every((x) => x._def.typeName in primitiveMappings && + (!x._def.checks || !x._def.checks.length))) { + // all types in union are primitive and lack checks, so might as well squash into {type: [...]} + const types = options.reduce((types, x) => { + const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43 + return type && !types.includes(type) ? [...types, type] : types; + }, []); + return { + type: types.length > 1 ? types : types[0], + }; + } + else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { + // all options literals + const types = options.reduce((acc, x) => { + const type = typeof x._def.value; + switch (type) { + case "string": + case "number": + case "boolean": + return [...acc, type]; + case "bigint": + return [...acc, "integer"]; + case "object": + if (x._def.value === null) + return [...acc, "null"]; + case "symbol": + case "undefined": + case "function": + default: + return acc; + } + }, []); + if (types.length === options.length) { + // all the literals are primitive, as far as null can be considered primitive + const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []), + }; + } + } + else if (options.every((x) => x._def.typeName === "ZodEnum")) { + return { + type: "string", + enum: options.reduce((acc, x) => [ + ...acc, + ...x._def.values.filter((x) => !acc.includes(x)), + ], []), + }; + } + return asAnyOf(def, refs); +} +const asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map + ? Array.from(def.options.values()) + : def.options) + .map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", `${i}`], + })) + .filter((x) => !!x && + (!refs.strictUnions || + (typeof x === "object" && Object.keys(x).length > 0))); + return anyOf.length ? { anyOf } : undefined; +}; diff --git a/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js b/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js new file mode 100644 index 000000000..6d73f8276 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js @@ -0,0 +1,4 @@ +import { parseAnyDef } from "./any.js"; +export function parseUnknownDef(refs) { + return parseAnyDef(refs); +} diff --git a/node_modules/zod-to-json-schema/dist/esm/selectParser.js b/node_modules/zod-to-json-schema/dist/esm/selectParser.js new file mode 100644 index 000000000..c4a05bb6a --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/selectParser.js @@ -0,0 +1,105 @@ +import { ZodFirstPartyTypeKind } from "zod/v3"; +import { parseAnyDef } from "./parsers/any.js"; +import { parseArrayDef } from "./parsers/array.js"; +import { parseBigintDef } from "./parsers/bigint.js"; +import { parseBooleanDef } from "./parsers/boolean.js"; +import { parseBrandedDef } from "./parsers/branded.js"; +import { parseCatchDef } from "./parsers/catch.js"; +import { parseDateDef } from "./parsers/date.js"; +import { parseDefaultDef } from "./parsers/default.js"; +import { parseEffectsDef } from "./parsers/effects.js"; +import { parseEnumDef } from "./parsers/enum.js"; +import { parseIntersectionDef } from "./parsers/intersection.js"; +import { parseLiteralDef } from "./parsers/literal.js"; +import { parseMapDef } from "./parsers/map.js"; +import { parseNativeEnumDef } from "./parsers/nativeEnum.js"; +import { parseNeverDef } from "./parsers/never.js"; +import { parseNullDef } from "./parsers/null.js"; +import { parseNullableDef } from "./parsers/nullable.js"; +import { parseNumberDef } from "./parsers/number.js"; +import { parseObjectDef } from "./parsers/object.js"; +import { parseOptionalDef } from "./parsers/optional.js"; +import { parsePipelineDef } from "./parsers/pipeline.js"; +import { parsePromiseDef } from "./parsers/promise.js"; +import { parseRecordDef } from "./parsers/record.js"; +import { parseSetDef } from "./parsers/set.js"; +import { parseStringDef } from "./parsers/string.js"; +import { parseTupleDef } from "./parsers/tuple.js"; +import { parseUndefinedDef } from "./parsers/undefined.js"; +import { parseUnionDef } from "./parsers/union.js"; +import { parseUnknownDef } from "./parsers/unknown.js"; +import { parseReadonlyDef } from "./parsers/readonly.js"; +export const selectParser = (def, typeName, refs) => { + switch (typeName) { + case ZodFirstPartyTypeKind.ZodString: + return parseStringDef(def, refs); + case ZodFirstPartyTypeKind.ZodNumber: + return parseNumberDef(def, refs); + case ZodFirstPartyTypeKind.ZodObject: + return parseObjectDef(def, refs); + case ZodFirstPartyTypeKind.ZodBigInt: + return parseBigintDef(def, refs); + case ZodFirstPartyTypeKind.ZodBoolean: + return parseBooleanDef(); + case ZodFirstPartyTypeKind.ZodDate: + return parseDateDef(def, refs); + case ZodFirstPartyTypeKind.ZodUndefined: + return parseUndefinedDef(refs); + case ZodFirstPartyTypeKind.ZodNull: + return parseNullDef(refs); + case ZodFirstPartyTypeKind.ZodArray: + return parseArrayDef(def, refs); + case ZodFirstPartyTypeKind.ZodUnion: + case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return parseUnionDef(def, refs); + case ZodFirstPartyTypeKind.ZodIntersection: + return parseIntersectionDef(def, refs); + case ZodFirstPartyTypeKind.ZodTuple: + return parseTupleDef(def, refs); + case ZodFirstPartyTypeKind.ZodRecord: + return parseRecordDef(def, refs); + case ZodFirstPartyTypeKind.ZodLiteral: + return parseLiteralDef(def, refs); + case ZodFirstPartyTypeKind.ZodEnum: + return parseEnumDef(def); + case ZodFirstPartyTypeKind.ZodNativeEnum: + return parseNativeEnumDef(def); + case ZodFirstPartyTypeKind.ZodNullable: + return parseNullableDef(def, refs); + case ZodFirstPartyTypeKind.ZodOptional: + return parseOptionalDef(def, refs); + case ZodFirstPartyTypeKind.ZodMap: + return parseMapDef(def, refs); + case ZodFirstPartyTypeKind.ZodSet: + return parseSetDef(def, refs); + case ZodFirstPartyTypeKind.ZodLazy: + return () => def.getter()._def; + case ZodFirstPartyTypeKind.ZodPromise: + return parsePromiseDef(def, refs); + case ZodFirstPartyTypeKind.ZodNaN: + case ZodFirstPartyTypeKind.ZodNever: + return parseNeverDef(refs); + case ZodFirstPartyTypeKind.ZodEffects: + return parseEffectsDef(def, refs); + case ZodFirstPartyTypeKind.ZodAny: + return parseAnyDef(refs); + case ZodFirstPartyTypeKind.ZodUnknown: + return parseUnknownDef(refs); + case ZodFirstPartyTypeKind.ZodDefault: + return parseDefaultDef(def, refs); + case ZodFirstPartyTypeKind.ZodBranded: + return parseBrandedDef(def, refs); + case ZodFirstPartyTypeKind.ZodReadonly: + return parseReadonlyDef(def, refs); + case ZodFirstPartyTypeKind.ZodCatch: + return parseCatchDef(def, refs); + case ZodFirstPartyTypeKind.ZodPipeline: + return parsePipelineDef(def, refs); + case ZodFirstPartyTypeKind.ZodFunction: + case ZodFirstPartyTypeKind.ZodVoid: + case ZodFirstPartyTypeKind.ZodSymbol: + return undefined; + default: + return ((_) => undefined)(typeName); + } +}; diff --git a/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js b/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js new file mode 100644 index 000000000..6359a758f --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js @@ -0,0 +1,87 @@ +import { parseDef } from "./parseDef.js"; +import { getRefs } from "./Refs.js"; +import { parseAnyDef } from "./parsers/any.js"; +const zodToJsonSchema = (schema, options) => { + const refs = getRefs(options); + let definitions = typeof options === "object" && options.definitions + ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({ + ...acc, + [name]: parseDef(schema._def, { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name], + }, true) ?? parseAnyDef(refs), + }), {}) + : undefined; + const name = typeof options === "string" + ? options + : options?.nameStrategy === "title" + ? undefined + : options?.name; + const main = parseDef(schema._def, name === undefined + ? refs + : { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name], + }, false) ?? parseAnyDef(refs); + const title = typeof options === "object" && + options.name !== undefined && + options.nameStrategy === "title" + ? options.name + : undefined; + if (title !== undefined) { + main.title = title; + } + if (refs.flags.hasReferencedOpenAiAnyType) { + if (!definitions) { + definitions = {}; + } + if (!definitions[refs.openAiAnyTypeName]) { + definitions[refs.openAiAnyTypeName] = { + // Skipping "object" as no properties can be defined and additionalProperties must be "false" + type: ["string", "number", "integer", "boolean", "array", "null"], + items: { + $ref: refs.$refStrategy === "relative" + ? "1" + : [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName, + ].join("/"), + }, + }; + } + } + const combined = name === undefined + ? definitions + ? { + ...main, + [refs.definitionPath]: definitions, + } + : main + : { + $ref: [ + ...(refs.$refStrategy === "relative" ? [] : refs.basePath), + refs.definitionPath, + name, + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name]: main, + }, + }; + if (refs.target === "jsonSchema7") { + combined.$schema = "http://json-schema.org/draft-07/schema#"; + } + else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { + combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + } + if (refs.target === "openAi" && + ("anyOf" in combined || + "oneOf" in combined || + "allOf" in combined || + ("type" in combined && Array.isArray(combined.type)))) { + console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); + } + return combined; +}; +export { zodToJsonSchema }; diff --git a/node_modules/zod-to-json-schema/dist/types/Options.d.ts b/node_modules/zod-to-json-schema/dist/types/Options.d.ts new file mode 100644 index 000000000..882f6ac77 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/Options.d.ts @@ -0,0 +1,37 @@ +import { ZodSchema, ZodTypeDef } from "zod/v3"; +import { Refs, Seen } from "./Refs"; +import { JsonSchema7Type } from "./parseTypes"; +export type Targets = "jsonSchema7" | "jsonSchema2019-09" | "openApi3" | "openAi"; +export type DateStrategy = "format:date-time" | "format:date" | "string" | "integer"; +export declare const ignoreOverride: unique symbol; +export type OverrideCallback = (def: ZodTypeDef, refs: Refs, seen: Seen | undefined, forceResolution?: boolean) => JsonSchema7Type | undefined | typeof ignoreOverride; +export type PostProcessCallback = (jsonSchema: JsonSchema7Type | undefined, def: ZodTypeDef, refs: Refs) => JsonSchema7Type | undefined; +export declare const jsonDescription: PostProcessCallback; +export type Options = { + name: string | undefined; + $refStrategy: "root" | "relative" | "none" | "seen"; + basePath: string[]; + effectStrategy: "input" | "any"; + pipeStrategy: "input" | "output" | "all"; + dateStrategy: DateStrategy | DateStrategy[]; + mapStrategy: "entries" | "record"; + removeAdditionalStrategy: "passthrough" | "strict"; + allowedAdditionalProperties: true | undefined; + rejectedAdditionalProperties: false | undefined; + target: Target; + strictUnions: boolean; + definitionPath: string; + definitions: Record; + errorMessages: boolean; + markdownDescription: boolean; + patternStrategy: "escape" | "preserve"; + applyRegexFlags: boolean; + emailStrategy: "format:email" | "format:idn-email" | "pattern:zod"; + base64Strategy: "format:binary" | "contentEncoding:base64" | "pattern:zod"; + nameStrategy: "ref" | "title"; + override?: OverrideCallback; + postProcess?: PostProcessCallback; + openAiAnyTypeName: string; +}; +export declare const defaultOptions: Options; +export declare const getDefaultOptions: (options: string | Partial> | undefined) => Options; diff --git a/node_modules/zod-to-json-schema/dist/types/Refs.d.ts b/node_modules/zod-to-json-schema/dist/types/Refs.d.ts new file mode 100644 index 000000000..482838f3b --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/Refs.d.ts @@ -0,0 +1,17 @@ +import { ZodTypeDef } from "zod/v3"; +import { Options, Targets } from "./Options.js"; +import { JsonSchema7Type } from "./parseTypes.js"; +export type Refs = { + seen: Map; + currentPath: string[]; + propertyPath: string[] | undefined; + flags: { + hasReferencedOpenAiAnyType: boolean; + }; +} & Options; +export type Seen = { + def: ZodTypeDef; + path: string[]; + jsonSchema: JsonSchema7Type | undefined; +}; +export declare const getRefs: (options?: string | Partial>) => Refs; diff --git a/node_modules/zod-to-json-schema/dist/types/errorMessages.d.ts b/node_modules/zod-to-json-schema/dist/types/errorMessages.d.ts new file mode 100644 index 000000000..85cb56248 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/errorMessages.d.ts @@ -0,0 +1,15 @@ +import { JsonSchema7TypeUnion } from "./parseTypes.js"; +import { Refs } from "./Refs.js"; +export type ErrorMessages = Partial>; +export declare function addErrorMessage; +}>(res: T, key: keyof T, errorMessage: string | undefined, refs: Refs): void; +export declare function setResponseValueAndErrors; +}, Key extends keyof Omit>(res: Json7Type, key: Key, value: Json7Type[Key], errorMessage: string | undefined, refs: Refs): void; diff --git a/node_modules/zod-to-json-schema/dist/types/getRelativePath.d.ts b/node_modules/zod-to-json-schema/dist/types/getRelativePath.d.ts new file mode 100644 index 000000000..5cf67e314 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/getRelativePath.d.ts @@ -0,0 +1 @@ +export declare const getRelativePath: (pathA: string[], pathB: string[]) => string; diff --git a/node_modules/zod-to-json-schema/dist/types/index.d.ts b/node_modules/zod-to-json-schema/dist/types/index.d.ts new file mode 100644 index 000000000..cdfb5306e --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/index.d.ts @@ -0,0 +1,40 @@ +export * from "./Options.js"; +export * from "./Refs.js"; +export * from "./errorMessages.js"; +export * from "./getRelativePath.js"; +export * from "./parseDef.js"; +export * from "./parseTypes.js"; +export * from "./parsers/any.js"; +export * from "./parsers/array.js"; +export * from "./parsers/bigint.js"; +export * from "./parsers/boolean.js"; +export * from "./parsers/branded.js"; +export * from "./parsers/catch.js"; +export * from "./parsers/date.js"; +export * from "./parsers/default.js"; +export * from "./parsers/effects.js"; +export * from "./parsers/enum.js"; +export * from "./parsers/intersection.js"; +export * from "./parsers/literal.js"; +export * from "./parsers/map.js"; +export * from "./parsers/nativeEnum.js"; +export * from "./parsers/never.js"; +export * from "./parsers/null.js"; +export * from "./parsers/nullable.js"; +export * from "./parsers/number.js"; +export * from "./parsers/object.js"; +export * from "./parsers/optional.js"; +export * from "./parsers/pipeline.js"; +export * from "./parsers/promise.js"; +export * from "./parsers/readonly.js"; +export * from "./parsers/record.js"; +export * from "./parsers/set.js"; +export * from "./parsers/string.js"; +export * from "./parsers/tuple.js"; +export * from "./parsers/undefined.js"; +export * from "./parsers/union.js"; +export * from "./parsers/unknown.js"; +export * from "./selectParser.js"; +export * from "./zodToJsonSchema.js"; +import { zodToJsonSchema } from "./zodToJsonSchema.js"; +export default zodToJsonSchema; diff --git a/node_modules/zod-to-json-schema/dist/types/parseDef.d.ts b/node_modules/zod-to-json-schema/dist/types/parseDef.d.ts new file mode 100644 index 000000000..cbbf0d7ee --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parseDef.d.ts @@ -0,0 +1,4 @@ +import { ZodTypeDef } from "zod/v3"; +import { Refs } from "./Refs.js"; +import { JsonSchema7Type } from "./parseTypes.js"; +export declare function parseDef(def: ZodTypeDef, refs: Refs, forceResolution?: boolean): JsonSchema7Type | undefined; diff --git a/node_modules/zod-to-json-schema/dist/types/parseTypes.d.ts b/node_modules/zod-to-json-schema/dist/types/parseTypes.d.ts new file mode 100644 index 000000000..dbfa17c84 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parseTypes.d.ts @@ -0,0 +1,34 @@ +import { JsonSchema7AnyType } from "./parsers/any.js"; +import { JsonSchema7ArrayType } from "./parsers/array.js"; +import { JsonSchema7BigintType } from "./parsers/bigint.js"; +import { JsonSchema7BooleanType } from "./parsers/boolean.js"; +import { JsonSchema7DateType } from "./parsers/date.js"; +import { JsonSchema7EnumType } from "./parsers/enum.js"; +import { JsonSchema7AllOfType } from "./parsers/intersection.js"; +import { JsonSchema7LiteralType } from "./parsers/literal.js"; +import { JsonSchema7MapType } from "./parsers/map.js"; +import { JsonSchema7NativeEnumType } from "./parsers/nativeEnum.js"; +import { JsonSchema7NeverType } from "./parsers/never.js"; +import { JsonSchema7NullType } from "./parsers/null.js"; +import { JsonSchema7NullableType } from "./parsers/nullable.js"; +import { JsonSchema7NumberType } from "./parsers/number.js"; +import { JsonSchema7ObjectType } from "./parsers/object.js"; +import { JsonSchema7RecordType } from "./parsers/record.js"; +import { JsonSchema7SetType } from "./parsers/set.js"; +import { JsonSchema7StringType } from "./parsers/string.js"; +import { JsonSchema7TupleType } from "./parsers/tuple.js"; +import { JsonSchema7UndefinedType } from "./parsers/undefined.js"; +import { JsonSchema7UnionType } from "./parsers/union.js"; +import { JsonSchema7UnknownType } from "./parsers/unknown.js"; +type JsonSchema7RefType = { + $ref: string; +}; +type JsonSchema7Meta = { + title?: string; + default?: any; + description?: string; + markdownDescription?: string; +}; +export type JsonSchema7TypeUnion = JsonSchema7StringType | JsonSchema7ArrayType | JsonSchema7NumberType | JsonSchema7BigintType | JsonSchema7BooleanType | JsonSchema7DateType | JsonSchema7EnumType | JsonSchema7LiteralType | JsonSchema7NativeEnumType | JsonSchema7NullType | JsonSchema7NumberType | JsonSchema7ObjectType | JsonSchema7RecordType | JsonSchema7TupleType | JsonSchema7UnionType | JsonSchema7UndefinedType | JsonSchema7RefType | JsonSchema7NeverType | JsonSchema7MapType | JsonSchema7AnyType | JsonSchema7NullableType | JsonSchema7AllOfType | JsonSchema7UnknownType | JsonSchema7SetType; +export type JsonSchema7Type = JsonSchema7TypeUnion & JsonSchema7Meta; +export {}; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/any.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/any.d.ts new file mode 100644 index 000000000..88deab458 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/any.d.ts @@ -0,0 +1,5 @@ +import { Refs } from "../Refs.js"; +export type JsonSchema7AnyType = { + $ref?: string; +}; +export declare function parseAnyDef(refs: Refs): JsonSchema7AnyType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/array.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/array.d.ts new file mode 100644 index 000000000..a8049318e --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/array.d.ts @@ -0,0 +1,12 @@ +import { ZodArrayDef } from "zod/v3"; +import { ErrorMessages } from "../errorMessages.js"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +export type JsonSchema7ArrayType = { + type: "array"; + items?: JsonSchema7Type; + minItems?: number; + maxItems?: number; + errorMessages?: ErrorMessages; +}; +export declare function parseArrayDef(def: ZodArrayDef, refs: Refs): JsonSchema7ArrayType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/bigint.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/bigint.d.ts new file mode 100644 index 000000000..44ad42b94 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/bigint.d.ts @@ -0,0 +1,14 @@ +import { ZodBigIntDef } from "zod/v3"; +import { Refs } from "../Refs.js"; +import { ErrorMessages } from "../errorMessages.js"; +export type JsonSchema7BigintType = { + type: "integer"; + format: "int64"; + minimum?: BigInt; + exclusiveMinimum?: BigInt; + maximum?: BigInt; + exclusiveMaximum?: BigInt; + multipleOf?: BigInt; + errorMessage?: ErrorMessages; +}; +export declare function parseBigintDef(def: ZodBigIntDef, refs: Refs): JsonSchema7BigintType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/boolean.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/boolean.d.ts new file mode 100644 index 000000000..c69bb884f --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/boolean.d.ts @@ -0,0 +1,4 @@ +export type JsonSchema7BooleanType = { + type: "boolean"; +}; +export declare function parseBooleanDef(): JsonSchema7BooleanType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/branded.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/branded.d.ts new file mode 100644 index 000000000..cf319c2a7 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/branded.d.ts @@ -0,0 +1,3 @@ +import { ZodBrandedDef } from "zod/v3"; +import { Refs } from "../Refs.js"; +export declare function parseBrandedDef(_def: ZodBrandedDef, refs: Refs): import("../parseTypes.js").JsonSchema7Type | undefined; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/catch.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/catch.d.ts new file mode 100644 index 000000000..92693e92e --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/catch.d.ts @@ -0,0 +1,3 @@ +import { ZodCatchDef } from "zod/v3"; +import { Refs } from "../Refs.js"; +export declare const parseCatchDef: (def: ZodCatchDef, refs: Refs) => import("../parseTypes.js").JsonSchema7Type | undefined; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/date.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/date.d.ts new file mode 100644 index 000000000..d3cc800bf --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/date.d.ts @@ -0,0 +1,15 @@ +import { ZodDateDef } from "zod/v3"; +import { Refs } from "../Refs.js"; +import { ErrorMessages } from "../errorMessages.js"; +import { JsonSchema7NumberType } from "./number.js"; +import { DateStrategy } from "../Options.js"; +export type JsonSchema7DateType = { + type: "integer" | "string"; + format: "unix-time" | "date-time" | "date"; + minimum?: number; + maximum?: number; + errorMessage?: ErrorMessages; +} | { + anyOf: JsonSchema7DateType[]; +}; +export declare function parseDateDef(def: ZodDateDef, refs: Refs, overrideDateStrategy?: DateStrategy): JsonSchema7DateType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/default.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/default.d.ts new file mode 100644 index 000000000..58c6ae94f --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/default.d.ts @@ -0,0 +1,6 @@ +import { ZodDefaultDef } from "zod/v3"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +export declare function parseDefaultDef(_def: ZodDefaultDef, refs: Refs): JsonSchema7Type & { + default: any; +}; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/effects.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/effects.d.ts new file mode 100644 index 000000000..15239c720 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/effects.d.ts @@ -0,0 +1,4 @@ +import { ZodEffectsDef } from "zod/v3"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +export declare function parseEffectsDef(_def: ZodEffectsDef, refs: Refs): JsonSchema7Type | undefined; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/enum.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/enum.d.ts new file mode 100644 index 000000000..ce30dbb7c --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/enum.d.ts @@ -0,0 +1,6 @@ +import { ZodEnumDef } from "zod/v3"; +export type JsonSchema7EnumType = { + type: "string"; + enum: string[]; +}; +export declare function parseEnumDef(def: ZodEnumDef): JsonSchema7EnumType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/intersection.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/intersection.d.ts new file mode 100644 index 000000000..d86a349b5 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/intersection.d.ts @@ -0,0 +1,8 @@ +import { ZodIntersectionDef } from "zod/v3"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +export type JsonSchema7AllOfType = { + allOf: JsonSchema7Type[]; + unevaluatedProperties?: boolean; +}; +export declare function parseIntersectionDef(def: ZodIntersectionDef, refs: Refs): JsonSchema7AllOfType | JsonSchema7Type | undefined; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/literal.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/literal.d.ts new file mode 100644 index 000000000..1e55226a8 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/literal.d.ts @@ -0,0 +1,9 @@ +import { ZodLiteralDef } from "zod/v3"; +import { Refs } from "../Refs.js"; +export type JsonSchema7LiteralType = { + type: "string" | "number" | "integer" | "boolean"; + const: string | number | boolean; +} | { + type: "object" | "array"; +}; +export declare function parseLiteralDef(def: ZodLiteralDef, refs: Refs): JsonSchema7LiteralType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/map.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/map.d.ts new file mode 100644 index 000000000..3663e7ae2 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/map.d.ts @@ -0,0 +1,15 @@ +import { ZodMapDef } from "zod/v3"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +import { JsonSchema7RecordType } from "./record.js"; +export type JsonSchema7MapType = { + type: "array"; + maxItems: 125; + items: { + type: "array"; + items: [JsonSchema7Type, JsonSchema7Type]; + minItems: 2; + maxItems: 2; + }; +}; +export declare function parseMapDef(def: ZodMapDef, refs: Refs): JsonSchema7MapType | JsonSchema7RecordType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/nativeEnum.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/nativeEnum.d.ts new file mode 100644 index 000000000..6be16b02e --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/nativeEnum.d.ts @@ -0,0 +1,6 @@ +import { ZodNativeEnumDef } from "zod/v3"; +export type JsonSchema7NativeEnumType = { + type: "string" | "number" | ["string", "number"]; + enum: (string | number)[]; +}; +export declare function parseNativeEnumDef(def: ZodNativeEnumDef): JsonSchema7NativeEnumType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/never.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/never.d.ts new file mode 100644 index 000000000..1301358fe --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/never.d.ts @@ -0,0 +1,6 @@ +import { Refs } from "../Refs.js"; +import { JsonSchema7AnyType } from "./any.js"; +export type JsonSchema7NeverType = { + not: JsonSchema7AnyType; +}; +export declare function parseNeverDef(refs: Refs): JsonSchema7NeverType | undefined; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/null.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/null.d.ts new file mode 100644 index 000000000..509a568a8 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/null.d.ts @@ -0,0 +1,5 @@ +import { Refs } from "../Refs.js"; +export type JsonSchema7NullType = { + type: "null"; +}; +export declare function parseNullDef(refs: Refs): JsonSchema7NullType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/nullable.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/nullable.d.ts new file mode 100644 index 000000000..68fc4daca --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/nullable.d.ts @@ -0,0 +1,10 @@ +import { ZodNullableDef } from "zod/v3"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +import { JsonSchema7NullType } from "./null.js"; +export type JsonSchema7NullableType = { + anyOf: [JsonSchema7Type, JsonSchema7NullType]; +} | { + type: [string, "null"]; +}; +export declare function parseNullableDef(def: ZodNullableDef, refs: Refs): JsonSchema7NullableType | undefined; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/number.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/number.d.ts new file mode 100644 index 000000000..6aca58678 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/number.d.ts @@ -0,0 +1,13 @@ +import { ZodNumberDef } from "zod/v3"; +import { ErrorMessages } from "../errorMessages.js"; +import { Refs } from "../Refs.js"; +export type JsonSchema7NumberType = { + type: "number" | "integer"; + minimum?: number; + exclusiveMinimum?: number; + maximum?: number; + exclusiveMaximum?: number; + multipleOf?: number; + errorMessage?: ErrorMessages; +}; +export declare function parseNumberDef(def: ZodNumberDef, refs: Refs): JsonSchema7NumberType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/object.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/object.d.ts new file mode 100644 index 000000000..6269c6206 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/object.d.ts @@ -0,0 +1,10 @@ +import { ZodObjectDef } from "zod/v3"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +export type JsonSchema7ObjectType = { + type: "object"; + properties: Record; + additionalProperties?: boolean | JsonSchema7Type; + required?: string[]; +}; +export declare function parseObjectDef(def: ZodObjectDef, refs: Refs): JsonSchema7ObjectType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/optional.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/optional.d.ts new file mode 100644 index 000000000..7799cd060 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/optional.d.ts @@ -0,0 +1,4 @@ +import { ZodOptionalDef } from "zod/v3"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +export declare const parseOptionalDef: (def: ZodOptionalDef, refs: Refs) => JsonSchema7Type | undefined; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/pipeline.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/pipeline.d.ts new file mode 100644 index 000000000..0382eacf3 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/pipeline.d.ts @@ -0,0 +1,5 @@ +import { ZodPipelineDef } from "zod/v3"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +import { JsonSchema7AllOfType } from "./intersection.js"; +export declare const parsePipelineDef: (def: ZodPipelineDef, refs: Refs) => JsonSchema7AllOfType | JsonSchema7Type | undefined; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/promise.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/promise.d.ts new file mode 100644 index 000000000..9b0d55a83 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/promise.d.ts @@ -0,0 +1,4 @@ +import { ZodPromiseDef } from "zod/v3"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +export declare function parsePromiseDef(def: ZodPromiseDef, refs: Refs): JsonSchema7Type | undefined; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/readonly.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/readonly.d.ts new file mode 100644 index 000000000..bf5b48026 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/readonly.d.ts @@ -0,0 +1,3 @@ +import { ZodReadonlyDef } from "zod/v3"; +import { Refs } from "../Refs.js"; +export declare const parseReadonlyDef: (def: ZodReadonlyDef, refs: Refs) => import("../parseTypes.js").JsonSchema7Type | undefined; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/record.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/record.d.ts new file mode 100644 index 000000000..784d378d1 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/record.d.ts @@ -0,0 +1,13 @@ +import { ZodMapDef, ZodRecordDef, ZodTypeAny } from "zod/v3"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +import { JsonSchema7EnumType } from "./enum.js"; +import { JsonSchema7StringType } from "./string.js"; +type JsonSchema7RecordPropertyNamesType = Omit | Omit; +export type JsonSchema7RecordType = { + type: "object"; + additionalProperties?: JsonSchema7Type | true; + propertyNames?: JsonSchema7RecordPropertyNamesType; +}; +export declare function parseRecordDef(def: ZodRecordDef | ZodMapDef, refs: Refs): JsonSchema7RecordType; +export {}; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/set.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/set.d.ts new file mode 100644 index 000000000..d527b48f5 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/set.d.ts @@ -0,0 +1,13 @@ +import { ZodSetDef } from "zod/v3"; +import { ErrorMessages } from "../errorMessages.js"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +export type JsonSchema7SetType = { + type: "array"; + uniqueItems: true; + items?: JsonSchema7Type; + minItems?: number; + maxItems?: number; + errorMessage?: ErrorMessages; +}; +export declare function parseSetDef(def: ZodSetDef, refs: Refs): JsonSchema7SetType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/string.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/string.d.ts new file mode 100644 index 000000000..296e75c3f --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/string.d.ts @@ -0,0 +1,73 @@ +import { ZodStringDef } from "zod/v3"; +import { ErrorMessages } from "../errorMessages.js"; +import { Refs } from "../Refs.js"; +/** + * Generated from the regular expressions found here as of 2024-05-22: + * https://github.com/colinhacks/zod/blob/master/src/types.ts. + * + * Expressions with /i flag have been changed accordingly. + */ +export declare const zodPatterns: { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + readonly cuid: RegExp; + readonly cuid2: RegExp; + readonly ulid: RegExp; + /** + * `a-z` was added to replicate /i flag + */ + readonly email: RegExp; + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + readonly emoji: () => RegExp; + /** + * Unused + */ + readonly uuid: RegExp; + /** + * Unused + */ + readonly ipv4: RegExp; + readonly ipv4Cidr: RegExp; + /** + * Unused + */ + readonly ipv6: RegExp; + readonly ipv6Cidr: RegExp; + readonly base64: RegExp; + readonly base64url: RegExp; + readonly nanoid: RegExp; + readonly jwt: RegExp; +}; +export type JsonSchema7StringType = { + type: "string"; + minLength?: number; + maxLength?: number; + format?: "email" | "idn-email" | "uri" | "uuid" | "date-time" | "ipv4" | "ipv6" | "date" | "time" | "duration"; + pattern?: string; + allOf?: { + pattern: string; + errorMessage?: ErrorMessages<{ + pattern: string; + }>; + }[]; + anyOf?: { + format: string; + errorMessage?: ErrorMessages<{ + format: string; + }>; + }[]; + errorMessage?: ErrorMessages; + contentEncoding?: string; +}; +export declare function parseStringDef(def: ZodStringDef, refs: Refs): JsonSchema7StringType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/tuple.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/tuple.d.ts new file mode 100644 index 000000000..25a5833be --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/tuple.d.ts @@ -0,0 +1,13 @@ +import { ZodTupleDef, ZodTupleItems, ZodTypeAny } from "zod/v3"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +export type JsonSchema7TupleType = { + type: "array"; + minItems: number; + items: JsonSchema7Type[]; +} & ({ + maxItems: number; +} | { + additionalItems?: JsonSchema7Type; +}); +export declare function parseTupleDef(def: ZodTupleDef, refs: Refs): JsonSchema7TupleType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/undefined.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/undefined.d.ts new file mode 100644 index 000000000..48e891921 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/undefined.d.ts @@ -0,0 +1,6 @@ +import { Refs } from "../Refs.js"; +import { JsonSchema7AnyType } from "./any.js"; +export type JsonSchema7UndefinedType = { + not: JsonSchema7AnyType; +}; +export declare function parseUndefinedDef(refs: Refs): JsonSchema7UndefinedType; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/union.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/union.d.ts new file mode 100644 index 000000000..cd9e49800 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/union.d.ts @@ -0,0 +1,23 @@ +import { ZodDiscriminatedUnionDef, ZodUnionDef } from "zod/v3"; +import { JsonSchema7Type } from "../parseTypes.js"; +import { Refs } from "../Refs.js"; +export declare const primitiveMappings: { + readonly ZodString: "string"; + readonly ZodNumber: "number"; + readonly ZodBigInt: "integer"; + readonly ZodBoolean: "boolean"; + readonly ZodNull: "null"; +}; +type JsonSchema7Primitive = (typeof primitiveMappings)[keyof typeof primitiveMappings]; +export type JsonSchema7UnionType = JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType; +type JsonSchema7PrimitiveUnionType = { + type: JsonSchema7Primitive | JsonSchema7Primitive[]; +} | { + type: JsonSchema7Primitive | JsonSchema7Primitive[]; + enum: (string | number | bigint | boolean | null)[]; +}; +type JsonSchema7AnyOfType = { + anyOf: JsonSchema7Type[]; +}; +export declare function parseUnionDef(def: ZodUnionDef | ZodDiscriminatedUnionDef, refs: Refs): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined; +export {}; diff --git a/node_modules/zod-to-json-schema/dist/types/parsers/unknown.d.ts b/node_modules/zod-to-json-schema/dist/types/parsers/unknown.d.ts new file mode 100644 index 000000000..a905d0353 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/parsers/unknown.d.ts @@ -0,0 +1,4 @@ +import { Refs } from "../Refs"; +import { JsonSchema7AnyType } from "./any.js"; +export type JsonSchema7UnknownType = JsonSchema7AnyType; +export declare function parseUnknownDef(refs: Refs): JsonSchema7UnknownType; diff --git a/node_modules/zod-to-json-schema/dist/types/selectParser.d.ts b/node_modules/zod-to-json-schema/dist/types/selectParser.d.ts new file mode 100644 index 000000000..39bee4950 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/selectParser.d.ts @@ -0,0 +1,5 @@ +import { ZodFirstPartyTypeKind } from "zod/v3"; +import { Refs } from "./Refs.js"; +import { JsonSchema7Type } from "./parseTypes.js"; +export type InnerDefGetter = () => any; +export declare const selectParser: (def: any, typeName: ZodFirstPartyTypeKind, refs: Refs) => JsonSchema7Type | undefined | InnerDefGetter; diff --git a/node_modules/zod-to-json-schema/dist/types/zodToJsonSchema.d.ts b/node_modules/zod-to-json-schema/dist/types/zodToJsonSchema.d.ts new file mode 100644 index 000000000..17853b7e0 --- /dev/null +++ b/node_modules/zod-to-json-schema/dist/types/zodToJsonSchema.d.ts @@ -0,0 +1,10 @@ +import { ZodSchema } from "zod/v3"; +import { Options, Targets } from "./Options.js"; +import { JsonSchema7Type } from "./parseTypes.js"; +declare const zodToJsonSchema: (schema: ZodSchema, options?: string | Partial> | undefined) => (Target extends "jsonSchema7" ? JsonSchema7Type : object) & { + $schema?: string | undefined; + definitions?: { + [key: string]: Target extends "jsonSchema7" ? JsonSchema7Type : Target extends "jsonSchema2019-09" ? JsonSchema7Type : object; + } | undefined; +}; +export { zodToJsonSchema }; diff --git a/node_modules/zod-to-json-schema/package.json b/node_modules/zod-to-json-schema/package.json new file mode 100644 index 000000000..8febe0986 --- /dev/null +++ b/node_modules/zod-to-json-schema/package.json @@ -0,0 +1,78 @@ +{ + "name": "zod-to-json-schema", + "version": "3.25.1", + "description": "Converts Zod schemas to Json Schemas", + "types": "./dist/types/index.d.ts", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.js", + "exports": { + "import": { + "types": "./dist/types/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/types/index.d.ts", + "default": "./dist/cjs/index.js" + } + }, + "scripts": { + "build:test": "npm --prefix ./dist-test-v3 test && npm --prefix ./dist-test-v4 test", + "build:types": "tsc -p tsconfig.types.json", + "build:cjs": "tsc -p tsconfig.cjs.json && tsx postcjs.ts", + "build:esm": "tsc -p tsconfig.esm.json && tsx postesm.ts", + "build": "npm i && npm run gen && npm test && rimraf ./dist && npm run build:types && npm run build:cjs && npm run build:esm && npm run build:test", + "dry": "npm run build && npm pub --dry-run", + "test:watch": "tsx watch test/index.ts", + "test:gen": "tsx test/createIndex.ts", + "test": "tsx test/index.ts", + "gen": "tsx createIndex.ts" + }, + "keywords": ["zod", "json", "schema", "open", "api", "conversion"], + "author": "Stefan Terdell", + "contributors": [ + "Hammad Asif (https://github.com/mrhammadasif)", + "Noah Rosenzweig (https://github.com/Noah2610)", + "John Wright (https://github.com/johngeorgewright)", + "Krzysztof Ciombor (https://github.com/krzysztofciombor)", + "Yuta Mombetsu (https://github.com/mokocm)", + "Tom Arad (https://github.com/tomarad)", + "Isaac Way (https://github.com/iway1)", + "Andreas Berger (https://github.com/Andy2003)", + "Jan Potoms (https://github.com/Janpot)", + "Santiago Cammi (https://github.com/scammi)", + "Philipp Burckhardt (https://github.com/Planeshifter)", + "Bram del Canho (https://github.com/Bram-dc)", + "Gilad Hecht (https://github.com/gthecht)", + "Colin McDonnell (https://github.com/colinhacks)", + "Spappz (https://github.com/Spappz)", + "Jacob Lee (https://github.com/jacoblee93)", + "Brett Zamir (https://github.com/brettz9)", + "Isaiah Marc Sanchez (https://github.com/imsanchez)", + "Mitchell Merry (https://github.com/mitchell-merry)", + "Enzo Monjardín (https://github.com/enzomonjardin)", + "Víctor Hernández (https://github.com/NanezX)", + "Faïz Hernawan Abdillah (https://github.com/Abdillah)", + "Felix Mosheev (https://github.com/felixmosh)" + ], + "repository": { + "type": "git", + "url": "https://github.com/StefanTerdell/zod-to-json-schema" + }, + "license": "ISC", + "peerDependencies": { + "zod": "^3.25 || ^4" + }, + "devDependencies": { + "@types/json-schema": "^7.0.9", + "@types/node": "^20.9.0", + "ajv": "^8.6.3", + "ajv-errors": "^3.0.0", + "ajv-formats": "^2.1.1", + "fast-diff": "^1.3.0", + "local-ref-resolver": "^0.2.0", + "rimraf": "^3.0.2", + "tsx": "^4.19.0", + "typescript": "^5.1.3", + "zod": "^3.25 || ^4" + } +} diff --git a/node_modules/zod-to-json-schema/postcjs.ts b/node_modules/zod-to-json-schema/postcjs.ts new file mode 100644 index 000000000..57c29eb60 --- /dev/null +++ b/node_modules/zod-to-json-schema/postcjs.ts @@ -0,0 +1,3 @@ +import { writeFileSync } from "fs"; + +writeFileSync("./dist/cjs/package.json", '{"type":"commonjs"}', "utf-8"); diff --git a/node_modules/zod-to-json-schema/postesm.ts b/node_modules/zod-to-json-schema/postesm.ts new file mode 100644 index 000000000..d9a7429fe --- /dev/null +++ b/node_modules/zod-to-json-schema/postesm.ts @@ -0,0 +1,3 @@ +import { writeFileSync } from "fs"; + +writeFileSync("./dist/esm/package.json", '{"type":"module","main":"index.js"}', "utf-8"); diff --git a/node_modules/zod/LICENSE b/node_modules/zod/LICENSE new file mode 100644 index 000000000..c06579627 --- /dev/null +++ b/node_modules/zod/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Colin McDonnell + +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/zod/README.md b/node_modules/zod/README.md new file mode 100644 index 000000000..5ffbaa84a --- /dev/null +++ b/node_modules/zod/README.md @@ -0,0 +1,208 @@ +

+ Zod logo +

Zod

+

+ TypeScript-first schema validation with static type inference +
+ by @colinhacks +

+

+
+ +

+Zod CI status +License +npm +discord server +stars +

+ +
+ Docs +   •   + Discord +   •   + 𝕏 +   •   + Bluesky +
+
+ +
+
+ +

Featured sponsor: Jazz

+ +
+ + + + jazz logo + + +
+

Learn more about featured sponsorships

+
+ +
+
+
+ +### [Read the docs →](https://zod.dev/api) + +
+
+ +## What is Zod? + +Zod is a TypeScript-first validation library. Define a schema and parse some data with it. You'll get back a strongly typed, validated result. + +```ts +import * as z from "zod/v4"; + +const User = z.object({ + name: z.string(), +}); + +// some untrusted data... +const input = { + /* stuff */ +}; + +// the parsed result is validated and type safe! +const data = User.parse(input); + +// so you can use it with confidence :) +console.log(data.name); +``` + +
+ +## Features + +- Zero external dependencies +- Works in Node.js and all modern browsers +- Tiny: `2kb` core bundle (gzipped) +- Immutable API: methods return a new instance +- Concise interface +- Works with TypeScript and plain JS +- Built-in JSON Schema conversion +- Extensive ecosystem + +
+ +## Installation + +```sh +npm install zod +``` + +
+ +## Basic usage + +Before you can do anything else, you need to define a schema. For the purposes of this guide, we'll use a simple object schema. + +```ts +import * as z from "zod/v4"; + +const Player = z.object({ + username: z.string(), + xp: z.number(), +}); +``` + +### Parsing data + +Given any Zod schema, use `.parse` to validate an input. If it's valid, Zod returns a strongly-typed _deep clone_ of the input. + +```ts +Player.parse({ username: "billie", xp: 100 }); +// => returns { username: "billie", xp: 100 } +``` + +**Note** — If your schema uses certain asynchronous APIs like `async` [refinements](#refine) or [transforms](#transform), you'll need to use the `.parseAsync()` method instead. + +```ts +const schema = z.string().refine(async (val) => val.length <= 8); + +await schema.parseAsync("hello"); +// => "hello" +``` + +### Handling errors + +When validation fails, the `.parse()` method will throw a `ZodError` instance with granular information about the validation issues. + +```ts +try { + Player.parse({ username: 42, xp: "100" }); +} catch (err) { + if (err instanceof z.ZodError) { + err.issues; + /* [ + { + expected: 'string', + code: 'invalid_type', + path: [ 'username' ], + message: 'Invalid input: expected string' + }, + { + expected: 'number', + code: 'invalid_type', + path: [ 'xp' ], + message: 'Invalid input: expected number' + } + ] */ + } +} +``` + +To avoid a `try/catch` block, you can use the `.safeParse()` method to get back a plain result object containing either the successfully parsed data or a `ZodError`. The result type is a [discriminated union](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions), so you can handle both cases conveniently. + +```ts +const result = Player.safeParse({ username: 42, xp: "100" }); +if (!result.success) { + result.error; // ZodError instance +} else { + result.data; // { username: string; xp: number } +} +``` + +**Note** — If your schema uses certain asynchronous APIs like `async` [refinements](#refine) or [transforms](#transform), you'll need to use the `.safeParseAsync()` method instead. + +```ts +const schema = z.string().refine(async (val) => val.length <= 8); + +await schema.safeParseAsync("hello"); +// => { success: true; data: "hello" } +``` + +### Inferring types + +Zod infers a static type from your schema definitions. You can extract this type with the `z.infer<>` utility and use it however you like. + +```ts +const Player = z.object({ + username: z.string(), + xp: z.number(), +}); + +// extract the inferred type +type Player = z.infer; + +// use it in your code +const player: Player = { username: "billie", xp: 100 }; +``` + +In some cases, the input & output types of a schema can diverge. For instance, the `.transform()` API can convert the input from one type to another. In these cases, you can extract the input and output types independently: + +```ts +const mySchema = z.string().transform((val) => val.length); + +type MySchemaIn = z.input; +// => string + +type MySchemaOut = z.output; // equivalent to z.infer +// number +``` diff --git a/node_modules/zod/index.cjs b/node_modules/zod/index.cjs new file mode 100644 index 000000000..62f74c802 --- /dev/null +++ b/node_modules/zod/index.cjs @@ -0,0 +1,33 @@ +"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 __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.z = void 0; +const z = __importStar(require("./v3/external.cjs")); +exports.z = z; +__exportStar(require("./v3/external.cjs"), exports); +exports.default = z; diff --git a/node_modules/zod/index.d.cts b/node_modules/zod/index.d.cts new file mode 100644 index 000000000..665bd24d9 --- /dev/null +++ b/node_modules/zod/index.d.cts @@ -0,0 +1,4 @@ +import * as z from "./v3/external.cjs"; +export * from "./v3/external.cjs"; +export { z }; +export default z; diff --git a/node_modules/zod/index.d.ts b/node_modules/zod/index.d.ts new file mode 100644 index 000000000..bf6f1643a --- /dev/null +++ b/node_modules/zod/index.d.ts @@ -0,0 +1,4 @@ +import * as z from "./v3/external.js"; +export * from "./v3/external.js"; +export { z }; +export default z; diff --git a/node_modules/zod/index.js b/node_modules/zod/index.js new file mode 100644 index 000000000..bf6f1643a --- /dev/null +++ b/node_modules/zod/index.js @@ -0,0 +1,4 @@ +import * as z from "./v3/external.js"; +export * from "./v3/external.js"; +export { z }; +export default z; diff --git a/node_modules/zod/package.json b/node_modules/zod/package.json new file mode 100644 index 000000000..eedcfb0f8 --- /dev/null +++ b/node_modules/zod/package.json @@ -0,0 +1,118 @@ +{ + "name": "zod", + "version": "3.25.76", + "type": "module", + "author": "Colin McDonnell ", + "description": "TypeScript-first schema declaration and validation library with static type inference", + "files": [ + "src", + "**/*.js", + "**/*.mjs", + "**/*.cjs", + "**/*.d.ts", + "**/*.d.mts", + "**/*.d.cts" + ], + "funding": "https://github.com/sponsors/colinhacks", + "homepage": "https://zod.dev", + "keywords": [ + "typescript", + "schema", + "validation", + "type", + "inference" + ], + "license": "MIT", + "sideEffects": false, + "main": "./index.cjs", + "types": "./index.d.cts", + "module": "./index.js", + "zshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts", + "./v3": "./src/v3/index.ts", + "./v4": "./src/v4/index.ts", + "./v4-mini": "./src/v4-mini/index.ts", + "./v4/mini": "./src/v4/mini/index.ts", + "./v4/core": "./src/v4/core/index.ts", + "./v4/locales": "./src/v4/locales/index.ts", + "./v4/locales/*": "./src/v4/locales/*" + }, + "sourceDialects": [ + "@zod/source" + ] + }, + "exports": { + "./package.json": "./package.json", + ".": { + "@zod/source": "./src/index.ts", + "types": "./index.d.cts", + "import": "./index.js", + "require": "./index.cjs" + }, + "./v3": { + "@zod/source": "./src/v3/index.ts", + "types": "./v3/index.d.cts", + "import": "./v3/index.js", + "require": "./v3/index.cjs" + }, + "./v4": { + "@zod/source": "./src/v4/index.ts", + "types": "./v4/index.d.cts", + "import": "./v4/index.js", + "require": "./v4/index.cjs" + }, + "./v4-mini": { + "@zod/source": "./src/v4-mini/index.ts", + "types": "./v4-mini/index.d.cts", + "import": "./v4-mini/index.js", + "require": "./v4-mini/index.cjs" + }, + "./v4/mini": { + "@zod/source": "./src/v4/mini/index.ts", + "types": "./v4/mini/index.d.cts", + "import": "./v4/mini/index.js", + "require": "./v4/mini/index.cjs" + }, + "./v4/core": { + "@zod/source": "./src/v4/core/index.ts", + "types": "./v4/core/index.d.cts", + "import": "./v4/core/index.js", + "require": "./v4/core/index.cjs" + }, + "./v4/locales": { + "@zod/source": "./src/v4/locales/index.ts", + "types": "./v4/locales/index.d.cts", + "import": "./v4/locales/index.js", + "require": "./v4/locales/index.cjs" + }, + "./v4/locales/*": { + "@zod/source": "./src/v4/locales/*", + "types": "./v4/locales/*", + "import": "./v4/locales/*", + "require": "./v4/locales/*" + } + }, + "repository": { + "type": "git", + "url": "git+https://github.com/colinhacks/zod.git" + }, + "bugs": { + "url": "https://github.com/colinhacks/zod/issues" + }, + "support": { + "backing": { + "npm-funding": true + } + }, + "scripts": { + "clean": "git clean -xdf . -e node_modules", + "build": "zshy --project tsconfig.build.json", + "postbuild": "pnpm biome check --write .", + "test:watch": "pnpm vitest", + "test": "pnpm vitest run", + "bump:beta": "pnpm version \"v$(pnpm pkg get version | jq -r)-beta.$(date +%Y%m%dT%H%M%S)\"", + "pub:beta": "pnpm bump:beta && pnpm publish --tag next --publish-branch v4 --no-git-checks --dry-run" + } +} diff --git a/node_modules/zod/src/index.ts b/node_modules/zod/src/index.ts new file mode 100644 index 000000000..bf6f1643a --- /dev/null +++ b/node_modules/zod/src/index.ts @@ -0,0 +1,4 @@ +import * as z from "./v3/external.js"; +export * from "./v3/external.js"; +export { z }; +export default z; diff --git a/node_modules/zod/src/v3/ZodError.ts b/node_modules/zod/src/v3/ZodError.ts new file mode 100644 index 000000000..6ee33c14a --- /dev/null +++ b/node_modules/zod/src/v3/ZodError.ts @@ -0,0 +1,330 @@ +import type { Primitive } from "./helpers/typeAliases.js"; +import { util, type ZodParsedType } from "./helpers/util.js"; +import type { TypeOf, ZodType } from "./index.js"; + +type allKeys = T extends any ? keyof T : never; + +export type inferFlattenedErrors, U = string> = typeToFlattenedError, U>; +export type typeToFlattenedError = { + formErrors: U[]; + fieldErrors: { + [P in allKeys]?: U[]; + }; +}; + +export const ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", +]); + +export type ZodIssueCode = keyof typeof ZodIssueCode; + +export type ZodIssueBase = { + path: (string | number)[]; + message?: string | undefined; +}; + +export interface ZodInvalidTypeIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_type; + expected: ZodParsedType; + received: ZodParsedType; +} + +export interface ZodInvalidLiteralIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_literal; + expected: unknown; + received: unknown; +} + +export interface ZodUnrecognizedKeysIssue extends ZodIssueBase { + code: typeof ZodIssueCode.unrecognized_keys; + keys: string[]; +} + +export interface ZodInvalidUnionIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_union; + unionErrors: ZodError[]; +} + +export interface ZodInvalidUnionDiscriminatorIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_union_discriminator; + options: Primitive[]; +} + +export interface ZodInvalidEnumValueIssue extends ZodIssueBase { + received: string | number; + code: typeof ZodIssueCode.invalid_enum_value; + options: (string | number)[]; +} + +export interface ZodInvalidArgumentsIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_arguments; + argumentsError: ZodError; +} + +export interface ZodInvalidReturnTypeIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_return_type; + returnTypeError: ZodError; +} + +export interface ZodInvalidDateIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_date; +} + +export type StringValidation = + | "email" + | "url" + | "emoji" + | "uuid" + | "nanoid" + | "regex" + | "cuid" + | "cuid2" + | "ulid" + | "datetime" + | "date" + | "time" + | "duration" + | "ip" + | "cidr" + | "base64" + | "jwt" + | "base64url" + | { includes: string; position?: number | undefined } + | { startsWith: string } + | { endsWith: string }; + +export interface ZodInvalidStringIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_string; + validation: StringValidation; +} + +export interface ZodTooSmallIssue extends ZodIssueBase { + code: typeof ZodIssueCode.too_small; + minimum: number | bigint; + inclusive: boolean; + exact?: boolean; + type: "array" | "string" | "number" | "set" | "date" | "bigint"; +} + +export interface ZodTooBigIssue extends ZodIssueBase { + code: typeof ZodIssueCode.too_big; + maximum: number | bigint; + inclusive: boolean; + exact?: boolean; + type: "array" | "string" | "number" | "set" | "date" | "bigint"; +} + +export interface ZodInvalidIntersectionTypesIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_intersection_types; +} + +export interface ZodNotMultipleOfIssue extends ZodIssueBase { + code: typeof ZodIssueCode.not_multiple_of; + multipleOf: number | bigint; +} + +export interface ZodNotFiniteIssue extends ZodIssueBase { + code: typeof ZodIssueCode.not_finite; +} + +export interface ZodCustomIssue extends ZodIssueBase { + code: typeof ZodIssueCode.custom; + params?: { [k: string]: any }; +} + +export type DenormalizedError = { [k: string]: DenormalizedError | string[] }; + +export type ZodIssueOptionalMessage = + | ZodInvalidTypeIssue + | ZodInvalidLiteralIssue + | ZodUnrecognizedKeysIssue + | ZodInvalidUnionIssue + | ZodInvalidUnionDiscriminatorIssue + | ZodInvalidEnumValueIssue + | ZodInvalidArgumentsIssue + | ZodInvalidReturnTypeIssue + | ZodInvalidDateIssue + | ZodInvalidStringIssue + | ZodTooSmallIssue + | ZodTooBigIssue + | ZodInvalidIntersectionTypesIssue + | ZodNotMultipleOfIssue + | ZodNotFiniteIssue + | ZodCustomIssue; + +export type ZodIssue = ZodIssueOptionalMessage & { + fatal?: boolean | undefined; + message: string; +}; + +export const quotelessJson = (obj: any) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; + +type recursiveZodFormattedError = T extends [any, ...any[]] + ? { [K in keyof T]?: ZodFormattedError } + : T extends any[] + ? { [k: number]: ZodFormattedError } + : T extends object + ? { [K in keyof T]?: ZodFormattedError } + : unknown; + +export type ZodFormattedError = { + _errors: U[]; +} & recursiveZodFormattedError>; + +export type inferFormattedError, U = string> = ZodFormattedError, U>; + +export class ZodError extends Error { + issues: ZodIssue[] = []; + + get errors() { + return this.issues; + } + + constructor(issues: ZodIssue[]) { + super(); + + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); + } else { + (this as any).__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + + format(): ZodFormattedError; + format(mapper: (issue: ZodIssue) => U): ZodFormattedError; + format(_mapper?: any) { + const mapper: (issue: ZodIssue) => any = + _mapper || + function (issue: ZodIssue) { + return issue.message; + }; + const fieldErrors: ZodFormattedError = { _errors: [] } as any; + const processError = (error: ZodError) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } else if (issue.path.length === 0) { + (fieldErrors as any)._errors.push(mapper(issue)); + } else { + let curr: any = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]!; + const terminal = i === issue.path.length - 1; + + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + + curr = curr[el]; + i++; + } + } + } + }; + + processError(this); + return fieldErrors; + } + + static create = (issues: ZodIssue[]) => { + const error = new ZodError(issues); + return error; + }; + + static assert(value: unknown): asserts value is ZodError { + if (!(value instanceof ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + + override toString() { + return this.message; + } + override get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + + get isEmpty(): boolean { + return this.issues.length === 0; + } + + addIssue = (sub: ZodIssue) => { + this.issues = [...this.issues, sub]; + }; + + addIssues = (subs: ZodIssue[] = []) => { + this.issues = [...this.issues, ...subs]; + }; + + flatten(): typeToFlattenedError; + flatten(mapper?: (issue: ZodIssue) => U): typeToFlattenedError; + flatten(mapper: (issue: ZodIssue) => U = (issue: ZodIssue) => issue.message as any): any { + const fieldErrors: any = {}; + const formErrors: U[] = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + const firstEl = sub.path[0]!; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + + get formErrors() { + return this.flatten(); + } +} + +type stripPath = T extends any ? util.OmitKeys : never; + +export type IssueData = stripPath & { + path?: (string | number)[]; + fatal?: boolean | undefined; +}; + +export type ErrorMapCtx = { + defaultError: string; + data: any; +}; + +export type ZodErrorMap = (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => { message: string }; diff --git a/node_modules/zod/src/v3/benchmarks/datetime.ts b/node_modules/zod/src/v3/benchmarks/datetime.ts new file mode 100644 index 000000000..85552c254 --- /dev/null +++ b/node_modules/zod/src/v3/benchmarks/datetime.ts @@ -0,0 +1,58 @@ +import Benchmark from "benchmark"; + +const datetimeValidationSuite = new Benchmark.Suite("datetime"); + +const DATA = "2021-01-01"; +const MONTHS_31 = new Set([1, 3, 5, 7, 8, 10, 12]); +const MONTHS_30 = new Set([4, 6, 9, 11]); + +const simpleDatetimeRegex = /^(\d{4})-(\d{2})-(\d{2})$/; +const datetimeRegexNoLeapYearValidation = + /^\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d))$/; +const datetimeRegexWithLeapYearValidation = + /^((\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\d|3[01])|(0[469]|11)-(0[1-9]|[12]\d|30)|(02)-(0[1-9]|1\d|2[0-8])))$/; + +datetimeValidationSuite + .add("new Date()", () => { + return !Number.isNaN(new Date(DATA).getTime()); + }) + .add("regex (no validation)", () => { + return simpleDatetimeRegex.test(DATA); + }) + .add("regex (no leap year)", () => { + return datetimeRegexNoLeapYearValidation.test(DATA); + }) + .add("regex (w/ leap year)", () => { + return datetimeRegexWithLeapYearValidation.test(DATA); + }) + .add("capture groups + code", () => { + const match = DATA.match(simpleDatetimeRegex); + if (!match) return false; + + // Extract year, month, and day from the capture groups + const year = Number.parseInt(match[1], 10); + const month = Number.parseInt(match[2], 10); // month is 0-indexed in JavaScript Date, so subtract 1 + const day = Number.parseInt(match[3], 10); + + if (month === 2) { + if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) { + return day <= 29; + } + return day <= 28; + } + if (MONTHS_30.has(month)) { + return day <= 30; + } + if (MONTHS_31.has(month)) { + return day <= 31; + } + return false; + }) + + .on("cycle", (e: Benchmark.Event) => { + console.log(`${datetimeValidationSuite.name!}: ${e.target}`); + }); + +export default { + suites: [datetimeValidationSuite], +}; diff --git a/node_modules/zod/src/v3/benchmarks/discriminatedUnion.ts b/node_modules/zod/src/v3/benchmarks/discriminatedUnion.ts new file mode 100644 index 000000000..47737e6c3 --- /dev/null +++ b/node_modules/zod/src/v3/benchmarks/discriminatedUnion.ts @@ -0,0 +1,80 @@ +import Benchmark from "benchmark"; + +import { z } from "zod/v3"; + +const doubleSuite = new Benchmark.Suite("z.discriminatedUnion: double"); +const manySuite = new Benchmark.Suite("z.discriminatedUnion: many"); + +const aSchema = z.object({ + type: z.literal("a"), +}); +const objA = { + type: "a", +}; + +const bSchema = z.object({ + type: z.literal("b"), +}); +const objB = { + type: "b", +}; + +const cSchema = z.object({ + type: z.literal("c"), +}); +const objC = { + type: "c", +}; + +const dSchema = z.object({ + type: z.literal("d"), +}); + +const double = z.discriminatedUnion("type", [aSchema, bSchema]); +const many = z.discriminatedUnion("type", [aSchema, bSchema, cSchema, dSchema]); + +doubleSuite + .add("valid: a", () => { + double.parse(objA); + }) + .add("valid: b", () => { + double.parse(objB); + }) + .add("invalid: null", () => { + try { + double.parse(null); + } catch (_err) {} + }) + .add("invalid: wrong shape", () => { + try { + double.parse(objC); + } catch (_err) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`${(doubleSuite as any).name}: ${e.target}`); + }); + +manySuite + .add("valid: a", () => { + many.parse(objA); + }) + .add("valid: c", () => { + many.parse(objC); + }) + .add("invalid: null", () => { + try { + many.parse(null); + } catch (_err) {} + }) + .add("invalid: wrong shape", () => { + try { + many.parse({ type: "unknown" }); + } catch (_err) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`${(manySuite as any).name}: ${e.target}`); + }); + +export default { + suites: [doubleSuite, manySuite], +}; diff --git a/node_modules/zod/src/v3/benchmarks/index.ts b/node_modules/zod/src/v3/benchmarks/index.ts new file mode 100644 index 000000000..ca81c5bb9 --- /dev/null +++ b/node_modules/zod/src/v3/benchmarks/index.ts @@ -0,0 +1,59 @@ +import type Benchmark from "benchmark"; + +import datetimeBenchmarks from "./datetime.js"; +import discriminatedUnionBenchmarks from "./discriminatedUnion.js"; +import ipv4Benchmarks from "./ipv4.js"; +import objectBenchmarks from "./object.js"; +import primitiveBenchmarks from "./primitives.js"; +import realworld from "./realworld.js"; +import stringBenchmarks from "./string.js"; +import unionBenchmarks from "./union.js"; + +const argv = process.argv.slice(2); +let suites: Benchmark.Suite[] = []; + +if (!argv.length) { + suites = [ + ...realworld.suites, + ...primitiveBenchmarks.suites, + ...stringBenchmarks.suites, + ...objectBenchmarks.suites, + ...unionBenchmarks.suites, + ...discriminatedUnionBenchmarks.suites, + ]; +} else { + if (argv.includes("--realworld")) { + suites.push(...realworld.suites); + } + if (argv.includes("--primitives")) { + suites.push(...primitiveBenchmarks.suites); + } + if (argv.includes("--string")) { + suites.push(...stringBenchmarks.suites); + } + if (argv.includes("--object")) { + suites.push(...objectBenchmarks.suites); + } + if (argv.includes("--union")) { + suites.push(...unionBenchmarks.suites); + } + if (argv.includes("--discriminatedUnion")) { + suites.push(...datetimeBenchmarks.suites); + } + if (argv.includes("--datetime")) { + suites.push(...datetimeBenchmarks.suites); + } + if (argv.includes("--ipv4")) { + suites.push(...ipv4Benchmarks.suites); + } +} + +for (const suite of suites) { + suite.run({}); +} + +// exit on Ctrl-C +process.on("SIGINT", function () { + console.log("Exiting..."); + process.exit(); +}); diff --git a/node_modules/zod/src/v3/benchmarks/ipv4.ts b/node_modules/zod/src/v3/benchmarks/ipv4.ts new file mode 100644 index 000000000..913ffd416 --- /dev/null +++ b/node_modules/zod/src/v3/benchmarks/ipv4.ts @@ -0,0 +1,57 @@ +import Benchmark from "benchmark"; + +const suite = new Benchmark.Suite("ipv4"); + +const DATA = "127.0.0.1"; +const ipv4RegexA = + /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; +const ipv4RegexB = + /^(?:(?:(?=(25[0-5]))\1|(?=(2[0-4][0-9]))\2|(?=(1[0-9]{2}))\3|(?=([0-9]{1,2}))\4)\.){3}(?:(?=(25[0-5]))\5|(?=(2[0-4][0-9]))\6|(?=(1[0-9]{2}))\7|(?=([0-9]{1,2}))\8)$/; +const ipv4RegexC = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/; +const ipv4RegexD = /^(\b25[0-5]|\b2[0-4][0-9]|\b[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/; +const ipv4RegexE = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.){3}(25[0-5]|(2[0-4]|1\d|[1-9]|)\d)$/; +const ipv4RegexF = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/; +const ipv4RegexG = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$/; +const ipv4RegexH = /^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\.(?!$)|$)){4}$/; +const ipv4RegexI = + /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + +suite + .add("A", () => { + return ipv4RegexA.test(DATA); + }) + .add("B", () => { + return ipv4RegexB.test(DATA); + }) + .add("C", () => { + return ipv4RegexC.test(DATA); + }) + .add("D", () => { + return ipv4RegexD.test(DATA); + }) + .add("E", () => { + return ipv4RegexE.test(DATA); + }) + .add("F", () => { + return ipv4RegexF.test(DATA); + }) + .add("G", () => { + return ipv4RegexG.test(DATA); + }) + .add("H", () => { + return ipv4RegexH.test(DATA); + }) + .add("I", () => { + return ipv4RegexI.test(DATA); + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`${suite.name!}: ${e.target}`); + }); + +export default { + suites: [suite], +}; + +if (require.main === module) { + suite.run(); +} diff --git a/node_modules/zod/src/v3/benchmarks/object.ts b/node_modules/zod/src/v3/benchmarks/object.ts new file mode 100644 index 000000000..3c1da1022 --- /dev/null +++ b/node_modules/zod/src/v3/benchmarks/object.ts @@ -0,0 +1,69 @@ +import Benchmark from "benchmark"; + +import { z } from "zod/v3"; + +const emptySuite = new Benchmark.Suite("z.object: empty"); +const shortSuite = new Benchmark.Suite("z.object: short"); +const longSuite = new Benchmark.Suite("z.object: long"); + +const empty = z.object({}); +const short = z.object({ + string: z.string(), +}); +const long = z.object({ + string: z.string(), + number: z.number(), + boolean: z.boolean(), +}); + +emptySuite + .add("valid", () => { + empty.parse({}); + }) + .add("valid: extra keys", () => { + empty.parse({ string: "string" }); + }) + .add("invalid: null", () => { + try { + empty.parse(null); + } catch (_err) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`${(emptySuite as any).name}: ${e.target}`); + }); + +shortSuite + .add("valid", () => { + short.parse({ string: "string" }); + }) + .add("valid: extra keys", () => { + short.parse({ string: "string", number: 42 }); + }) + .add("invalid: null", () => { + try { + short.parse(null); + } catch (_err) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`${(shortSuite as any).name}: ${e.target}`); + }); + +longSuite + .add("valid", () => { + long.parse({ string: "string", number: 42, boolean: true }); + }) + .add("valid: extra keys", () => { + long.parse({ string: "string", number: 42, boolean: true, list: [] }); + }) + .add("invalid: null", () => { + try { + long.parse(null); + } catch (_err) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`${(longSuite as any).name}: ${e.target}`); + }); + +export default { + suites: [emptySuite, shortSuite, longSuite], +}; diff --git a/node_modules/zod/src/v3/benchmarks/primitives.ts b/node_modules/zod/src/v3/benchmarks/primitives.ts new file mode 100644 index 000000000..fd61b38fe --- /dev/null +++ b/node_modules/zod/src/v3/benchmarks/primitives.ts @@ -0,0 +1,162 @@ +import Benchmark from "benchmark"; + +import { z } from "zod/v3"; +import { Mocker } from "../tests/Mocker.js"; + +const val = new Mocker(); + +const enumSuite = new Benchmark.Suite("z.enum"); +const enumSchema = z.enum(["a", "b", "c"]); + +enumSuite + .add("valid", () => { + enumSchema.parse("a"); + }) + .add("invalid", () => { + try { + enumSchema.parse("x"); + } catch (_e: any) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`z.enum: ${e.target}`); + }); + +const longEnumSuite = new Benchmark.Suite("long z.enum"); +const longEnumSchema = z.enum([ + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "ten", + "eleven", + "twelve", + "thirteen", + "fourteen", + "fifteen", + "sixteen", + "seventeen", +]); + +longEnumSuite + .add("valid", () => { + longEnumSchema.parse("five"); + }) + .add("invalid", () => { + try { + longEnumSchema.parse("invalid"); + } catch (_e: any) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`long z.enum: ${e.target}`); + }); + +const undefinedSuite = new Benchmark.Suite("z.undefined"); +const undefinedSchema = z.undefined(); + +undefinedSuite + .add("valid", () => { + undefinedSchema.parse(undefined); + }) + .add("invalid", () => { + try { + undefinedSchema.parse(1); + } catch (_e: any) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`z.undefined: ${e.target}`); + }); + +const literalSuite = new Benchmark.Suite("z.literal"); +const short = "short"; +const bad = "bad"; +const literalSchema = z.literal("short"); + +literalSuite + .add("valid", () => { + literalSchema.parse(short); + }) + .add("invalid", () => { + try { + literalSchema.parse(bad); + } catch (_e: any) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`z.literal: ${e.target}`); + }); + +const numberSuite = new Benchmark.Suite("z.number"); +const numberSchema = z.number().int(); + +numberSuite + .add("valid", () => { + numberSchema.parse(1); + }) + .add("invalid type", () => { + try { + numberSchema.parse("bad"); + } catch (_e: any) {} + }) + .add("invalid number", () => { + try { + numberSchema.parse(0.5); + } catch (_e: any) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`z.number: ${e.target}`); + }); + +const dateSuite = new Benchmark.Suite("z.date"); + +const plainDate = z.date(); +const minMaxDate = z.date().min(new Date("2021-01-01")).max(new Date("2030-01-01")); + +dateSuite + .add("valid", () => { + plainDate.parse(new Date()); + }) + .add("invalid", () => { + try { + plainDate.parse(1); + } catch (_e: any) {} + }) + .add("valid min and max", () => { + minMaxDate.parse(new Date("2023-01-01")); + }) + .add("invalid min", () => { + try { + minMaxDate.parse(new Date("2019-01-01")); + } catch (_e: any) {} + }) + .add("invalid max", () => { + try { + minMaxDate.parse(new Date("2031-01-01")); + } catch (_e: any) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`z.date: ${e.target}`); + }); + +const symbolSuite = new Benchmark.Suite("z.symbol"); +const symbolSchema = z.symbol(); + +symbolSuite + .add("valid", () => { + symbolSchema.parse(val.symbol); + }) + .add("invalid", () => { + try { + symbolSchema.parse(1); + } catch (_e: any) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`z.symbol: ${e.target}`); + }); + +export default { + suites: [enumSuite, longEnumSuite, undefinedSuite, literalSuite, numberSuite, dateSuite, symbolSuite], +}; diff --git a/node_modules/zod/src/v3/benchmarks/realworld.ts b/node_modules/zod/src/v3/benchmarks/realworld.ts new file mode 100644 index 000000000..d64c4f0d0 --- /dev/null +++ b/node_modules/zod/src/v3/benchmarks/realworld.ts @@ -0,0 +1,63 @@ +import Benchmark from "benchmark"; + +import { z } from "zod/v3"; + +const shortSuite = new Benchmark.Suite("realworld"); + +const People = z.array( + z.object({ + type: z.literal("person"), + hair: z.enum(["blue", "brown"]), + active: z.boolean(), + name: z.string(), + age: z.number().int(), + hobbies: z.array(z.string()), + address: z.object({ + street: z.string(), + zip: z.string(), + country: z.string(), + }), + }) +); + +let i = 0; + +function num() { + return ++i; +} + +function str() { + return (++i % 100).toString(16); +} + +function array(fn: () => T): T[] { + return Array.from({ length: ++i % 10 }, () => fn()); +} + +const people = Array.from({ length: 100 }, () => { + return { + type: "person", + hair: i % 2 ? "blue" : "brown", + active: !!(i % 2), + name: str(), + age: num(), + hobbies: array(str), + address: { + street: str(), + zip: str(), + country: str(), + }, + }; +}); + +shortSuite + .add("valid", () => { + People.parse(people); + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`${(shortSuite as any).name}: ${e.target}`); + }); + +export default { + suites: [shortSuite], +}; diff --git a/node_modules/zod/src/v3/benchmarks/string.ts b/node_modules/zod/src/v3/benchmarks/string.ts new file mode 100644 index 000000000..6b3d29f94 --- /dev/null +++ b/node_modules/zod/src/v3/benchmarks/string.ts @@ -0,0 +1,55 @@ +import Benchmark from "benchmark"; + +import { z } from "zod/v3"; + +const SUITE_NAME = "z.string"; +const suite = new Benchmark.Suite(SUITE_NAME); + +const empty = ""; +const short = "short"; +const long = "long".repeat(256); +const manual = (str: unknown) => { + if (typeof str !== "string") { + throw new Error("Not a string"); + } + + return str; +}; +const stringSchema = z.string(); +const optionalStringSchema = z.string().optional(); +const optionalNullableStringSchema = z.string().optional().nullable(); + +suite + .add("empty string", () => { + stringSchema.parse(empty); + }) + .add("short string", () => { + stringSchema.parse(short); + }) + .add("long string", () => { + stringSchema.parse(long); + }) + .add("optional string", () => { + optionalStringSchema.parse(long); + }) + .add("nullable string", () => { + optionalNullableStringSchema.parse(long); + }) + .add("nullable (null) string", () => { + optionalNullableStringSchema.parse(null); + }) + .add("invalid: null", () => { + try { + stringSchema.parse(null); + } catch (_err) {} + }) + .add("manual parser: long", () => { + manual(long); + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`${SUITE_NAME}: ${e.target}`); + }); + +export default { + suites: [suite], +}; diff --git a/node_modules/zod/src/v3/benchmarks/union.ts b/node_modules/zod/src/v3/benchmarks/union.ts new file mode 100644 index 000000000..d716dcef0 --- /dev/null +++ b/node_modules/zod/src/v3/benchmarks/union.ts @@ -0,0 +1,80 @@ +import Benchmark from "benchmark"; + +import { z } from "zod/v3"; + +const doubleSuite = new Benchmark.Suite("z.union: double"); +const manySuite = new Benchmark.Suite("z.union: many"); + +const aSchema = z.object({ + type: z.literal("a"), +}); +const objA = { + type: "a", +}; + +const bSchema = z.object({ + type: z.literal("b"), +}); +const objB = { + type: "b", +}; + +const cSchema = z.object({ + type: z.literal("c"), +}); +const objC = { + type: "c", +}; + +const dSchema = z.object({ + type: z.literal("d"), +}); + +const double = z.union([aSchema, bSchema]); +const many = z.union([aSchema, bSchema, cSchema, dSchema]); + +doubleSuite + .add("valid: a", () => { + double.parse(objA); + }) + .add("valid: b", () => { + double.parse(objB); + }) + .add("invalid: null", () => { + try { + double.parse(null); + } catch (_err) {} + }) + .add("invalid: wrong shape", () => { + try { + double.parse(objC); + } catch (_err) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`${(doubleSuite as any).name}: ${e.target}`); + }); + +manySuite + .add("valid: a", () => { + many.parse(objA); + }) + .add("valid: c", () => { + many.parse(objC); + }) + .add("invalid: null", () => { + try { + many.parse(null); + } catch (_err) {} + }) + .add("invalid: wrong shape", () => { + try { + many.parse({ type: "unknown" }); + } catch (_err) {} + }) + .on("cycle", (e: Benchmark.Event) => { + console.log(`${(manySuite as any).name}: ${e.target}`); + }); + +export default { + suites: [doubleSuite, manySuite], +}; diff --git a/node_modules/zod/src/v3/errors.ts b/node_modules/zod/src/v3/errors.ts new file mode 100644 index 000000000..3c0dae659 --- /dev/null +++ b/node_modules/zod/src/v3/errors.ts @@ -0,0 +1,13 @@ +import type { ZodErrorMap } from "./ZodError.js"; +import defaultErrorMap from "./locales/en.js"; + +let overrideErrorMap = defaultErrorMap; +export { defaultErrorMap }; + +export function setErrorMap(map: ZodErrorMap) { + overrideErrorMap = map; +} + +export function getErrorMap() { + return overrideErrorMap; +} diff --git a/node_modules/zod/src/v3/external.ts b/node_modules/zod/src/v3/external.ts new file mode 100644 index 000000000..f0a4be4c7 --- /dev/null +++ b/node_modules/zod/src/v3/external.ts @@ -0,0 +1,6 @@ +export * from "./errors.js"; +export * from "./helpers/parseUtil.js"; +export * from "./helpers/typeAliases.js"; +export * from "./helpers/util.js"; +export * from "./types.js"; +export * from "./ZodError.js"; diff --git a/node_modules/zod/src/v3/helpers/enumUtil.ts b/node_modules/zod/src/v3/helpers/enumUtil.ts new file mode 100644 index 000000000..526b22736 --- /dev/null +++ b/node_modules/zod/src/v3/helpers/enumUtil.ts @@ -0,0 +1,17 @@ +export namespace enumUtil { + type UnionToIntersectionFn = (T extends unknown ? (k: () => T) => void : never) extends ( + k: infer Intersection + ) => void + ? Intersection + : never; + + type GetUnionLast = UnionToIntersectionFn extends () => infer Last ? Last : never; + + type UnionToTuple = [T] extends [never] + ? Tuple + : UnionToTuple>, [GetUnionLast, ...Tuple]>; + + type CastToStringTuple = T extends [string, ...string[]] ? T : never; + + export type UnionToTupleString = CastToStringTuple>; +} diff --git a/node_modules/zod/src/v3/helpers/errorUtil.ts b/node_modules/zod/src/v3/helpers/errorUtil.ts new file mode 100644 index 000000000..319ef6b74 --- /dev/null +++ b/node_modules/zod/src/v3/helpers/errorUtil.ts @@ -0,0 +1,8 @@ +export namespace errorUtil { + export type ErrMessage = string | { message?: string | undefined }; + export const errToObj = (message?: ErrMessage): { message?: string | undefined } => + typeof message === "string" ? { message } : message || {}; + // biome-ignore lint: + export const toString = (message?: ErrMessage): string | undefined => + typeof message === "string" ? message : message?.message; +} diff --git a/node_modules/zod/src/v3/helpers/parseUtil.ts b/node_modules/zod/src/v3/helpers/parseUtil.ts new file mode 100644 index 000000000..1076ad9de --- /dev/null +++ b/node_modules/zod/src/v3/helpers/parseUtil.ts @@ -0,0 +1,176 @@ +import type { IssueData, ZodErrorMap, ZodIssue } from "../ZodError.js"; +import { getErrorMap } from "../errors.js"; +import defaultErrorMap from "../locales/en.js"; +import type { ZodParsedType } from "./util.js"; + +export const makeIssue = (params: { + data: any; + path: (string | number)[]; + errorMaps: ZodErrorMap[]; + issueData: IssueData; +}): ZodIssue => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + + if (issueData.message !== undefined) { + return { + ...issueData, + path: fullPath, + message: issueData.message, + }; + } + + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + + return { + ...issueData, + path: fullPath, + message: errorMessage, + }; +}; + +export type ParseParams = { + path: (string | number)[]; + errorMap: ZodErrorMap; + async: boolean; +}; + +export type ParsePathComponent = string | number; +export type ParsePath = ParsePathComponent[]; +export const EMPTY_PATH: ParsePath = []; + +export interface ParseContext { + readonly common: { + readonly issues: ZodIssue[]; + readonly contextualErrorMap?: ZodErrorMap | undefined; + readonly async: boolean; + }; + readonly path: ParsePath; + readonly schemaErrorMap?: ZodErrorMap | undefined; + readonly parent: ParseContext | null; + readonly data: any; + readonly parsedType: ZodParsedType; +} + +export type ParseInput = { + data: any; + path: (string | number)[]; + parent: ParseContext; +}; + +export function addIssueToContext(ctx: ParseContext, issueData: IssueData): void { + const overrideMap = getErrorMap(); + const issue = makeIssue({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, // contextual error map is first priority + ctx.schemaErrorMap, // then schema-bound map if available + overrideMap, // then global override map + overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); +} + +export type ObjectPair = { + key: SyncParseReturnType; + value: SyncParseReturnType; +}; +export class ParseStatus { + value: "aborted" | "dirty" | "valid" = "valid"; + dirty(): void { + if (this.value === "valid") this.value = "dirty"; + } + abort(): void { + if (this.value !== "aborted") this.value = "aborted"; + } + + static mergeArray(status: ParseStatus, results: SyncParseReturnType[]): SyncParseReturnType { + const arrayValue: any[] = []; + for (const s of results) { + if (s.status === "aborted") return INVALID; + if (s.status === "dirty") status.dirty(); + arrayValue.push(s.value); + } + + return { status: status.value, value: arrayValue }; + } + + static async mergeObjectAsync( + status: ParseStatus, + pairs: { key: ParseReturnType; value: ParseReturnType }[] + ): Promise> { + const syncPairs: ObjectPair[] = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + + static mergeObjectSync( + status: ParseStatus, + pairs: { + key: SyncParseReturnType; + value: SyncParseReturnType; + alwaysSet?: boolean; + }[] + ): SyncParseReturnType { + const finalObject: any = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") return INVALID; + if (value.status === "aborted") return INVALID; + if (key.status === "dirty") status.dirty(); + if (value.status === "dirty") status.dirty(); + + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + + return { status: status.value, value: finalObject }; + } +} +export interface ParseResult { + status: "aborted" | "dirty" | "valid"; + data: any; +} + +export type INVALID = { status: "aborted" }; +export const INVALID: INVALID = Object.freeze({ + status: "aborted", +}); + +export type DIRTY = { status: "dirty"; value: T }; +export const DIRTY = (value: T): DIRTY => ({ status: "dirty", value }); + +export type OK = { status: "valid"; value: T }; +export const OK = (value: T): OK => ({ status: "valid", value }); + +export type SyncParseReturnType = OK | DIRTY | INVALID; +export type AsyncParseReturnType = Promise>; +export type ParseReturnType = SyncParseReturnType | AsyncParseReturnType; + +export const isAborted = (x: ParseReturnType): x is INVALID => (x as any).status === "aborted"; +export const isDirty = (x: ParseReturnType): x is OK | DIRTY => (x as any).status === "dirty"; +export const isValid = (x: ParseReturnType): x is OK => (x as any).status === "valid"; +export const isAsync = (x: ParseReturnType): x is AsyncParseReturnType => + typeof Promise !== "undefined" && x instanceof Promise; diff --git a/node_modules/zod/src/v3/helpers/partialUtil.ts b/node_modules/zod/src/v3/helpers/partialUtil.ts new file mode 100644 index 000000000..0eff8ff34 --- /dev/null +++ b/node_modules/zod/src/v3/helpers/partialUtil.ts @@ -0,0 +1,34 @@ +import type { + ZodArray, + ZodNullable, + ZodObject, + ZodOptional, + ZodRawShape, + ZodTuple, + ZodTupleItems, + ZodTypeAny, +} from "../types.js"; + +export namespace partialUtil { + export type DeepPartial = T extends ZodObject + ? ZodObject< + { [k in keyof T["shape"]]: ZodOptional> }, + T["_def"]["unknownKeys"], + T["_def"]["catchall"] + > + : T extends ZodArray + ? ZodArray, Card> + : T extends ZodOptional + ? ZodOptional> + : T extends ZodNullable + ? ZodNullable> + : T extends ZodTuple + ? { + [k in keyof Items]: Items[k] extends ZodTypeAny ? DeepPartial : never; + } extends infer PI + ? PI extends ZodTupleItems + ? ZodTuple + : never + : never + : T; +} diff --git a/node_modules/zod/src/v3/helpers/typeAliases.ts b/node_modules/zod/src/v3/helpers/typeAliases.ts new file mode 100644 index 000000000..32df022ca --- /dev/null +++ b/node_modules/zod/src/v3/helpers/typeAliases.ts @@ -0,0 +1,2 @@ +export type Primitive = string | number | symbol | bigint | boolean | null | undefined; +export type Scalars = Primitive | Primitive[]; diff --git a/node_modules/zod/src/v3/helpers/util.ts b/node_modules/zod/src/v3/helpers/util.ts new file mode 100644 index 000000000..030ea821b --- /dev/null +++ b/node_modules/zod/src/v3/helpers/util.ts @@ -0,0 +1,224 @@ +export namespace util { + type AssertEqual = (() => V extends T ? 1 : 2) extends () => V extends U ? 1 : 2 ? true : false; + + export type isAny = 0 extends 1 & T ? true : false; + export const assertEqual = (_: AssertEqual): void => {}; + export function assertIs(_arg: T): void {} + export function assertNever(_x: never): never { + throw new Error(); + } + + export type Omit = Pick>; + export type OmitKeys = Pick>; + export type MakePartial = Omit & Partial>; + export type Exactly = T & Record, never>; + export type InexactPartial = { [k in keyof T]?: T[k] | undefined }; + export const arrayToEnum = (items: U): { [k in U[number]]: k } => { + const obj: any = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + + export const getValidEnumValues = (obj: any): any[] => { + const validKeys = objectKeys(obj).filter((k: any) => typeof obj[obj[k]] !== "number"); + const filtered: any = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return objectValues(filtered); + }; + + export const objectValues = (obj: any): any[] => { + return objectKeys(obj).map(function (e) { + return obj[e]; + }); + }; + + export const objectKeys: ObjectConstructor["keys"] = + typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj: any) => Object.keys(obj) // eslint-disable-line ban/ban + : (object: any) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + + export const find = (arr: T[], checker: (arg: T) => any): T | undefined => { + for (const item of arr) { + if (checker(item)) return item; + } + return undefined; + }; + + export type identity = objectUtil.identity; + export type flatten = objectUtil.flatten; + + export type noUndefined = T extends undefined ? never : T; + + export const isInteger: NumberConstructor["isInteger"] = + typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + + export function joinValues(array: T, separator = " | "): string { + return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator); + } + + export const jsonStringifyReplacer = (_: string, value: any): any => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +} + +export namespace objectUtil { + export type MergeShapes = + // fast path when there is no keys overlap + keyof U & keyof V extends never + ? U & V + : { + [k in Exclude]: U[k]; + } & V; + + type optionalKeys = { + [k in keyof T]: undefined extends T[k] ? k : never; + }[keyof T]; + type requiredKeys = { + [k in keyof T]: undefined extends T[k] ? never : k; + }[keyof T]; + export type addQuestionMarks = { + [K in requiredKeys]: T[K]; + } & { + [K in optionalKeys]?: T[K]; + } & { [k in keyof T]?: unknown }; + + export type identity = T; + export type flatten = identity<{ [k in keyof T]: T[k] }>; + + export type noNeverKeys = { + [k in keyof T]: [T[k]] extends [never] ? never : k; + }[keyof T]; + + export type noNever = identity<{ + [k in noNeverKeys]: k extends keyof T ? T[k] : never; + }>; + + export const mergeShapes = (first: U, second: T): T & U => { + return { + ...first, + ...second, // second overwrites first + }; + }; + + export type extendShape = keyof A & keyof B extends never // fast path when there is no keys overlap + ? A & B + : { + [K in keyof A as K extends keyof B ? never : K]: A[K]; + } & { + [K in keyof B]: B[K]; + }; +} + +export const ZodParsedType: { + string: "string"; + nan: "nan"; + number: "number"; + integer: "integer"; + float: "float"; + boolean: "boolean"; + date: "date"; + bigint: "bigint"; + symbol: "symbol"; + function: "function"; + undefined: "undefined"; + null: "null"; + array: "array"; + object: "object"; + unknown: "unknown"; + promise: "promise"; + void: "void"; + never: "never"; + map: "map"; + set: "set"; +} = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", +]); + +export type ZodParsedType = keyof typeof ZodParsedType; + +export const getParsedType = (data: any): ZodParsedType => { + const t = typeof data; + + switch (t) { + case "undefined": + return ZodParsedType.undefined; + + case "string": + return ZodParsedType.string; + + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + + case "boolean": + return ZodParsedType.boolean; + + case "function": + return ZodParsedType.function; + + case "bigint": + return ZodParsedType.bigint; + + case "symbol": + return ZodParsedType.symbol; + + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + + default: + return ZodParsedType.unknown; + } +}; diff --git a/node_modules/zod/src/v3/index.ts b/node_modules/zod/src/v3/index.ts new file mode 100644 index 000000000..a9dab5738 --- /dev/null +++ b/node_modules/zod/src/v3/index.ts @@ -0,0 +1,4 @@ +import * as z from "./external.js"; +export * from "./external.js"; +export { z }; +export default z; diff --git a/node_modules/zod/src/v3/locales/en.ts b/node_modules/zod/src/v3/locales/en.ts new file mode 100644 index 000000000..0264f82ef --- /dev/null +++ b/node_modules/zod/src/v3/locales/en.ts @@ -0,0 +1,124 @@ +import { type ZodErrorMap, ZodIssueCode } from "../ZodError.js"; +import { util, ZodParsedType } from "../helpers/util.js"; + +const errorMap: ZodErrorMap = (issue, _ctx) => { + let message: string; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } else { + util.assertNever(issue.validation); + } + } else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${ + issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than` + } ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${ + issue.exact ? "exactly" : issue.inclusive ? `at least` : `over` + } ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${ + issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than ` + }${issue.minimum}`; + else if (issue.type === "bigint") + message = `Number must be ${ + issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than ` + }${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${ + issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than ` + }${new Date(Number(issue.minimum))}`; + else message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${ + issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than` + } ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${ + issue.exact ? `exactly` : issue.inclusive ? `at most` : `under` + } ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${ + issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than` + } ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${ + issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than` + } ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${ + issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than` + } ${new Date(Number(issue.maximum))}`; + else message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue); + } + return { message }; +}; + +export default errorMap; diff --git a/node_modules/zod/src/v3/standard-schema.ts b/node_modules/zod/src/v3/standard-schema.ts new file mode 100644 index 000000000..07193fd13 --- /dev/null +++ b/node_modules/zod/src/v3/standard-schema.ts @@ -0,0 +1,113 @@ +/** + * The Standard Schema interface. + */ +export type StandardSchemaV1 = { + /** + * The Standard Schema properties. + */ + readonly "~standard": StandardSchemaV1.Props; +}; + +export declare namespace StandardSchemaV1 { + /** + * The Standard Schema properties interface. + */ + export interface Props { + /** + * The version number of the standard. + */ + readonly version: 1; + /** + * The vendor name of the schema library. + */ + readonly vendor: string; + /** + * Validates unknown input values. + */ + readonly validate: (value: unknown) => Result | Promise>; + /** + * Inferred types associated with the schema. + */ + readonly types?: Types | undefined; + } + + /** + * The result interface of the validate function. + */ + export type Result = SuccessResult | FailureResult; + + /** + * The result interface if validation succeeds. + */ + export interface SuccessResult { + /** + * The typed output value. + */ + readonly value: Output; + /** + * The non-existent issues. + */ + readonly issues?: undefined; + } + + /** + * The result interface if validation fails. + */ + export interface FailureResult { + /** + * The issues of failed validation. + */ + readonly issues: ReadonlyArray; + } + + /** + * The issue interface of the failure output. + */ + export interface Issue { + /** + * The error message of the issue. + */ + readonly message: string; + /** + * The path of the issue, if any. + */ + readonly path?: ReadonlyArray | undefined; + } + + /** + * The path segment interface of the issue. + */ + export interface PathSegment { + /** + * The key representing a path segment. + */ + readonly key: PropertyKey; + } + + /** + * The Standard Schema types interface. + */ + export interface Types { + /** + * The input type of the schema. + */ + readonly input: Input; + /** + * The output type of the schema. + */ + readonly output: Output; + } + + /** + * Infers the input type of a Standard Schema. + */ + export type InferInput = NonNullable["input"]; + + /** + * Infers the output type of a Standard Schema. + */ + export type InferOutput = NonNullable["output"]; + + // biome-ignore lint/complexity/noUselessEmptyExport: needed for granular visibility control of TS namespace + export {}; +} diff --git a/node_modules/zod/src/v3/tests/Mocker.ts b/node_modules/zod/src/v3/tests/Mocker.ts new file mode 100644 index 000000000..c9fbdd51a --- /dev/null +++ b/node_modules/zod/src/v3/tests/Mocker.ts @@ -0,0 +1,54 @@ +function getRandomInt(max: number) { + return Math.floor(Math.random() * Math.floor(max)); +} + +const testSymbol = Symbol("test"); + +export class Mocker { + pick = (...args: any[]): any => { + return args[getRandomInt(args.length)]; + }; + + get string(): string { + return Math.random().toString(36).substring(7); + } + get number(): number { + return Math.random() * 100; + } + get bigint(): bigint { + return BigInt(Math.floor(Math.random() * 10000)); + } + get boolean(): boolean { + return Math.random() < 0.5; + } + get date(): Date { + return new Date(Math.floor(Date.now() * Math.random())); + } + get symbol(): symbol { + return testSymbol; + } + get null(): null { + return null; + } + get undefined(): undefined { + return undefined; + } + get stringOptional(): string | undefined { + return this.pick(this.string, this.undefined); + } + get stringNullable(): string | null { + return this.pick(this.string, this.null); + } + get numberOptional(): number | undefined { + return this.pick(this.number, this.undefined); + } + get numberNullable(): number | null { + return this.pick(this.number, this.null); + } + get booleanOptional(): boolean | undefined { + return this.pick(this.boolean, this.undefined); + } + get booleanNullable(): boolean | null { + return this.pick(this.boolean, this.null); + } +} diff --git a/node_modules/zod/src/v3/tests/all-errors.test.ts b/node_modules/zod/src/v3/tests/all-errors.test.ts new file mode 100644 index 000000000..8fdf8f426 --- /dev/null +++ b/node_modules/zod/src/v3/tests/all-errors.test.ts @@ -0,0 +1,157 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const Test = z.object({ + f1: z.number(), + f2: z.string().optional(), + f3: z.string().nullable(), + f4: z.array(z.object({ t: z.union([z.string(), z.boolean()]) })), +}); +type TestFlattenedErrors = z.inferFlattenedErrors; +type TestFormErrors = z.inferFlattenedErrors; + +test("default flattened errors type inference", () => { + type TestTypeErrors = { + formErrors: string[]; + fieldErrors: { [P in keyof z.TypeOf]?: string[] | undefined }; + }; + + util.assertEqual, TestTypeErrors>(true); + util.assertEqual, TestTypeErrors>(false); +}); + +test("custom flattened errors type inference", () => { + type ErrorType = { message: string; code: number }; + type TestTypeErrors = { + formErrors: ErrorType[]; + fieldErrors: { + [P in keyof z.TypeOf]?: ErrorType[] | undefined; + }; + }; + + util.assertEqual, TestTypeErrors>(false); + util.assertEqual, TestTypeErrors>(true); + util.assertEqual, TestTypeErrors>(false); +}); + +test("form errors type inference", () => { + type TestTypeErrors = { + formErrors: string[]; + fieldErrors: { [P in keyof z.TypeOf]?: string[] | undefined }; + }; + + util.assertEqual, TestTypeErrors>(true); +}); + +test(".flatten() type assertion", () => { + const parsed = Test.safeParse({}) as z.SafeParseError; + const validFlattenedErrors: TestFlattenedErrors = parsed.error.flatten(() => ({ message: "", code: 0 })); + // @ts-expect-error should fail assertion between `TestFlattenedErrors` and unmapped `flatten()`. + const invalidFlattenedErrors: TestFlattenedErrors = parsed.error.flatten(); + const validFormErrors: TestFormErrors = parsed.error.flatten(); + // @ts-expect-error should fail assertion between `TestFormErrors` and mapped `flatten()`. + const invalidFormErrors: TestFormErrors = parsed.error.flatten(() => ({ + message: "string", + code: 0, + })); + + [validFlattenedErrors, invalidFlattenedErrors, validFormErrors, invalidFormErrors]; +}); + +test(".formErrors type assertion", () => { + const parsed = Test.safeParse({}) as z.SafeParseError; + const validFormErrors: TestFormErrors = parsed.error.formErrors; + // @ts-expect-error should fail assertion between `TestFlattenedErrors` and `.formErrors`. + const invalidFlattenedErrors: TestFlattenedErrors = parsed.error.formErrors; + + [validFormErrors, invalidFlattenedErrors]; +}); + +test("all errors", () => { + const propertySchema = z.string(); + const schema = z + .object({ + a: propertySchema, + b: propertySchema, + }) + .refine( + (val) => { + return val.a === val.b; + }, + { message: "Must be equal" } + ); + + try { + schema.parse({ + a: "asdf", + b: "qwer", + }); + } catch (error) { + if (error instanceof z.ZodError) { + expect(error.flatten()).toEqual({ + formErrors: ["Must be equal"], + fieldErrors: {}, + }); + } + } + + try { + schema.parse({ + a: null, + b: null, + }); + } catch (_error) { + const error = _error as z.ZodError; + expect(error.flatten()).toEqual({ + formErrors: [], + fieldErrors: { + a: ["Expected string, received null"], + b: ["Expected string, received null"], + }, + }); + + expect(error.flatten((iss) => iss.message.toUpperCase())).toEqual({ + formErrors: [], + fieldErrors: { + a: ["EXPECTED STRING, RECEIVED NULL"], + b: ["EXPECTED STRING, RECEIVED NULL"], + }, + }); + // Test identity + + expect(error.flatten((i: z.ZodIssue) => i)).toEqual({ + formErrors: [], + fieldErrors: { + a: [ + { + code: "invalid_type", + expected: "string", + message: "Expected string, received null", + path: ["a"], + received: "null", + }, + ], + b: [ + { + code: "invalid_type", + expected: "string", + message: "Expected string, received null", + path: ["b"], + received: "null", + }, + ], + }, + }); + // Test mapping + expect(error.flatten((i: z.ZodIssue) => i.message.length)).toEqual({ + formErrors: [], + fieldErrors: { + a: ["Expected string, received null".length], + b: ["Expected string, received null".length], + }, + }); + } +}); diff --git a/node_modules/zod/src/v3/tests/anyunknown.test.ts b/node_modules/zod/src/v3/tests/anyunknown.test.ts new file mode 100644 index 000000000..49d07db2c --- /dev/null +++ b/node_modules/zod/src/v3/tests/anyunknown.test.ts @@ -0,0 +1,28 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("check any inference", () => { + const t1 = z.any(); + t1.optional(); + t1.nullable(); + type t1 = z.infer; + util.assertEqual(true); +}); + +test("check unknown inference", () => { + const t1 = z.unknown(); + t1.optional(); + t1.nullable(); + type t1 = z.infer; + util.assertEqual(true); +}); + +test("check never inference", () => { + const t1 = z.never(); + expect(() => t1.parse(undefined)).toThrow(); + expect(() => t1.parse("asdf")).toThrow(); + expect(() => t1.parse(null)).toThrow(); +}); diff --git a/node_modules/zod/src/v3/tests/array.test.ts b/node_modules/zod/src/v3/tests/array.test.ts new file mode 100644 index 000000000..df5b9d373 --- /dev/null +++ b/node_modules/zod/src/v3/tests/array.test.ts @@ -0,0 +1,71 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const minTwo = z.string().array().min(2); +const maxTwo = z.string().array().max(2); +const justTwo = z.string().array().length(2); +const intNum = z.string().array().nonempty(); +const nonEmptyMax = z.string().array().nonempty().max(2); + +type t1 = z.infer; +util.assertEqual<[string, ...string[]], t1>(true); + +type t2 = z.infer; +util.assertEqual(true); + +test("passing validations", () => { + minTwo.parse(["a", "a"]); + minTwo.parse(["a", "a", "a"]); + maxTwo.parse(["a", "a"]); + maxTwo.parse(["a"]); + justTwo.parse(["a", "a"]); + intNum.parse(["a"]); + nonEmptyMax.parse(["a"]); +}); + +test("failing validations", () => { + expect(() => minTwo.parse(["a"])).toThrow(); + expect(() => maxTwo.parse(["a", "a", "a"])).toThrow(); + expect(() => justTwo.parse(["a"])).toThrow(); + expect(() => justTwo.parse(["a", "a", "a"])).toThrow(); + expect(() => intNum.parse([])).toThrow(); + expect(() => nonEmptyMax.parse([])).toThrow(); + expect(() => nonEmptyMax.parse(["a", "a", "a"])).toThrow(); +}); + +test("parse empty array in nonempty", () => { + expect(() => + z + .array(z.string()) + .nonempty() + .parse([] as any) + ).toThrow(); +}); + +test("get element", () => { + justTwo.element.parse("asdf"); + expect(() => justTwo.element.parse(12)).toThrow(); +}); + +test("continue parsing despite array size error", () => { + const schema = z.object({ + people: z.string().array().min(2), + }); + + const result = schema.safeParse({ + people: [123], + }); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(2); + } +}); + +test("parse should fail given sparse array", () => { + const schema = z.array(z.string()).nonempty().min(1).max(3); + + expect(() => schema.parse(new Array(3))).toThrow(); +}); diff --git a/node_modules/zod/src/v3/tests/async-parsing.test.ts b/node_modules/zod/src/v3/tests/async-parsing.test.ts new file mode 100644 index 000000000..01dbc4f1e --- /dev/null +++ b/node_modules/zod/src/v3/tests/async-parsing.test.ts @@ -0,0 +1,388 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +/// string +const stringSchema = z.string(); + +test("string async parse", async () => { + const goodData = "XXX"; + const badData = 12; + + const goodResult = await stringSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await stringSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// number +const numberSchema = z.number(); +test("number async parse", async () => { + const goodData = 1234.2353; + const badData = "1234"; + + const goodResult = await numberSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await numberSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// bigInt +const bigIntSchema = z.bigint(); +test("bigInt async parse", async () => { + const goodData = BigInt(145); + const badData = 134; + + const goodResult = await bigIntSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await bigIntSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// boolean +const booleanSchema = z.boolean(); +test("boolean async parse", async () => { + const goodData = true; + const badData = 1; + + const goodResult = await booleanSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await booleanSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// date +const dateSchema = z.date(); +test("date async parse", async () => { + const goodData = new Date(); + const badData = new Date().toISOString(); + + const goodResult = await dateSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await dateSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// undefined +const undefinedSchema = z.undefined(); +test("undefined async parse", async () => { + const goodData = undefined; + const badData = "XXX"; + + const goodResult = await undefinedSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(undefined); + + const badResult = await undefinedSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// null +const nullSchema = z.null(); +test("null async parse", async () => { + const goodData = null; + const badData = undefined; + + const goodResult = await nullSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await nullSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// any +const anySchema = z.any(); +test("any async parse", async () => { + const goodData = [{}]; + // const badData = 'XXX'; + + const goodResult = await anySchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + // const badResult = await anySchema.safeParseAsync(badData); + // expect(badResult.success).toBe(false); + // if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// unknown +const unknownSchema = z.unknown(); +test("unknown async parse", async () => { + const goodData = ["asdf", 124, () => {}]; + // const badData = 'XXX'; + + const goodResult = await unknownSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + // const badResult = await unknownSchema.safeParseAsync(badData); + // expect(badResult.success).toBe(false); + // if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// void +const voidSchema = z.void(); +test("void async parse", async () => { + const goodData = undefined; + const badData = 0; + + const goodResult = await voidSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await voidSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// array +const arraySchema = z.array(z.string()); +test("array async parse", async () => { + const goodData = ["XXX"]; + const badData = "XXX"; + + const goodResult = await arraySchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await arraySchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// object +const objectSchema = z.object({ string: z.string() }); +test("object async parse", async () => { + const goodData = { string: "XXX" }; + const badData = { string: 12 }; + + const goodResult = await objectSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await objectSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// union +const unionSchema = z.union([z.string(), z.undefined()]); +test("union async parse", async () => { + const goodData = undefined; + const badData = null; + + const goodResult = await unionSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await unionSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// record +const recordSchema = z.record(z.object({})); +test("record async parse", async () => { + const goodData = { adsf: {}, asdf: {} }; + const badData = [{}]; + + const goodResult = await recordSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await recordSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// function +const functionSchema = z.function(); +test("function async parse", async () => { + const goodData = () => {}; + const badData = "XXX"; + + const goodResult = await functionSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(typeof goodResult.data).toEqual("function"); + + const badResult = await functionSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// literal +const literalSchema = z.literal("asdf"); +test("literal async parse", async () => { + const goodData = "asdf"; + const badData = "asdff"; + + const goodResult = await literalSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await literalSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// enum +const enumSchema = z.enum(["fish", "whale"]); +test("enum async parse", async () => { + const goodData = "whale"; + const badData = "leopard"; + + const goodResult = await enumSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await enumSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// nativeEnum +enum nativeEnumTest { + asdf = "qwer", +} +// @ts-ignore +const nativeEnumSchema = z.nativeEnum(nativeEnumTest); +test("nativeEnum async parse", async () => { + const goodData = nativeEnumTest.asdf; + const badData = "asdf"; + + const goodResult = await nativeEnumSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await nativeEnumSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// promise +const promiseSchema = z.promise(z.number()); +test("promise async parse good", async () => { + const goodData = Promise.resolve(123); + + const goodResult = await promiseSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) { + expect(goodResult.data).toBeInstanceOf(Promise); + const data = await goodResult.data; + expect(data).toEqual(123); + // expect(goodResult.data).resolves.toEqual(124); + // return goodResult.data; + } else { + throw new Error("success should be true"); + } +}); + +test("promise async parse bad", async () => { + const badData = Promise.resolve("XXX"); + const badResult = await promiseSchema.safeParseAsync(badData); + expect(badResult.success).toBe(true); + if (badResult.success) { + await expect(badResult.data).rejects.toBeInstanceOf(z.ZodError); + } else { + throw new Error("success should be true"); + } +}); + +test("async validation non-empty strings", async () => { + const base = z.object({ + hello: z.string().refine((x) => x && x.length > 0), + foo: z.string().refine((x) => x && x.length > 0), + }); + + const testval = { hello: "", foo: "" }; + const result1 = base.safeParse(testval); + const result2 = base.safeParseAsync(testval); + + const r1 = result1; + await result2.then((r2) => { + if (r1.success === false && r2.success === false) expect(r1.error.issues.length).toBe(r2.error.issues.length); // <--- r1 has length 2, r2 has length 1 + }); +}); + +test("async validation multiple errors 1", async () => { + const base = z.object({ + hello: z.string(), + foo: z.number(), + }); + + const testval = { hello: 3, foo: "hello" }; + const result1 = base.safeParse(testval); + const result2 = base.safeParseAsync(testval); + + const r1 = result1; + await result2.then((r2) => { + if (r1.success === false && r2.success === false) expect(r2.error.issues.length).toBe(r1.error.issues.length); + }); +}); + +test("async validation multiple errors 2", async () => { + const base = (is_async?: boolean) => + z.object({ + hello: z.string(), + foo: z.object({ + bar: z.number().refine(is_async ? async () => false : () => false), + }), + }); + + const testval = { hello: 3, foo: { bar: 4 } }; + const result1 = base().safeParse(testval); + const result2 = base(true).safeParseAsync(testval); + + const r1 = result1; + await result2.then((r2) => { + if (r1.success === false && r2.success === false) expect(r2.error.issues.length).toBe(r1.error.issues.length); + }); +}); + +test("ensure early async failure prevents follow-up refinement checks", async () => { + let count = 0; + const base = z.object({ + hello: z.string(), + foo: z + .number() + .refine(async () => { + count++; + return true; + }) + .refine(async () => { + count++; + return true; + }, "Good"), + }); + + const testval = { hello: "bye", foo: 3 }; + const result = await base.safeParseAsync(testval); + if (result.success === false) { + expect(result.error.issues.length).toBe(1); + expect(count).toBe(1); + } + + // await result.then((r) => { + // if (r.success === false) expect(r.error.issues.length).toBe(1); + // expect(count).toBe(2); + // }); +}); diff --git a/node_modules/zod/src/v3/tests/async-refinements.test.ts b/node_modules/zod/src/v3/tests/async-refinements.test.ts new file mode 100644 index 000000000..509475db6 --- /dev/null +++ b/node_modules/zod/src/v3/tests/async-refinements.test.ts @@ -0,0 +1,46 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("parse async test", async () => { + const schema1 = z.string().refine(async (_val) => false); + expect(() => schema1.parse("asdf")).toThrow(); + + const schema2 = z.string().refine((_val) => Promise.resolve(true)); + return await expect(() => schema2.parse("asdf")).toThrow(); +}); + +test("parseAsync async test", async () => { + const schema1 = z.string().refine(async (_val) => true); + await schema1.parseAsync("asdf"); + + const schema2 = z.string().refine(async (_val) => false); + return await expect(schema2.parseAsync("asdf")).rejects.toBeDefined(); + // expect(async () => await schema2.parseAsync('asdf')).toThrow(); +}); + +test("parseAsync async test", async () => { + // expect.assertions(2); + + const schema1 = z.string().refine((_val) => Promise.resolve(true)); + const v1 = await schema1.parseAsync("asdf"); + expect(v1).toEqual("asdf"); + + const schema2 = z.string().refine((_val) => Promise.resolve(false)); + await expect(schema2.parseAsync("asdf")).rejects.toBeDefined(); + + const schema3 = z.string().refine((_val) => Promise.resolve(true)); + await expect(schema3.parseAsync("asdf")).resolves.toEqual("asdf"); + return await expect(schema3.parseAsync("qwer")).resolves.toEqual("qwer"); +}); + +test("parseAsync async with value", async () => { + const schema1 = z.string().refine(async (val) => { + return val.length > 5; + }); + await expect(schema1.parseAsync("asdf")).rejects.toBeDefined(); + + const v = await schema1.parseAsync("asdf123"); + return await expect(v).toEqual("asdf123"); +}); diff --git a/node_modules/zod/src/v3/tests/base.test.ts b/node_modules/zod/src/v3/tests/base.test.ts new file mode 100644 index 000000000..ab743d565 --- /dev/null +++ b/node_modules/zod/src/v3/tests/base.test.ts @@ -0,0 +1,29 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("type guard", () => { + const stringToNumber = z.string().transform((arg) => arg.length); + + const s1 = z.object({ + stringToNumber, + }); + type t1 = z.input; + + const data = { stringToNumber: "asdf" }; + const parsed = s1.safeParse(data); + if (parsed.success) { + util.assertEqual(true); + } +}); + +test("test this binding", () => { + const callback = (predicate: (val: string) => boolean) => { + return predicate("hello"); + }; + + expect(callback((value) => z.string().safeParse(value).success)).toBe(true); // true + expect(callback((value) => z.string().safeParse(value).success)).toBe(true); // true +}); diff --git a/node_modules/zod/src/v3/tests/bigint.test.ts b/node_modules/zod/src/v3/tests/bigint.test.ts new file mode 100644 index 000000000..9692f5700 --- /dev/null +++ b/node_modules/zod/src/v3/tests/bigint.test.ts @@ -0,0 +1,55 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const gtFive = z.bigint().gt(BigInt(5)); +const gteFive = z.bigint().gte(BigInt(5)); +const ltFive = z.bigint().lt(BigInt(5)); +const lteFive = z.bigint().lte(BigInt(5)); +const positive = z.bigint().positive(); +const negative = z.bigint().negative(); +const nonnegative = z.bigint().nonnegative(); +const nonpositive = z.bigint().nonpositive(); +const multipleOfFive = z.bigint().multipleOf(BigInt(5)); + +test("passing validations", () => { + z.bigint().parse(BigInt(1)); + z.bigint().parse(BigInt(0)); + z.bigint().parse(BigInt(-1)); + gtFive.parse(BigInt(6)); + gteFive.parse(BigInt(5)); + gteFive.parse(BigInt(6)); + ltFive.parse(BigInt(4)); + lteFive.parse(BigInt(5)); + lteFive.parse(BigInt(4)); + positive.parse(BigInt(3)); + negative.parse(BigInt(-2)); + nonnegative.parse(BigInt(0)); + nonnegative.parse(BigInt(7)); + nonpositive.parse(BigInt(0)); + nonpositive.parse(BigInt(-12)); + multipleOfFive.parse(BigInt(15)); +}); + +test("failing validations", () => { + expect(() => gtFive.parse(BigInt(5))).toThrow(); + expect(() => gteFive.parse(BigInt(4))).toThrow(); + expect(() => ltFive.parse(BigInt(5))).toThrow(); + expect(() => lteFive.parse(BigInt(6))).toThrow(); + expect(() => positive.parse(BigInt(0))).toThrow(); + expect(() => positive.parse(BigInt(-2))).toThrow(); + expect(() => negative.parse(BigInt(0))).toThrow(); + expect(() => negative.parse(BigInt(3))).toThrow(); + expect(() => nonnegative.parse(BigInt(-1))).toThrow(); + expect(() => nonpositive.parse(BigInt(1))).toThrow(); + expect(() => multipleOfFive.parse(BigInt(13))).toThrow(); +}); + +test("min max getters", () => { + expect(z.bigint().min(BigInt(5)).minValue).toEqual(BigInt(5)); + expect(z.bigint().min(BigInt(5)).min(BigInt(10)).minValue).toEqual(BigInt(10)); + + expect(z.bigint().max(BigInt(5)).maxValue).toEqual(BigInt(5)); + expect(z.bigint().max(BigInt(5)).max(BigInt(1)).maxValue).toEqual(BigInt(1)); +}); diff --git a/node_modules/zod/src/v3/tests/branded.test.ts b/node_modules/zod/src/v3/tests/branded.test.ts new file mode 100644 index 000000000..b19786cf6 --- /dev/null +++ b/node_modules/zod/src/v3/tests/branded.test.ts @@ -0,0 +1,53 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("branded types", () => { + const mySchema = z + .object({ + name: z.string(), + }) + .brand<"superschema">(); + + // simple branding + type MySchema = z.infer; + util.assertEqual(true); + + const doStuff = (arg: MySchema) => arg; + doStuff(mySchema.parse({ name: "hello there" })); + + // inheritance + const extendedSchema = mySchema.brand<"subschema">(); + type ExtendedSchema = z.infer; + util.assertEqual & z.BRAND<"subschema">>(true); + + doStuff(extendedSchema.parse({ name: "hello again" })); + + // number branding + const numberSchema = z.number().brand<42>(); + type NumberSchema = z.infer; + util.assertEqual(true); + + // symbol branding + const MyBrand: unique symbol = Symbol("hello"); + type MyBrand = typeof MyBrand; + const symbolBrand = z.number().brand<"sup">().brand(); + type SymbolBrand = z.infer; + // number & { [z.BRAND]: { sup: true, [MyBrand]: true } } + util.assertEqual & z.BRAND>(true); + + // keeping brands out of input types + const age = z.number().brand<"age">(); + + type Age = z.infer; + type AgeInput = z.input; + + util.assertEqual(false); + util.assertEqual(true); + util.assertEqual, Age>(true); + + // @ts-expect-error + doStuff({ name: "hello there!" }); +}); diff --git a/node_modules/zod/src/v3/tests/catch.test.ts b/node_modules/zod/src/v3/tests/catch.test.ts new file mode 100644 index 000000000..94d12aa2b --- /dev/null +++ b/node_modules/zod/src/v3/tests/catch.test.ts @@ -0,0 +1,220 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import { z } from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("basic catch", () => { + expect(z.string().catch("default").parse(undefined)).toBe("default"); +}); + +test("catch fn does not run when parsing succeeds", () => { + let isCalled = false; + const cb = () => { + isCalled = true; + return "asdf"; + }; + expect(z.string().catch(cb).parse("test")).toBe("test"); + expect(isCalled).toEqual(false); +}); + +test("basic catch async", async () => { + const result = await z.string().catch("default").parseAsync(1243); + expect(result).toBe("default"); +}); + +test("catch replace wrong types", () => { + expect(z.string().catch("default").parse(true)).toBe("default"); + expect(z.string().catch("default").parse(true)).toBe("default"); + expect(z.string().catch("default").parse(15)).toBe("default"); + expect(z.string().catch("default").parse([])).toBe("default"); + expect(z.string().catch("default").parse(new Map())).toBe("default"); + expect(z.string().catch("default").parse(new Set())).toBe("default"); + expect(z.string().catch("default").parse({})).toBe("default"); +}); + +test("catch with transform", () => { + const stringWithDefault = z + .string() + .transform((val) => val.toUpperCase()) + .catch("default"); + expect(stringWithDefault.parse(undefined)).toBe("default"); + expect(stringWithDefault.parse(15)).toBe("default"); + expect(stringWithDefault).toBeInstanceOf(z.ZodCatch); + expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodEffects); + expect(stringWithDefault._def.innerType._def.schema).toBeInstanceOf(z.ZodSchema); + + type inp = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); +}); + +test("catch on existing optional", () => { + const stringWithDefault = z.string().optional().catch("asdf"); + expect(stringWithDefault.parse(undefined)).toBe(undefined); + expect(stringWithDefault.parse(15)).toBe("asdf"); + expect(stringWithDefault).toBeInstanceOf(z.ZodCatch); + expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodOptional); + expect(stringWithDefault._def.innerType._def.innerType).toBeInstanceOf(z.ZodString); + + type inp = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); +}); + +test("optional on catch", () => { + const stringWithDefault = z.string().catch("asdf").optional(); + + type inp = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); +}); + +test("complex chain example", () => { + const complex = z + .string() + .catch("asdf") + .transform((val) => val + "!") + .transform((val) => val.toUpperCase()) + .catch("qwer") + .removeCatch() + .optional() + .catch("asdfasdf"); + + expect(complex.parse("qwer")).toBe("QWER!"); + expect(complex.parse(15)).toBe("ASDF!"); + expect(complex.parse(true)).toBe("ASDF!"); +}); + +test("removeCatch", () => { + const stringWithRemovedDefault = z.string().catch("asdf").removeCatch(); + + type out = z.output; + util.assertEqual(true); +}); + +test("nested", () => { + const inner = z.string().catch("asdf"); + const outer = z.object({ inner }).catch({ + inner: "asdf", + }); + type input = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); + expect(outer.parse(undefined)).toEqual({ inner: "asdf" }); + expect(outer.parse({})).toEqual({ inner: "asdf" }); + expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" }); +}); + +test("chained catch", () => { + const stringWithDefault = z.string().catch("inner").catch("outer"); + const result = stringWithDefault.parse(undefined); + expect(result).toEqual("inner"); + const resultDiff = stringWithDefault.parse(5); + expect(resultDiff).toEqual("inner"); +}); + +test("factory", () => { + z.ZodCatch.create(z.string(), { + catch: "asdf", + }).parse(undefined); +}); + +test("native enum", () => { + enum Fruits { + apple = "apple", + orange = "orange", + } + + const schema = z.object({ + fruit: z.nativeEnum(Fruits).catch(Fruits.apple), + }); + + expect(schema.parse({})).toEqual({ fruit: Fruits.apple }); + expect(schema.parse({ fruit: 15 })).toEqual({ fruit: Fruits.apple }); +}); + +test("enum", () => { + const schema = z.object({ + fruit: z.enum(["apple", "orange"]).catch("apple"), + }); + + expect(schema.parse({})).toEqual({ fruit: "apple" }); + expect(schema.parse({ fruit: true })).toEqual({ fruit: "apple" }); + expect(schema.parse({ fruit: 15 })).toEqual({ fruit: "apple" }); +}); + +test("reported issues with nested usage", () => { + const schema = z.object({ + string: z.string(), + obj: z.object({ + sub: z.object({ + lit: z.literal("a"), + subCatch: z.number().catch(23), + }), + midCatch: z.number().catch(42), + }), + number: z.number().catch(0), + bool: z.boolean(), + }); + + try { + schema.parse({ + string: {}, + obj: { + sub: { + lit: "b", + subCatch: "24", + }, + midCatch: 444, + }, + number: "", + bool: "yes", + }); + } catch (error) { + const issues = (error as z.ZodError).issues; + + expect(issues.length).toEqual(3); + expect(issues[0].message).toMatch("string"); + expect(issues[1].message).toMatch("literal"); + expect(issues[2].message).toMatch("boolean"); + } +}); + +test("catch error", () => { + let catchError: z.ZodError | undefined = undefined; + + const schema = z.object({ + age: z.number(), + name: z.string().catch((ctx) => { + catchError = ctx.error; + + return "John Doe"; + }), + }); + + const result = schema.safeParse({ + age: null, + name: null, + }); + + expect(result.success).toEqual(false); + expect(!result.success && result.error.issues.length).toEqual(1); + expect(!result.success && result.error.issues[0].message).toMatch("number"); + + expect(catchError).toBeInstanceOf(z.ZodError); + expect(catchError !== undefined && (catchError as z.ZodError).issues.length).toEqual(1); + expect(catchError !== undefined && (catchError as z.ZodError).issues[0].message).toMatch("string"); +}); + +test("ctx.input", () => { + const schema = z.string().catch((ctx) => { + return String(ctx.input); + }); + + expect(schema.parse(123)).toEqual("123"); +}); diff --git a/node_modules/zod/src/v3/tests/coerce.test.ts b/node_modules/zod/src/v3/tests/coerce.test.ts new file mode 100644 index 000000000..1f5300416 --- /dev/null +++ b/node_modules/zod/src/v3/tests/coerce.test.ts @@ -0,0 +1,133 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("string coercion", () => { + const schema = z.coerce.string(); + expect(schema.parse("sup")).toEqual("sup"); + expect(schema.parse("")).toEqual(""); + expect(schema.parse(12)).toEqual("12"); + expect(schema.parse(0)).toEqual("0"); + expect(schema.parse(-12)).toEqual("-12"); + expect(schema.parse(3.14)).toEqual("3.14"); + expect(schema.parse(BigInt(15))).toEqual("15"); + expect(schema.parse(Number.NaN)).toEqual("NaN"); + expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual("Infinity"); + expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual("-Infinity"); + expect(schema.parse(true)).toEqual("true"); + expect(schema.parse(false)).toEqual("false"); + expect(schema.parse(null)).toEqual("null"); + expect(schema.parse(undefined)).toEqual("undefined"); + expect(schema.parse({ hello: "world!" })).toEqual("[object Object]"); + expect(schema.parse(["item", "another_item"])).toEqual("item,another_item"); + expect(schema.parse([])).toEqual(""); + expect(schema.parse(new Date("2022-01-01T00:00:00.000Z"))).toEqual(new Date("2022-01-01T00:00:00.000Z").toString()); +}); + +test("number coercion", () => { + const schema = z.coerce.number(); + expect(schema.parse("12")).toEqual(12); + expect(schema.parse("0")).toEqual(0); + expect(schema.parse("-12")).toEqual(-12); + expect(schema.parse("3.14")).toEqual(3.14); + expect(schema.parse("")).toEqual(0); + expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // z.ZodError + expect(schema.parse(12)).toEqual(12); + expect(schema.parse(0)).toEqual(0); + expect(schema.parse(-12)).toEqual(-12); + expect(schema.parse(3.14)).toEqual(3.14); + expect(schema.parse(BigInt(15))).toEqual(15); + expect(() => schema.parse(Number.NaN)).toThrow(); // z.ZodError + expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual(Number.POSITIVE_INFINITY); + expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual(Number.NEGATIVE_INFINITY); + expect(schema.parse(true)).toEqual(1); + expect(schema.parse(false)).toEqual(0); + expect(schema.parse(null)).toEqual(0); + expect(() => schema.parse(undefined)).toThrow(); // z.ZodError + expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError + expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError + expect(schema.parse([])).toEqual(0); + expect(schema.parse(new Date(1670139203496))).toEqual(1670139203496); +}); + +test("boolean coercion", () => { + const schema = z.coerce.boolean(); + expect(schema.parse("true")).toEqual(true); + expect(schema.parse("false")).toEqual(true); + expect(schema.parse("0")).toEqual(true); + expect(schema.parse("1")).toEqual(true); + expect(schema.parse("")).toEqual(false); + expect(schema.parse(1)).toEqual(true); + expect(schema.parse(0)).toEqual(false); + expect(schema.parse(-1)).toEqual(true); + expect(schema.parse(3.14)).toEqual(true); + expect(schema.parse(BigInt(15))).toEqual(true); + expect(schema.parse(Number.NaN)).toEqual(false); + expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual(true); + expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual(true); + expect(schema.parse(true)).toEqual(true); + expect(schema.parse(false)).toEqual(false); + expect(schema.parse(null)).toEqual(false); + expect(schema.parse(undefined)).toEqual(false); + expect(schema.parse({ hello: "world!" })).toEqual(true); + expect(schema.parse(["item", "another_item"])).toEqual(true); + expect(schema.parse([])).toEqual(true); + expect(schema.parse(new Date(1670139203496))).toEqual(true); +}); + +test("bigint coercion", () => { + const schema = z.coerce.bigint(); + expect(schema.parse("5")).toEqual(BigInt(5)); + expect(schema.parse("0")).toEqual(BigInt(0)); + expect(schema.parse("-5")).toEqual(BigInt(-5)); + expect(() => schema.parse("3.14")).toThrow(); // not a z.ZodError! + expect(schema.parse("")).toEqual(BigInt(0)); + expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // not a z.ZodError! + expect(schema.parse(5)).toEqual(BigInt(5)); + expect(schema.parse(0)).toEqual(BigInt(0)); + expect(schema.parse(-5)).toEqual(BigInt(-5)); + expect(() => schema.parse(3.14)).toThrow(); // not a z.ZodError! + expect(schema.parse(BigInt(5))).toEqual(BigInt(5)); + expect(() => schema.parse(Number.NaN)).toThrow(); // not a z.ZodError! + expect(() => schema.parse(Number.POSITIVE_INFINITY)).toThrow(); // not a z.ZodError! + expect(() => schema.parse(Number.NEGATIVE_INFINITY)).toThrow(); // not a z.ZodError! + expect(schema.parse(true)).toEqual(BigInt(1)); + expect(schema.parse(false)).toEqual(BigInt(0)); + expect(() => schema.parse(null)).toThrow(); // not a z.ZodError! + expect(() => schema.parse(undefined)).toThrow(); // not a z.ZodError! + expect(() => schema.parse({ hello: "world!" })).toThrow(); // not a z.ZodError! + expect(() => schema.parse(["item", "another_item"])).toThrow(); // not a z.ZodError! + expect(schema.parse([])).toEqual(BigInt(0)); + expect(schema.parse(new Date(1670139203496))).toEqual(BigInt(1670139203496)); +}); + +test("date coercion", () => { + const schema = z.coerce.date(); + expect(schema.parse(new Date().toDateString())).toBeInstanceOf(Date); + expect(schema.parse(new Date().toISOString())).toBeInstanceOf(Date); + expect(schema.parse(new Date().toUTCString())).toBeInstanceOf(Date); + expect(schema.parse("5")).toBeInstanceOf(Date); + expect(schema.parse("2000-01-01")).toBeInstanceOf(Date); + // expect(schema.parse("0")).toBeInstanceOf(Date); + // expect(schema.parse("-5")).toBeInstanceOf(Date); + // expect(schema.parse("3.14")).toBeInstanceOf(Date); + expect(() => schema.parse("")).toThrow(); // z.ZodError + expect(() => schema.parse("NOT_A_DATE")).toThrow(); // z.ZodError + expect(schema.parse(5)).toBeInstanceOf(Date); + expect(schema.parse(0)).toBeInstanceOf(Date); + expect(schema.parse(-5)).toBeInstanceOf(Date); + expect(schema.parse(3.14)).toBeInstanceOf(Date); + expect(() => schema.parse(BigInt(5))).toThrow(); // not a z.ZodError! + expect(() => schema.parse(Number.NaN)).toThrow(); // z.ZodError + expect(() => schema.parse(Number.POSITIVE_INFINITY)).toThrow(); // z.ZodError + expect(() => schema.parse(Number.NEGATIVE_INFINITY)).toThrow(); // z.ZodError + expect(schema.parse(true)).toBeInstanceOf(Date); + expect(schema.parse(false)).toBeInstanceOf(Date); + expect(schema.parse(null)).toBeInstanceOf(Date); + expect(() => schema.parse(undefined)).toThrow(); // z.ZodError + expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError + expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError + expect(() => schema.parse([])).toThrow(); // z.ZodError + expect(schema.parse(new Date())).toBeInstanceOf(Date); +}); diff --git a/node_modules/zod/src/v3/tests/complex.test.ts b/node_modules/zod/src/v3/tests/complex.test.ts new file mode 100644 index 000000000..7807b2b11 --- /dev/null +++ b/node_modules/zod/src/v3/tests/complex.test.ts @@ -0,0 +1,56 @@ +import { test } from "vitest"; +import * as z from "zod/v3"; + +const crazySchema = z.object({ + tuple: z.tuple([ + z.string().nullable().optional(), + z.number().nullable().optional(), + z.boolean().nullable().optional(), + z.null().nullable().optional(), + z.undefined().nullable().optional(), + z.literal("1234").nullable().optional(), + ]), + merged: z + .object({ + k1: z.string().optional(), + }) + .merge(z.object({ k1: z.string().nullable(), k2: z.number() })), + union: z.array(z.union([z.literal("asdf"), z.literal(12)])).nonempty(), + array: z.array(z.number()), + // sumTransformer: z.transformer(z.array(z.number()), z.number(), (arg) => { + // return arg.reduce((a, b) => a + b, 0); + // }), + sumMinLength: z.array(z.number()).refine((arg) => arg.length > 5), + intersection: z.intersection(z.object({ p1: z.string().optional() }), z.object({ p1: z.number().optional() })), + enum: z.intersection(z.enum(["zero", "one"]), z.enum(["one", "two"])), + nonstrict: z.object({ points: z.number() }).nonstrict(), + numProm: z.promise(z.number()), + lenfun: z.function(z.tuple([z.string()]), z.boolean()), +}); + +// const asyncCrazySchema = crazySchema.extend({ +// // async_transform: z.transformer( +// // z.array(z.number()), +// // z.number(), +// // async (arg) => { +// // return arg.reduce((a, b) => a + b, 0); +// // } +// // ), +// async_refine: z.array(z.number()).refine(async (arg) => arg.length > 5), +// }); + +test("parse", () => { + crazySchema.parse({ + tuple: ["asdf", 1234, true, null, undefined, "1234"], + merged: { k1: "asdf", k2: 12 }, + union: ["asdf", 12, "asdf", 12, "asdf", 12], + array: [12, 15, 16], + // sumTransformer: [12, 15, 16], + sumMinLength: [12, 15, 16, 98, 24, 63], + intersection: {}, + enum: "one", + nonstrict: { points: 1234 }, + numProm: Promise.resolve(12), + lenfun: (x: string) => x.length, + }); +}); diff --git a/node_modules/zod/src/v3/tests/custom.test.ts b/node_modules/zod/src/v3/tests/custom.test.ts new file mode 100644 index 000000000..b24b6762d --- /dev/null +++ b/node_modules/zod/src/v3/tests/custom.test.ts @@ -0,0 +1,31 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("passing validations", () => { + const example1 = z.custom((x) => typeof x === "number"); + example1.parse(1234); + expect(() => example1.parse({})).toThrow(); +}); + +test("string params", () => { + const example1 = z.custom((x) => typeof x !== "number", "customerr"); + const result = example1.safeParse(1234); + expect(result.success).toEqual(false); + // @ts-ignore + expect(JSON.stringify(result.error).includes("customerr")).toEqual(true); +}); + +test("async validations", async () => { + const example1 = z.custom(async (x) => { + return typeof x === "number"; + }); + const r1 = await example1.safeParseAsync(1234); + expect(r1.success).toEqual(true); + expect(r1.data).toEqual(1234); + + const r2 = await example1.safeParseAsync("asdf"); + expect(r2.success).toEqual(false); + expect(r2.error!.issues.length).toEqual(1); +}); diff --git a/node_modules/zod/src/v3/tests/date.test.ts b/node_modules/zod/src/v3/tests/date.test.ts new file mode 100644 index 000000000..c86dc84fc --- /dev/null +++ b/node_modules/zod/src/v3/tests/date.test.ts @@ -0,0 +1,32 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const beforeBenchmarkDate = new Date(2022, 10, 4); +const benchmarkDate = new Date(2022, 10, 5); +const afterBenchmarkDate = new Date(2022, 10, 6); + +const minCheck = z.date().min(benchmarkDate); +const maxCheck = z.date().max(benchmarkDate); + +test("passing validations", () => { + minCheck.parse(benchmarkDate); + minCheck.parse(afterBenchmarkDate); + + maxCheck.parse(benchmarkDate); + maxCheck.parse(beforeBenchmarkDate); +}); + +test("failing validations", () => { + expect(() => minCheck.parse(beforeBenchmarkDate)).toThrow(); + expect(() => maxCheck.parse(afterBenchmarkDate)).toThrow(); +}); + +test("min max getters", () => { + expect(minCheck.minDate).toEqual(benchmarkDate); + expect(minCheck.min(afterBenchmarkDate).minDate).toEqual(afterBenchmarkDate); + + expect(maxCheck.maxDate).toEqual(benchmarkDate); + expect(maxCheck.max(beforeBenchmarkDate).maxDate).toEqual(beforeBenchmarkDate); +}); diff --git a/node_modules/zod/src/v3/tests/deepmasking.test.ts b/node_modules/zod/src/v3/tests/deepmasking.test.ts new file mode 100644 index 000000000..d707e79a0 --- /dev/null +++ b/node_modules/zod/src/v3/tests/deepmasking.test.ts @@ -0,0 +1,186 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +import * as z from "zod/v3"; + +test("test", () => { + z; +}); + +// const fish = z.object({ +// name: z.string(), +// props: z.object({ +// color: z.string(), +// numScales: z.number(), +// }), +// }); + +// const nonStrict = z +// .object({ +// name: z.string(), +// color: z.string(), +// }) +// .nonstrict(); + +// test('object pick type', () => { +// const modNonStrictFish = nonStrict.omit({ name: true }); +// modNonStrictFish.parse({ color: 'asdf' }); + +// const bad1 = () => fish.pick({ props: { unknown: true } } as any); +// const bad2 = () => fish.omit({ name: true, props: { unknown: true } } as any); + +// expect(bad1).toThrow(); +// expect(bad2).toThrow(); +// }); + +// test('f1', () => { +// const f1 = fish.pick(true); +// f1.parse({ name: 'a', props: { color: 'b', numScales: 3 } }); +// }); +// test('f2', () => { +// const f2 = fish.pick({ props: true }); +// f2.parse({ props: { color: 'asdf', numScales: 1 } }); +// const badcheck2 = () => f2.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any); +// expect(badcheck2).toThrow(); +// }); +// test('f3', () => { +// const f3 = fish.pick({ props: { color: true } }); +// f3.parse({ props: { color: 'b' } }); +// const badcheck3 = () => f3.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any); +// expect(badcheck3).toThrow(); +// }); +// test('f4', () => { +// const badcheck4 = () => fish.pick({ props: { color: true, unknown: true } }); +// expect(badcheck4).toThrow(); +// }); +// test('f6', () => { +// const f6 = fish.omit({ props: true }); +// const badcheck6 = () => f6.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any); +// f6.parse({ name: 'adsf' }); +// expect(badcheck6).toThrow(); +// }); +// test('f7', () => { +// const f7 = fish.omit({ props: { color: true } }); +// f7.parse({ name: 'a', props: { numScales: 3 } }); +// const badcheck7 = () => f7.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any); +// expect(badcheck7).toThrow(); +// }); +// test('f8', () => { +// const badcheck8 = () => fish.omit({ props: { color: true, unknown: true } }); +// expect(badcheck8).toThrow(); +// }); +// test('f9', () => { +// const f9 = nonStrict.pick(true); +// f9.parse({ name: 'a', color: 'asdf' }); +// }); +// test('f10', () => { +// const f10 = nonStrict.pick({ name: true }); +// f10.parse({ name: 'a' }); +// const val = f10.parse({ name: 'a', color: 'b' }); +// expect(val).toEqual({ name: 'a' }); +// }); +// test('f12', () => { +// const badfcheck12 = () => nonStrict.omit({ color: true, asdf: true }); +// expect(badfcheck12).toThrow(); +// }); + +// test('array masking', () => { +// const fishArray = z.array(fish); +// const modFishArray = fishArray.pick({ +// name: true, +// props: { +// numScales: true, +// }, +// }); + +// modFishArray.parse([{ name: 'fish', props: { numScales: 12 } }]); +// const bad1 = () => modFishArray.parse([{ name: 'fish', props: { numScales: 12, color: 'asdf' } }] as any); +// expect(bad1).toThrow(); +// }); + +// test('array masking', () => { +// const fishArray = z.array(fish); +// const fail = () => +// fishArray.pick({ +// name: true, +// props: { +// whatever: true, +// }, +// } as any); +// expect(fail).toThrow(); +// }); + +// test('array masking', () => { +// const fishArray = z.array(fish); +// const fail = () => +// fishArray.omit({ +// whateve: true, +// } as any); +// expect(fail).toThrow(); +// }); + +// test('array masking', () => { +// const fishArray = z.array(fish); +// const modFishList = fishArray.omit({ +// name: true, +// props: { +// color: true, +// }, +// }); + +// modFishList.parse([{ props: { numScales: 12 } }]); +// const fail = () => modFishList.parse([{ name: 'hello', props: { numScales: 12 } }] as any); +// expect(fail).toThrow(); +// }); + +// test('primitive array masking', () => { +// const fishArray = z.array(z.number()); +// const fail = () => fishArray.pick({} as any); +// expect(fail).toThrow(); +// }); + +// test('other array masking', () => { +// const fishArray = z.array(z.array(z.number())); +// const fail = () => fishArray.pick({} as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #1', () => { +// const fail = () => fish.pick(1 as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #2', () => { +// const fail = () => fish.pick([] as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #3', () => { +// const fail = () => fish.pick(false as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #4', () => { +// const fail = () => fish.pick('asdf' as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #5', () => { +// const fail = () => fish.omit(1 as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #6', () => { +// const fail = () => fish.omit([] as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #7', () => { +// const fail = () => fish.omit(false as any); +// expect(fail).toThrow(); +// }); + +// test('invalid mask #8', () => { +// const fail = () => fish.omit('asdf' as any); +// expect(fail).toThrow(); +// }); diff --git a/node_modules/zod/src/v3/tests/default.test.ts b/node_modules/zod/src/v3/tests/default.test.ts new file mode 100644 index 000000000..29e007c93 --- /dev/null +++ b/node_modules/zod/src/v3/tests/default.test.ts @@ -0,0 +1,112 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import { z } from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("basic defaults", () => { + expect(z.string().default("default").parse(undefined)).toBe("default"); +}); + +test("default with transform", () => { + const stringWithDefault = z + .string() + .transform((val) => val.toUpperCase()) + .default("default"); + expect(stringWithDefault.parse(undefined)).toBe("DEFAULT"); + expect(stringWithDefault).toBeInstanceOf(z.ZodDefault); + expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodEffects); + expect(stringWithDefault._def.innerType._def.schema).toBeInstanceOf(z.ZodSchema); + + type inp = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); +}); + +test("default on existing optional", () => { + const stringWithDefault = z.string().optional().default("asdf"); + expect(stringWithDefault.parse(undefined)).toBe("asdf"); + expect(stringWithDefault).toBeInstanceOf(z.ZodDefault); + expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodOptional); + expect(stringWithDefault._def.innerType._def.innerType).toBeInstanceOf(z.ZodString); + + type inp = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); +}); + +test("optional on default", () => { + const stringWithDefault = z.string().default("asdf").optional(); + + type inp = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); +}); + +test("complex chain example", () => { + const complex = z + .string() + .default("asdf") + .transform((val) => val.toUpperCase()) + .default("qwer") + .removeDefault() + .optional() + .default("asdfasdf"); + + expect(complex.parse(undefined)).toBe("ASDFASDF"); +}); + +test("removeDefault", () => { + const stringWithRemovedDefault = z.string().default("asdf").removeDefault(); + + type out = z.output; + util.assertEqual(true); +}); + +test("nested", () => { + const inner = z.string().default("asdf"); + const outer = z.object({ inner }).default({ + inner: undefined, + }); + type input = z.input; + util.assertEqual(true); + type out = z.output; + util.assertEqual(true); + expect(outer.parse(undefined)).toEqual({ inner: "asdf" }); + expect(outer.parse({})).toEqual({ inner: "asdf" }); + expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" }); +}); + +test("chained defaults", () => { + const stringWithDefault = z.string().default("inner").default("outer"); + const result = stringWithDefault.parse(undefined); + expect(result).toEqual("outer"); +}); + +test("factory", () => { + expect(z.ZodDefault.create(z.string(), { default: "asdf" }).parse(undefined)).toEqual("asdf"); +}); + +test("native enum", () => { + enum Fruits { + apple = "apple", + orange = "orange", + } + + const schema = z.object({ + fruit: z.nativeEnum(Fruits).default(Fruits.apple), + }); + + expect(schema.parse({})).toEqual({ fruit: Fruits.apple }); +}); + +test("enum", () => { + const schema = z.object({ + fruit: z.enum(["apple", "orange"]).default("apple"), + }); + + expect(schema.parse({})).toEqual({ fruit: "apple" }); +}); diff --git a/node_modules/zod/src/v3/tests/description.test.ts b/node_modules/zod/src/v3/tests/description.test.ts new file mode 100644 index 000000000..1edaa1cc2 --- /dev/null +++ b/node_modules/zod/src/v3/tests/description.test.ts @@ -0,0 +1,33 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const description = "a description"; + +test("passing `description` to schema should add a description", () => { + expect(z.string({ description }).description).toEqual(description); + expect(z.number({ description }).description).toEqual(description); + expect(z.boolean({ description }).description).toEqual(description); +}); + +test("`.describe` should add a description", () => { + expect(z.string().describe(description).description).toEqual(description); + expect(z.number().describe(description).description).toEqual(description); + expect(z.boolean().describe(description).description).toEqual(description); +}); + +test("description should carry over to chained schemas", () => { + const schema = z.string({ description }); + expect(schema.description).toEqual(description); + expect(schema.optional().description).toEqual(description); + expect(schema.optional().nullable().default("default").description).toEqual(description); +}); + +test("description should not carry over to chained array schema", () => { + const schema = z.string().describe(description); + + expect(schema.description).toEqual(description); + expect(schema.array().description).toEqual(undefined); + expect(z.array(schema).description).toEqual(undefined); +}); diff --git a/node_modules/zod/src/v3/tests/discriminated-unions.test.ts b/node_modules/zod/src/v3/tests/discriminated-unions.test.ts new file mode 100644 index 000000000..7fb5cfefe --- /dev/null +++ b/node_modules/zod/src/v3/tests/discriminated-unions.test.ts @@ -0,0 +1,315 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("valid", () => { + expect( + z + .discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]) + .parse({ type: "a", a: "abc" }) + ).toEqual({ type: "a", a: "abc" }); +}); + +test("valid - discriminator value of various primitive types", () => { + const schema = z.discriminatedUnion("type", [ + z.object({ type: z.literal("1"), val: z.literal(1) }), + z.object({ type: z.literal(1), val: z.literal(2) }), + z.object({ type: z.literal(BigInt(1)), val: z.literal(3) }), + z.object({ type: z.literal("true"), val: z.literal(4) }), + z.object({ type: z.literal(true), val: z.literal(5) }), + z.object({ type: z.literal("null"), val: z.literal(6) }), + z.object({ type: z.literal(null), val: z.literal(7) }), + z.object({ type: z.literal("undefined"), val: z.literal(8) }), + z.object({ type: z.literal(undefined), val: z.literal(9) }), + z.object({ type: z.literal("transform"), val: z.literal(10) }), + z.object({ type: z.literal("refine"), val: z.literal(11) }), + z.object({ type: z.literal("superRefine"), val: z.literal(12) }), + ]); + + expect(schema.parse({ type: "1", val: 1 })).toEqual({ type: "1", val: 1 }); + expect(schema.parse({ type: 1, val: 2 })).toEqual({ type: 1, val: 2 }); + expect(schema.parse({ type: BigInt(1), val: 3 })).toEqual({ + type: BigInt(1), + val: 3, + }); + expect(schema.parse({ type: "true", val: 4 })).toEqual({ + type: "true", + val: 4, + }); + expect(schema.parse({ type: true, val: 5 })).toEqual({ + type: true, + val: 5, + }); + expect(schema.parse({ type: "null", val: 6 })).toEqual({ + type: "null", + val: 6, + }); + expect(schema.parse({ type: null, val: 7 })).toEqual({ + type: null, + val: 7, + }); + expect(schema.parse({ type: "undefined", val: 8 })).toEqual({ + type: "undefined", + val: 8, + }); + expect(schema.parse({ type: undefined, val: 9 })).toEqual({ + type: undefined, + val: 9, + }); +}); + +test("invalid - null", () => { + try { + z.discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]).parse(null); + throw new Error(); + } catch (e: any) { + expect(JSON.parse(e.message)).toEqual([ + { + code: z.ZodIssueCode.invalid_type, + expected: z.ZodParsedType.object, + message: "Expected object, received null", + received: z.ZodParsedType.null, + path: [], + }, + ]); + } +}); + +test("invalid discriminator value", () => { + try { + z.discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]).parse({ type: "x", a: "abc" }); + throw new Error(); + } catch (e: any) { + expect(JSON.parse(e.message)).toEqual([ + { + code: z.ZodIssueCode.invalid_union_discriminator, + options: ["a", "b"], + message: "Invalid discriminator value. Expected 'a' | 'b'", + path: ["type"], + }, + ]); + } +}); + +test("valid discriminator value, invalid data", () => { + try { + z.discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]).parse({ type: "a", b: "abc" }); + throw new Error(); + } catch (e: any) { + expect(JSON.parse(e.message)).toEqual([ + { + code: z.ZodIssueCode.invalid_type, + expected: z.ZodParsedType.string, + message: "Required", + path: ["a"], + received: z.ZodParsedType.undefined, + }, + ]); + } +}); + +test("wrong schema - missing discriminator", () => { + try { + z.discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ b: z.string() }) as any, + ]); + throw new Error(); + } catch (e: any) { + expect(e.message.includes("could not be extracted")).toBe(true); + } +}); + +test("wrong schema - duplicate discriminator values", () => { + try { + z.discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("a"), b: z.string() }), + ]); + throw new Error(); + } catch (e: any) { + expect(e.message.includes("has duplicate value")).toEqual(true); + } +}); + +test("async - valid", async () => { + expect( + await z + .discriminatedUnion("type", [ + z.object({ + type: z.literal("a"), + a: z + .string() + .refine(async () => true) + .transform(async (val) => Number(val)), + }), + z.object({ + type: z.literal("b"), + b: z.string(), + }), + ]) + .parseAsync({ type: "a", a: "1" }) + ).toEqual({ type: "a", a: 1 }); +}); + +test("async - invalid", async () => { + try { + await z + .discriminatedUnion("type", [ + z.object({ + type: z.literal("a"), + a: z + .string() + .refine(async () => true) + .transform(async (val) => val), + }), + z.object({ + type: z.literal("b"), + b: z.string(), + }), + ]) + .parseAsync({ type: "a", a: 1 }); + throw new Error(); + } catch (e: any) { + expect(JSON.parse(e.message)).toEqual([ + { + code: "invalid_type", + expected: "string", + received: "number", + path: ["a"], + message: "Expected string, received number", + }, + ]); + } +}); + +test("valid - literals with .default or .preprocess", () => { + const schema = z.discriminatedUnion("type", [ + z.object({ + type: z.literal("foo").default("foo"), + a: z.string(), + }), + z.object({ + type: z.literal("custom"), + method: z.string(), + }), + z.object({ + type: z.preprocess((val) => String(val), z.literal("bar")), + c: z.string(), + }), + ]); + expect(schema.parse({ type: "foo", a: "foo" })).toEqual({ + type: "foo", + a: "foo", + }); +}); + +test("enum and nativeEnum", () => { + enum MyEnum { + d = 0, + e = "e", + } + + const schema = z.discriminatedUnion("key", [ + z.object({ + key: z.literal("a"), + // Add other properties specific to this option + }), + z.object({ + key: z.enum(["b", "c"]), + // Add other properties specific to this option + }), + z.object({ + key: z.nativeEnum(MyEnum), + // Add other properties specific to this option + }), + ]); + + // type schema = z.infer; + + schema.parse({ key: "a" }); + schema.parse({ key: "b" }); + schema.parse({ key: "c" }); + schema.parse({ key: MyEnum.d }); + schema.parse({ key: MyEnum.e }); + schema.parse({ key: "e" }); +}); + +test("branded", () => { + const schema = z.discriminatedUnion("key", [ + z.object({ + key: z.literal("a"), + // Add other properties specific to this option + }), + z.object({ + key: z.literal("b").brand("asdfaf"), + // Add other properties specific to this option + }), + ]); + + // type schema = z.infer; + + schema.parse({ key: "a" }); + schema.parse({ key: "b" }); + expect(() => { + schema.parse({ key: "c" }); + }).toThrow(); +}); + +test("optional and nullable", () => { + const schema = z.discriminatedUnion("key", [ + z.object({ + key: z.literal("a").optional(), + a: z.literal(true), + }), + z.object({ + key: z.literal("b").nullable(), + b: z.literal(true), + // Add other properties specific to this option + }), + ]); + + type schema = z.infer; + z.util.assertEqual(true); + + schema.parse({ key: "a", a: true }); + schema.parse({ key: undefined, a: true }); + schema.parse({ key: "b", b: true }); + schema.parse({ key: null, b: true }); + expect(() => { + schema.parse({ key: null, a: true }); + }).toThrow(); + expect(() => { + schema.parse({ key: "b", a: true }); + }).toThrow(); + + const value = schema.parse({ key: null, b: true }); + + if (!("key" in value)) value.a; + if (value.key === undefined) value.a; + if (value.key === "a") value.a; + if (value.key === "b") value.b; + if (value.key === null) value.b; +}); + +test("readonly array of options", () => { + const options = [ + z.object({ type: z.literal("x"), val: z.literal(1) }), + z.object({ type: z.literal("y"), val: z.literal(2) }), + ] as const; + + expect(z.discriminatedUnion("type", options).parse({ type: "x", val: 1 })).toEqual({ type: "x", val: 1 }); +}); diff --git a/node_modules/zod/src/v3/tests/enum.test.ts b/node_modules/zod/src/v3/tests/enum.test.ts new file mode 100644 index 000000000..53f4a3e84 --- /dev/null +++ b/node_modules/zod/src/v3/tests/enum.test.ts @@ -0,0 +1,80 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("create enum", () => { + const MyEnum = z.enum(["Red", "Green", "Blue"]); + expect(MyEnum.Values.Red).toEqual("Red"); + expect(MyEnum.Enum.Red).toEqual("Red"); + expect(MyEnum.enum.Red).toEqual("Red"); +}); + +test("infer enum", () => { + const MyEnum = z.enum(["Red", "Green", "Blue"]); + type MyEnum = z.infer; + util.assertEqual(true); +}); + +test("get options", () => { + expect(z.enum(["tuna", "trout"]).options).toEqual(["tuna", "trout"]); +}); + +test("readonly enum", () => { + const HTTP_SUCCESS = ["200", "201"] as const; + const arg = z.enum(HTTP_SUCCESS); + type arg = z.infer; + util.assertEqual(true); + + arg.parse("201"); + expect(() => arg.parse("202")).toThrow(); +}); + +test("error params", () => { + const result = z.enum(["test"], { required_error: "REQUIRED" }).safeParse(undefined); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("REQUIRED"); + } +}); + +test("extract/exclude", () => { + const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const; + const FoodEnum = z.enum(foods); + const ItalianEnum = FoodEnum.extract(["Pasta", "Pizza"]); + const UnhealthyEnum = FoodEnum.exclude(["Salad"]); + const EmptyFoodEnum = FoodEnum.exclude(foods); + + util.assertEqual, "Pasta" | "Pizza">(true); + util.assertEqual, "Pasta" | "Pizza" | "Tacos" | "Burgers">(true); + // @ts-expect-error TS2344 + util.assertEqual>(true); + util.assertEqual, never>(true); +}); + +test("error map in extract/exclude", () => { + const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const; + const FoodEnum = z.enum(foods, { + errorMap: () => ({ message: "This is not food!" }), + }); + const ItalianEnum = FoodEnum.extract(["Pasta", "Pizza"]); + const foodsError = FoodEnum.safeParse("Cucumbers"); + const italianError = ItalianEnum.safeParse("Tacos"); + if (!foodsError.success && !italianError.success) { + expect(foodsError.error.issues[0].message).toEqual(italianError.error.issues[0].message); + } + + const UnhealthyEnum = FoodEnum.exclude(["Salad"], { + errorMap: () => ({ message: "This is not healthy food!" }), + }); + const unhealthyError = UnhealthyEnum.safeParse("Salad"); + if (!unhealthyError.success) { + expect(unhealthyError.error.issues[0].message).toEqual("This is not healthy food!"); + } +}); + +test("readonly in ZodEnumDef", () => { + let _t!: z.ZodEnumDef; + _t; +}); diff --git a/node_modules/zod/src/v3/tests/error.test.ts b/node_modules/zod/src/v3/tests/error.test.ts new file mode 100644 index 000000000..5caaa6d81 --- /dev/null +++ b/node_modules/zod/src/v3/tests/error.test.ts @@ -0,0 +1,551 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { ZodError, ZodIssueCode } from "../ZodError.js"; +import { ZodParsedType } from "../helpers/util.js"; + +test("error creation", () => { + const err1 = ZodError.create([]); + err1.addIssue({ + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ZodParsedType.string, + path: [], + message: "", + fatal: true, + }); + err1.isEmpty; + + const err2 = ZodError.create(err1.issues); + const err3 = new ZodError([]); + err3.addIssues(err1.issues); + err3.addIssue(err1.issues[0]); + err1.message; + err2.message; + err3.message; +}); + +const errorMap: z.ZodErrorMap = (error, ctx) => { + if (error.code === ZodIssueCode.invalid_type) { + if (error.expected === "string") { + return { message: "bad type!" }; + } + } + if (error.code === ZodIssueCode.custom) { + return { message: `less-than-${error.params?.minimum}` }; + } + return { message: ctx.defaultError }; +}; + +test("type error with custom error map", () => { + try { + z.string().parse(234, { errorMap }); + } catch (err) { + const zerr: z.ZodError = err as any; + + expect(zerr.issues[0].code).toEqual(z.ZodIssueCode.invalid_type); + expect(zerr.issues[0].message).toEqual(`bad type!`); + } +}); + +test("refinement fail with params", () => { + try { + z.number() + .refine((val) => val >= 3, { + params: { minimum: 3 }, + }) + .parse(2, { errorMap }); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues[0].code).toEqual(z.ZodIssueCode.custom); + expect(zerr.issues[0].message).toEqual(`less-than-3`); + } +}); + +test("custom error with custom errormap", () => { + try { + z.string() + .refine((val) => val.length > 12, { + params: { minimum: 13 }, + message: "override", + }) + .parse("asdf", { errorMap }); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues[0].message).toEqual("override"); + } +}); + +test("default error message", () => { + try { + z.number() + .refine((x) => x > 3) + .parse(2); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual("Invalid input"); + } +}); + +test("override error in refine", () => { + try { + z.number() + .refine((x) => x > 3, "override") + .parse(2); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual("override"); + } +}); + +test("override error in refinement", () => { + try { + z.number() + .refine((x) => x > 3, { + message: "override", + }) + .parse(2); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual("override"); + } +}); + +test("array minimum", () => { + try { + z.array(z.string()).min(3, "tooshort").parse(["asdf", "qwer"]); + } catch (err) { + const zerr: ZodError = err as any; + expect(zerr.issues[0].code).toEqual(ZodIssueCode.too_small); + expect(zerr.issues[0].message).toEqual("tooshort"); + } + try { + z.array(z.string()).min(3).parse(["asdf", "qwer"]); + } catch (err) { + const zerr: ZodError = err as any; + expect(zerr.issues[0].code).toEqual(ZodIssueCode.too_small); + expect(zerr.issues[0].message).toEqual(`Array must contain at least 3 element(s)`); + } +}); + +// implement test for semi-smart union logic that checks for type error on either left or right +// test("union smart errors", () => { +// // expect.assertions(2); + +// const p1 = z +// .union([z.string(), z.number().refine((x) => x > 0)]) +// .safeParse(-3.2); + +// if (p1.success === true) throw new Error(); +// expect(p1.success).toBe(false); +// expect(p1.error.issues[0].code).toEqual(ZodIssueCode.custom); + +// const p2 = z.union([z.string(), z.number()]).safeParse(false); +// // .catch(err => expect(err.issues[0].code).toEqual(ZodIssueCode.invalid_union)); +// if (p2.success === true) throw new Error(); +// expect(p2.success).toBe(false); +// expect(p2.error.issues[0].code).toEqual(ZodIssueCode.invalid_union); +// }); + +test("custom path in custom error map", () => { + const schema = z.object({ + items: z.array(z.string()).refine((data) => data.length > 3, { + path: ["items-too-few"], + }), + }); + + const errorMap: z.ZodErrorMap = (error) => { + expect(error.path.length).toBe(2); + return { message: "doesnt matter" }; + }; + const result = schema.safeParse({ items: ["first"] }, { errorMap }); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].path).toEqual(["items", "items-too-few"]); + } +}); + +test("error metadata from value", () => { + const dynamicRefine = z.string().refine( + (val) => val === val.toUpperCase(), + (val) => ({ params: { val } }) + ); + + const result = dynamicRefine.safeParse("asdf"); + expect(result.success).toEqual(false); + if (!result.success) { + const sub = result.error.issues[0]; + expect(result.error.issues[0].code).toEqual("custom"); + if (sub.code === "custom") { + expect(sub.params!.val).toEqual("asdf"); + } + } +}); + +// test("don't call refine after validation failed", () => { +// const asdf = z +// .union([ +// z.number(), +// z.string().transform(z.number(), (val) => { +// return parseFloat(val); +// }), +// ]) +// .refine((v) => v >= 1); + +// expect(() => asdf.safeParse("foo")).not.toThrow(); +// }); + +test("root level formatting", () => { + const schema = z.string().email(); + const result = schema.safeParse("asdfsdf"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.format()._errors).toEqual(["Invalid email"]); + } +}); + +test("custom path", () => { + const schema = z + .object({ + password: z.string(), + confirm: z.string(), + }) + .refine((val) => val.confirm === val.password, { path: ["confirm"] }); + + const result = schema.safeParse({ + password: "peanuts", + confirm: "qeanuts", + }); + + expect(result.success).toEqual(false); + if (!result.success) { + // nested errors + const error = result.error.format(); + expect(error._errors).toEqual([]); + expect(error.password?._errors).toEqual(undefined); + expect(error.confirm?._errors).toEqual(["Invalid input"]); + } +}); + +test("custom path", () => { + const schema = z + .object({ + password: z.string().min(6), + confirm: z.string().min(6), + }) + .refine((val) => val.confirm === val.password); + + const result = schema.safeParse({ + password: "qwer", + confirm: "asdf", + }); + + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(3); + } +}); + +const schema = z.object({ + inner: z.object({ + name: z + .string() + .refine((val) => val.length > 5) + .array() + .refine((val) => val.length <= 1), + }), +}); + +test("no abort early on refinements", () => { + const invalidItem = { + inner: { name: ["aasd", "asdfasdfasfd"] }, + }; + + const result1 = schema.safeParse(invalidItem); + expect(result1.success).toEqual(false); + if (!result1.success) { + expect(result1.error.issues.length).toEqual(2); + } +}); +test("formatting", () => { + const invalidItem = { + inner: { name: ["aasd", "asdfasdfasfd"] }, + }; + const invalidArray = { + inner: { name: ["asdfasdf", "asdfasdfasfd"] }, + }; + const result1 = schema.safeParse(invalidItem); + const result2 = schema.safeParse(invalidArray); + + expect(result1.success).toEqual(false); + expect(result2.success).toEqual(false); + if (!result1.success) { + const error = result1.error.format(); + + expect(error._errors).toEqual([]); + expect(error.inner?._errors).toEqual([]); + // expect(error.inner?.name?._errors).toEqual(["Invalid input"]); + // expect(error.inner?.name?.[0]._errors).toEqual(["Invalid input"]); + expect(error.inner?.name?.[1]).toEqual(undefined); + } + if (!result2.success) { + type FormattedError = z.inferFormattedError; + const error: FormattedError = result2.error.format(); + expect(error._errors).toEqual([]); + expect(error.inner?._errors).toEqual([]); + expect(error.inner?.name?._errors).toEqual(["Invalid input"]); + expect(error.inner?.name?.[0]).toEqual(undefined); + expect(error.inner?.name?.[1]).toEqual(undefined); + expect(error.inner?.name?.[2]).toEqual(undefined); + } + + // test custom mapper + if (!result2.success) { + type FormattedError = z.inferFormattedError; + const error: FormattedError = result2.error.format(() => 5); + expect(error._errors).toEqual([]); + expect(error.inner?._errors).toEqual([]); + expect(error.inner?.name?._errors).toEqual([5]); + } +}); + +test("formatting with nullable and optional fields", () => { + const nameSchema = z.string().refine((val) => val.length > 5); + const schema = z.object({ + nullableObject: z.object({ name: nameSchema }).nullable(), + nullableArray: z.array(nameSchema).nullable(), + nullableTuple: z.tuple([nameSchema, nameSchema, z.number()]).nullable(), + optionalObject: z.object({ name: nameSchema }).optional(), + optionalArray: z.array(nameSchema).optional(), + optionalTuple: z.tuple([nameSchema, nameSchema, z.number()]).optional(), + }); + const invalidItem = { + nullableObject: { name: "abcd" }, + nullableArray: ["abcd"], + nullableTuple: ["abcd", "abcd", 1], + optionalObject: { name: "abcd" }, + optionalArray: ["abcd"], + optionalTuple: ["abcd", "abcd", 1], + }; + const result = schema.safeParse(invalidItem); + expect(result.success).toEqual(false); + if (!result.success) { + type FormattedError = z.inferFormattedError; + const error: FormattedError = result.error.format(); + expect(error._errors).toEqual([]); + expect(error.nullableObject?._errors).toEqual([]); + expect(error.nullableObject?.name?._errors).toEqual(["Invalid input"]); + expect(error.nullableArray?._errors).toEqual([]); + expect(error.nullableArray?.[0]?._errors).toEqual(["Invalid input"]); + expect(error.nullableTuple?._errors).toEqual([]); + expect(error.nullableTuple?.[0]?._errors).toEqual(["Invalid input"]); + expect(error.nullableTuple?.[1]?._errors).toEqual(["Invalid input"]); + expect(error.optionalObject?._errors).toEqual([]); + expect(error.optionalObject?.name?._errors).toEqual(["Invalid input"]); + expect(error.optionalArray?._errors).toEqual([]); + expect(error.optionalArray?.[0]?._errors).toEqual(["Invalid input"]); + expect(error.optionalTuple?._errors).toEqual([]); + expect(error.optionalTuple?.[0]?._errors).toEqual(["Invalid input"]); + expect(error.optionalTuple?.[1]?._errors).toEqual(["Invalid input"]); + } +}); + +const stringWithCustomError = z.string({ + errorMap: (issue, ctx) => ({ + message: issue.code === "invalid_type" ? (ctx.data ? "Invalid name" : "Name is required") : ctx.defaultError, + }), +}); + +test("schema-bound error map", () => { + const result = stringWithCustomError.safeParse(1234); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("Invalid name"); + } + + const result2 = stringWithCustomError.safeParse(undefined); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].message).toEqual("Name is required"); + } + + // support contextual override + const result3 = stringWithCustomError.safeParse(undefined, { + errorMap: () => ({ message: "OVERRIDE" }), + }); + expect(result3.success).toEqual(false); + if (!result3.success) { + expect(result3.error.issues[0].message).toEqual("OVERRIDE"); + } +}); + +test("overrideErrorMap", () => { + // support overrideErrorMap + z.setErrorMap(() => ({ message: "OVERRIDE" })); + const result4 = stringWithCustomError.min(10).safeParse("tooshort"); + expect(result4.success).toEqual(false); + if (!result4.success) { + expect(result4.error.issues[0].message).toEqual("OVERRIDE"); + } + z.setErrorMap(z.defaultErrorMap); +}); + +test("invalid and required", () => { + const str = z.string({ + invalid_type_error: "Invalid name", + required_error: "Name is required", + }); + const result1 = str.safeParse(1234); + expect(result1.success).toEqual(false); + if (!result1.success) { + expect(result1.error.issues[0].message).toEqual("Invalid name"); + } + const result2 = str.safeParse(undefined); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].message).toEqual("Name is required"); + } +}); + +test("Fallback to default required error", () => { + const str = z.string({ + invalid_type_error: "Invalid name", + // required_error: "Name is required", + }); + + const result2 = str.safeParse(undefined); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].message).toEqual("Required"); + } +}); + +test("invalid and required and errorMap", () => { + expect(() => { + return z.string({ + invalid_type_error: "Invalid name", + required_error: "Name is required", + errorMap: () => ({ message: "OVERRIDE" }), + }); + }).toThrow(); +}); + +test("strict error message", () => { + const errorMsg = "Invalid object"; + const obj = z.object({ x: z.string() }).strict(errorMsg); + const result = obj.safeParse({ x: "a", y: "b" }); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual(errorMsg); + } +}); + +test("enum error message, invalid enum elementstring", () => { + try { + z.enum(["Tuna", "Trout"]).parse("Salmon"); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual("Invalid enum value. Expected 'Tuna' | 'Trout', received 'Salmon'"); + } +}); + +test("enum error message, invalid type", () => { + try { + z.enum(["Tuna", "Trout"]).parse(12); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual("Expected 'Tuna' | 'Trout', received number"); + } +}); + +test("nativeEnum default error message", () => { + enum Fish { + Tuna = "Tuna", + Trout = "Trout", + } + try { + z.nativeEnum(Fish).parse("Salmon"); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual("Invalid enum value. Expected 'Tuna' | 'Trout', received 'Salmon'"); + } +}); + +test("literal default error message", () => { + try { + z.literal("Tuna").parse("Trout"); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual(`Invalid literal value, expected "Tuna"`); + } +}); + +test("literal bigint default error message", () => { + try { + z.literal(BigInt(12)).parse(BigInt(13)); + } catch (err) { + const zerr: z.ZodError = err as any; + expect(zerr.issues.length).toEqual(1); + expect(zerr.issues[0].message).toEqual(`Invalid literal value, expected "12"`); + } +}); + +test("enum with message returns the custom error message", () => { + const schema = z.enum(["apple", "banana"], { + message: "the value provided is invalid", + }); + + const result1 = schema.safeParse("berries"); + expect(result1.success).toEqual(false); + if (!result1.success) { + expect(result1.error.issues[0].message).toEqual("the value provided is invalid"); + } + + const result2 = schema.safeParse(undefined); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].message).toEqual("the value provided is invalid"); + } + + const result3 = schema.safeParse("banana"); + expect(result3.success).toEqual(true); + + const result4 = schema.safeParse(null); + expect(result4.success).toEqual(false); + if (!result4.success) { + expect(result4.error.issues[0].message).toEqual("the value provided is invalid"); + } +}); + +test("when the message is falsy, it is used as is provided", () => { + const schema = z.string().max(1, { message: "" }); + const result = schema.safeParse("asdf"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual(""); + } +}); + +// test("dont short circuit on continuable errors", () => { +// const user = z +// .object({ +// password: z.string().min(6), +// confirm: z.string(), +// }) +// .refine((data) => data.password === data.confirm, { +// message: "Passwords don't match", +// path: ["confirm"], +// }); +// const result = user.safeParse({ password: "asdf", confirm: "qwer" }); +// if (!result.success) { +// expect(result.error.issues.length).toEqual(2); +// } +// }); diff --git a/node_modules/zod/src/v3/tests/firstparty.test.ts b/node_modules/zod/src/v3/tests/firstparty.test.ts new file mode 100644 index 000000000..017a1c13e --- /dev/null +++ b/node_modules/zod/src/v3/tests/firstparty.test.ts @@ -0,0 +1,87 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("first party switch", () => { + const myType = z.string() as z.ZodFirstPartySchemaTypes; + const def = myType._def; + + switch (def.typeName) { + case z.ZodFirstPartyTypeKind.ZodString: + break; + case z.ZodFirstPartyTypeKind.ZodNumber: + break; + case z.ZodFirstPartyTypeKind.ZodNaN: + break; + case z.ZodFirstPartyTypeKind.ZodBigInt: + break; + case z.ZodFirstPartyTypeKind.ZodBoolean: + break; + case z.ZodFirstPartyTypeKind.ZodDate: + break; + case z.ZodFirstPartyTypeKind.ZodUndefined: + break; + case z.ZodFirstPartyTypeKind.ZodNull: + break; + case z.ZodFirstPartyTypeKind.ZodAny: + break; + case z.ZodFirstPartyTypeKind.ZodUnknown: + break; + case z.ZodFirstPartyTypeKind.ZodNever: + break; + case z.ZodFirstPartyTypeKind.ZodVoid: + break; + case z.ZodFirstPartyTypeKind.ZodArray: + break; + case z.ZodFirstPartyTypeKind.ZodObject: + break; + case z.ZodFirstPartyTypeKind.ZodUnion: + break; + case z.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + break; + case z.ZodFirstPartyTypeKind.ZodIntersection: + break; + case z.ZodFirstPartyTypeKind.ZodTuple: + break; + case z.ZodFirstPartyTypeKind.ZodRecord: + break; + case z.ZodFirstPartyTypeKind.ZodMap: + break; + case z.ZodFirstPartyTypeKind.ZodSet: + break; + case z.ZodFirstPartyTypeKind.ZodFunction: + break; + case z.ZodFirstPartyTypeKind.ZodLazy: + break; + case z.ZodFirstPartyTypeKind.ZodLiteral: + break; + case z.ZodFirstPartyTypeKind.ZodEnum: + break; + case z.ZodFirstPartyTypeKind.ZodEffects: + break; + case z.ZodFirstPartyTypeKind.ZodNativeEnum: + break; + case z.ZodFirstPartyTypeKind.ZodOptional: + break; + case z.ZodFirstPartyTypeKind.ZodNullable: + break; + case z.ZodFirstPartyTypeKind.ZodDefault: + break; + case z.ZodFirstPartyTypeKind.ZodCatch: + break; + case z.ZodFirstPartyTypeKind.ZodPromise: + break; + case z.ZodFirstPartyTypeKind.ZodBranded: + break; + case z.ZodFirstPartyTypeKind.ZodPipeline: + break; + case z.ZodFirstPartyTypeKind.ZodSymbol: + break; + case z.ZodFirstPartyTypeKind.ZodReadonly: + break; + default: + util.assertNever(def); + } +}); diff --git a/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts b/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts new file mode 100644 index 000000000..ad397d8b8 --- /dev/null +++ b/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts @@ -0,0 +1,21 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +import type { ZodFirstPartySchemaTypes, ZodFirstPartyTypeKind } from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("Identify missing [ZodFirstPartySchemaTypes]", () => { + type ZodFirstPartySchemaForType = ZodFirstPartySchemaTypes extends infer Schema + ? Schema extends { _def: { typeName: T } } + ? Schema + : never + : never; + type ZodMappedTypes = { + [key in ZodFirstPartyTypeKind]: ZodFirstPartySchemaForType; + }; + type ZodFirstPartySchemaTypesMissingFromUnion = keyof { + [key in keyof ZodMappedTypes as ZodMappedTypes[key] extends { _def: never } ? key : never]: unknown; + }; + + util.assertEqual(true); +}); diff --git a/node_modules/zod/src/v3/tests/function.test.ts b/node_modules/zod/src/v3/tests/function.test.ts new file mode 100644 index 000000000..a0f03bb5c --- /dev/null +++ b/node_modules/zod/src/v3/tests/function.test.ts @@ -0,0 +1,257 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const args1 = z.tuple([z.string()]); +const returns1 = z.number(); +const func1 = z.function(args1, returns1); + +test("function parsing", () => { + const parsed = func1.parse((arg: any) => arg.length); + parsed("asdf"); +}); + +test("parsed function fail 1", () => { + const parsed = func1.parse((x: string) => x); + expect(() => parsed("asdf")).toThrow(); +}); + +test("parsed function fail 2", () => { + const parsed = func1.parse((x: string) => x); + expect(() => parsed(13 as any)).toThrow(); +}); + +test("function inference 1", () => { + type func1 = z.TypeOf; + util.assertEqual number>(true); +}); + +test("method parsing", () => { + const methodObject = z.object({ + property: z.number(), + method: z.function().args(z.string()).returns(z.number()), + }); + const methodInstance = { + property: 3, + method: function (s: string) { + return s.length + this.property; + }, + }; + const parsed = methodObject.parse(methodInstance); + expect(parsed.method("length=8")).toBe(11); // 8 length + 3 property +}); + +test("async method parsing", async () => { + const methodObject = z.object({ + property: z.number(), + method: z.function().args(z.string()).returns(z.promise(z.number())), + }); + const methodInstance = { + property: 3, + method: async function (s: string) { + return s.length + this.property; + }, + }; + const parsed = methodObject.parse(methodInstance); + expect(await parsed.method("length=8")).toBe(11); // 8 length + 3 property +}); + +test("args method", () => { + const t1 = z.function(); + type t1 = z.infer; + util.assertEqual unknown>(true); + + const t2 = t1.args(z.string()); + type t2 = z.infer; + util.assertEqual unknown>(true); + + const t3 = t2.returns(z.boolean()); + type t3 = z.infer; + util.assertEqual boolean>(true); +}); + +const args2 = z.tuple([ + z.object({ + f1: z.number(), + f2: z.string().nullable(), + f3: z.array(z.boolean().optional()).optional(), + }), +]); +const returns2 = z.union([z.string(), z.number()]); + +const func2 = z.function(args2, returns2); + +test("function inference 2", () => { + type func2 = z.TypeOf; + util.assertEqual< + func2, + (arg: { + f1: number; + f2: string | null; + f3?: (boolean | undefined)[] | undefined; + }) => string | number + >(true); +}); + +test("valid function run", () => { + const validFunc2Instance = func2.validate((_x) => { + return "adf" as any; + }); + + const checker = () => { + validFunc2Instance({ + f1: 21, + f2: "asdf", + f3: [true, false], + }); + }; + + checker(); +}); + +test("input validation error", () => { + const invalidFuncInstance = func2.validate((_x) => { + return "adf" as any; + }); + + const checker = () => { + invalidFuncInstance("Invalid_input" as any); + }; + + expect(checker).toThrow(); +}); + +test("output validation error", () => { + const invalidFuncInstance = func2.validate((_x) => { + return ["this", "is", "not", "valid", "output"] as any; + }); + + const checker = () => { + invalidFuncInstance({ + f1: 21, + f2: "asdf", + f3: [true, false], + }); + }; + + expect(checker).toThrow(); +}); + +z.function(z.tuple([z.string()])).args()._def.args; + +test("special function error codes", () => { + const checker = z.function(z.tuple([z.string()]), z.boolean()).implement((arg) => { + return arg.length as any; + }); + try { + checker("12" as any); + } catch (err) { + const zerr = err as z.ZodError; + const first = zerr.issues[0]; + if (first.code !== z.ZodIssueCode.invalid_return_type) throw new Error(); + + expect(first.returnTypeError).toBeInstanceOf(z.ZodError); + } + + try { + checker(12 as any); + } catch (err) { + const zerr = err as z.ZodError; + const first = zerr.issues[0]; + if (first.code !== z.ZodIssueCode.invalid_arguments) throw new Error(); + expect(first.argumentsError).toBeInstanceOf(z.ZodError); + } +}); + +test("function with async refinements", async () => { + const func = z + .function() + .args(z.string().refine(async (val) => val.length > 10)) + .returns(z.promise(z.number().refine(async (val) => val > 10))) + .implement(async (val) => { + return val.length; + }); + const results = []; + try { + await func("asdfasdf"); + results.push("success"); + } catch (_err) { + results.push("fail"); + } + try { + await func("asdflkjasdflkjsf"); + results.push("success"); + } catch (_err) { + results.push("fail"); + } + + expect(results).toEqual(["fail", "success"]); +}); + +test("non async function with async refinements should fail", async () => { + const func = z + .function() + .args(z.string().refine(async (val) => val.length > 10)) + .returns(z.number().refine(async (val) => val > 10)) + .implement((val) => { + return val.length; + }); + + const results = []; + try { + await func("asdasdfasdffasdf"); + results.push("success"); + } catch (_err) { + results.push("fail"); + } + + expect(results).toEqual(["fail"]); +}); + +test("allow extra parameters", () => { + const maxLength5 = z + .function() + .args(z.string()) + .returns(z.boolean()) + .implement((str, _arg, _qewr) => { + return str.length <= 5; + }); + + const filteredList = ["apple", "orange", "pear", "banana", "strawberry"].filter(maxLength5); + expect(filteredList.length).toEqual(2); +}); + +test("params and returnType getters", () => { + const func = z.function().args(z.string()).returns(z.string()); + + func.parameters().items[0].parse("asdf"); + func.returnType().parse("asdf"); +}); + +test("inference with transforms", () => { + const funcSchema = z + .function() + .args(z.string().transform((val) => val.length)) + .returns(z.object({ val: z.number() })); + const myFunc = funcSchema.implement((val) => { + return { val, extra: "stuff" }; + }); + myFunc("asdf"); + + util.assertEqual { val: number; extra: string }>(true); +}); + +test("fallback to OuterTypeOfFunction", () => { + const funcSchema = z + .function() + .args(z.string().transform((val) => val.length)) + .returns(z.object({ arg: z.number() }).transform((val) => val.arg)); + + const myFunc = funcSchema.implement((val) => { + return { arg: val, arg2: false }; + }); + + util.assertEqual number>(true); +}); diff --git a/node_modules/zod/src/v3/tests/generics.test.ts b/node_modules/zod/src/v3/tests/generics.test.ts new file mode 100644 index 000000000..e0af470f0 --- /dev/null +++ b/node_modules/zod/src/v3/tests/generics.test.ts @@ -0,0 +1,48 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("generics", () => { + async function stripOuter(schema: TData, data: unknown) { + return z + .object({ + nested: schema, // as z.ZodTypeAny, + }) + .transform((data) => { + return data.nested!; + }) + .parse({ nested: data }); + } + + const result = stripOuter(z.object({ a: z.string() }), { a: "asdf" }); + util.assertEqual>(true); +}); + +// test("assignability", () => { +// const createSchemaAndParse = ( +// key: K, +// valueSchema: VS, +// data: unknown +// ) => { +// const schema = z.object({ +// [key]: valueSchema, +// } as { [k in K]: VS }); +// return { [key]: valueSchema }; +// const parsed = schema.parse(data); +// return parsed; +// // const inferred: z.infer> = parsed; +// // return inferred; +// }; +// const parsed = createSchemaAndParse("foo", z.string(), { foo: "" }); +// util.assertEqual(true); +// }); + +test("nested no undefined", () => { + const inner = z.string().or(z.array(z.string())); + const outer = z.object({ inner }); + type outerSchema = z.infer; + z.util.assertEqual(true); + expect(outer.safeParse({ inner: undefined }).success).toEqual(false); +}); diff --git a/node_modules/zod/src/v3/tests/instanceof.test.ts b/node_modules/zod/src/v3/tests/instanceof.test.ts new file mode 100644 index 000000000..de66f3f09 --- /dev/null +++ b/node_modules/zod/src/v3/tests/instanceof.test.ts @@ -0,0 +1,37 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("instanceof", async () => { + class Test {} + class Subtest extends Test {} + abstract class AbstractBar { + constructor(public val: string) {} + } + class Bar extends AbstractBar {} + + const TestSchema = z.instanceof(Test); + const SubtestSchema = z.instanceof(Subtest); + const AbstractSchema = z.instanceof(AbstractBar); + const BarSchema = z.instanceof(Bar); + + TestSchema.parse(new Test()); + TestSchema.parse(new Subtest()); + SubtestSchema.parse(new Subtest()); + AbstractSchema.parse(new Bar("asdf")); + const bar = BarSchema.parse(new Bar("asdf")); + expect(bar.val).toEqual("asdf"); + + await expect(() => SubtestSchema.parse(new Test())).toThrow(/Input not instance of Subtest/); + await expect(() => TestSchema.parse(12)).toThrow(/Input not instance of Test/); + + util.assertEqual>(true); +}); + +test("instanceof fatal", () => { + const schema = z.instanceof(Date).refine((d) => d.toString()); + const res = schema.safeParse(null); + expect(res.success).toBe(false); +}); diff --git a/node_modules/zod/src/v3/tests/intersection.test.ts b/node_modules/zod/src/v3/tests/intersection.test.ts new file mode 100644 index 000000000..6d7936c19 --- /dev/null +++ b/node_modules/zod/src/v3/tests/intersection.test.ts @@ -0,0 +1,110 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("object intersection", () => { + const BaseTeacher = z.object({ + subjects: z.array(z.string()), + }); + const HasID = z.object({ id: z.string() }); + + const Teacher = z.intersection(BaseTeacher.passthrough(), HasID); // BaseTeacher.merge(HasID); + const data = { + subjects: ["math"], + id: "asdfasdf", + }; + expect(Teacher.parse(data)).toEqual(data); + expect(() => Teacher.parse({ subject: data.subjects })).toThrow(); + expect(Teacher.parse({ ...data, extra: 12 })).toEqual({ ...data, extra: 12 }); + + expect(() => z.intersection(BaseTeacher.strict(), HasID).parse({ ...data, extra: 12 })).toThrow(); +}); + +test("deep intersection", () => { + const Animal = z.object({ + properties: z.object({ + is_animal: z.boolean(), + }), + }); + const Cat = z + .object({ + properties: z.object({ + jumped: z.boolean(), + }), + }) + .and(Animal); + + type _Cat = z.infer; + // const cat:Cat = 'asdf' as any; + const cat = Cat.parse({ properties: { is_animal: true, jumped: true } }); + expect(cat.properties).toEqual({ is_animal: true, jumped: true }); +}); + +test("deep intersection of arrays", async () => { + const Author = z.object({ + posts: z.array( + z.object({ + post_id: z.number(), + }) + ), + }); + const Registry = z + .object({ + posts: z.array( + z.object({ + title: z.string(), + }) + ), + }) + .and(Author); + + const posts = [ + { post_id: 1, title: "Novels" }, + { post_id: 2, title: "Fairy tales" }, + ]; + const cat = Registry.parse({ posts }); + expect(cat.posts).toEqual(posts); + const asyncCat = await Registry.parseAsync({ posts }); + expect(asyncCat.posts).toEqual(posts); +}); + +test("invalid intersection types", async () => { + const numberIntersection = z.intersection( + z.number(), + z.number().transform((x) => x + 1) + ); + + const syncResult = numberIntersection.safeParse(1234); + expect(syncResult.success).toEqual(false); + if (!syncResult.success) { + expect(syncResult.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_intersection_types); + } + + const asyncResult = await numberIntersection.spa(1234); + expect(asyncResult.success).toEqual(false); + if (!asyncResult.success) { + expect(asyncResult.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_intersection_types); + } +}); + +test("invalid array merge", async () => { + const stringArrInt = z.intersection( + z.string().array(), + z + .string() + .array() + .transform((val) => [...val, "asdf"]) + ); + const syncResult = stringArrInt.safeParse(["asdf", "qwer"]); + expect(syncResult.success).toEqual(false); + if (!syncResult.success) { + expect(syncResult.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_intersection_types); + } + + const asyncResult = await stringArrInt.spa(["asdf", "qwer"]); + expect(asyncResult.success).toEqual(false); + if (!asyncResult.success) { + expect(asyncResult.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_intersection_types); + } +}); diff --git a/node_modules/zod/src/v3/tests/language-server.source.ts b/node_modules/zod/src/v3/tests/language-server.source.ts new file mode 100644 index 000000000..cbe818bb3 --- /dev/null +++ b/node_modules/zod/src/v3/tests/language-server.source.ts @@ -0,0 +1,76 @@ +import * as z from "zod/v3"; + +export const filePath = __filename; + +// z.object() + +export const Test = z.object({ + f1: z.number(), +}); + +export type Test = z.infer; + +export const instanceOfTest: Test = { + f1: 1, +}; + +// z.object().merge() + +export const TestMerge = z + .object({ + f2: z.string().optional(), + }) + .merge(Test); + +export type TestMerge = z.infer; + +export const instanceOfTestMerge: TestMerge = { + f1: 1, + f2: "string", +}; + +// z.union() + +export const TestUnion = z.union([ + z.object({ + f2: z.string().optional(), + }), + Test, +]); + +export type TestUnion = z.infer; + +export const instanceOfTestUnion: TestUnion = { + f1: 1, + f2: "string", +}; + +// z.object().partial() + +export const TestPartial = Test.partial(); + +export type TestPartial = z.infer; + +export const instanceOfTestPartial: TestPartial = { + f1: 1, +}; + +// z.object().pick() + +export const TestPick = TestMerge.pick({ f1: true }); + +export type TestPick = z.infer; + +export const instanceOfTestPick: TestPick = { + f1: 1, +}; + +// z.object().omit() + +export const TestOmit = TestMerge.omit({ f2: true }); + +export type TestOmit = z.infer; + +export const instanceOfTestOmit: TestOmit = { + f1: 1, +}; diff --git a/node_modules/zod/src/v3/tests/language-server.test.ts b/node_modules/zod/src/v3/tests/language-server.test.ts new file mode 100644 index 000000000..851fdc483 --- /dev/null +++ b/node_modules/zod/src/v3/tests/language-server.test.ts @@ -0,0 +1,207 @@ +import { test } from "vitest"; +// import path from "path"; +// import { Node, Project, SyntaxKind } from "ts-morph"; + +// import { filePath } from "./language-server.source"; + +// The following tool is helpful for understanding the TypeScript AST associated with these tests: +// https://ts-ast-viewer.com/ (just copy the contents of language-server.source into the viewer) + +test("", () => {}); +// describe("Executing Go To Definition (and therefore Find Usages and Rename Refactoring) using an IDE works on inferred object properties", () => { +// // Compile file developmentEnvironment.source +// const project = new Project({ +// tsConfigFilePath: path.join(__dirname, "..", "..", "tsconfig.json"), +// skipAddingFilesFromTsConfig: true, +// }); +// const sourceFile = project.addSourceFileAtPath(filePath); + +// test("works for object properties inferred from z.object()", () => { +// // Find usage of Test.f1 property +// const instanceVariable = +// sourceFile.getVariableDeclarationOrThrow("instanceOfTest"); +// const propertyBeingAssigned = getPropertyBeingAssigned( +// instanceVariable, +// "f1" +// ); + +// // Find definition of Test.f1 property +// const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// SyntaxKind.VariableDeclaration +// ); + +// // Assert that find definition returned the Zod definition of Test +// expect(definitionOfProperty?.getText()).toEqual("f1: z.number()"); +// expect(parentOfProperty?.getName()).toEqual("Test"); +// }); + +// // test("works for first object properties inferred from z.object().merge()", () => { +// // // Find usage of TestMerge.f1 property +// // const instanceVariable = sourceFile.getVariableDeclarationOrThrow( +// // "instanceOfTestMerge" +// // ); +// // const propertyBeingAssigned = getPropertyBeingAssigned( +// // instanceVariable, +// // "f1" +// // ); + +// // // Find definition of TestMerge.f1 property +// // const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// // const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// // SyntaxKind.VariableDeclaration +// // ); + +// // // Assert that find definition returned the Zod definition of Test +// // expect(definitionOfProperty?.getText()).toEqual("f1: z.number()"); +// // expect(parentOfProperty?.getName()).toEqual("Test"); +// // }); + +// // test("works for second object properties inferred from z.object().merge()", () => { +// // // Find usage of TestMerge.f2 property +// // const instanceVariable = sourceFile.getVariableDeclarationOrThrow( +// // "instanceOfTestMerge" +// // ); +// // const propertyBeingAssigned = getPropertyBeingAssigned( +// // instanceVariable, +// // "f2" +// // ); + +// // // Find definition of TestMerge.f2 property +// // const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// // const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// // SyntaxKind.VariableDeclaration +// // ); + +// // // Assert that find definition returned the Zod definition of TestMerge +// // expect(definitionOfProperty?.getText()).toEqual( +// // "f2: z.string().optional()" +// // ); +// // expect(parentOfProperty?.getName()).toEqual("TestMerge"); +// // }); + +// test("works for first object properties inferred from z.union()", () => { +// // Find usage of TestUnion.f1 property +// const instanceVariable = sourceFile.getVariableDeclarationOrThrow( +// "instanceOfTestUnion" +// ); +// const propertyBeingAssigned = getPropertyBeingAssigned( +// instanceVariable, +// "f1" +// ); + +// // Find definition of TestUnion.f1 property +// const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// SyntaxKind.VariableDeclaration +// ); + +// // Assert that find definition returned the Zod definition of Test +// expect(definitionOfProperty?.getText()).toEqual("f1: z.number()"); +// expect(parentOfProperty?.getName()).toEqual("Test"); +// }); + +// test("works for second object properties inferred from z.union()", () => { +// // Find usage of TestUnion.f2 property +// const instanceVariable = sourceFile.getVariableDeclarationOrThrow( +// "instanceOfTestUnion" +// ); +// const propertyBeingAssigned = getPropertyBeingAssigned( +// instanceVariable, +// "f2" +// ); + +// // Find definition of TestUnion.f2 property +// const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// SyntaxKind.VariableDeclaration +// ); + +// // Assert that find definition returned the Zod definition of TestUnion +// expect(definitionOfProperty?.getText()).toEqual( +// "f2: z.string().optional()" +// ); +// expect(parentOfProperty?.getName()).toEqual("TestUnion"); +// }); + +// test("works for object properties inferred from z.object().partial()", () => { +// // Find usage of TestPartial.f1 property +// const instanceVariable = sourceFile.getVariableDeclarationOrThrow( +// "instanceOfTestPartial" +// ); +// const propertyBeingAssigned = getPropertyBeingAssigned( +// instanceVariable, +// "f1" +// ); + +// // Find definition of TestPartial.f1 property +// const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// SyntaxKind.VariableDeclaration +// ); + +// // Assert that find definition returned the Zod definition of Test +// expect(definitionOfProperty?.getText()).toEqual("f1: z.number()"); +// expect(parentOfProperty?.getName()).toEqual("Test"); +// }); + +// test("works for object properties inferred from z.object().pick()", () => { +// // Find usage of TestPick.f1 property +// const instanceVariable = +// sourceFile.getVariableDeclarationOrThrow("instanceOfTestPick"); +// const propertyBeingAssigned = getPropertyBeingAssigned( +// instanceVariable, +// "f1" +// ); + +// // Find definition of TestPick.f1 property +// const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// SyntaxKind.VariableDeclaration +// ); + +// // Assert that find definition returned the Zod definition of Test +// expect(definitionOfProperty?.getText()).toEqual("f1: z.number()"); +// expect(parentOfProperty?.getName()).toEqual("Test"); +// }); + +// test("works for object properties inferred from z.object().omit()", () => { +// // Find usage of TestOmit.f1 property +// const instanceVariable = +// sourceFile.getVariableDeclarationOrThrow("instanceOfTestOmit"); +// const propertyBeingAssigned = getPropertyBeingAssigned( +// instanceVariable, +// "f1" +// ); + +// // Find definition of TestOmit.f1 property +// const definitionOfProperty = propertyBeingAssigned?.getDefinitionNodes()[0]; +// const parentOfProperty = definitionOfProperty?.getFirstAncestorByKind( +// SyntaxKind.VariableDeclaration +// ); + +// // Assert that find definition returned the Zod definition of Test +// expect(definitionOfProperty?.getText()).toEqual("f1: z.number()"); +// expect(parentOfProperty?.getName()).toEqual("Test"); +// }); +// }); + +// const getPropertyBeingAssigned = (node: Node, name: string) => { +// const propertyAssignment = node.forEachDescendant((descendent) => +// Node.isPropertyAssignment(descendent) && descendent.getName() == name +// ? descendent +// : undefined +// ); + +// if (propertyAssignment == null) +// fail(`Could not find property assignment with name ${name}`); + +// const propertyLiteral = propertyAssignment.getFirstDescendantByKind( +// SyntaxKind.Identifier +// ); + +// if (propertyLiteral == null) +// fail(`Could not find property literal with name ${name}`); + +// return propertyLiteral; +// }; diff --git a/node_modules/zod/src/v3/tests/literal.test.ts b/node_modules/zod/src/v3/tests/literal.test.ts new file mode 100644 index 000000000..d166a24f2 --- /dev/null +++ b/node_modules/zod/src/v3/tests/literal.test.ts @@ -0,0 +1,36 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const literalTuna = z.literal("tuna"); +const literalFortyTwo = z.literal(42); +const literalTrue = z.literal(true); + +const terrificSymbol = Symbol("terrific"); +const literalTerrificSymbol = z.literal(terrificSymbol); + +test("passing validations", () => { + literalTuna.parse("tuna"); + literalFortyTwo.parse(42); + literalTrue.parse(true); + literalTerrificSymbol.parse(terrificSymbol); +}); + +test("failing validations", () => { + expect(() => literalTuna.parse("shark")).toThrow(); + expect(() => literalFortyTwo.parse(43)).toThrow(); + expect(() => literalTrue.parse(false)).toThrow(); + expect(() => literalTerrificSymbol.parse(Symbol("terrific"))).toThrow(); +}); + +test("invalid_literal should have `received` field with data", () => { + const data = "shark"; + const result = literalTuna.safeParse(data); + if (!result.success) { + const issue = result.error.issues[0]; + if (issue.code === "invalid_literal") { + expect(issue.received).toBe(data); + } + } +}); diff --git a/node_modules/zod/src/v3/tests/map.test.ts b/node_modules/zod/src/v3/tests/map.test.ts new file mode 100644 index 000000000..947181903 --- /dev/null +++ b/node_modules/zod/src/v3/tests/map.test.ts @@ -0,0 +1,110 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { ZodIssueCode } from "zod/v3"; +import { util } from "../helpers/util.js"; + +const stringMap = z.map(z.string(), z.string()); +type stringMap = z.infer; + +test("type inference", () => { + util.assertEqual>(true); +}); + +test("valid parse", () => { + const result = stringMap.safeParse( + new Map([ + ["first", "foo"], + ["second", "bar"], + ]) + ); + expect(result.success).toEqual(true); + if (result.success) { + expect(result.data.has("first")).toEqual(true); + expect(result.data.has("second")).toEqual(true); + expect(result.data.get("first")).toEqual("foo"); + expect(result.data.get("second")).toEqual("bar"); + } +}); + +test("valid parse async", async () => { + const result = await stringMap.spa( + new Map([ + ["first", "foo"], + ["second", "bar"], + ]) + ); + expect(result.success).toEqual(true); + if (result.success) { + expect(result.data.has("first")).toEqual(true); + expect(result.data.has("second")).toEqual(true); + expect(result.data.get("first")).toEqual("foo"); + expect(result.data.get("second")).toEqual("bar"); + } +}); + +test("throws when a Set is given", () => { + const result = stringMap.safeParse(new Set([])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); + } +}); + +test("throws when the given map has invalid key and invalid input", () => { + const result = stringMap.safeParse(new Map([[42, Symbol()]])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(2); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[0].path).toEqual([0, "key"]); + expect(result.error.issues[1].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[1].path).toEqual([0, "value"]); + } +}); + +test("throws when the given map has multiple invalid entries", () => { + // const result = stringMap.safeParse(new Map([[42, Symbol()]])); + + const result = stringMap.safeParse( + new Map([ + [1, "foo"], + ["bar", 2], + ] as [any, any][]) as Map + ); + + // const result = stringMap.safeParse(new Map([[42, Symbol()]])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(2); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[0].path).toEqual([0, "key"]); + expect(result.error.issues[1].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[1].path).toEqual([1, "value"]); + } +}); + +test("dirty", async () => { + const map = z.map( + z.string().refine((val) => val === val.toUpperCase(), { + message: "Keys must be uppercase", + }), + z.string() + ); + const result = await map.spa( + new Map([ + ["first", "foo"], + ["second", "bar"], + ]) + ); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(2); + expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.custom); + expect(result.error.issues[0].message).toEqual("Keys must be uppercase"); + expect(result.error.issues[1].code).toEqual(z.ZodIssueCode.custom); + expect(result.error.issues[1].message).toEqual("Keys must be uppercase"); + } +}); diff --git a/node_modules/zod/src/v3/tests/masking.test.ts b/node_modules/zod/src/v3/tests/masking.test.ts new file mode 100644 index 000000000..63817e2c1 --- /dev/null +++ b/node_modules/zod/src/v3/tests/masking.test.ts @@ -0,0 +1,4 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +test("masking test", () => {}); diff --git a/node_modules/zod/src/v3/tests/mocker.test.ts b/node_modules/zod/src/v3/tests/mocker.test.ts new file mode 100644 index 000000000..3a2506b90 --- /dev/null +++ b/node_modules/zod/src/v3/tests/mocker.test.ts @@ -0,0 +1,19 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +import { Mocker } from "./Mocker.js"; + +test("mocker", () => { + const mocker = new Mocker(); + mocker.string; + mocker.number; + mocker.boolean; + mocker.null; + mocker.undefined; + mocker.stringOptional; + mocker.stringNullable; + mocker.numberOptional; + mocker.numberNullable; + mocker.booleanOptional; + mocker.booleanNullable; +}); diff --git a/node_modules/zod/src/v3/tests/nan.test.ts b/node_modules/zod/src/v3/tests/nan.test.ts new file mode 100644 index 000000000..e24567abc --- /dev/null +++ b/node_modules/zod/src/v3/tests/nan.test.ts @@ -0,0 +1,21 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const schema = z.nan(); + +test("passing validations", () => { + schema.parse(Number.NaN); + schema.parse(Number("Not a number")); +}); + +test("failing validations", () => { + expect(() => schema.parse(5)).toThrow(); + expect(() => schema.parse("John")).toThrow(); + expect(() => schema.parse(true)).toThrow(); + expect(() => schema.parse(null)).toThrow(); + expect(() => schema.parse(undefined)).toThrow(); + expect(() => schema.parse({})).toThrow(); + expect(() => schema.parse([])).toThrow(); +}); diff --git a/node_modules/zod/src/v3/tests/nativeEnum.test.ts b/node_modules/zod/src/v3/tests/nativeEnum.test.ts new file mode 100644 index 000000000..61eb37a13 --- /dev/null +++ b/node_modules/zod/src/v3/tests/nativeEnum.test.ts @@ -0,0 +1,87 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("nativeEnum test with consts", () => { + const Fruits: { Apple: "apple"; Banana: "banana" } = { + Apple: "apple", + Banana: "banana", + }; + const fruitEnum = z.nativeEnum(Fruits); + type fruitEnum = z.infer; + fruitEnum.parse("apple"); + fruitEnum.parse("banana"); + fruitEnum.parse(Fruits.Apple); + fruitEnum.parse(Fruits.Banana); + util.assertEqual(true); +}); + +test("nativeEnum test with real enum", () => { + enum Fruits { + Apple = "apple", + Banana = "banana", + } + // @ts-ignore + const fruitEnum = z.nativeEnum(Fruits); + type fruitEnum = z.infer; + fruitEnum.parse("apple"); + fruitEnum.parse("banana"); + fruitEnum.parse(Fruits.Apple); + fruitEnum.parse(Fruits.Banana); + util.assertIs(true); +}); + +test("nativeEnum test with const with numeric keys", () => { + const FruitValues = { + Apple: 10, + Banana: 20, + // @ts-ignore + } as const; + const fruitEnum = z.nativeEnum(FruitValues); + type fruitEnum = z.infer; + fruitEnum.parse(10); + fruitEnum.parse(20); + fruitEnum.parse(FruitValues.Apple); + fruitEnum.parse(FruitValues.Banana); + util.assertEqual(true); +}); + +test("from enum", () => { + enum Fruits { + Cantaloupe = 0, + Apple = "apple", + Banana = "banana", + } + + const FruitEnum = z.nativeEnum(Fruits as any); + type _FruitEnum = z.infer; + FruitEnum.parse(Fruits.Cantaloupe); + FruitEnum.parse(Fruits.Apple); + FruitEnum.parse("apple"); + FruitEnum.parse(0); + expect(() => FruitEnum.parse(1)).toThrow(); + expect(() => FruitEnum.parse("Apple")).toThrow(); + expect(() => FruitEnum.parse("Cantaloupe")).toThrow(); +}); + +test("from const", () => { + const Greek = { + Alpha: "a", + Beta: "b", + Gamma: 3, + // @ts-ignore + } as const; + + const GreekEnum = z.nativeEnum(Greek); + type _GreekEnum = z.infer; + GreekEnum.parse("a"); + GreekEnum.parse("b"); + GreekEnum.parse(3); + expect(() => GreekEnum.parse("v")).toThrow(); + expect(() => GreekEnum.parse("Alpha")).toThrow(); + expect(() => GreekEnum.parse(2)).toThrow(); + + expect(GreekEnum.enum.Alpha).toEqual("a"); +}); diff --git a/node_modules/zod/src/v3/tests/nullable.test.ts b/node_modules/zod/src/v3/tests/nullable.test.ts new file mode 100644 index 000000000..90c1eed4d --- /dev/null +++ b/node_modules/zod/src/v3/tests/nullable.test.ts @@ -0,0 +1,42 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +function checkErrors(a: z.ZodTypeAny, bad: any) { + let expected: any; + try { + a.parse(bad); + } catch (error) { + expected = (error as z.ZodError).formErrors; + } + try { + a.nullable().parse(bad); + } catch (error) { + expect((error as z.ZodError).formErrors).toEqual(expected); + } +} + +test("Should have error messages appropriate for the underlying type", () => { + checkErrors(z.string().min(2), 1); + z.string().min(2).nullable().parse(null); + checkErrors(z.number().gte(2), 1); + z.number().gte(2).nullable().parse(null); + checkErrors(z.boolean(), ""); + z.boolean().nullable().parse(null); + checkErrors(z.null(), null); + z.null().nullable().parse(null); + checkErrors(z.null(), {}); + z.null().nullable().parse(null); + checkErrors(z.object({}), 1); + z.object({}).nullable().parse(null); + checkErrors(z.tuple([]), 1); + z.tuple([]).nullable().parse(null); + checkErrors(z.unknown(), 1); + z.unknown().nullable().parse(null); +}); + +test("unwrap", () => { + const unwrapped = z.string().nullable().unwrap(); + expect(unwrapped).toBeInstanceOf(z.ZodString); +}); diff --git a/node_modules/zod/src/v3/tests/number.test.ts b/node_modules/zod/src/v3/tests/number.test.ts new file mode 100644 index 000000000..db3f73b2d --- /dev/null +++ b/node_modules/zod/src/v3/tests/number.test.ts @@ -0,0 +1,176 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const gtFive = z.number().gt(5); +const gteFive = z.number().gte(-5).gte(5); +const minFive = z.number().min(0).min(5); +const ltFive = z.number().lte(10).lt(5); +const lteFive = z.number().lte(5); +const maxFive = z.number().max(10).max(5); +const intNum = z.number().int(); +const positive = z.number().positive(); +const negative = z.number().negative(); +const nonpositive = z.number().nonpositive(); +const nonnegative = z.number().nonnegative(); +const multipleOfFive = z.number().multipleOf(5); +const multipleOfNegativeFive = z.number().multipleOf(-5); +const finite = z.number().finite(); +const safe = z.number().safe(); +const stepPointOne = z.number().step(0.1); +const stepPointZeroZeroZeroOne = z.number().step(0.0001); +const stepSixPointFour = z.number().step(6.4); + +test("passing validations", () => { + z.number().parse(1); + z.number().parse(1.5); + z.number().parse(0); + z.number().parse(-1.5); + z.number().parse(-1); + z.number().parse(Number.POSITIVE_INFINITY); + z.number().parse(Number.NEGATIVE_INFINITY); + gtFive.parse(6); + gtFive.parse(Number.POSITIVE_INFINITY); + gteFive.parse(5); + gteFive.parse(Number.POSITIVE_INFINITY); + minFive.parse(5); + minFive.parse(Number.POSITIVE_INFINITY); + ltFive.parse(4); + ltFive.parse(Number.NEGATIVE_INFINITY); + lteFive.parse(5); + lteFive.parse(Number.NEGATIVE_INFINITY); + maxFive.parse(5); + maxFive.parse(Number.NEGATIVE_INFINITY); + intNum.parse(4); + positive.parse(1); + positive.parse(Number.POSITIVE_INFINITY); + negative.parse(-1); + negative.parse(Number.NEGATIVE_INFINITY); + nonpositive.parse(0); + nonpositive.parse(-1); + nonpositive.parse(Number.NEGATIVE_INFINITY); + nonnegative.parse(0); + nonnegative.parse(1); + nonnegative.parse(Number.POSITIVE_INFINITY); + multipleOfFive.parse(15); + multipleOfFive.parse(-15); + multipleOfNegativeFive.parse(-15); + multipleOfNegativeFive.parse(15); + finite.parse(123); + safe.parse(Number.MIN_SAFE_INTEGER); + safe.parse(Number.MAX_SAFE_INTEGER); + stepPointOne.parse(6); + stepPointOne.parse(6.1); + stepPointOne.parse(6.1); + stepSixPointFour.parse(12.8); + stepPointZeroZeroZeroOne.parse(3.01); +}); + +test("failing validations", () => { + expect(() => ltFive.parse(5)).toThrow(); + expect(() => lteFive.parse(6)).toThrow(); + expect(() => maxFive.parse(6)).toThrow(); + expect(() => gtFive.parse(5)).toThrow(); + expect(() => gteFive.parse(4)).toThrow(); + expect(() => minFive.parse(4)).toThrow(); + expect(() => intNum.parse(3.14)).toThrow(); + expect(() => positive.parse(0)).toThrow(); + expect(() => positive.parse(-1)).toThrow(); + expect(() => negative.parse(0)).toThrow(); + expect(() => negative.parse(1)).toThrow(); + expect(() => nonpositive.parse(1)).toThrow(); + expect(() => nonnegative.parse(-1)).toThrow(); + expect(() => multipleOfFive.parse(7.5)).toThrow(); + expect(() => multipleOfFive.parse(-7.5)).toThrow(); + expect(() => multipleOfNegativeFive.parse(-7.5)).toThrow(); + expect(() => multipleOfNegativeFive.parse(7.5)).toThrow(); + expect(() => finite.parse(Number.POSITIVE_INFINITY)).toThrow(); + expect(() => finite.parse(Number.NEGATIVE_INFINITY)).toThrow(); + expect(() => safe.parse(Number.MIN_SAFE_INTEGER - 1)).toThrow(); + expect(() => safe.parse(Number.MAX_SAFE_INTEGER + 1)).toThrow(); + + expect(() => stepPointOne.parse(6.11)).toThrow(); + expect(() => stepPointOne.parse(6.1000000001)).toThrow(); + expect(() => stepSixPointFour.parse(6.41)).toThrow(); +}); + +test("parse NaN", () => { + expect(() => z.number().parse(Number.NaN)).toThrow(); +}); + +test("min max getters", () => { + expect(z.number().minValue).toBeNull; + expect(ltFive.minValue).toBeNull; + expect(lteFive.minValue).toBeNull; + expect(maxFive.minValue).toBeNull; + expect(negative.minValue).toBeNull; + expect(nonpositive.minValue).toBeNull; + expect(intNum.minValue).toBeNull; + expect(multipleOfFive.minValue).toBeNull; + expect(finite.minValue).toBeNull; + expect(gtFive.minValue).toEqual(5); + expect(gteFive.minValue).toEqual(5); + expect(minFive.minValue).toEqual(5); + expect(minFive.min(10).minValue).toEqual(10); + expect(positive.minValue).toEqual(0); + expect(nonnegative.minValue).toEqual(0); + expect(safe.minValue).toEqual(Number.MIN_SAFE_INTEGER); + + expect(z.number().maxValue).toBeNull; + expect(gtFive.maxValue).toBeNull; + expect(gteFive.maxValue).toBeNull; + expect(minFive.maxValue).toBeNull; + expect(positive.maxValue).toBeNull; + expect(nonnegative.maxValue).toBeNull; + expect(intNum.minValue).toBeNull; + expect(multipleOfFive.minValue).toBeNull; + expect(finite.minValue).toBeNull; + expect(ltFive.maxValue).toEqual(5); + expect(lteFive.maxValue).toEqual(5); + expect(maxFive.maxValue).toEqual(5); + expect(maxFive.max(1).maxValue).toEqual(1); + expect(negative.maxValue).toEqual(0); + expect(nonpositive.maxValue).toEqual(0); + expect(safe.maxValue).toEqual(Number.MAX_SAFE_INTEGER); +}); + +test("int getter", () => { + expect(z.number().isInt).toEqual(false); + expect(z.number().multipleOf(1.5).isInt).toEqual(false); + expect(gtFive.isInt).toEqual(false); + expect(gteFive.isInt).toEqual(false); + expect(minFive.isInt).toEqual(false); + expect(positive.isInt).toEqual(false); + expect(nonnegative.isInt).toEqual(false); + expect(finite.isInt).toEqual(false); + expect(ltFive.isInt).toEqual(false); + expect(lteFive.isInt).toEqual(false); + expect(maxFive.isInt).toEqual(false); + expect(negative.isInt).toEqual(false); + expect(nonpositive.isInt).toEqual(false); + expect(safe.isInt).toEqual(false); + + expect(intNum.isInt).toEqual(true); + expect(multipleOfFive.isInt).toEqual(true); +}); + +test("finite getter", () => { + expect(z.number().isFinite).toEqual(false); + expect(gtFive.isFinite).toEqual(false); + expect(gteFive.isFinite).toEqual(false); + expect(minFive.isFinite).toEqual(false); + expect(positive.isFinite).toEqual(false); + expect(nonnegative.isFinite).toEqual(false); + expect(ltFive.isFinite).toEqual(false); + expect(lteFive.isFinite).toEqual(false); + expect(maxFive.isFinite).toEqual(false); + expect(negative.isFinite).toEqual(false); + expect(nonpositive.isFinite).toEqual(false); + + expect(finite.isFinite).toEqual(true); + expect(intNum.isFinite).toEqual(true); + expect(multipleOfFive.isFinite).toEqual(true); + expect(z.number().min(5).max(10).isFinite).toEqual(true); + expect(safe.isFinite).toEqual(true); +}); diff --git a/node_modules/zod/src/v3/tests/object-augmentation.test.ts b/node_modules/zod/src/v3/tests/object-augmentation.test.ts new file mode 100644 index 000000000..964ea3dae --- /dev/null +++ b/node_modules/zod/src/v3/tests/object-augmentation.test.ts @@ -0,0 +1,29 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("object augmentation", () => { + const Animal = z + .object({ + species: z.string(), + }) + .augment({ + population: z.number(), + }); + // overwrites `species` + const ModifiedAnimal = Animal.augment({ + species: z.array(z.string()), + }); + ModifiedAnimal.parse({ + species: ["asd"], + population: 1324, + }); + + const bad = () => + ModifiedAnimal.parse({ + species: "asdf", + population: 1324, + } as any); + expect(bad).toThrow(); +}); diff --git a/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts b/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts new file mode 100644 index 000000000..293ebf0c7 --- /dev/null +++ b/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts @@ -0,0 +1,29 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const RealSet = Set; +const RealMap = Map; +const RealDate = Date; + +test("doesn’t throw when Date is undefined", () => { + delete (globalThis as any).Date; + const result = z.object({}).safeParse({}); + expect(result.success).toEqual(true); + globalThis.Date = RealDate; +}); + +test("doesn’t throw when Set is undefined", () => { + delete (globalThis as any).Set; + const result = z.object({}).safeParse({}); + expect(result.success).toEqual(true); + globalThis.Set = RealSet; +}); + +test("doesn’t throw when Map is undefined", () => { + delete (globalThis as any).Map; + const result = z.object({}).safeParse({}); + expect(result.success).toEqual(true); + globalThis.Map = RealMap; +}); diff --git a/node_modules/zod/src/v3/tests/object.test.ts b/node_modules/zod/src/v3/tests/object.test.ts new file mode 100644 index 000000000..d8772d4f9 --- /dev/null +++ b/node_modules/zod/src/v3/tests/object.test.ts @@ -0,0 +1,434 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const Test = z.object({ + f1: z.number(), + f2: z.string().optional(), + f3: z.string().nullable(), + f4: z.array(z.object({ t: z.union([z.string(), z.boolean()]) })), +}); + +test("object type inference", () => { + type TestType = { + f1: number; + f2?: string | undefined; + f3: string | null; + f4: { t: string | boolean }[]; + }; + + util.assertEqual, TestType>(true); +}); + +test("unknown throw", () => { + const asdf: unknown = 35; + expect(() => Test.parse(asdf)).toThrow(); +}); + +test("shape() should return schema of particular key", () => { + const f1Schema = Test.shape.f1; + const f2Schema = Test.shape.f2; + const f3Schema = Test.shape.f3; + const f4Schema = Test.shape.f4; + + expect(f1Schema).toBeInstanceOf(z.ZodNumber); + expect(f2Schema).toBeInstanceOf(z.ZodOptional); + expect(f3Schema).toBeInstanceOf(z.ZodNullable); + expect(f4Schema).toBeInstanceOf(z.ZodArray); +}); + +test("correct parsing", () => { + Test.parse({ + f1: 12, + f2: "string", + f3: "string", + f4: [ + { + t: "string", + }, + ], + }); + + Test.parse({ + f1: 12, + f3: null, + f4: [ + { + t: false, + }, + ], + }); +}); + +test("incorrect #1", () => { + expect(() => Test.parse({} as any)).toThrow(); +}); + +test("nonstrict by default", () => { + z.object({ points: z.number() }).parse({ + points: 2314, + unknown: "asdf", + }); +}); + +const data = { + points: 2314, + unknown: "asdf", +}; + +test("strip by default", () => { + const val = z.object({ points: z.number() }).parse(data); + expect(val).toEqual({ points: 2314 }); +}); + +test("unknownkeys override", () => { + const val = z.object({ points: z.number() }).strict().passthrough().strip().nonstrict().parse(data); + + expect(val).toEqual(data); +}); + +test("passthrough unknown", () => { + const val = z.object({ points: z.number() }).passthrough().parse(data); + + expect(val).toEqual(data); +}); + +test("strip unknown", () => { + const val = z.object({ points: z.number() }).strip().parse(data); + + expect(val).toEqual({ points: 2314 }); +}); + +test("strict", () => { + const val = z.object({ points: z.number() }).strict().safeParse(data); + + expect(val.success).toEqual(false); +}); + +test("catchall inference", () => { + const o1 = z + .object({ + first: z.string(), + }) + .catchall(z.number()); + + const d1 = o1.parse({ first: "asdf", num: 1243 }); + util.assertEqual(true); + util.assertEqual(true); +}); + +test("catchall overrides strict", () => { + const o1 = z.object({ first: z.string().optional() }).strict().catchall(z.number()); + + // should run fine + // setting a catchall overrides the unknownKeys behavior + o1.parse({ + asdf: 1234, + }); + + // should only run catchall validation + // against unknown keys + o1.parse({ + first: "asdf", + asdf: 1234, + }); +}); + +test("catchall overrides strict", () => { + const o1 = z + .object({ + first: z.string(), + }) + .strict() + .catchall(z.number()); + + // should run fine + // setting a catchall overrides the unknownKeys behavior + o1.parse({ + first: "asdf", + asdf: 1234, + }); +}); + +test("test that optional keys are unset", async () => { + const SNamedEntity = z.object({ + id: z.string(), + set: z.string().optional(), + unset: z.string().optional(), + }); + const result = await SNamedEntity.parse({ + id: "asdf", + set: undefined, + }); + // eslint-disable-next-line ban/ban + expect(Object.keys(result)).toEqual(["id", "set"]); +}); + +test("test catchall parsing", async () => { + const result = z.object({ name: z.string() }).catchall(z.number()).parse({ name: "Foo", validExtraKey: 61 }); + + expect(result).toEqual({ name: "Foo", validExtraKey: 61 }); + + const result2 = z + .object({ name: z.string() }) + .catchall(z.number()) + .safeParse({ name: "Foo", validExtraKey: 61, invalid: "asdf" }); + + expect(result2.success).toEqual(false); +}); + +test("test nonexistent keys", async () => { + const Schema = z.union([z.object({ a: z.string() }), z.object({ b: z.number() })]); + const obj = { a: "A" }; + const result = await Schema.spa(obj); // Works with 1.11.10, breaks with 2.0.0-beta.21 + expect(result.success).toBe(true); +}); + +test("test async union", async () => { + const Schema2 = z.union([ + z.object({ + ty: z.string(), + }), + z.object({ + ty: z.number(), + }), + ]); + + const obj = { ty: "A" }; + const result = await Schema2.spa(obj); // Works with 1.11.10, breaks with 2.0.0-beta.21 + expect(result.success).toEqual(true); +}); + +test("test inferred merged type", async () => { + const asdf = z.object({ a: z.string() }).merge(z.object({ a: z.number() })); + type asdf = z.infer; + util.assertEqual(true); +}); + +test("inferred merged object type with optional properties", async () => { + const Merged = z + .object({ a: z.string(), b: z.string().optional() }) + .merge(z.object({ a: z.string().optional(), b: z.string() })); + type Merged = z.infer; + util.assertEqual(true); + // todo + // util.assertEqual(true); +}); + +test("inferred unioned object type with optional properties", async () => { + const Unioned = z.union([ + z.object({ a: z.string(), b: z.string().optional() }), + z.object({ a: z.string().optional(), b: z.string() }), + ]); + type Unioned = z.infer; + util.assertEqual(true); +}); + +test("inferred enum type", async () => { + const Enum = z.object({ a: z.string(), b: z.string().optional() }).keyof(); + + expect(Enum.Values).toEqual({ + a: "a", + b: "b", + }); + expect(Enum.enum).toEqual({ + a: "a", + b: "b", + }); + expect(Enum._def.values).toEqual(["a", "b"]); + type Enum = z.infer; + util.assertEqual(true); +}); + +test("inferred partial object type with optional properties", async () => { + const Partial = z.object({ a: z.string(), b: z.string().optional() }).partial(); + type Partial = z.infer; + util.assertEqual(true); +}); + +test("inferred picked object type with optional properties", async () => { + const Picked = z.object({ a: z.string(), b: z.string().optional() }).pick({ b: true }); + type Picked = z.infer; + util.assertEqual(true); +}); + +test("inferred type for unknown/any keys", () => { + const myType = z.object({ + anyOptional: z.any().optional(), + anyRequired: z.any(), + unknownOptional: z.unknown().optional(), + unknownRequired: z.unknown(), + }); + type myType = z.infer; + util.assertEqual< + myType, + { + anyOptional?: any; + anyRequired?: any; + unknownOptional?: unknown; + unknownRequired?: unknown; + } + >(true); +}); + +test("setKey", () => { + const base = z.object({ name: z.string() }); + const withNewKey = base.setKey("age", z.number()); + + type withNewKey = z.infer; + util.assertEqual(true); + withNewKey.parse({ name: "asdf", age: 1234 }); +}); + +test("strictcreate", async () => { + const strictObj = z.strictObject({ + name: z.string(), + }); + + const syncResult = strictObj.safeParse({ name: "asdf", unexpected: 13 }); + expect(syncResult.success).toEqual(false); + + const asyncResult = await strictObj.spa({ name: "asdf", unexpected: 13 }); + expect(asyncResult.success).toEqual(false); +}); + +test("object with refine", async () => { + const schema = z + .object({ + a: z.string().default("foo"), + b: z.number(), + }) + .refine(() => true); + expect(schema.parse({ b: 5 })).toEqual({ b: 5, a: "foo" }); + const result = await schema.parseAsync({ b: 5 }); + expect(result).toEqual({ b: 5, a: "foo" }); +}); + +test("intersection of object with date", async () => { + const schema = z.object({ + a: z.date(), + }); + expect(schema.and(schema).parse({ a: new Date(1637353595983) })).toEqual({ + a: new Date(1637353595983), + }); + const result = await schema.parseAsync({ a: new Date(1637353595983) }); + expect(result).toEqual({ a: new Date(1637353595983) }); +}); + +test("intersection of object with refine with date", async () => { + const schema = z + .object({ + a: z.date(), + }) + .refine(() => true); + expect(schema.and(schema).parse({ a: new Date(1637353595983) })).toEqual({ + a: new Date(1637353595983), + }); + const result = await schema.parseAsync({ a: new Date(1637353595983) }); + expect(result).toEqual({ a: new Date(1637353595983) }); +}); + +test("constructor key", () => { + const person = z + .object({ + name: z.string(), + }) + .strict(); + + expect(() => + person.parse({ + name: "bob dylan", + constructor: 61, + }) + ).toThrow(); +}); + +test("constructor key", () => { + const Example = z.object({ + prop: z.string(), + opt: z.number().optional(), + arr: z.string().array(), + }); + + type Example = z.infer; + util.assertEqual(true); +}); + +test("unknownkeys merging", () => { + // This one is "strict" + const schemaA = z + .object({ + a: z.string(), + }) + .strict(); + + // This one is "strip" + const schemaB = z + .object({ + b: z.string(), + }) + .catchall(z.string()); + + const mergedSchema = schemaA.merge(schemaB); + type mergedSchema = typeof mergedSchema; + util.assertEqual(true); + expect(mergedSchema._def.unknownKeys).toEqual("strip"); + + util.assertEqual(true); + expect(mergedSchema._def.catchall instanceof z.ZodString).toEqual(true); +}); + +const personToExtend = z.object({ + firstName: z.string(), + lastName: z.string(), +}); + +test("extend() should return schema with new key", () => { + const PersonWithNickname = personToExtend.extend({ nickName: z.string() }); + type PersonWithNickname = z.infer; + + const expected = { firstName: "f", nickName: "n", lastName: "l" }; + const actual = PersonWithNickname.parse(expected); + + expect(actual).toEqual(expected); + util.assertEqual(true); + util.assertEqual(true); +}); + +test("extend() should have power to override existing key", () => { + const PersonWithNumberAsLastName = personToExtend.extend({ + lastName: z.number(), + }); + type PersonWithNumberAsLastName = z.infer; + + const expected = { firstName: "f", lastName: 42 }; + const actual = PersonWithNumberAsLastName.parse(expected); + + expect(actual).toEqual(expected); + util.assertEqual(true); +}); + +test("passthrough index signature", () => { + const a = z.object({ a: z.string() }); + type a = z.infer; + util.assertEqual<{ a: string }, a>(true); + const b = a.passthrough(); + type b = z.infer; + util.assertEqual<{ a: string } & { [k: string]: unknown }, b>(true); +}); + +test("xor", () => { + type Without = { [P in Exclude]?: never }; + type XOR = T extends object ? (U extends object ? (Without & U) | (Without & T) : U) : T; + + type A = { name: string; a: number }; + type B = { name: string; b: number }; + type C = XOR; + type Outer = { data: C }; + + const _Outer: z.ZodType = z.object({ + data: z.union([z.object({ name: z.string(), a: z.number() }), z.object({ name: z.string(), b: z.number() })]), + }); +}); diff --git a/node_modules/zod/src/v3/tests/optional.test.ts b/node_modules/zod/src/v3/tests/optional.test.ts new file mode 100644 index 000000000..016c954fc --- /dev/null +++ b/node_modules/zod/src/v3/tests/optional.test.ts @@ -0,0 +1,42 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +function checkErrors(a: z.ZodTypeAny, bad: any) { + let expected: any; + try { + a.parse(bad); + } catch (error) { + expected = (error as z.ZodError).formErrors; + } + try { + a.optional().parse(bad); + } catch (error) { + expect((error as z.ZodError).formErrors).toEqual(expected); + } +} + +test("Should have error messages appropriate for the underlying type", () => { + checkErrors(z.string().min(2), 1); + z.string().min(2).optional().parse(undefined); + checkErrors(z.number().gte(2), 1); + z.number().gte(2).optional().parse(undefined); + checkErrors(z.boolean(), ""); + z.boolean().optional().parse(undefined); + checkErrors(z.undefined(), null); + z.undefined().optional().parse(undefined); + checkErrors(z.null(), {}); + z.null().optional().parse(undefined); + checkErrors(z.object({}), 1); + z.object({}).optional().parse(undefined); + checkErrors(z.tuple([]), 1); + z.tuple([]).optional().parse(undefined); + checkErrors(z.unknown(), 1); + z.unknown().optional().parse(undefined); +}); + +test("unwrap", () => { + const unwrapped = z.string().optional().unwrap(); + expect(unwrapped).toBeInstanceOf(z.ZodString); +}); diff --git a/node_modules/zod/src/v3/tests/parseUtil.test.ts b/node_modules/zod/src/v3/tests/parseUtil.test.ts new file mode 100644 index 000000000..8882d4c34 --- /dev/null +++ b/node_modules/zod/src/v3/tests/parseUtil.test.ts @@ -0,0 +1,23 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import { type SyncParseReturnType, isAborted, isDirty, isValid } from "../helpers/parseUtil.js"; + +test("parseUtil isInvalid should use structural typing", () => { + // Test for issue #556: https://github.com/colinhacks/zod/issues/556 + const aborted: SyncParseReturnType = { status: "aborted" }; + const dirty: SyncParseReturnType = { status: "dirty", value: "whatever" }; + const valid: SyncParseReturnType = { status: "valid", value: "whatever" }; + + expect(isAborted(aborted)).toBe(true); + expect(isAborted(dirty)).toBe(false); + expect(isAborted(valid)).toBe(false); + + expect(isDirty(aborted)).toBe(false); + expect(isDirty(dirty)).toBe(true); + expect(isDirty(valid)).toBe(false); + + expect(isValid(aborted)).toBe(false); + expect(isValid(dirty)).toBe(false); + expect(isValid(valid)).toBe(true); +}); diff --git a/node_modules/zod/src/v3/tests/parser.test.ts b/node_modules/zod/src/v3/tests/parser.test.ts new file mode 100644 index 000000000..6e685f9f5 --- /dev/null +++ b/node_modules/zod/src/v3/tests/parser.test.ts @@ -0,0 +1,41 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("parse strict object with unknown keys", () => { + expect(() => + z + .object({ name: z.string() }) + .strict() + .parse({ name: "bill", unknownKey: 12 } as any) + ).toThrow(); +}); + +test("parse nonstrict object with unknown keys", () => { + z.object({ name: z.string() }).nonstrict().parse({ name: "bill", unknownKey: 12 }); +}); + +test("invalid left side of intersection", () => { + expect(() => z.intersection(z.string(), z.number()).parse(12 as any)).toThrow(); +}); + +test("invalid right side of intersection", () => { + expect(() => z.intersection(z.string(), z.number()).parse("12" as any)).toThrow(); +}); + +test("parsing non-array in tuple schema", () => { + expect(() => z.tuple([]).parse("12" as any)).toThrow(); +}); + +test("incorrect num elements in tuple", () => { + expect(() => z.tuple([]).parse(["asdf"] as any)).toThrow(); +}); + +test("invalid enum value", () => { + expect(() => z.enum(["Blue"]).parse("Red" as any)).toThrow(); +}); + +test("parsing unknown", () => { + z.string().parse("Red" as unknown); +}); diff --git a/node_modules/zod/src/v3/tests/partials.test.ts b/node_modules/zod/src/v3/tests/partials.test.ts new file mode 100644 index 000000000..a2fb6ed9c --- /dev/null +++ b/node_modules/zod/src/v3/tests/partials.test.ts @@ -0,0 +1,243 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { ZodNullable, ZodOptional } from "zod/v3"; +import { util } from "../helpers/util.js"; + +const nested = z.object({ + name: z.string(), + age: z.number(), + outer: z.object({ + inner: z.string(), + }), + array: z.array(z.object({ asdf: z.string() })), +}); + +test("shallow inference", () => { + const shallow = nested.partial(); + type shallow = z.infer; + type correct = { + name?: string | undefined; + age?: number | undefined; + outer?: { inner: string } | undefined; + array?: { asdf: string }[]; + }; + util.assertEqual(true); +}); + +test("shallow partial parse", () => { + const shallow = nested.partial(); + shallow.parse({}); + shallow.parse({ + name: "asdf", + age: 23143, + }); +}); + +test("deep partial inference", () => { + const deep = nested.deepPartial(); + const asdf = deep.shape.array.unwrap().element.shape.asdf.unwrap(); + asdf.parse("asdf"); + type deep = z.infer; + type correct = { + array?: { asdf?: string }[]; + name?: string | undefined; + age?: number | undefined; + outer?: { inner?: string | undefined } | undefined; + }; + + util.assertEqual(true); +}); + +test("deep partial parse", () => { + const deep = nested.deepPartial(); + + expect(deep.shape.name instanceof z.ZodOptional).toBe(true); + expect(deep.shape.outer instanceof z.ZodOptional).toBe(true); + expect(deep.shape.outer._def.innerType instanceof z.ZodObject).toBe(true); + expect(deep.shape.outer._def.innerType.shape.inner instanceof z.ZodOptional).toBe(true); + expect(deep.shape.outer._def.innerType.shape.inner._def.innerType instanceof z.ZodString).toBe(true); +}); + +test("deep partial runtime tests", () => { + const deep = nested.deepPartial(); + deep.parse({}); + deep.parse({ + outer: {}, + }); + deep.parse({ + name: "asdf", + age: 23143, + outer: { + inner: "adsf", + }, + }); +}); + +test("deep partial optional/nullable", () => { + const schema = z + .object({ + name: z.string().optional(), + age: z.number().nullable(), + }) + .deepPartial(); + + expect(schema.shape.name.unwrap()).toBeInstanceOf(ZodOptional); + expect(schema.shape.age.unwrap()).toBeInstanceOf(ZodNullable); +}); + +test("deep partial tuple", () => { + const schema = z + .object({ + tuple: z.tuple([ + z.object({ + name: z.string().optional(), + age: z.number().nullable(), + }), + ]), + }) + .deepPartial(); + + expect(schema.shape.tuple.unwrap().items[0].shape.name).toBeInstanceOf(ZodOptional); +}); + +test("deep partial inference", () => { + const mySchema = z.object({ + name: z.string(), + array: z.array(z.object({ asdf: z.string() })), + tuple: z.tuple([z.object({ value: z.string() })]), + }); + + const partialed = mySchema.deepPartial(); + type partialed = z.infer; + type expected = { + name?: string | undefined; + array?: + | { + asdf?: string | undefined; + }[] + | undefined; + tuple?: [{ value?: string }] | undefined; + }; + util.assertEqual(true); +}); + +test("required", () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + nullableField: z.number().nullable(), + nullishField: z.string().nullish(), + }); + + const requiredObject = object.required(); + expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString); + expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNumber); + expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault); + expect(requiredObject.shape.nullableField).toBeInstanceOf(z.ZodNullable); + expect(requiredObject.shape.nullishField).toBeInstanceOf(z.ZodNullable); +}); + +test("required inference", () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + nullableField: z.number().nullable(), + nullishField: z.string().nullish(), + }); + + const requiredObject = object.required(); + + type required = z.infer; + type expected = { + name: string; + age: number; + field: string; + nullableField: number | null; + nullishField: string | null; + }; + util.assertEqual(true); +}); + +test("required with mask", () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + country: z.string().optional(), + }); + + const requiredObject = object.required({ age: true }); + expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString); + expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNumber); + expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault); + expect(requiredObject.shape.country).toBeInstanceOf(z.ZodOptional); +}); + +test("required with mask -- ignore falsy values", () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + country: z.string().optional(), + }); + + // @ts-expect-error + const requiredObject = object.required({ age: true, country: false }); + expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString); + expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNumber); + expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault); + expect(requiredObject.shape.country).toBeInstanceOf(z.ZodOptional); +}); + +test("partial with mask", async () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + country: z.string(), + }); + + const masked = object.partial({ age: true, field: true, name: true }).strict(); + + expect(masked.shape.name).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.age).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.field).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.country).toBeInstanceOf(z.ZodString); + + masked.parse({ country: "US" }); + await masked.parseAsync({ country: "US" }); +}); + +test("partial with mask -- ignore falsy values", async () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + country: z.string(), + }); + + // @ts-expect-error + const masked = object.partial({ name: true, country: false }).strict(); + + expect(masked.shape.name).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.age).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.field).toBeInstanceOf(z.ZodDefault); + expect(masked.shape.country).toBeInstanceOf(z.ZodString); + + masked.parse({ country: "US" }); + await masked.parseAsync({ country: "US" }); +}); + +test("deeppartial array", () => { + const schema = z.object({ array: z.string().array().min(42) }).deepPartial(); + + // works as expected + schema.parse({}); + + // should be false, but is true + expect(schema.safeParse({ array: [] }).success).toBe(false); +}); diff --git a/node_modules/zod/src/v3/tests/pickomit.test.ts b/node_modules/zod/src/v3/tests/pickomit.test.ts new file mode 100644 index 000000000..b1056e5af --- /dev/null +++ b/node_modules/zod/src/v3/tests/pickomit.test.ts @@ -0,0 +1,111 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const fish = z.object({ + name: z.string(), + age: z.number(), + nested: z.object({}), +}); + +test("pick type inference", () => { + const nameonlyFish = fish.pick({ name: true }); + type nameonlyFish = z.infer; + util.assertEqual(true); +}); + +test("pick parse - success", () => { + const nameonlyFish = fish.pick({ name: true }); + nameonlyFish.parse({ name: "bob" }); + + // @ts-expect-error checking runtime picks `name` only. + const anotherNameonlyFish = fish.pick({ name: true, age: false }); + anotherNameonlyFish.parse({ name: "bob" }); +}); + +test("pick parse - fail", () => { + fish.pick({ name: true }).parse({ name: "12" } as any); + fish.pick({ name: true }).parse({ name: "bob", age: 12 } as any); + fish.pick({ age: true }).parse({ age: 12 } as any); + + const nameonlyFish = fish.pick({ name: true }).strict(); + const bad1 = () => nameonlyFish.parse({ name: 12 } as any); + const bad2 = () => nameonlyFish.parse({ name: "bob", age: 12 } as any); + const bad3 = () => nameonlyFish.parse({ age: 12 } as any); + + // @ts-expect-error checking runtime picks `name` only. + const anotherNameonlyFish = fish.pick({ name: true, age: false }).strict(); + const bad4 = () => anotherNameonlyFish.parse({ name: "bob", age: 12 } as any); + + expect(bad1).toThrow(); + expect(bad2).toThrow(); + expect(bad3).toThrow(); + expect(bad4).toThrow(); +}); + +test("omit type inference", () => { + const nonameFish = fish.omit({ name: true }); + type nonameFish = z.infer; + util.assertEqual(true); +}); + +test("omit parse - success", () => { + const nonameFish = fish.omit({ name: true }); + nonameFish.parse({ age: 12, nested: {} }); + + // @ts-expect-error checking runtime omits `name` only. + const anotherNonameFish = fish.omit({ name: true, age: false }); + anotherNonameFish.parse({ age: 12, nested: {} }); +}); + +test("omit parse - fail", () => { + const nonameFish = fish.omit({ name: true }); + const bad1 = () => nonameFish.parse({ name: 12 } as any); + const bad2 = () => nonameFish.parse({ age: 12 } as any); + const bad3 = () => nonameFish.parse({} as any); + + // @ts-expect-error checking runtime omits `name` only. + const anotherNonameFish = fish.omit({ name: true, age: false }); + const bad4 = () => anotherNonameFish.parse({ nested: {} } as any); + + expect(bad1).toThrow(); + expect(bad2).toThrow(); + expect(bad3).toThrow(); + expect(bad4).toThrow(); +}); + +test("nonstrict inference", () => { + const laxfish = fish.pick({ name: true }).catchall(z.any()); + type laxfish = z.infer; + util.assertEqual(true); +}); + +test("nonstrict parsing - pass", () => { + const laxfish = fish.passthrough().pick({ name: true }); + laxfish.parse({ name: "asdf", whatever: "asdf" }); + laxfish.parse({ name: "asdf", age: 12, nested: {} }); +}); + +test("nonstrict parsing - fail", () => { + const laxfish = fish.passthrough().pick({ name: true }); + const bad = () => laxfish.parse({ whatever: "asdf" } as any); + expect(bad).toThrow(); +}); + +test("pick/omit/required/partial - do not allow unknown keys", () => { + const schema = z.object({ + name: z.string(), + age: z.number(), + }); + + // @ts-expect-error + schema.pick({ $unknown: true }); + // @ts-expect-error + schema.omit({ $unknown: true }); + // @ts-expect-error + schema.required({ $unknown: true }); + // @ts-expect-error + schema.partial({ $unknown: true }); +}); diff --git a/node_modules/zod/src/v3/tests/pipeline.test.ts b/node_modules/zod/src/v3/tests/pipeline.test.ts new file mode 100644 index 000000000..cc94fc554 --- /dev/null +++ b/node_modules/zod/src/v3/tests/pipeline.test.ts @@ -0,0 +1,29 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("string to number pipeline", () => { + const schema = z.string().transform(Number).pipe(z.number()); + expect(schema.parse("1234")).toEqual(1234); +}); + +test("string to number pipeline async", async () => { + const schema = z + .string() + .transform(async (val) => Number(val)) + .pipe(z.number()); + expect(await schema.parseAsync("1234")).toEqual(1234); +}); + +test("break if dirty", () => { + const schema = z + .string() + .refine((c) => c === "1234") + .transform(async (val) => Number(val)) + .pipe(z.number().refine((v) => v < 100)); + const r1: any = schema.safeParse("12345"); + expect(r1.error.issues.length).toBe(1); + const r2: any = schema.safeParse("3"); + expect(r2.error.issues.length).toBe(1); +}); diff --git a/node_modules/zod/src/v3/tests/preprocess.test.ts b/node_modules/zod/src/v3/tests/preprocess.test.ts new file mode 100644 index 000000000..7e1b5a1d7 --- /dev/null +++ b/node_modules/zod/src/v3/tests/preprocess.test.ts @@ -0,0 +1,186 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +test("preprocess", () => { + const schema = z.preprocess((data) => [data], z.string().array()); + + const value = schema.parse("asdf"); + expect(value).toEqual(["asdf"]); + util.assertEqual<(typeof schema)["_input"], unknown>(true); +}); + +test("async preprocess", async () => { + const schema = z.preprocess(async (data) => [data], z.string().array()); + + const value = await schema.parseAsync("asdf"); + expect(value).toEqual(["asdf"]); +}); + +test("preprocess ctx.addIssue with parse", () => { + expect(() => { + z.preprocess((data, ctx) => { + ctx.addIssue({ + code: "custom", + message: `${data} is not one of our allowed strings`, + }); + return data; + }, z.string()).parse("asdf"); + }).toThrow( + JSON.stringify( + [ + { + code: "custom", + message: "asdf is not one of our allowed strings", + path: [], + }, + ], + null, + 2 + ) + ); +}); + +test("preprocess ctx.addIssue non-fatal by default", () => { + try { + z.preprocess((data, ctx) => { + ctx.addIssue({ + code: "custom", + message: `custom error`, + }); + return data; + }, z.string()).parse(1234); + } catch (err) { + z.ZodError.assert(err); + expect(err.issues.length).toEqual(2); + } +}); + +test("preprocess ctx.addIssue fatal true", () => { + try { + z.preprocess((data, ctx) => { + ctx.addIssue({ + code: "custom", + message: `custom error`, + fatal: true, + }); + return data; + }, z.string()).parse(1234); + } catch (err) { + z.ZodError.assert(err); + expect(err.issues.length).toEqual(1); + } +}); + +test("async preprocess ctx.addIssue with parse", async () => { + const schema = z.preprocess(async (data, ctx) => { + ctx.addIssue({ + code: "custom", + message: `custom error`, + }); + return data; + }, z.string()); + + expect(await schema.safeParseAsync("asdf")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "message": "custom error", + "path": [] + } + ]], + "success": false, + } + `); +}); + +test("preprocess ctx.addIssue with parseAsync", async () => { + const result = await z + .preprocess(async (data, ctx) => { + ctx.addIssue({ + code: "custom", + message: `${data} is not one of our allowed strings`, + }); + return data; + }, z.string()) + .safeParseAsync("asdf"); + + expect(JSON.parse(JSON.stringify(result))).toEqual({ + success: false, + error: { + issues: [ + { + code: "custom", + message: "asdf is not one of our allowed strings", + path: [], + }, + ], + name: "ZodError", + }, + }); +}); + +test("z.NEVER in preprocess", () => { + const foo = z.preprocess((val, ctx) => { + if (!val) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "bad" }); + return z.NEVER; + } + return val; + }, z.number()); + + type foo = z.infer; + util.assertEqual(true); + const arg = foo.safeParse(undefined); + expect(arg.error!.issues).toHaveLength(2); + expect(arg.error!.issues[0].message).toEqual("bad"); +}); +test("preprocess as the second property of object", () => { + const schema = z.object({ + nonEmptyStr: z.string().min(1), + positiveNum: z.preprocess((v) => Number(v), z.number().positive()), + }); + const result = schema.safeParse({ + nonEmptyStr: "", + positiveNum: "", + }); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(2); + expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.too_small); + expect(result.error.issues[1].code).toEqual(z.ZodIssueCode.too_small); + } +}); + +test("preprocess validates with sibling errors", () => { + expect(() => { + z.object({ + // Must be first + missing: z.string().refine(() => false), + preprocess: z.preprocess((data: any) => data?.trim(), z.string().regex(/ asdf/)), + }).parse({ preprocess: " asdf" }); + }).toThrow( + JSON.stringify( + [ + { + code: "invalid_type", + expected: "string", + received: "undefined", + path: ["missing"], + message: "Required", + }, + { + validation: "regex", + code: "invalid_string", + message: "Invalid", + path: ["preprocess"], + }, + ], + null, + 2 + ) + ); +}); diff --git a/node_modules/zod/src/v3/tests/primitive.test.ts b/node_modules/zod/src/v3/tests/primitive.test.ts new file mode 100644 index 000000000..48e36a21c --- /dev/null +++ b/node_modules/zod/src/v3/tests/primitive.test.ts @@ -0,0 +1,440 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; +import { Mocker } from "./Mocker.js"; + +const literalStringSchema = z.literal("asdf"); +const literalNumberSchema = z.literal(12); +const literalBooleanSchema = z.literal(true); +const literalBigIntSchema = z.literal(BigInt(42)); +const MySymbol = Symbol("stuff"); +const literalSymbolSchema = z.literal(MySymbol); +const stringSchema = z.string(); +const numberSchema = z.number(); +const bigintSchema = z.bigint(); +const booleanSchema = z.boolean(); +const dateSchema = z.date(); +const symbolSchema = z.symbol(); + +const nullSchema = z.null(); +const undefinedSchema = z.undefined(); +const stringSchemaOptional = z.string().optional(); +const stringSchemaNullable = z.string().nullable(); +const numberSchemaOptional = z.number().optional(); +const numberSchemaNullable = z.number().nullable(); +const bigintSchemaOptional = z.bigint().optional(); +const bigintSchemaNullable = z.bigint().nullable(); +const booleanSchemaOptional = z.boolean().optional(); +const booleanSchemaNullable = z.boolean().nullable(); +const dateSchemaOptional = z.date().optional(); +const dateSchemaNullable = z.date().nullable(); +const symbolSchemaOptional = z.symbol().optional(); +const symbolSchemaNullable = z.symbol().nullable(); + +const val = new Mocker(); + +test("literal string correct", () => { + expect(literalStringSchema.parse("asdf")).toBe("asdf"); +}); + +test("literal string incorrect", () => { + const f = () => literalStringSchema.parse("not_asdf"); + expect(f).toThrow(); +}); + +test("literal string number", () => { + const f = () => literalStringSchema.parse(123); + expect(f).toThrow(); +}); + +test("literal string boolean", () => { + const f = () => literalStringSchema.parse(true); + expect(f).toThrow(); +}); + +test("literal string boolean", () => { + const f = () => literalStringSchema.parse(true); + expect(f).toThrow(); +}); + +test("literal string object", () => { + const f = () => literalStringSchema.parse({}); + expect(f).toThrow(); +}); + +test("literal number correct", () => { + expect(literalNumberSchema.parse(12)).toBe(12); +}); + +test("literal number incorrect", () => { + const f = () => literalNumberSchema.parse(13); + expect(f).toThrow(); +}); + +test("literal number number", () => { + const f = () => literalNumberSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("literal number boolean", () => { + const f = () => literalNumberSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("literal number object", () => { + const f = () => literalStringSchema.parse({}); + expect(f).toThrow(); +}); + +test("literal boolean correct", () => { + expect(literalBooleanSchema.parse(true)).toBe(true); +}); + +test("literal boolean incorrect", () => { + const f = () => literalBooleanSchema.parse(false); + expect(f).toThrow(); +}); + +test("literal boolean number", () => { + const f = () => literalBooleanSchema.parse("asdf"); + expect(f).toThrow(); +}); + +test("literal boolean boolean", () => { + const f = () => literalBooleanSchema.parse(123); + expect(f).toThrow(); +}); + +test("literal boolean object", () => { + const f = () => literalBooleanSchema.parse({}); + expect(f).toThrow(); +}); + +test("literal bigint correct", () => { + expect(literalBigIntSchema.parse(BigInt(42))).toBe(BigInt(42)); +}); + +test("literal bigint incorrect", () => { + const f = () => literalBigIntSchema.parse(BigInt(43)); + expect(f).toThrow(); +}); + +test("literal bigint number", () => { + const f = () => literalBigIntSchema.parse("asdf"); + expect(f).toThrow(); +}); + +test("literal bigint boolean", () => { + const f = () => literalBigIntSchema.parse(123); + expect(f).toThrow(); +}); + +test("literal bigint object", () => { + const f = () => literalBigIntSchema.parse({}); + expect(f).toThrow(); +}); + +test("literal symbol", () => { + util.assertEqual, typeof MySymbol>(true); + literalSymbolSchema.parse(MySymbol); + expect(() => literalSymbolSchema.parse(Symbol("asdf"))).toThrow(); +}); + +test("parse stringSchema string", () => { + stringSchema.parse(val.string); +}); + +test("parse stringSchema number", () => { + const f = () => stringSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse stringSchema boolean", () => { + const f = () => stringSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse stringSchema undefined", () => { + const f = () => stringSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse stringSchema null", () => { + const f = () => stringSchema.parse(val.null); + expect(f).toThrow(); +}); + +test("parse numberSchema string", () => { + const f = () => numberSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse numberSchema number", () => { + numberSchema.parse(val.number); +}); + +test("parse numberSchema bigint", () => { + const f = () => numberSchema.parse(val.bigint); + expect(f).toThrow(); +}); + +test("parse numberSchema boolean", () => { + const f = () => numberSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse numberSchema undefined", () => { + const f = () => numberSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse numberSchema null", () => { + const f = () => numberSchema.parse(val.null); + expect(f).toThrow(); +}); + +test("parse bigintSchema string", () => { + const f = () => bigintSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse bigintSchema number", () => { + const f = () => bigintSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse bigintSchema bigint", () => { + bigintSchema.parse(val.bigint); +}); + +test("parse bigintSchema boolean", () => { + const f = () => bigintSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse bigintSchema undefined", () => { + const f = () => bigintSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse bigintSchema null", () => { + const f = () => bigintSchema.parse(val.null); + expect(f).toThrow(); +}); + +test("parse booleanSchema string", () => { + const f = () => booleanSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse booleanSchema number", () => { + const f = () => booleanSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse booleanSchema boolean", () => { + booleanSchema.parse(val.boolean); +}); + +test("parse booleanSchema undefined", () => { + const f = () => booleanSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse booleanSchema null", () => { + const f = () => booleanSchema.parse(val.null); + expect(f).toThrow(); +}); + +// ============== + +test("parse dateSchema string", () => { + const f = () => dateSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse dateSchema number", () => { + const f = () => dateSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse dateSchema boolean", () => { + const f = () => dateSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse dateSchema date", () => { + dateSchema.parse(val.date); +}); + +test("parse dateSchema undefined", () => { + const f = () => dateSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse dateSchema null", () => { + const f = () => dateSchema.parse(val.null); + expect(f).toThrow(); +}); + +test("parse dateSchema invalid date", async () => { + try { + await dateSchema.parseAsync(new Date("invalid")); + } catch (err) { + expect((err as z.ZodError).issues[0].code).toEqual(z.ZodIssueCode.invalid_date); + } +}); +// ============== + +test("parse symbolSchema string", () => { + const f = () => symbolSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse symbolSchema number", () => { + const f = () => symbolSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse symbolSchema boolean", () => { + const f = () => symbolSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse symbolSchema date", () => { + const f = () => symbolSchema.parse(val.date); + expect(f).toThrow(); +}); + +test("parse symbolSchema symbol", () => { + symbolSchema.parse(val.symbol); +}); + +test("parse symbolSchema undefined", () => { + const f = () => symbolSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse symbolSchema null", () => { + const f = () => symbolSchema.parse(val.null); + expect(f).toThrow(); +}); + +// ============== + +test("parse undefinedSchema string", () => { + const f = () => undefinedSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse undefinedSchema number", () => { + const f = () => undefinedSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse undefinedSchema boolean", () => { + const f = () => undefinedSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse undefinedSchema undefined", () => { + undefinedSchema.parse(val.undefined); +}); + +test("parse undefinedSchema null", () => { + const f = () => undefinedSchema.parse(val.null); + expect(f).toThrow(); +}); + +test("parse nullSchema string", () => { + const f = () => nullSchema.parse(val.string); + expect(f).toThrow(); +}); + +test("parse nullSchema number", () => { + const f = () => nullSchema.parse(val.number); + expect(f).toThrow(); +}); + +test("parse nullSchema boolean", () => { + const f = () => nullSchema.parse(val.boolean); + expect(f).toThrow(); +}); + +test("parse nullSchema undefined", () => { + const f = () => nullSchema.parse(val.undefined); + expect(f).toThrow(); +}); + +test("parse nullSchema null", () => { + nullSchema.parse(val.null); +}); + +test("primitive inference", () => { + util.assertEqual, "asdf">(true); + util.assertEqual, 12>(true); + util.assertEqual, true>(true); + util.assertEqual, bigint>(true); + util.assertEqual, string>(true); + util.assertEqual, number>(true); + util.assertEqual, bigint>(true); + util.assertEqual, boolean>(true); + util.assertEqual, Date>(true); + util.assertEqual, symbol>(true); + + util.assertEqual, null>(true); + util.assertEqual, undefined>(true); + util.assertEqual, string | undefined>(true); + util.assertEqual, string | null>(true); + util.assertEqual, number | undefined>(true); + util.assertEqual, number | null>(true); + util.assertEqual, bigint | undefined>(true); + util.assertEqual, bigint | null>(true); + util.assertEqual, boolean | undefined>(true); + util.assertEqual, boolean | null>(true); + util.assertEqual, Date | undefined>(true); + util.assertEqual, Date | null>(true); + util.assertEqual, symbol | undefined>(true); + util.assertEqual, symbol | null>(true); + + // [ + // literalStringSchemaTest, + // literalNumberSchemaTest, + // literalBooleanSchemaTest, + // literalBigIntSchemaTest, + // stringSchemaTest, + // numberSchemaTest, + // bigintSchemaTest, + // booleanSchemaTest, + // dateSchemaTest, + // symbolSchemaTest, + + // nullSchemaTest, + // undefinedSchemaTest, + // stringSchemaOptionalTest, + // stringSchemaNullableTest, + // numberSchemaOptionalTest, + // numberSchemaNullableTest, + // bigintSchemaOptionalTest, + // bigintSchemaNullableTest, + // booleanSchemaOptionalTest, + // booleanSchemaNullableTest, + // dateSchemaOptionalTest, + // dateSchemaNullableTest, + // symbolSchemaOptionalTest, + // symbolSchemaNullableTest, + + // ]; +}); + +test("get literal value", () => { + expect(literalStringSchema.value).toEqual("asdf"); +}); + +test("optional convenience method", () => { + z.ostring().parse(undefined); + z.onumber().parse(undefined); + z.oboolean().parse(undefined); +}); diff --git a/node_modules/zod/src/v3/tests/promise.test.ts b/node_modules/zod/src/v3/tests/promise.test.ts new file mode 100644 index 000000000..23b6de178 --- /dev/null +++ b/node_modules/zod/src/v3/tests/promise.test.ts @@ -0,0 +1,90 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const promSchema = z.promise( + z.object({ + name: z.string(), + age: z.number(), + }) +); + +test("promise inference", () => { + type promSchemaType = z.infer; + util.assertEqual>(true); +}); + +test("promise parsing success", async () => { + const pr = promSchema.parse(Promise.resolve({ name: "Bobby", age: 10 })); + expect(pr).toBeInstanceOf(Promise); + const result = await pr; + expect(typeof result).toBe("object"); + expect(typeof result.age).toBe("number"); + expect(typeof result.name).toBe("string"); +}); + +test("promise parsing success 2", () => { + const fakePromise = { + then() { + return this; + }, + catch() { + return this; + }, + }; + promSchema.parse(fakePromise); +}); + +test("promise parsing fail", async () => { + const bad = promSchema.parse(Promise.resolve({ name: "Bobby", age: "10" })); + // return await expect(bad).resolves.toBe({ name: 'Bobby', age: '10' }); + return await expect(bad).rejects.toBeInstanceOf(z.ZodError); + // done(); +}); + +test("promise parsing fail 2", async () => { + const failPromise = promSchema.parse(Promise.resolve({ name: "Bobby", age: "10" })); + await expect(failPromise).rejects.toBeInstanceOf(z.ZodError); + // done();/z +}); + +test("promise parsing fail", () => { + const bad = () => promSchema.parse({ then: () => {}, catch: {} }); + expect(bad).toThrow(); +}); + +// test('sync promise parsing', () => { +// expect(() => z.promise(z.string()).parse(Promise.resolve('asfd'))).toThrow(); +// }); + +const asyncFunction = z.function(z.tuple([]), promSchema); + +test("async function pass", async () => { + const validatedFunction = asyncFunction.implement(async () => { + return { name: "jimmy", age: 14 }; + }); + await expect(validatedFunction()).resolves.toEqual({ + name: "jimmy", + age: 14, + }); +}); + +test("async function fail", async () => { + const validatedFunction = asyncFunction.implement(() => { + return Promise.resolve("asdf" as any); + }); + await expect(validatedFunction()).rejects.toBeInstanceOf(z.ZodError); +}); + +test("async promise parsing", () => { + const res = z.promise(z.number()).parseAsync(Promise.resolve(12)); + expect(res).toBeInstanceOf(Promise); +}); + +test("resolves", () => { + const foo = z.literal("foo"); + const res = z.promise(foo); + expect(res.unwrap()).toEqual(foo); +}); diff --git a/node_modules/zod/src/v3/tests/readonly.test.ts b/node_modules/zod/src/v3/tests/readonly.test.ts new file mode 100644 index 000000000..5078955f4 --- /dev/null +++ b/node_modules/zod/src/v3/tests/readonly.test.ts @@ -0,0 +1,194 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +enum testEnum { + A = 0, + B = 1, +} + +const schemas = [ + z.string().readonly(), + z.number().readonly(), + z.nan().readonly(), + z.bigint().readonly(), + z.boolean().readonly(), + z.date().readonly(), + z.undefined().readonly(), + z.null().readonly(), + z.any().readonly(), + z.unknown().readonly(), + z.void().readonly(), + z.function().args(z.string(), z.number()).readonly(), + + z.array(z.string()).readonly(), + z.tuple([z.string(), z.number()]).readonly(), + z.map(z.string(), z.date()).readonly(), + z.set(z.promise(z.string())).readonly(), + z.record(z.string()).readonly(), + z.record(z.string(), z.number()).readonly(), + z.object({ a: z.string(), 1: z.number() }).readonly(), + z.nativeEnum(testEnum).readonly(), + z.promise(z.string()).readonly(), +] as const; + +test("flat inference", () => { + util.assertEqual, string>(true); + util.assertEqual, number>(true); + util.assertEqual, number>(true); + util.assertEqual, bigint>(true); + util.assertEqual, boolean>(true); + util.assertEqual, Date>(true); + util.assertEqual, undefined>(true); + util.assertEqual, null>(true); + util.assertEqual, any>(true); + util.assertEqual, Readonly>(true); + util.assertEqual, void>(true); + util.assertEqual, (args_0: string, args_1: number, ...args_2: unknown[]) => unknown>( + true + ); + util.assertEqual, readonly string[]>(true); + + util.assertEqual, readonly [string, number]>(true); + util.assertEqual, ReadonlyMap>(true); + util.assertEqual, ReadonlySet>>(true); + util.assertEqual, Readonly>>(true); + util.assertEqual, Readonly>>(true); + util.assertEqual, { readonly a: string; readonly 1: number }>(true); + util.assertEqual, Readonly>(true); + util.assertEqual, Promise>(true); +}); + +// test("deep inference", () => { +// util.assertEqual, string>(true); +// util.assertEqual, number>(true); +// util.assertEqual, number>(true); +// util.assertEqual, bigint>(true); +// util.assertEqual, boolean>(true); +// util.assertEqual, Date>(true); +// util.assertEqual, undefined>(true); +// util.assertEqual, null>(true); +// util.assertEqual, any>(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[9]>, +// Readonly +// >(true); +// util.assertEqual, void>(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[11]>, +// (args_0: string, args_1: number, ...args_2: unknown[]) => unknown +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[12]>, +// readonly string[] +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[13]>, +// readonly [string, number] +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[14]>, +// ReadonlyMap +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[15]>, +// ReadonlySet> +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[16]>, +// Readonly> +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[17]>, +// Readonly> +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[18]>, +// { readonly a: string; readonly 1: number } +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[19]>, +// Readonly +// >(true); +// util.assertEqual< +// z.infer<(typeof deepReadonlySchemas_0)[20]>, +// Promise +// >(true); + +// util.assertEqual< +// z.infer, +// ReadonlyMap< +// ReadonlySet, +// { +// readonly a: { +// readonly [x: string]: readonly any[]; +// }; +// readonly b: { +// readonly c: { +// readonly d: { +// readonly e: { +// readonly f: { +// readonly g?: {}; +// }; +// }; +// }; +// }; +// }; +// } +// > +// >(true); +// }); + +test("object freezing", () => { + expect(Object.isFrozen(z.array(z.string()).readonly().parse(["a"]))).toBe(true); + expect(Object.isFrozen(z.tuple([z.string(), z.number()]).readonly().parse(["a", 1]))).toBe(true); + expect( + Object.isFrozen( + z + .map(z.string(), z.date()) + .readonly() + .parse(new Map([["a", new Date()]])) + ) + ).toBe(true); + expect( + Object.isFrozen( + z + .set(z.promise(z.string())) + .readonly() + .parse(new Set([Promise.resolve("a")])) + ) + ).toBe(true); + expect(Object.isFrozen(z.record(z.string()).readonly().parse({ a: "b" }))).toBe(true); + expect(Object.isFrozen(z.record(z.string(), z.number()).readonly().parse({ a: 1 }))).toBe(true); + expect(Object.isFrozen(z.object({ a: z.string(), 1: z.number() }).readonly().parse({ a: "b", 1: 2 }))).toBe(true); + expect(Object.isFrozen(z.promise(z.string()).readonly().parse(Promise.resolve("a")))).toBe(true); +}); + +test("async object freezing", async () => { + expect(Object.isFrozen(await z.array(z.string()).readonly().parseAsync(["a"]))).toBe(true); + expect(Object.isFrozen(await z.tuple([z.string(), z.number()]).readonly().parseAsync(["a", 1]))).toBe(true); + expect( + Object.isFrozen( + await z + .map(z.string(), z.date()) + .readonly() + .parseAsync(new Map([["a", new Date()]])) + ) + ).toBe(true); + expect( + Object.isFrozen( + await z + .set(z.promise(z.string())) + .readonly() + .parseAsync(new Set([Promise.resolve("a")])) + ) + ).toBe(true); + expect(Object.isFrozen(await z.record(z.string()).readonly().parseAsync({ a: "b" }))).toBe(true); + expect(Object.isFrozen(await z.record(z.string(), z.number()).readonly().parseAsync({ a: 1 }))).toBe(true); + expect( + Object.isFrozen(await z.object({ a: z.string(), 1: z.number() }).readonly().parseAsync({ a: "b", 1: 2 })) + ).toBe(true); + expect(Object.isFrozen(await z.promise(z.string()).readonly().parseAsync(Promise.resolve("a")))).toBe(true); +}); diff --git a/node_modules/zod/src/v3/tests/record.test.ts b/node_modules/zod/src/v3/tests/record.test.ts new file mode 100644 index 000000000..83c363f33 --- /dev/null +++ b/node_modules/zod/src/v3/tests/record.test.ts @@ -0,0 +1,171 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const booleanRecord = z.record(z.boolean()); +type booleanRecord = z.infer; + +const recordWithEnumKeys = z.record(z.enum(["Tuna", "Salmon"]), z.string()); +type recordWithEnumKeys = z.infer; + +const recordWithLiteralKeys = z.record(z.union([z.literal("Tuna"), z.literal("Salmon")]), z.string()); +type recordWithLiteralKeys = z.infer; + +test("type inference", () => { + util.assertEqual>(true); + + util.assertEqual>>(true); + + util.assertEqual>>(true); +}); + +test("methods", () => { + booleanRecord.optional(); + booleanRecord.nullable(); +}); + +test("string record parse - pass", () => { + booleanRecord.parse({ + k1: true, + k2: false, + 1234: false, + }); +}); + +test("string record parse - fail", () => { + const badCheck = () => + booleanRecord.parse({ + asdf: 1234, + } as any); + expect(badCheck).toThrow(); + + expect(() => booleanRecord.parse("asdf")).toThrow(); +}); + +test("string record parse - fail", () => { + const badCheck = () => + booleanRecord.parse({ + asdf: {}, + } as any); + expect(badCheck).toThrow(); +}); + +test("string record parse - fail", () => { + const badCheck = () => + booleanRecord.parse({ + asdf: [], + } as any); + expect(badCheck).toThrow(); +}); + +test("key schema", () => { + const result1 = recordWithEnumKeys.parse({ + Tuna: "asdf", + Salmon: "asdf", + }); + expect(result1).toEqual({ + Tuna: "asdf", + Salmon: "asdf", + }); + + const result2 = recordWithLiteralKeys.parse({ + Tuna: "asdf", + Salmon: "asdf", + }); + expect(result2).toEqual({ + Tuna: "asdf", + Salmon: "asdf", + }); + + // shouldn't require us to specify all props in record + const result3 = recordWithEnumKeys.parse({ + Tuna: "abcd", + }); + expect(result3).toEqual({ + Tuna: "abcd", + }); + + // shouldn't require us to specify all props in record + const result4 = recordWithLiteralKeys.parse({ + Salmon: "abcd", + }); + expect(result4).toEqual({ + Salmon: "abcd", + }); + + expect(() => + recordWithEnumKeys.parse({ + Tuna: "asdf", + Salmon: "asdf", + Trout: "asdf", + }) + ).toThrow(); + + expect(() => + recordWithLiteralKeys.parse({ + Tuna: "asdf", + Salmon: "asdf", + + Trout: "asdf", + }) + ).toThrow(); +}); + +// test("record element", () => { +// expect(booleanRecord.element).toBeInstanceOf(z.ZodBoolean); +// }); + +test("key and value getters", () => { + const rec = z.record(z.string(), z.number()); + + rec.keySchema.parse("asdf"); + rec.valueSchema.parse(1234); + rec.element.parse(1234); +}); + +test("is not vulnerable to prototype pollution", async () => { + const rec = z.record( + z.object({ + a: z.string(), + }) + ); + + const data = JSON.parse(` + { + "__proto__": { + "a": "evil" + }, + "b": { + "a": "good" + } + } + `); + + const obj1 = rec.parse(data); + expect(obj1.a).toBeUndefined(); + + const obj2 = rec.safeParse(data); + expect(obj2.success).toBe(true); + if (obj2.success) { + expect(obj2.data.a).toBeUndefined(); + } + + const obj3 = await rec.parseAsync(data); + expect(obj3.a).toBeUndefined(); + + const obj4 = await rec.safeParseAsync(data); + expect(obj4.success).toBe(true); + if (obj4.success) { + expect(obj4.data.a).toBeUndefined(); + } +}); + +test("dont parse undefined values", () => { + const result1 = z.record(z.any()).parse({ foo: undefined }); + + expect(result1).toEqual({ + foo: undefined, + }); +}); diff --git a/node_modules/zod/src/v3/tests/recursive.test.ts b/node_modules/zod/src/v3/tests/recursive.test.ts new file mode 100644 index 000000000..f5bb1088a --- /dev/null +++ b/node_modules/zod/src/v3/tests/recursive.test.ts @@ -0,0 +1,197 @@ +// @ts-ignore TS6133 +import { test } from "vitest"; + +import { z } from "zod/v3"; + +interface Category { + name: string; + subcategories: Category[]; +} + +const testCategory: Category = { + name: "I", + subcategories: [ + { + name: "A", + subcategories: [ + { + name: "1", + subcategories: [ + { + name: "a", + subcategories: [], + }, + ], + }, + ], + }, + ], +}; + +test("recursion with z.late.object", () => { + const Category: z.ZodType = z.late.object(() => ({ + name: z.string(), + subcategories: z.array(Category), + })); + Category.parse(testCategory); +}); + +test("recursion with z.lazy", () => { + const Category: z.ZodType = z.lazy(() => + z.object({ + name: z.string(), + subcategories: z.array(Category), + }) + ); + Category.parse(testCategory); +}); + +test("schema getter", () => { + z.lazy(() => z.string()).schema.parse("asdf"); +}); + +type LinkedList = null | { value: number; next: LinkedList }; + +const linkedListExample = { + value: 1, + next: { + value: 2, + next: { + value: 3, + next: { + value: 4, + next: null, + }, + }, + }, +}; + +test("recursion involving union type", () => { + const LinkedListSchema: z.ZodType = z.lazy(() => + z.union([ + z.null(), + z.object({ + value: z.number(), + next: LinkedListSchema, + }), + ]) + ); + LinkedListSchema.parse(linkedListExample); +}); + +// interface A { +// val: number; +// b: B; +// } + +// interface B { +// val: number; +// a: A; +// } + +// const A: z.ZodType = z.late.object(() => ({ +// val: z.number(), +// b: B, +// })); + +// const B: z.ZodType = z.late.object(() => ({ +// val: z.number(), +// a: A, +// })); + +// const Alazy: z.ZodType = z.lazy(() => z.object({ +// val: z.number(), +// b: B, +// })); + +// const Blazy: z.ZodType = z.lazy(() => z.object({ +// val: z.number(), +// a: A, +// })); + +// const a: any = { val: 1 }; +// const b: any = { val: 2 }; +// a.b = b; +// b.a = a; + +// test('valid check', () => { +// A.parse(a); +// B.parse(b); +// }); + +// test("valid check lazy", () => { +// A.parse({val:1, b:}); +// B.parse(b); +// }); + +// test('masking check', () => { +// const FragmentOnA = z +// .object({ +// val: z.number(), +// b: z +// .object({ +// val: z.number(), +// a: z +// .object({ +// val: z.number(), +// }) +// .nonstrict(), +// }) +// .nonstrict(), +// }) +// .nonstrict(); + +// const fragment = FragmentOnA.parse(a); +// fragment; +// }); + +// test('invalid check', () => { +// expect(() => A.parse({} as any)).toThrow(); +// }); + +// test('schema getter', () => { +// (A as z.ZodLazy).schema; +// }); + +// test("self recursion with cyclical data", () => { +// interface Category { +// name: string; +// subcategories: Category[]; +// } + +// const Category: z.ZodType = z.late.object(() => ({ +// name: z.string(), +// subcategories: z.array(Category), +// })); + +// const untypedCategory: any = { +// name: "Category A", +// }; +// // creating a cycle +// untypedCategory.subcategories = [untypedCategory]; +// Category.parse(untypedCategory); +// }); + +// test("self recursion with base type", () => { +// const BaseCategory = z.object({ +// name: z.string(), +// }); +// type BaseCategory = z.infer; + +// type Category = BaseCategory & { subcategories: Category[] }; + +// const Category: z.ZodType = z.late +// .object(() => ({ +// subcategories: z.array(Category), +// })) +// .extend({ +// name: z.string(), +// }); + +// const untypedCategory: any = { +// name: "Category A", +// }; +// // creating a cycle +// untypedCategory.subcategories = [untypedCategory]; +// Category.parse(untypedCategory); // parses successfully +// }); diff --git a/node_modules/zod/src/v3/tests/refine.test.ts b/node_modules/zod/src/v3/tests/refine.test.ts new file mode 100644 index 000000000..55c27fea5 --- /dev/null +++ b/node_modules/zod/src/v3/tests/refine.test.ts @@ -0,0 +1,313 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { ZodIssueCode } from "../ZodError.js"; +import { util } from "../helpers/util.js"; + +test("refinement", () => { + const obj1 = z.object({ + first: z.string(), + second: z.string(), + }); + const obj2 = obj1.partial().strict(); + + const obj3 = obj2.refine((data) => data.first || data.second, "Either first or second should be filled in."); + + expect(obj1 === (obj2 as any)).toEqual(false); + expect(obj2 === (obj3 as any)).toEqual(false); + + expect(() => obj1.parse({})).toThrow(); + expect(() => obj2.parse({ third: "adsf" })).toThrow(); + expect(() => obj3.parse({})).toThrow(); + obj3.parse({ first: "a" }); + obj3.parse({ second: "a" }); + obj3.parse({ first: "a", second: "a" }); +}); + +test("refinement 2", () => { + const validationSchema = z + .object({ + email: z.string().email(), + password: z.string(), + confirmPassword: z.string(), + }) + .refine((data) => data.password === data.confirmPassword, "Both password and confirmation must match"); + + expect(() => + validationSchema.parse({ + email: "aaaa@gmail.com", + password: "aaaaaaaa", + confirmPassword: "bbbbbbbb", + }) + ).toThrow(); +}); + +test("refinement type guard", () => { + const validationSchema = z.object({ + a: z.string().refine((s): s is "a" => s === "a"), + }); + type Input = z.input; + type Schema = z.infer; + + util.assertEqual<"a", Input["a"]>(false); + util.assertEqual(true); + + util.assertEqual<"a", Schema["a"]>(true); + util.assertEqual(false); +}); + +test("refinement Promise", async () => { + const validationSchema = z + .object({ + email: z.string().email(), + password: z.string(), + confirmPassword: z.string(), + }) + .refine( + (data) => Promise.resolve().then(() => data.password === data.confirmPassword), + "Both password and confirmation must match" + ); + + await validationSchema.parseAsync({ + email: "aaaa@gmail.com", + password: "password", + confirmPassword: "password", + }); +}); + +test("custom path", async () => { + const result = await z + .object({ + password: z.string(), + confirm: z.string(), + }) + .refine((data) => data.confirm === data.password, { path: ["confirm"] }) + .spa({ password: "asdf", confirm: "qewr" }); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].path).toEqual(["confirm"]); + } +}); + +test("use path in refinement context", async () => { + const noNested = z.string()._refinement((_val, ctx) => { + if (ctx.path.length > 0) { + ctx.addIssue({ + code: ZodIssueCode.custom, + message: `schema cannot be nested. path: ${ctx.path.join(".")}`, + }); + return false; + } else { + return true; + } + }); + + const data = z.object({ + foo: noNested, + }); + + const t1 = await noNested.spa("asdf"); + const t2 = await data.spa({ foo: "asdf" }); + + expect(t1.success).toBe(true); + expect(t2.success).toBe(false); + if (t2.success === false) { + expect(t2.error.issues[0].message).toEqual("schema cannot be nested. path: foo"); + } +}); + +test("superRefine", () => { + const Strings = z.array(z.string()).superRefine((val, ctx) => { + if (val.length > 3) { + ctx.addIssue({ + code: z.ZodIssueCode.too_big, + maximum: 3, + type: "array", + inclusive: true, + exact: true, + message: "Too many items 😡", + }); + } + + if (val.length !== new Set(val).size) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `No duplicates allowed.`, + }); + } + }); + + const result = Strings.safeParse(["asfd", "asfd", "asfd", "asfd"]); + + expect(result.success).toEqual(false); + if (!result.success) expect(result.error.issues.length).toEqual(2); + + Strings.parse(["asfd", "qwer"]); +}); + +test("superRefine async", async () => { + const Strings = z.array(z.string()).superRefine(async (val, ctx) => { + if (val.length > 3) { + ctx.addIssue({ + code: z.ZodIssueCode.too_big, + maximum: 3, + type: "array", + inclusive: true, + exact: true, + message: "Too many items 😡", + }); + } + + if (val.length !== new Set(val).size) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `No duplicates allowed.`, + }); + } + }); + + const result = await Strings.safeParseAsync(["asfd", "asfd", "asfd", "asfd"]); + + expect(result.success).toEqual(false); + if (!result.success) expect(result.error.issues.length).toEqual(2); + + Strings.parseAsync(["asfd", "qwer"]); +}); + +test("superRefine - type narrowing", () => { + type NarrowType = { type: string; age: number }; + const schema = z + .object({ + type: z.string(), + age: z.number(), + }) + .nullable() + .superRefine((arg, ctx): arg is NarrowType => { + if (!arg) { + // still need to make a call to ctx.addIssue + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "cannot be null", + fatal: true, + }); + return false; + } + return true; + }); + + util.assertEqual, NarrowType>(true); + + expect(schema.safeParse({ type: "test", age: 0 }).success).toEqual(true); + expect(schema.safeParse(null).success).toEqual(false); +}); + +test("chained mixed refining types", () => { + type firstRefinement = { first: string; second: number; third: true }; + type secondRefinement = { first: "bob"; second: number; third: true }; + type thirdRefinement = { first: "bob"; second: 33; third: true }; + const schema = z + .object({ + first: z.string(), + second: z.number(), + third: z.boolean(), + }) + .nullable() + .refine((arg): arg is firstRefinement => !!arg?.third) + .superRefine((arg, ctx): arg is secondRefinement => { + util.assertEqual(true); + if (arg.first !== "bob") { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "`first` property must be `bob`", + }); + return false; + } + return true; + }) + .refine((arg): arg is thirdRefinement => { + util.assertEqual(true); + return arg.second === 33; + }); + + util.assertEqual, thirdRefinement>(true); +}); + +test("get inner type", () => { + z.string() + .refine(() => true) + .innerType() + .parse("asdf"); +}); + +test("chained refinements", () => { + const objectSchema = z + .object({ + length: z.number(), + size: z.number(), + }) + .refine(({ length }) => length > 5, { + path: ["length"], + message: "length greater than 5", + }) + .refine(({ size }) => size > 7, { + path: ["size"], + message: "size greater than 7", + }); + const r1 = objectSchema.safeParse({ + length: 4, + size: 9, + }); + expect(r1.success).toEqual(false); + if (!r1.success) expect(r1.error.issues.length).toEqual(1); + + const r2 = objectSchema.safeParse({ + length: 4, + size: 3, + }); + expect(r2.success).toEqual(false); + if (!r2.success) expect(r2.error.issues.length).toEqual(2); +}); + +test("fatal superRefine", () => { + const Strings = z + .string() + .superRefine((val, ctx) => { + if (val === "") { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "foo", + fatal: true, + }); + } + }) + .superRefine((val, ctx) => { + if (val !== " ") { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "bar", + }); + } + }); + + const result = Strings.safeParse(""); + + expect(result.success).toEqual(false); + if (!result.success) expect(result.error.issues.length).toEqual(1); +}); + +test("superRefine after skipped transform", () => { + const schema = z + .string() + .regex(/^\d+$/) + .transform((val) => Number(val)) + .superRefine((val) => { + if (typeof val !== "number") { + throw new Error("Called without transform"); + } + }); + + const result = schema.safeParse(""); + + expect(result.success).toEqual(false); +}); diff --git a/node_modules/zod/src/v3/tests/safeparse.test.ts b/node_modules/zod/src/v3/tests/safeparse.test.ts new file mode 100644 index 000000000..950a2df5e --- /dev/null +++ b/node_modules/zod/src/v3/tests/safeparse.test.ts @@ -0,0 +1,27 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +const stringSchema = z.string(); + +test("safeparse fail", () => { + const safe = stringSchema.safeParse(12); + expect(safe.success).toEqual(false); + expect(safe.error).toBeInstanceOf(z.ZodError); +}); + +test("safeparse pass", () => { + const safe = stringSchema.safeParse("12"); + expect(safe.success).toEqual(true); + expect(safe.data).toEqual("12"); +}); + +test("safeparse unexpected error", () => { + expect(() => + stringSchema + .refine((data) => { + throw new Error(data); + }) + .safeParse("12") + ).toThrow(); +}); diff --git a/node_modules/zod/src/v3/tests/set.test.ts b/node_modules/zod/src/v3/tests/set.test.ts new file mode 100644 index 000000000..890cdd205 --- /dev/null +++ b/node_modules/zod/src/v3/tests/set.test.ts @@ -0,0 +1,142 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { ZodIssueCode } from "zod/v3"; +import { util } from "../helpers/util.js"; + +const stringSet = z.set(z.string()); +type stringSet = z.infer; + +const minTwo = z.set(z.string()).min(2); +const maxTwo = z.set(z.string()).max(2); +const justTwo = z.set(z.string()).size(2); +const nonEmpty = z.set(z.string()).nonempty(); +const nonEmptyMax = z.set(z.string()).nonempty().max(2); + +test("type inference", () => { + util.assertEqual>(true); +}); + +test("valid parse", () => { + const result = stringSet.safeParse(new Set(["first", "second"])); + expect(result.success).toEqual(true); + if (result.success) { + expect(result.data.has("first")).toEqual(true); + expect(result.data.has("second")).toEqual(true); + expect(result.data.has("third")).toEqual(false); + } + + expect(() => { + minTwo.parse(new Set(["a", "b"])); + minTwo.parse(new Set(["a", "b", "c"])); + maxTwo.parse(new Set(["a", "b"])); + maxTwo.parse(new Set(["a"])); + justTwo.parse(new Set(["a", "b"])); + nonEmpty.parse(new Set(["a"])); + nonEmptyMax.parse(new Set(["a"])); + }).not.toThrow(); +}); + +test("valid parse async", async () => { + const result = await stringSet.spa(new Set(["first", "second"])); + expect(result.success).toEqual(true); + if (result.success) { + expect(result.data.has("first")).toEqual(true); + expect(result.data.has("second")).toEqual(true); + expect(result.data.has("third")).toEqual(false); + } + + const asyncResult = await stringSet.safeParse(new Set(["first", "second"])); + expect(asyncResult.success).toEqual(true); + if (asyncResult.success) { + expect(asyncResult.data.has("first")).toEqual(true); + expect(asyncResult.data.has("second")).toEqual(true); + expect(asyncResult.data.has("third")).toEqual(false); + } +}); + +test("valid parse: size-related methods", () => { + expect(() => { + minTwo.parse(new Set(["a", "b"])); + minTwo.parse(new Set(["a", "b", "c"])); + maxTwo.parse(new Set(["a", "b"])); + maxTwo.parse(new Set(["a"])); + justTwo.parse(new Set(["a", "b"])); + nonEmpty.parse(new Set(["a"])); + nonEmptyMax.parse(new Set(["a"])); + }).not.toThrow(); + + const sizeZeroResult = stringSet.parse(new Set()); + expect(sizeZeroResult.size).toBe(0); + + const sizeTwoResult = minTwo.parse(new Set(["a", "b"])); + expect(sizeTwoResult.size).toBe(2); +}); + +test("failing when parsing empty set in nonempty ", () => { + const result = nonEmpty.safeParse(new Set()); + expect(result.success).toEqual(false); + + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.too_small); + } +}); + +test("failing when set is smaller than min() ", () => { + const result = minTwo.safeParse(new Set(["just_one"])); + expect(result.success).toEqual(false); + + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.too_small); + } +}); + +test("failing when set is bigger than max() ", () => { + const result = maxTwo.safeParse(new Set(["one", "two", "three"])); + expect(result.success).toEqual(false); + + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.too_big); + } +}); + +test("doesn’t throw when an empty set is given", () => { + const result = stringSet.safeParse(new Set([])); + expect(result.success).toEqual(true); +}); + +test("throws when a Map is given", () => { + const result = stringSet.safeParse(new Map([])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); + } +}); + +test("throws when the given set has invalid input", () => { + const result = stringSet.safeParse(new Set([Symbol()])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[0].path).toEqual([0]); + } +}); + +test("throws when the given set has multiple invalid entries", () => { + const result = stringSet.safeParse(new Set([1, 2] as any[]) as Set); + + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(2); + expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[0].path).toEqual([0]); + expect(result.error.issues[1].code).toEqual(ZodIssueCode.invalid_type); + expect(result.error.issues[1].path).toEqual([1]); + } +}); diff --git a/node_modules/zod/src/v3/tests/standard-schema.test.ts b/node_modules/zod/src/v3/tests/standard-schema.test.ts new file mode 100644 index 000000000..74b3d2ba6 --- /dev/null +++ b/node_modules/zod/src/v3/tests/standard-schema.test.ts @@ -0,0 +1,83 @@ +// import type { StandardSchemaV1 } from "@standard-schema/spec"; +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; +import type { StandardSchemaV1 } from "../standard-schema.js"; + +test("assignability", () => { + const _s1: StandardSchemaV1 = z.string(); + const _s2: StandardSchemaV1 = z.string(); + const _s3: StandardSchemaV1 = z.string(); + const _s4: StandardSchemaV1 = z.string(); + [_s1, _s2, _s3, _s4]; +}); + +test("type inference", () => { + const stringToNumber = z.string().transform((x) => x.length); + type input = StandardSchemaV1.InferInput; + util.assertEqual(true); + type output = StandardSchemaV1.InferOutput; + util.assertEqual(true); +}); + +test("valid parse", () => { + const schema = z.string(); + const result = schema["~standard"].validate("hello"); + if (result instanceof Promise) { + throw new Error("Expected sync result"); + } + expect(result.issues).toEqual(undefined); + if (result.issues) { + throw new Error("Expected no issues"); + } else { + expect(result.value).toEqual("hello"); + } +}); + +test("invalid parse", () => { + const schema = z.string(); + const result = schema["~standard"].validate(1234); + if (result instanceof Promise) { + throw new Error("Expected sync result"); + } + expect(result.issues).toBeDefined(); + if (!result.issues) { + throw new Error("Expected issues"); + } + expect(result.issues.length).toEqual(1); + expect(result.issues[0].path).toEqual([]); +}); + +test("valid parse async", async () => { + const schema = z.string().refine(async () => true); + const _result = schema["~standard"].validate("hello"); + if (_result instanceof Promise) { + const result = await _result; + expect(result.issues).toEqual(undefined); + if (result.issues) { + throw new Error("Expected no issues"); + } else { + expect(result.value).toEqual("hello"); + } + } else { + throw new Error("Expected async result"); + } +}); + +test("invalid parse async", async () => { + const schema = z.string().refine(async () => false); + const _result = schema["~standard"].validate("hello"); + if (_result instanceof Promise) { + const result = await _result; + expect(result.issues).toBeDefined(); + if (!result.issues) { + throw new Error("Expected issues"); + } + expect(result.issues.length).toEqual(1); + expect(result.issues[0].path).toEqual([]); + } else { + throw new Error("Expected async result"); + } +}); diff --git a/node_modules/zod/src/v3/tests/string.test.ts b/node_modules/zod/src/v3/tests/string.test.ts new file mode 100644 index 000000000..c91ac53b3 --- /dev/null +++ b/node_modules/zod/src/v3/tests/string.test.ts @@ -0,0 +1,916 @@ +import { Buffer } from "node:buffer"; +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +const minFive = z.string().min(5, "min5"); +const maxFive = z.string().max(5, "max5"); +const justFive = z.string().length(5); +const nonempty = z.string().nonempty("nonempty"); +const includes = z.string().includes("includes"); +const includesFromIndex2 = z.string().includes("includes", { position: 2 }); +const startsWith = z.string().startsWith("startsWith"); +const endsWith = z.string().endsWith("endsWith"); + +test("passing validations", () => { + minFive.parse("12345"); + minFive.parse("123456"); + maxFive.parse("12345"); + maxFive.parse("1234"); + nonempty.parse("1"); + justFive.parse("12345"); + includes.parse("XincludesXX"); + includesFromIndex2.parse("XXXincludesXX"); + startsWith.parse("startsWithX"); + endsWith.parse("XendsWith"); +}); + +test("failing validations", () => { + expect(() => minFive.parse("1234")).toThrow(); + expect(() => maxFive.parse("123456")).toThrow(); + expect(() => nonempty.parse("")).toThrow(); + expect(() => justFive.parse("1234")).toThrow(); + expect(() => justFive.parse("123456")).toThrow(); + expect(() => includes.parse("XincludeXX")).toThrow(); + expect(() => includesFromIndex2.parse("XincludesXX")).toThrow(); + expect(() => startsWith.parse("x")).toThrow(); + expect(() => endsWith.parse("x")).toThrow(); +}); + +test("email validations", () => { + const validEmails = [ + `email@domain.com`, + `firstname.lastname@domain.com`, + `email@subdomain.domain.com`, + `firstname+lastname@domain.com`, + `1234567890@domain.com`, + `email@domain-one.com`, + `_______@domain.com`, + `email@domain.name`, + `email@domain.co.jp`, + `firstname-lastname@domain.com`, + `very.common@example.com`, + `disposable.style.email.with+symbol@example.com`, + `other.email-with-hyphen@example.com`, + `fully-qualified-domain@example.com`, + `user.name+tag+sorting@example.com`, + `x@example.com`, + `mojojojo@asdf.example.com`, + `example-indeed@strange-example.com`, + `example@s.example`, + `user-@example.org`, + `user@my-example.com`, + `a@b.cd`, + `work+user@mail.com`, + `tom@test.te-st.com`, + `something@subdomain.domain-with-hyphens.tld`, + `common'name@domain.com`, + `francois@etu.inp-n7.fr`, + ]; + const invalidEmails = [ + // no "printable characters" + // `user%example.com@example.org`, + // `mailhost!username@example.org`, + // `test/test@test.com`, + + // double @ + `francois@@etu.inp-n7.fr`, + // do not support quotes + `"email"@domain.com`, + `"e asdf sadf ?<>ail"@domain.com`, + `" "@example.org`, + `"john..doe"@example.org`, + `"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com`, + // do not support comma + `a,b@domain.com`, + + // do not support IPv4 + `email@123.123.123.123`, + `email@[123.123.123.123]`, + `postmaster@123.123.123.123`, + `user@[68.185.127.196]`, + `ipv4@[85.129.96.247]`, + `valid@[79.208.229.53]`, + `valid@[255.255.255.255]`, + `valid@[255.0.55.2]`, + `valid@[255.0.55.2]`, + + // do not support ipv6 + `hgrebert0@[IPv6:4dc8:ac7:ce79:8878:1290:6098:5c50:1f25]`, + `bshapiro4@[IPv6:3669:c709:e981:4884:59a3:75d1:166b:9ae]`, + `jsmith@[IPv6:2001:db8::1]`, + `postmaster@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:7334]`, + `postmaster@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:192.168.1.1]`, + + // microsoft test cases + `plainaddress`, + `#@%^%#$@#$@#.com`, + `@domain.com`, + `Joe Smith <email@domain.com>`, + `email.domain.com`, + `email@domain@domain.com`, + `.email@domain.com`, + `email.@domain.com`, + `email..email@domain.com`, + `あいうえお@domain.com`, + `email@domain.com (Joe Smith)`, + `email@domain`, + `email@-domain.com`, + `email@111.222.333.44444`, + `email@domain..com`, + `Abc.example.com`, + `A@b@c@example.com`, + `colin..hacks@domain.com`, + `a"b(c)d,e:f;gi[j\k]l@example.com`, + `just"not"right@example.com`, + `this is"not\allowed@example.com`, + `this\ still\"not\\allowed@example.com`, + + // random + `i_like_underscore@but_its_not_allowed_in_this_part.example.com`, + `QA[icon]CHOCOLATE[icon]@test.com`, + `invalid@-start.com`, + `invalid@end.com-`, + `a.b@c.d`, + `invalid@[1.1.1.-1]`, + `invalid@[68.185.127.196.55]`, + `temp@[192.168.1]`, + `temp@[9.18.122.]`, + `double..point@test.com`, + `asdad@test..com`, + `asdad@hghg...sd...au`, + `asdad@hghg........au`, + `invalid@[256.2.2.48]`, + `invalid@[256.2.2.48]`, + `invalid@[999.465.265.1]`, + `jkibbey4@[IPv6:82c4:19a8::70a9:2aac:557::ea69:d985:28d]`, + `mlivesay3@[9952:143f:b4df:2179:49a1:5e82:b92e:6b6]`, + `gbacher0@[IPv6:bc37:4d3f:5048:2e26:37cc:248e:df8e:2f7f:af]`, + `invalid@[IPv6:5348:4ed3:5d38:67fb:e9b:acd2:c13:192.168.256.1]`, + `test@.com`, + `aaaaaaaaaaaaaaalongemailthatcausesregexDoSvulnerability@test.c`, + ]; + const emailSchema = z.string().email(); + + expect( + validEmails.every((email) => { + return emailSchema.safeParse(email).success; + }) + ).toBe(true); + expect( + invalidEmails.every((email) => { + return emailSchema.safeParse(email).success === false; + }) + ).toBe(true); +}); + +const validBase64Strings = [ + "SGVsbG8gV29ybGQ=", // "Hello World" + "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==", // "This is an encoded string" + "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcms=", // "Many hands make light work" + "UGF0aWVuY2UgaXMgdGhlIGtleSB0byBzdWNjZXNz", // "Patience is the key to success" + "QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg==", // "Base64 encoding is fun" + "MTIzNDU2Nzg5MA==", // "1234567890" + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=", // "abcdefghijklmnopqrstuvwxyz" + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=", // "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "ISIkJSMmJyonKCk=", // "!\"#$%&'()*" + "", // Empty string is technically valid base64 + "w7/Dv8O+w74K", // ÿÿþþ +]; + +for (const str of validBase64Strings) { + test(`base64 should accept ${str}`, () => { + expect(z.string().base64().safeParse(str).success).toBe(true); + }); +} + +const invalidBase64Strings = [ + "12345", // Not padded correctly, not a multiple of 4 characters + "12345===", // Not padded correctly + "SGVsbG8gV29ybGQ", // Missing padding + "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw", // Missing padding + "!UGF0aWVuY2UgaXMgdGhlIGtleSB0byBzdWNjZXNz", // Invalid character '!' + "?QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg==", // Invalid character '?' + ".MTIzND2Nzg5MC4=", // Invalid character '.' + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo", // Missing padding + "w7_Dv8O-w74K", // Has - and _ characters (is base64url) +]; + +for (const str of invalidBase64Strings) { + test(`base64 should reject ${str}`, () => { + expect(z.string().base64().safeParse(str).success).toBe(false); + }); +} + +const validBase64URLStrings = [ + "SGVsbG8gV29ybGQ", // "Hello World" + "SGVsbG8gV29ybGQ=", // "Hello World" with padding + "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw", // "This is an encoded string" + "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==", // "This is an encoded string" with padding + "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcms", // "Many hands make light work" + "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcms=", // "Many hands make light work" with padding + "UGF0aWVuY2UgaXMgdGhlIGtleSB0byBzdWNjZXNz", // "Patience is the key to success" + "QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg", // "Base64 encoding is fun" + "QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg==", // "Base64 encoding is fun" with padding + "MTIzNDU2Nzg5MA", // "1234567890" + "MTIzNDU2Nzg5MA==", // "1234567890" with padding + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo", // "abcdefghijklmnopqrstuvwxyz" + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=", // "abcdefghijklmnopqrstuvwxyz with padding" + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo", // "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=", // "ABCDEFGHIJKLMNOPQRSTUVWXYZ" with padding + "ISIkJSMmJyonKCk", // "!\"#$%&'()*" + "ISIkJSMmJyonKCk=", // "!\"#$%&'()*" with padding + "", // Empty string is technically valid base64url + "w7_Dv8O-w74K", // ÿÿþþ + "123456", +]; + +for (const str of validBase64URLStrings) { + test(`base64url should accept ${str}`, () => { + expect(z.string().base64url().safeParse(str).success).toBe(true); + }); +} + +const invalidBase64URLStrings = [ + "w7/Dv8O+w74K", // Has + and / characters (is base64) + "12345", // Invalid length (not a multiple of 4 characters when adding allowed number of padding characters) + "12345===", // Not padded correctly + "!UGF0aWVuY2UgaXMgdGhlIGtleSB0byBzdWNjZXNz", // Invalid character '!' + "?QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg==", // Invalid character '?' + ".MTIzND2Nzg5MC4=", // Invalid character '.' +]; + +for (const str of invalidBase64URLStrings) { + test(`base64url should reject ${str}`, () => { + expect(z.string().base64url().safeParse(str).success).toBe(false); + }); +} + +function makeJwt(header: object, payload: object) { + const headerBase64 = Buffer.from(JSON.stringify(header)).toString("base64url"); + const payloadBase64 = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const signature = "signature"; // Placeholder for the signature + return `${headerBase64}.${payloadBase64}.${signature}`; +} + +test("jwt validations", () => { + const jwt = z.string().jwt(); + const jwtWithAlg = z.string().jwt({ alg: "HS256" }); + + expect(() => jwt.parse("invalid")).toThrow(); + expect(() => jwt.parse("invalid.invalid")).toThrow(); + expect(() => jwt.parse("invalid.invalid.invalid")).toThrow(); + + // Valid JWTs + const d1 = makeJwt({ typ: "JWT", alg: "HS256" }, {}); + expect(() => jwt.parse(d1)).not.toThrow(); + expect(() => jwtWithAlg.parse(d1)).not.toThrow(); + + // Invalid header + const d2 = makeJwt({}, {}); + expect(() => jwt.parse(d2)).toThrow(); + + // Wrong algorithm + const d3 = makeJwt({ typ: "JWT", alg: "RS256" }, {}); + expect(() => jwtWithAlg.parse(d3)).toThrow(); + + // missing typ is fine + const d4 = makeJwt({ alg: "HS256" }, {}); + jwt.parse(d4); + + // type isn't JWT + const d5 = makeJwt({ typ: "SUP", alg: "HS256" }, { foo: "bar" }); + expect(() => jwt.parse(d5)).toThrow(); + + // Custom error message + const customMsg = "Invalid JWT token"; + const jwtWithMsg = z.string().jwt({ message: customMsg }); + try { + jwtWithMsg.parse("invalid"); + } catch (error) { + expect((error as z.ZodError).issues[0].message).toBe(customMsg); + } +}); + +test("url validations", () => { + const url = z.string().url(); + url.parse("http://google.com"); + url.parse("https://google.com/asdf?asdf=ljk3lk4&asdf=234#asdf"); + expect(() => url.parse("asdf")).toThrow(); + expect(() => url.parse("https:/")).toThrow(); + expect(() => url.parse("asdfj@lkjsdf.com")).toThrow(); +}); + +test("url error overrides", () => { + try { + z.string().url().parse("https"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Invalid url"); + } + try { + z.string().url("badurl").parse("https"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("badurl"); + } + try { + z.string().url({ message: "badurl" }).parse("https"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("badurl"); + } +}); + +test("emoji validations", () => { + const emoji = z.string().emoji(); + + emoji.parse("👋👋👋👋"); + emoji.parse("🍺👩‍🚀🫡"); + emoji.parse("💚💙💜💛❤️"); + emoji.parse("🐛🗝🐏🍡🎦🚢🏨💫🎌☘🗡😹🔒🎬➡️🍹🗂🚨⚜🕑〽️🚦🌊🍴💍🍌💰😳🌺🍃"); + emoji.parse("🇹🇷🤽🏿‍♂️"); + emoji.parse( + "😀😁😂🤣😃😄😅😆😉😊😋😎😍😘🥰😗😙😚☺️☺🙂🤗🤩🤔🤨😐😑😶🙄😏😣😥😮🤐😯😪😫😴😌😛😜😝🤤😒😓😔😕🙃🤑😲☹️☹🙁😖😞😟😤😢😭😦😧😨😩🤯😬😰😱🥵🥶😳🤪😵😡😠🤬😷🤒🤕🤢🤮🤧😇🤠🥳🥴🥺🤥🤫🤭🧐🤓😈👿🤡👹👺💀☠️☠👻👽👾🤖💩😺😸😹😻😼😽🙀😿😾🙈🙉🙊🏻🏼🏽🏾🏿👶👶🏻👶🏼👶🏽👶🏾👶🏿🧒🧒🏻🧒🏼🧒🏽🧒🏾🧒🏿👦👦🏻👦🏼👦🏽👦🏾👦🏿👧👧🏻👧🏼👧🏽👧🏾👧🏿🧑🧑🏻🧑🏼🧑🏽🧑🏾🧑🏿👨👨🏻👨🏼👨🏽👨🏾👨🏿👩👩🏻👩🏼👩🏽👩🏾👩🏿🧓🧓🏻🧓🏼🧓🏽🧓🏾🧓🏿👴👴🏻👴🏼👴🏽👴🏾👴🏿👵👵🏻👵🏼👵🏽👵🏾👵🏿👨‍⚕️👨‍⚕👨🏻‍⚕️👨🏻‍⚕👨🏼‍⚕️👨🏼‍⚕👨🏽‍⚕️👨🏽‍⚕👨🏾‍⚕️👨🏾‍⚕👨🏿‍⚕️👨🏿‍⚕👩‍⚕️👩‍⚕👩🏻‍⚕️👩🏻‍⚕👩🏼‍⚕️👩🏼‍⚕👩🏽‍⚕️👩🏽‍⚕👩🏾‍⚕️👩🏾‍⚕👩🏿‍⚕️👩🏿‍⚕👨‍🎓👨🏻‍🎓👨🏼‍🎓👨🏽‍🎓👨🏾‍🎓👨🏿‍🎓👩‍🎓👩🏻‍🎓👩🏼‍🎓👩🏽‍🎓👩🏾‍🎓👩🏿‍🎓👨‍🏫👨🏻‍🏫👨🏼‍🏫👨🏽‍🏫👨🏾‍🏫👨🏿‍🏫👩‍🏫👩🏻‍🏫👩🏼‍🏫👩🏽‍🏫👩🏾‍🏫👩🏿‍🏫👨‍⚖️👨‍⚖👨🏻‍⚖️👨🏻‍⚖👨🏼‍⚖️👨🏼‍⚖👨🏽‍⚖️👨🏽‍⚖👨🏾‍⚖️👨🏾‍⚖👨🏿‍⚖️👨🏿‍⚖👩‍⚖️👩‍⚖👩🏻‍⚖️👩🏻‍⚖👩🏼‍⚖️👩🏼‍⚖👩🏽‍⚖️👩🏽‍⚖👩🏾‍⚖️👩🏾‍⚖👩🏿‍⚖️👩🏿‍⚖👨‍🌾👨🏻‍🌾👨🏼‍🌾👨🏽‍🌾👨🏾‍🌾👨🏿‍🌾👩‍🌾👩🏻‍🌾👩🏼‍🌾👩🏽‍🌾👩🏾‍🌾👩🏿‍🌾👨‍🍳👨🏻‍🍳👨🏼‍🍳👨🏽‍🍳👨🏾‍🍳👨🏿‍🍳👩‍🍳👩🏻‍🍳👩🏼‍🍳👩🏽‍🍳👩🏾‍🍳👩🏿‍🍳👨‍🔧👨🏻‍🔧👨🏼‍🔧👨🏽‍🔧👨🏾‍🔧👨🏿‍🔧👩‍🔧👩🏻‍🔧👩🏼‍🔧👩🏽‍🔧👩🏾‍🔧👩🏿‍🔧👨‍🏭👨🏻‍🏭👨🏼‍🏭👨🏽‍🏭👨🏾‍🏭👨🏿‍🏭👩‍🏭👩🏻‍🏭👩🏼‍🏭👩🏽‍🏭👩🏾‍🏭👩🏿‍🏭👨‍💼👨🏻‍💼👨🏼‍💼👨🏽‍💼👨🏾‍💼👨🏿‍💼👩‍💼👩🏻‍💼👩🏼‍💼👩🏽‍💼👩🏾‍💼👩🏿‍💼👨‍🔬👨🏻‍🔬👨🏼‍🔬👨🏽‍🔬👨🏾‍🔬👨🏿‍🔬👩‍🔬👩🏻‍🔬👩🏼‍🔬👩🏽‍🔬👩🏾‍🔬👩🏿‍🔬👨‍💻👨🏻‍💻👨🏼‍💻👨🏽‍💻👨🏾‍💻👨🏿‍💻👩‍💻👩🏻‍💻👩🏼‍💻👩🏽‍💻👩🏾‍💻👩🏿‍💻👨‍🎤👨🏻‍🎤👨🏼‍🎤👨🏽‍🎤👨🏾‍🎤👨🏿‍🎤👩‍🎤👩🏻‍🎤👩🏼‍🎤👩🏽‍🎤👩🏾‍🎤👩🏿‍🎤👨‍🎨👨🏻‍🎨👨🏼‍🎨👨🏽‍🎨👨🏾‍🎨👨🏿‍🎨👩‍🎨👩🏻‍🎨👩🏼‍🎨👩🏽‍🎨👩🏾‍🎨👩🏿‍🎨👨‍✈️👨‍✈👨🏻‍✈️👨🏻‍✈👨🏼‍✈️👨🏼‍✈👨🏽‍✈️👨🏽‍✈👨🏾‍✈️👨🏾‍✈👨🏿‍✈️👨🏿‍✈👩‍✈️👩‍✈👩🏻‍✈️👩🏻‍✈👩🏼‍✈️👩🏼‍✈👩🏽‍✈️👩🏽‍✈👩🏾‍✈️👩🏾‍✈👩🏿‍✈️👩🏿‍✈👨‍🚀👨🏻‍🚀👨🏼‍🚀👨🏽‍🚀👨🏾‍🚀👨🏿‍🚀👩‍🚀👩🏻‍🚀👩🏼‍🚀👩🏽‍🚀👩🏾‍🚀👩🏿‍🚀👨‍🚒👨🏻‍🚒👨🏼‍🚒👨🏽‍🚒👨🏾‍🚒👨🏿‍🚒👩‍🚒👩🏻‍🚒👩🏼‍🚒👩🏽‍🚒👩🏾‍🚒👩🏿‍🚒👮👮🏻👮🏼👮🏽👮🏾👮🏿👮‍♂️👮‍♂👮🏻‍♂️👮🏻‍♂👮🏼‍♂️👮🏼‍♂👮🏽‍♂️👮🏽‍♂👮🏾‍♂️👮🏾‍♂👮🏿‍♂️👮🏿‍♂👮‍♀️👮‍♀👮🏻‍♀️👮🏻‍♀👮🏼‍♀️👮🏼‍♀👮🏽‍♀️👮🏽‍♀👮🏾‍♀️👮🏾‍♀👮🏿‍♀️👮🏿‍♀🕵️🕵🕵🏻🕵🏼🕵🏽🕵🏾🕵🏿🕵️‍♂️🕵‍♂️🕵️‍♂🕵‍♂🕵🏻‍♂️🕵🏻‍♂🕵🏼‍♂️🕵🏼‍♂🕵🏽‍♂️🕵🏽‍♂🕵🏾‍♂️🕵🏾‍♂🕵🏿‍♂️🕵🏿‍♂🕵️‍♀️🕵‍♀️🕵️‍♀🕵‍♀🕵🏻‍♀️🕵🏻‍♀🕵🏼‍♀️🕵🏼‍♀🕵🏽‍♀️🕵🏽‍♀🕵🏾‍♀️🕵🏾‍♀🕵🏿‍♀️🕵🏿‍♀💂💂🏻💂🏼💂🏽💂🏾💂🏿💂‍♂️💂‍♂💂🏻‍♂️💂🏻‍♂💂🏼‍♂️💂🏼‍♂💂🏽‍♂️💂🏽‍♂💂🏾‍♂️💂🏾‍♂💂🏿‍♂️💂🏿‍♂💂‍♀️💂‍♀💂🏻‍♀️💂🏻‍♀💂🏼‍♀️💂🏼‍♀💂🏽‍♀️💂🏽‍♀💂🏾‍♀️💂🏾‍♀💂🏿‍♀️💂🏿‍♀👷👷🏻👷🏼👷🏽👷🏾👷🏿👷‍♂️👷‍♂👷🏻‍♂️👷🏻‍♂👷🏼‍♂️👷🏼‍♂👷🏽‍♂️👷🏽‍♂👷🏾‍♂️👷🏾‍♂👷🏿‍♂️👷🏿‍♂👷‍♀️👷‍♀👷🏻‍♀️👷🏻‍♀👷🏼‍♀️👷🏼‍♀👷🏽‍♀️👷🏽‍♀👷🏾‍♀️👷🏾‍♀👷🏿‍♀️👷🏿‍♀🤴🤴🏻🤴🏼🤴🏽🤴🏾🤴🏿👸👸🏻👸🏼👸🏽👸🏾👸🏿👳👳🏻👳🏼👳🏽👳🏾👳🏿👳‍♂️👳‍♂👳🏻‍♂️👳🏻‍♂👳🏼‍♂️👳🏼‍♂👳🏽‍♂️👳🏽‍♂👳🏾‍♂️👳🏾‍♂👳🏿‍♂️👳🏿‍♂👳‍♀️👳‍♀👳🏻‍♀️👳🏻‍♀👳🏼‍♀️👳🏼‍♀👳🏽‍♀️👳🏽‍♀👳🏾‍♀️👳🏾‍♀👳🏿‍♀️👳🏿‍♀👲👲🏻👲🏼👲🏽👲🏾👲🏿🧕🧕🏻🧕🏼🧕🏽🧕🏾🧕🏿🧔🧔🏻🧔🏼🧔🏽🧔🏾🧔🏿👱👱🏻👱🏼👱🏽👱🏾👱🏿👱‍♂️👱‍♂👱🏻‍♂️👱🏻‍♂👱🏼‍♂️👱🏼‍♂👱🏽‍♂️👱🏽‍♂👱🏾‍♂️👱🏾‍♂👱🏿‍♂️👱🏿‍♂👱‍♀️👱‍♀👱🏻‍♀️👱🏻‍♀👱🏼‍♀️👱🏼‍♀👱🏽‍♀️👱🏽‍♀👱🏾‍♀️👱🏾‍♀👱🏿‍♀️👱🏿‍♀👨‍🦰👨🏻‍🦰👨🏼‍🦰👨🏽‍🦰👨🏾‍🦰👨🏿‍🦰👩‍🦰👩🏻‍🦰👩🏼‍🦰👩🏽‍🦰👩🏾‍🦰👩🏿‍🦰👨‍🦱👨🏻‍🦱👨🏼‍🦱👨🏽‍🦱👨🏾‍🦱👨🏿‍🦱👩‍🦱👩🏻‍🦱👩🏼‍🦱👩🏽‍🦱👩🏾‍🦱👩🏿‍🦱👨‍🦲👨🏻‍🦲👨🏼‍🦲👨🏽‍🦲👨🏾‍🦲👨🏿‍🦲👩‍🦲👩🏻‍🦲👩🏼‍🦲👩🏽‍🦲👩🏾‍🦲👩🏿‍🦲👨‍🦳👨🏻‍🦳👨🏼‍🦳👨🏽‍🦳👨🏾‍🦳👨🏿‍🦳👩‍🦳👩🏻‍🦳👩🏼‍🦳👩🏽‍🦳👩🏾‍🦳👩🏿‍🦳🤵🤵🏻🤵🏼🤵🏽🤵🏾🤵🏿👰👰🏻👰🏼👰🏽👰🏾👰🏿🤰🤰🏻🤰🏼🤰🏽🤰🏾🤰🏿🤱🤱🏻🤱🏼🤱🏽🤱🏾🤱🏿👼👼🏻👼🏼👼🏽👼🏾👼🏿🎅🎅🏻🎅🏼🎅🏽🎅🏾🎅🏿🤶🤶🏻🤶🏼🤶🏽🤶🏾🤶🏿🦸🦸🏻🦸🏼🦸🏽🦸🏾🦸🏿🦸‍♀️🦸‍♀🦸🏻‍♀️🦸🏻‍♀🦸🏼‍♀️🦸🏼‍♀🦸🏽‍♀️🦸🏽‍♀🦸🏾‍♀️🦸🏾‍♀🦸🏿‍♀️🦸🏿‍♀🦸‍♂️🦸‍♂🦸🏻‍♂️🦸🏻‍♂🦸🏼‍♂️🦸🏼‍♂🦸🏽‍♂️🦸🏽‍♂🦸🏾‍♂️🦸🏾‍♂🦸🏿‍♂️🦸🏿‍♂🦹🦹🏻🦹🏼🦹🏽🦹🏾🦹🏿🦹‍♀️🦹‍♀🦹🏻‍♀️🦹🏻‍♀🦹🏼‍♀️🦹🏼‍♀🦹🏽‍♀️🦹🏽‍♀🦹🏾‍♀️🦹🏾‍♀🦹🏿‍♀️🦹🏿‍♀🦹‍♂️🦹‍♂🦹🏻‍♂️🦹🏻‍♂🦹🏼‍♂️🦹🏼‍♂🦹🏽‍♂️🦹🏽‍♂🦹🏾‍♂️🦹🏾‍♂🦹🏿‍♂️🦹🏿‍♂🧙🧙🏻🧙🏼🧙🏽🧙🏾🧙🏿🧙‍♀️🧙‍♀🧙🏻‍♀️🧙🏻‍♀🧙🏼‍♀️🧙🏼‍♀🧙🏽‍♀️🧙🏽‍♀🧙🏾‍♀️🧙🏾‍♀🧙🏿‍♀️🧙🏿‍♀🧙‍♂️🧙‍♂🧙🏻‍♂️🧙🏻‍♂🧙🏼‍♂️🧙🏼‍♂🧙🏽‍♂️🧙🏽‍♂🧙🏾‍♂️🧙🏾‍♂🧙🏿‍♂️🧙🏿‍♂🧚🧚🏻🧚🏼🧚🏽🧚🏾🧚🏿🧚‍♀️🧚‍♀🧚🏻‍♀️🧚🏻‍♀🧚🏼‍♀️🧚🏼‍♀🧚🏽‍♀️🧚🏽‍♀🧚🏾‍♀️🧚🏾‍♀🧚🏿‍♀️🧚🏿‍♀🧚‍♂️🧚‍♂🧚🏻‍♂️🧚🏻‍♂🧚🏼‍♂️🧚🏼‍♂🧚🏽‍♂️🧚🏽‍♂🧚🏾‍♂️🧚🏾‍♂🧚🏿‍♂️🧚🏿‍♂🧛🧛🏻🧛🏼🧛🏽🧛🏾🧛🏿🧛‍♀️🧛‍♀🧛🏻‍♀️🧛🏻‍♀🧛🏼‍♀️🧛🏼‍♀🧛🏽‍♀️🧛🏽‍♀🧛🏾‍♀️🧛🏾‍♀🧛🏿‍♀️🧛🏿‍♀🧛‍♂️🧛‍♂🧛🏻‍♂️🧛🏻‍♂🧛🏼‍♂️🧛🏼‍♂🧛🏽‍♂️🧛🏽‍♂🧛🏾‍♂️🧛🏾‍♂🧛🏿‍♂️🧛🏿‍♂🧜🧜🏻🧜🏼🧜🏽🧜🏾🧜🏿🧜‍♀️🧜‍♀🧜🏻‍♀️🧜🏻‍♀🧜🏼‍♀️🧜🏼‍♀🧜🏽‍♀️🧜🏽‍♀🧜🏾‍♀️🧜🏾‍♀🧜🏿‍♀️🧜🏿‍♀🧜‍♂️🧜‍♂🧜🏻‍♂️🧜🏻‍♂🧜🏼‍♂️🧜🏼‍♂🧜🏽‍♂️🧜🏽‍♂🧜🏾‍♂️🧜🏾‍♂🧜🏿‍♂️🧜🏿‍♂🧝🧝🏻🧝🏼🧝🏽🧝🏾🧝🏿🧝‍♀️🧝‍♀🧝🏻‍♀️🧝🏻‍♀🧝🏼‍♀️🧝🏼‍♀🧝🏽‍♀️🧝🏽‍♀🧝🏾‍♀️🧝🏾‍♀🧝🏿‍♀️🧝🏿‍♀🧝‍♂️🧝‍♂🧝🏻‍♂️🧝🏻‍♂🧝🏼‍♂️🧝🏼‍♂🧝🏽‍♂️🧝🏽‍♂🧝🏾‍♂️🧝🏾‍♂🧝🏿‍♂️🧝🏿‍♂🧞🧞‍♀️🧞‍♀🧞‍♂️🧞‍♂🧟🧟‍♀️🧟‍♀🧟‍♂️🧟‍♂🙍🙍🏻🙍🏼🙍🏽🙍🏾🙍🏿🙍‍♂️🙍‍♂🙍🏻‍♂️🙍🏻‍♂🙍🏼‍♂️🙍🏼‍♂🙍🏽‍♂️🙍🏽‍♂🙍🏾‍♂️🙍🏾‍♂🙍🏿‍♂️🙍🏿‍♂🙍‍♀️🙍‍♀🙍🏻‍♀️🙍🏻‍♀🙍🏼‍♀️🙍🏼‍♀🙍🏽‍♀️🙍🏽‍♀🙍🏾‍♀️🙍🏾‍♀🙍🏿‍♀️🙍🏿‍♀🙎🙎🏻🙎🏼🙎🏽🙎🏾🙎🏿🙎‍♂️🙎‍♂🙎🏻‍♂️🙎🏻‍♂🙎🏼‍♂️🙎🏼‍♂🙎🏽‍♂️🙎🏽‍♂🙎🏾‍♂️🙎🏾‍♂🙎🏿‍♂️🙎🏿‍♂🙎‍♀️🙎‍♀🙎🏻‍♀️🙎🏻‍♀🙎🏼‍♀️🙎🏼‍♀🙎🏽‍♀️🙎🏽‍♀🙎🏾‍♀️🙎🏾‍♀🙎🏿‍♀️🙎🏿‍♀🙅🙅🏻🙅🏼🙅🏽🙅🏾🙅🏿🙅‍♂️🙅‍♂🙅🏻‍♂️🙅🏻‍♂🙅🏼‍♂️🙅🏼‍♂🙅🏽‍♂️🙅🏽‍♂🙅🏾‍♂️🙅🏾‍♂🙅🏿‍♂️🙅🏿‍♂🙅‍♀️🙅‍♀🙅🏻‍♀️🙅🏻‍♀🙅🏼‍♀️🙅🏼‍♀🙅🏽‍♀️🙅🏽‍♀🙅🏾‍♀️🙅🏾‍♀🙅🏿‍♀️🙅🏿‍♀🙆🙆🏻🙆🏼🙆🏽🙆🏾🙆🏿🙆‍♂️🙆‍♂🙆🏻‍♂️🙆🏻‍♂🙆🏼‍♂️🙆🏼‍♂🙆🏽‍♂️🙆🏽‍♂🙆🏾‍♂️🙆🏾‍♂🙆🏿‍♂️🙆🏿‍♂🙆‍♀️🙆‍♀🙆🏻‍♀️🙆🏻‍♀🙆🏼‍♀️🙆🏼‍♀🙆🏽‍♀️🙆🏽‍♀🙆🏾‍♀️🙆🏾‍♀🙆🏿‍♀️🙆🏿‍♀💁💁🏻💁🏼💁🏽💁🏾💁🏿💁‍♂️💁‍♂💁🏻‍♂️💁🏻‍♂💁🏼‍♂️💁🏼‍♂💁🏽‍♂️💁🏽‍♂💁🏾‍♂️💁🏾‍♂💁🏿‍♂️💁🏿‍♂💁‍♀️💁‍♀💁🏻‍♀️💁🏻‍♀💁🏼‍♀️💁🏼‍♀💁🏽‍♀️💁🏽‍♀💁🏾‍♀️💁🏾‍♀💁🏿‍♀️💁🏿‍♀🙋🙋🏻🙋🏼🙋🏽🙋🏾🙋🏿🙋‍♂️🙋‍♂🙋🏻‍♂️🙋🏻‍♂🙋🏼‍♂️🙋🏼‍♂🙋🏽‍♂️🙋🏽‍♂🙋🏾‍♂️🙋🏾‍♂🙋🏿‍♂️🙋🏿‍♂🙋‍♀️🙋‍♀🙋🏻‍♀️🙋🏻‍♀🙋🏼‍♀️🙋🏼‍♀🙋🏽‍♀️🙋🏽‍♀🙋🏾‍♀️🙋🏾‍♀🙋🏿‍♀️🙋🏿‍♀🙇🙇🏻🙇🏼🙇🏽🙇🏾🙇🏿🙇‍♂️🙇‍♂🙇🏻‍♂️🙇🏻‍♂🙇🏼‍♂️🙇🏼‍♂🙇🏽‍♂️🙇🏽‍♂🙇🏾‍♂️🙇🏾‍♂🙇🏿‍♂️🙇🏿‍♂🙇‍♀️🙇‍♀🙇🏻‍♀️🙇🏻‍♀🙇🏼‍♀️🙇🏼‍♀🙇🏽‍♀️🙇🏽‍♀🙇🏾‍♀️🙇🏾‍♀🙇🏿‍♀️🙇🏿‍♀🤦🤦🏻🤦🏼🤦🏽🤦🏾🤦🏿🤦‍♂️🤦‍♂🤦🏻‍♂️🤦🏻‍♂🤦🏼‍♂️🤦🏼‍♂🤦🏽‍♂️🤦🏽‍♂🤦🏾‍♂️🤦🏾‍♂🤦🏿‍♂️🤦🏿‍♂🤦‍♀️🤦‍♀🤦🏻‍♀️🤦🏻‍♀🤦🏼‍♀️🤦🏼‍♀🤦🏽‍♀️🤦🏽‍♀🤦🏾‍♀️🤦🏾‍♀🤦🏿‍♀️🤦🏿‍♀🤷🤷🏻🤷🏼🤷🏽🤷🏾🤷🏿🤷‍♂️🤷‍♂🤷🏻‍♂️🤷🏻‍♂🤷🏼‍♂️🤷🏼‍♂🤷🏽‍♂️🤷🏽‍♂🤷🏾‍♂️🤷🏾‍♂🤷🏿‍♂️🤷🏿‍♂🤷‍♀️🤷‍♀🤷🏻‍♀️🤷🏻‍♀🤷🏼‍♀️🤷🏼‍♀🤷🏽‍♀️🤷🏽‍♀🤷🏾‍♀️🤷🏾‍♀🤷🏿‍♀️🤷🏿‍♀💆💆🏻💆🏼💆🏽💆🏾💆🏿💆‍♂️💆‍♂💆🏻‍♂️💆🏻‍♂💆🏼‍♂️💆🏼‍♂💆🏽‍♂️💆🏽‍♂💆🏾‍♂️💆🏾‍♂💆🏿‍♂️💆🏿‍♂💆‍♀️💆‍♀💆🏻‍♀️💆🏻‍♀💆🏼‍♀️💆🏼‍♀💆🏽‍♀️💆🏽‍♀💆🏾‍♀️💆🏾‍♀💆🏿‍♀️💆🏿‍♀💇💇🏻💇🏼💇🏽💇🏾💇🏿💇‍♂️💇‍♂💇🏻‍♂️💇🏻‍♂💇🏼‍♂️💇🏼‍♂💇🏽‍♂️💇🏽‍♂💇🏾‍♂️💇🏾‍♂💇🏿‍♂️💇🏿‍♂💇‍♀️💇‍♀💇🏻‍♀️💇🏻‍♀💇🏼‍♀️💇🏼‍♀💇🏽‍♀️💇🏽‍♀💇🏾‍♀️💇🏾‍♀💇🏿‍♀️💇🏿‍♀🚶🚶🏻🚶🏼🚶🏽🚶🏾🚶🏿🚶‍♂️🚶‍♂🚶🏻‍♂️🚶🏻‍♂🚶🏼‍♂️🚶🏼‍♂🚶🏽‍♂️🚶🏽‍♂🚶🏾‍♂️🚶🏾‍♂🚶🏿‍♂️🚶🏿‍♂🚶‍♀️🚶‍♀🚶🏻‍♀️🚶🏻‍♀🚶🏼‍♀️🚶🏼‍♀🚶🏽‍♀️🚶🏽‍♀🚶🏾‍♀️🚶🏾‍♀🚶🏿‍♀️🚶🏿‍♀🏃🏃🏻🏃🏼🏃🏽🏃🏾🏃🏿🏃‍♂️🏃‍♂🏃🏻‍♂️🏃🏻‍♂🏃🏼‍♂️🏃🏼‍♂🏃🏽‍♂️🏃🏽‍♂🏃🏾‍♂️🏃🏾‍♂🏃🏿‍♂️🏃🏿‍♂🏃‍♀️🏃‍♀🏃🏻‍♀️🏃🏻‍♀🏃🏼‍♀️🏃🏼‍♀🏃🏽‍♀️🏃🏽‍♀🏃🏾‍♀️🏃🏾‍♀🏃🏿‍♀️🏃🏿‍♀💃💃🏻💃🏼💃🏽💃🏾💃🏿🕺🕺🏻🕺🏼🕺🏽🕺🏾🕺🏿👯👯‍♂️👯‍♂👯‍♀️👯‍♀🧖🧖🏻🧖🏼🧖🏽🧖🏾🧖🏿🧖‍♀️🧖‍♀🧖🏻‍♀️🧖🏻‍♀🧖🏼‍♀️🧖🏼‍♀🧖🏽‍♀️🧖🏽‍♀🧖🏾‍♀️🧖🏾‍♀🧖🏿‍♀️🧖🏿‍♀🧖‍♂️🧖‍♂🧖🏻‍♂️🧖🏻‍♂🧖🏼‍♂️🧖🏼‍♂🧖🏽‍♂️🧖🏽‍♂🧖🏾‍♂️🧖🏾‍♂🧖🏿‍♂️🧖🏿‍♂🧗🧗🏻🧗🏼🧗🏽🧗🏾🧗🏿🧗‍♀️🧗‍♀🧗🏻‍♀️🧗🏻‍♀🧗🏼‍♀️🧗🏼‍♀🧗🏽‍♀️🧗🏽‍♀🧗🏾‍♀️🧗🏾‍♀🧗🏿‍♀️🧗🏿‍♀🧗‍♂️🧗‍♂🧗🏻‍♂️🧗🏻‍♂🧗🏼‍♂️🧗🏼‍♂🧗🏽‍♂️🧗🏽‍♂🧗🏾‍♂️🧗🏾‍♂🧗🏿‍♂️🧗🏿‍♂🧘🧘🏻🧘🏼🧘🏽🧘🏾🧘🏿🧘‍♀️🧘‍♀🧘🏻‍♀️🧘🏻‍♀🧘🏼‍♀️🧘🏼‍♀🧘🏽‍♀️🧘🏽‍♀🧘🏾‍♀️🧘🏾‍♀🧘🏿‍♀️🧘🏿‍♀🧘‍♂️🧘‍♂🧘🏻‍♂️🧘🏻‍♂🧘🏼‍♂️🧘🏼‍♂🧘🏽‍♂️🧘🏽‍♂🧘🏾‍♂️🧘🏾‍♂🧘🏿‍♂️🧘🏿‍♂🛀🛀🏻🛀🏼🛀🏽🛀🏾🛀🏿🛌🛌🏻🛌🏼🛌🏽🛌🏾🛌🏿🕴️🕴🕴🏻🕴🏼🕴🏽🕴🏾🕴🏿🗣️🗣👤👥🤺🏇🏇🏻🏇🏼🏇🏽🏇🏾🏇🏿⛷️⛷🏂🏂🏻🏂🏼🏂🏽🏂🏾🏂🏿🏌️🏌🏌🏻🏌🏼🏌🏽🏌🏾🏌🏿🏌️‍♂️🏌‍♂️🏌️‍♂🏌‍♂🏌🏻‍♂️🏌🏻‍♂🏌🏼‍♂️🏌🏼‍♂🏌🏽‍♂️🏌🏽‍♂🏌🏾‍♂️🏌🏾‍♂🏌🏿‍♂️🏌🏿‍♂🏌️‍♀️🏌‍♀️🏌️‍♀🏌‍♀🏌🏻‍♀️🏌🏻‍♀🏌🏼‍♀️🏌🏼‍♀🏌🏽‍♀️🏌🏽‍♀🏌🏾‍♀️🏌🏾‍♀🏌🏿‍♀️🏌🏿‍♀🏄🏄🏻🏄🏼🏄🏽🏄🏾🏄🏿🏄‍♂️🏄‍♂🏄🏻‍♂️🏄🏻‍♂🏄🏼‍♂️🏄🏼‍♂🏄🏽‍♂️🏄🏽‍♂🏄🏾‍♂️🏄🏾‍♂🏄🏿‍♂️🏄🏿‍♂🏄‍♀️🏄‍♀🏄🏻‍♀️🏄🏻‍♀🏄🏼‍♀️🏄🏼‍♀🏄🏽‍♀️🏄🏽‍♀🏄🏾‍♀️🏄🏾‍♀🏄🏿‍♀️🏄🏿‍♀🚣🚣🏻🚣🏼🚣🏽🚣🏾🚣🏿🚣‍♂️🚣‍♂🚣🏻‍♂️🚣🏻‍♂🚣🏼‍♂️🚣🏼‍♂🚣🏽‍♂️🚣🏽‍♂🚣🏾‍♂️🚣🏾‍♂🚣🏿‍♂️🚣🏿‍♂🚣‍♀️🚣‍♀🚣🏻‍♀️🚣🏻‍♀🚣🏼‍♀️🚣🏼‍♀🚣🏽‍♀️🚣🏽‍♀🚣🏾‍♀️🚣🏾‍♀🚣🏿‍♀️🚣🏿‍♀🏊🏊🏻🏊🏼🏊🏽🏊🏾🏊🏿🏊‍♂️🏊‍♂🏊🏻‍♂️🏊🏻‍♂🏊🏼‍♂️🏊🏼‍♂🏊🏽‍♂️🏊🏽‍♂🏊🏾‍♂️🏊🏾‍♂🏊🏿‍♂️🏊🏿‍♂🏊‍♀️🏊‍♀🏊🏻‍♀️🏊🏻‍♀🏊🏼‍♀️🏊🏼‍♀🏊🏽‍♀️🏊🏽‍♀🏊🏾‍♀️🏊🏾‍♀🏊🏿‍♀️🏊🏿‍♀⛹️⛹⛹🏻⛹🏼⛹🏽⛹🏾⛹🏿⛹️‍♂️⛹‍♂️⛹️‍♂⛹‍♂⛹🏻‍♂️⛹🏻‍♂⛹🏼‍♂️⛹🏼‍♂⛹🏽‍♂️⛹🏽‍♂⛹🏾‍♂️⛹🏾‍♂⛹🏿‍♂️⛹🏿‍♂⛹️‍♀️⛹‍♀️⛹️‍♀⛹‍♀⛹🏻‍♀️⛹🏻‍♀⛹🏼‍♀️⛹🏼‍♀⛹🏽‍♀️⛹🏽‍♀⛹🏾‍♀️⛹🏾‍♀⛹🏿‍♀️⛹🏿‍♀🏋️🏋🏋🏻🏋🏼🏋🏽🏋🏾🏋🏿🏋️‍♂️🏋‍♂️🏋️‍♂🏋‍♂🏋🏻‍♂️🏋🏻‍♂🏋🏼‍♂️🏋🏼‍♂🏋🏽‍♂️🏋🏽‍♂🏋🏾‍♂️🏋🏾‍♂🏋🏿‍♂️🏋🏿‍♂🏋️‍♀️🏋‍♀️🏋️‍♀🏋‍♀🏋🏻‍♀️🏋🏻‍♀🏋🏼‍♀️🏋🏼‍♀🏋🏽‍♀️🏋🏽‍♀🏋🏾‍♀️🏋🏾‍♀🏋🏿‍♀️🏋🏿‍♀🚴🚴🏻🚴🏼🚴🏽🚴🏾🚴🏿🚴‍♂️🚴‍♂🚴🏻‍♂️🚴🏻‍♂🚴🏼‍♂️🚴🏼‍♂🚴🏽‍♂️🚴🏽‍♂🚴🏾‍♂️🚴🏾‍♂🚴🏿‍♂️🚴🏿‍♂🚴‍♀️🚴‍♀🚴🏻‍♀️🚴🏻‍♀🚴🏼‍♀️🚴🏼‍♀🚴🏽‍♀️🚴🏽‍♀🚴🏾‍♀️🚴🏾‍♀🚴🏿‍♀️🚴🏿‍♀🚵🚵🏻🚵🏼🚵🏽🚵🏾🚵🏿🚵‍♂️🚵‍♂🚵🏻‍♂️🚵🏻‍♂🚵🏼‍♂️🚵🏼‍♂🚵🏽‍♂️🚵🏽‍♂🚵🏾‍♂️🚵🏾‍♂🚵🏿‍♂️🚵🏿‍♂🚵‍♀️🚵‍♀🚵🏻‍♀️🚵🏻‍♀🚵🏼‍♀️🚵🏼‍♀🚵🏽‍♀️🚵🏽‍♀🚵🏾‍♀️🚵🏾‍♀🚵🏿‍♀️🚵🏿‍♀🏎️🏎🏍️🏍🤸🤸🏻🤸🏼🤸🏽🤸🏾🤸🏿🤸‍♂️🤸‍♂🤸🏻‍♂️🤸🏻‍♂🤸🏼‍♂️🤸🏼‍♂🤸🏽‍♂️🤸🏽‍♂🤸🏾‍♂️🤸🏾‍♂🤸🏿‍♂️🤸🏿‍♂🤸‍♀️🤸‍♀🤸🏻‍♀️🤸🏻‍♀🤸🏼‍♀️🤸🏼‍♀🤸🏽‍♀️🤸🏽‍♀🤸🏾‍♀️🤸🏾‍♀🤸🏿‍♀️🤸🏿‍♀🤼🤼‍♂️🤼‍♂🤼‍♀️🤼‍♀🤽🤽🏻🤽🏼🤽🏽🤽🏾🤽🏿🤽‍♂️🤽‍♂🤽🏻‍♂️🤽🏻‍♂🤽🏼‍♂️🤽🏼‍♂🤽🏽‍♂️🤽🏽‍♂🤽🏾‍♂️🤽🏾‍♂🤽🏿‍♂️🤽🏿‍♂🤽‍♀️🤽‍♀🤽🏻‍♀️🤽🏻‍♀🤽🏼‍♀️🤽🏼‍♀🤽🏽‍♀️🤽🏽‍♀🤽🏾‍♀️🤽🏾‍♀🤽🏿‍♀️🤽🏿‍♀🤾🤾🏻🤾🏼🤾🏽🤾🏾🤾🏿🤾‍♂️🤾‍♂🤾🏻‍♂️🤾🏻‍♂🤾🏼‍♂️🤾🏼‍♂🤾🏽‍♂️🤾🏽‍♂🤾🏾‍♂️🤾🏾‍♂🤾🏿‍♂️🤾🏿‍♂🤾‍♀️🤾‍♀🤾🏻‍♀️🤾🏻‍♀🤾🏼‍♀️🤾🏼‍♀🤾🏽‍♀️🤾🏽‍♀🤾🏾‍♀️🤾🏾‍♀🤾🏿‍♀️🤾🏿‍♀🤹🤹🏻🤹🏼🤹🏽🤹🏾🤹🏿🤹‍♂️🤹‍♂🤹🏻‍♂️🤹🏻‍♂🤹🏼‍♂️🤹🏼‍♂🤹🏽‍♂️🤹🏽‍♂🤹🏾‍♂️🤹🏾‍♂🤹🏿‍♂️🤹🏿‍♂🤹‍♀️🤹‍♀🤹🏻‍♀️🤹🏻‍♀🤹🏼‍♀️🤹🏼‍♀🤹🏽‍♀️🤹🏽‍♀🤹🏾‍♀️🤹🏾‍♀🤹🏿‍♀️🤹🏿‍♀👫👬👭💏👩‍❤️‍💋‍👨👩‍❤‍💋‍👨👨‍❤️‍💋‍👨👨‍❤‍💋‍👨👩‍❤️‍💋‍👩👩‍❤‍💋‍👩💑👩‍❤️‍👨👩‍❤‍👨👨‍❤️‍👨👨‍❤‍👨👩‍❤️‍👩👩‍❤‍👩👪👨‍👩‍👦👨‍👩‍👧👨‍👩‍👧‍👦👨‍👩‍👦‍👦👨‍👩‍👧‍👧👨‍👨‍👦👨‍👨‍👧👨‍👨‍👧‍👦👨‍👨‍👦‍👦👨‍👨‍👧‍👧👩‍👩‍👦👩‍👩‍👧👩‍👩‍👧‍👦👩‍👩‍👦‍👦👩‍👩‍👧‍👧👨‍👦👨‍👦‍👦👨‍👧👨‍👧‍👦👨‍👧‍👧👩‍👦👩‍👦‍👦👩‍👧👩‍👧‍👦👩‍👧‍👧🤳🤳🏻🤳🏼🤳🏽🤳🏾🤳🏿💪💪🏻💪🏼💪🏽💪🏾💪🏿🦵🦵🏻🦵🏼🦵🏽🦵🏾🦵🏿🦶🦶🏻🦶🏼🦶🏽🦶🏾🦶🏿👈👈🏻👈🏼👈🏽👈🏾👈🏿👉👉🏻👉🏼👉🏽👉🏾👉🏿☝️☝☝🏻☝🏼☝🏽☝🏾☝🏿👆👆🏻👆🏼👆🏽👆🏾👆🏿🖕🖕🏻🖕🏼🖕🏽🖕🏾🖕🏿👇👇🏻👇🏼👇🏽👇🏾👇🏿✌️✌✌🏻✌🏼✌🏽✌🏾✌🏿🤞🤞🏻🤞🏼🤞🏽🤞🏾🤞🏿🖖🖖🏻🖖🏼🖖🏽🖖🏾🖖🏿🤘🤘🏻🤘🏼🤘🏽🤘🏾🤘🏿🤙🤙🏻🤙🏼🤙🏽🤙🏾🤙🏿🖐️🖐🖐🏻🖐🏼🖐🏽🖐🏾🖐🏿✋✋🏻✋🏼✋🏽✋🏾✋🏿👌👌🏻👌🏼👌🏽👌🏾👌🏿👍👍🏻👍🏼👍🏽👍🏾👍🏿👎👎🏻👎🏼👎🏽👎🏾👎🏿✊✊🏻✊🏼✊🏽✊🏾✊🏿👊👊🏻👊🏼👊🏽👊🏾👊🏿🤛🤛🏻🤛🏼🤛🏽🤛🏾🤛🏿🤜🤜🏻🤜🏼🤜🏽🤜🏾🤜🏿🤚🤚🏻🤚🏼🤚🏽🤚🏾🤚🏿👋👋🏻👋🏼👋🏽👋🏾👋🏿🤟🤟🏻🤟🏼🤟🏽🤟🏾🤟🏿✍️✍✍🏻✍🏼✍🏽✍🏾✍🏿👏👏🏻👏🏼👏🏽👏🏾👏🏿👐👐🏻👐🏼👐🏽👐🏾👐🏿🙌🙌🏻🙌🏼🙌🏽🙌🏾🙌🏿🤲🤲🏻🤲🏼🤲🏽🤲🏾🤲🏿🙏🙏🏻🙏🏼🙏🏽🙏🏾🙏🏿🤝💅💅🏻💅🏼💅🏽💅🏾💅🏿👂👂🏻👂🏼👂🏽👂🏾👂🏿👃👃🏻👃🏼👃🏽👃🏾👃🏿🦰🦱🦲🦳👣👀👁️👁👁️‍🗨️👁‍🗨️👁️‍🗨👁‍🗨🧠🦴🦷👅👄💋💘❤️❤💓💔💕💖💗💙💚💛🧡💜🖤💝💞💟❣️❣💌💤💢💣💥💦💨💫💬🗨️🗨🗯️🗯💭🕳️🕳👓🕶️🕶🥽🥼👔👕👖🧣🧤🧥🧦👗👘👙👚👛👜👝🛍️🛍🎒👞👟🥾🥿👠👡👢👑👒🎩🎓🧢⛑️⛑📿💄💍💎🐵🐒🦍🐶🐕🐩🐺🦊🦝🐱🐈🦁🐯🐅🐆🐴🐎🦄🦓🦌🐮🐂🐃🐄🐷🐖🐗🐽🐏🐑🐐🐪🐫🦙🦒🐘🦏🦛🐭🐁🐀🐹🐰🐇🐿️🐿🦔🦇🐻🐨🐼🦘🦡🐾🦃🐔🐓🐣🐤🐥🐦🐧🕊️🕊🦅🦆🦢🦉🦚🦜🐸🐊🐢🦎🐍🐲🐉🦕🦖🐳🐋🐬🐟🐠🐡🦈🐙🐚🦀🦞🦐🦑🐌🦋🐛🐜🐝🐞🦗🕷️🕷🕸️🕸🦂🦟🦠💐🌸💮🏵️🏵🌹🥀🌺🌻🌼🌷🌱🌲🌳🌴🌵🌾🌿☘️☘🍀🍁🍂🍃🍇🍈🍉🍊🍋🍌🍍🥭🍎🍏🍐🍑🍒🍓🥝🍅🥥🥑🍆🥔🥕🌽🌶️🌶🥒🥬🥦🍄🥜🌰🍞🥐🥖🥨🥯🥞🧀🍖🍗🥩🥓🍔🍟🍕🌭🥪🌮🌯🥙🥚🍳🥘🍲🥣🥗🍿🧂🥫🍱🍘🍙🍚🍛🍜🍝🍠🍢🍣🍤🍥🥮🍡🥟🥠🥡🍦🍧🍨🍩🍪🎂🍰🧁🥧🍫🍬🍭🍮🍯🍼🥛☕🍵🍶🍾🍷🍸🍹🍺🍻🥂🥃🥤🥢🍽️🍽🍴🥄🔪🏺🌍🌎🌏🌐🗺️🗺🗾🧭🏔️🏔⛰️⛰🌋🗻🏕️🏕🏖️🏖🏜️🏜🏝️🏝🏞️🏞🏟️🏟🏛️🏛🏗️🏗🧱🏘️🏘🏚️🏚🏠🏡🏢🏣🏤🏥🏦🏨🏩🏪🏫🏬🏭🏯🏰💒🗼🗽⛪🕌🕍⛩️⛩🕋⛲⛺🌁🌃🏙️🏙🌄🌅🌆🌇🌉♨️♨🌌🎠🎡🎢💈🎪🚂🚃🚄🚅🚆🚇🚈🚉🚊🚝🚞🚋🚌🚍🚎🚐🚑🚒🚓🚔🚕🚖🚗🚘🚙🚚🚛🚜🚲🛴🛹🛵🚏🛣️🛣🛤️🛤🛢️🛢⛽🚨🚥🚦🛑🚧⚓⛵🛶🚤🛳️🛳⛴️⛴🛥️🛥🚢✈️✈🛩️🛩🛫🛬💺🚁🚟🚠🚡🛰️🛰🚀🛸🛎️🛎🧳⌛⏳⌚⏰⏱️⏱⏲️⏲🕰️🕰🕛🕧🕐🕜🕑🕝🕒🕞🕓🕟🕔🕠🕕🕡🕖🕢🕗🕣🕘🕤🕙🕥🕚🕦🌑🌒🌓🌔🌕🌖🌗🌘🌙🌚🌛🌜🌡️🌡☀️☀🌝🌞⭐🌟🌠☁️☁⛅⛈️⛈🌤️🌤🌥️🌥🌦️🌦🌧️🌧🌨️🌨🌩️🌩🌪️🌪🌫️🌫🌬️🌬🌀🌈🌂☂️☂☔⛱️⛱⚡❄️❄☃️☃⛄☄️☄🔥💧🌊🎃🎄🎆🎇🧨✨🎈🎉🎊🎋🎍🎎🎏🎐🎑🧧🎀🎁🎗️🎗🎟️🎟🎫🎖️🎖🏆🏅🥇🥈🥉⚽⚾🥎🏀🏐🏈🏉🎾🥏🎳🏏🏑🏒🥍🏓🏸🥊🥋🥅⛳⛸️⛸🎣🎽🎿🛷🥌🎯🎱🔮🧿🎮🕹️🕹🎰🎲🧩🧸♠️♠♥️♥♦️♦♣️♣♟️♟🃏🀄🎴🎭🖼️🖼🎨🧵🧶🔇🔈🔉🔊📢📣📯🔔🔕🎼🎵🎶🎙️🎙🎚️🎚🎛️🎛🎤🎧📻🎷🎸🎹🎺🎻🥁📱📲☎️☎📞📟📠🔋🔌💻🖥️🖥🖨️🖨⌨️⌨🖱️🖱🖲️🖲💽💾💿📀🧮🎥🎞️🎞📽️📽🎬📺📷📸📹📼🔍🔎🕯️🕯💡🔦🏮📔📕📖📗📘📙📚📓📒📃📜📄📰🗞️🗞📑🔖🏷️🏷💰💴💵💶💷💸💳🧾💹💱💲✉️✉📧📨📩📤📥📦📫📪📬📭📮🗳️🗳✏️✏✒️✒🖋️🖋🖊️🖊🖌️🖌🖍️🖍📝💼📁📂🗂️🗂📅📆🗒️🗒🗓️🗓📇📈📉📊📋📌📍📎🖇️🖇📏📐✂️✂🗃️🗃🗄️🗄🗑️🗑🔒🔓🔏🔐🔑🗝️🗝🔨⛏️⛏⚒️⚒🛠️🛠🗡️🗡⚔️⚔🔫🏹🛡️🛡🔧🔩⚙️⚙🗜️🗜⚖️⚖🔗⛓️⛓🧰🧲⚗️⚗🧪🧫🧬🔬🔭📡💉💊🚪🛏️🛏🛋️🛋🚽🚿🛁🧴🧷🧹🧺🧻🧼🧽🧯🛒🚬⚰️⚰⚱️⚱🗿🏧🚮🚰♿🚹🚺🚻🚼🚾🛂🛃🛄🛅⚠️⚠🚸⛔🚫🚳🚭🚯🚱🚷📵🔞☢️☢☣️☣⬆️⬆↗️↗➡️➡↘️↘⬇️⬇↙️↙⬅️⬅↖️↖↕️↕↔️↔↩️↩↪️↪⤴️⤴⤵️⤵🔃🔄🔙🔚🔛🔜🔝🛐⚛️⚛🕉️🕉✡️✡☸️☸☯️☯✝️✝☦️☦☪️☪☮️☮🕎🔯♈♉♊♋♌♍♎♏♐♑♒♓⛎🔀🔁🔂▶️▶⏩⏭️⏭⏯️⏯◀️◀⏪⏮️⏮🔼⏫🔽⏬⏸️⏸⏹️⏹⏺️⏺⏏️⏏🎦🔅🔆📶📳📴♀️♀♂️♂⚕️⚕♾️♾♻️♻⚜️⚜🔱📛🔰⭕✅☑️☑✔️✔✖️✖❌❎➕➖➗➰➿〽️〽✳️✳✴️✴❇️❇‼️‼⁉️⁉❓❔❕❗〰️〰©️©®️®™️™#️⃣#⃣*️⃣*⃣0️⃣0⃣1️⃣1⃣2️⃣2⃣3️⃣3⃣4️⃣4⃣5️⃣5⃣6️⃣6⃣7️⃣7⃣8️⃣8⃣9️⃣9⃣🔟💯🔠🔡🔢🔣🔤🅰️🅰🆎🅱️🅱🆑🆒🆓ℹ️ℹ🆔Ⓜ️Ⓜ🆕🆖🅾️🅾🆗🅿️🅿🆘🆙🆚🈁🈂️🈂🈷️🈷🈶🈯🉐🈹🈚🈲🉑🈸🈴🈳㊗️㊗㊙️㊙🈺🈵▪️▪▫️▫◻️◻◼️◼◽◾⬛⬜🔶🔷🔸🔹🔺🔻💠🔘🔲🔳⚪⚫🔴🔵🏁🚩🎌🏴🏳️🏳🏳️‍🌈🏳‍🌈🏴‍☠️🏴‍☠🇦🇨🇦🇩🇦🇪🇦🇫🇦🇬🇦🇮🇦🇱🇦🇲🇦🇴🇦🇶🇦🇷🇦🇸🇦🇹🇦🇺🇦🇼🇦🇽🇦🇿🇧🇦🇧🇧🇧🇩🇧🇪🇧🇫🇧🇬🇧🇭🇧🇮🇧🇯🇧🇱🇧🇲🇧🇳🇧🇴🇧🇶🇧🇷🇧🇸🇧🇹🇧🇻🇧🇼🇧🇾🇧🇿🇨🇦🇨🇨🇨🇩🇨🇫🇨🇬🇨🇭🇨🇮🇨🇰🇨🇱🇨🇲🇨🇳🇨🇴🇨🇵🇨🇷🇨🇺🇨🇻🇨🇼🇨🇽🇨🇾🇨🇿🇩🇪🇩🇬🇩🇯🇩🇰🇩🇲🇩🇴🇩🇿🇪🇦🇪🇨🇪🇪🇪🇬🇪🇭🇪🇷🇪🇸🇪🇹🇪🇺🇫🇮🇫🇯🇫🇰🇫🇲🇫🇴🇫🇷🇬🇦🇬🇧🇬🇩🇬🇪🇬🇫🇬🇬🇬🇭🇬🇮🇬🇱🇬🇲🇬🇳🇬🇵🇬🇶🇬🇷🇬🇸🇬🇹🇬🇺🇬🇼🇬🇾🇭🇰🇭🇲🇭🇳🇭🇷🇭🇹🇭🇺🇮🇨🇮🇩🇮🇪🇮🇱🇮🇲🇮🇳🇮🇴🇮🇶🇮🇷🇮🇸🇮🇹🇯🇪🇯🇲🇯🇴🇯🇵🇰🇪🇰🇬🇰🇭🇰🇮🇰🇲🇰🇳🇰🇵🇰🇷🇰🇼🇰🇾🇰🇿🇱🇦🇱🇧🇱🇨🇱🇮🇱🇰🇱🇷🇱🇸🇱🇹🇱🇺🇱🇻🇱🇾🇲🇦🇲🇨🇲🇩🇲🇪🇲🇫🇲🇬🇲🇭🇲🇰🇲🇱🇲🇲🇲🇳🇲🇴🇲🇵🇲🇶🇲🇷🇲🇸🇲🇹🇲🇺🇲🇻🇲🇼🇲🇽🇲🇾🇲🇿🇳🇦🇳🇨🇳🇪🇳🇫🇳🇬🇳🇮🇳🇱🇳🇴🇳🇵🇳🇷🇳🇺🇳🇿🇴🇲🇵🇦🇵🇪🇵🇫🇵🇬🇵🇭🇵🇰🇵🇱🇵🇲🇵🇳🇵🇷🇵🇸🇵🇹🇵🇼🇵🇾🇶🇦🇷🇪🇷🇴🇷🇸🇷🇺🇷🇼🇸🇦🇸🇧🇸🇨🇸🇩🇸🇪🇸🇬🇸🇭🇸🇮🇸🇯🇸🇰🇸🇱🇸🇲🇸🇳🇸🇴🇸🇷🇸🇸🇸🇹🇸🇻🇸🇽🇸🇾🇸🇿🇹🇦🇹🇨🇹🇩🇹🇫🇹🇬🇹🇭🇹🇯🇹🇰🇹🇱🇹🇲🇹🇳🇹🇴🇹🇷🇹🇹🇹🇻🇹🇼🇹🇿🇺🇦🇺🇬🇺🇲🇺🇳🇺🇸🇺🇾🇺🇿🇻🇦🇻🇨🇻🇪🇻🇬🇻🇮🇻🇳🇻🇺🇼🇫🇼🇸🇽🇰🇾🇪🇾🇹🇿🇦🇿🇲🇿🇼🏴󠁧󠁢󠁥󠁮󠁧󠁿🏴󠁧󠁢󠁳󠁣󠁴󠁿🏴󠁧󠁢󠁷󠁬󠁳󠁿" + ); + expect(() => emoji.parse(":-)")).toThrow(); + expect(() => emoji.parse("😀 is an emoji")).toThrow(); + expect(() => emoji.parse("😀stuff")).toThrow(); + expect(() => emoji.parse("stuff😀")).toThrow(); +}); + +test("uuid", () => { + const uuid = z.string().uuid("custom error"); + uuid.parse("9491d710-3185-4e06-bea0-6a2f275345e0"); + uuid.parse("d89e7b01-7598-ed11-9d7a-0022489382fd"); // new sequential id + uuid.parse("00000000-0000-0000-0000-000000000000"); + uuid.parse("b3ce60f8-e8b9-40f5-1150-172ede56ff74"); // Variant 0 - RFC 4122: Reserved, NCS backward compatibility + uuid.parse("92e76bf9-28b3-4730-cd7f-cb6bc51f8c09"); // Variant 2 - RFC 4122: Reserved, Microsoft Corporation backward compatibility + const result = uuid.safeParse("9491d710-3185-4e06-bea0-6a2f275345e0X"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("custom error"); + } +}); + +test("bad uuid", () => { + const uuid = z.string().uuid("custom error"); + uuid.parse("9491d710-3185-4e06-bea0-6a2f275345e0"); + const result = uuid.safeParse("invalid uuid"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("custom error"); + } +}); + +test("nanoid", () => { + const nanoid = z.string().nanoid("custom error"); + nanoid.parse("lfNZluvAxMkf7Q8C5H-QS"); + nanoid.parse("mIU_4PJWikaU8fMbmkouz"); + nanoid.parse("Hb9ZUtUa2JDm_dD-47EGv"); + nanoid.parse("5Noocgv_8vQ9oPijj4ioQ"); + const result = nanoid.safeParse("Xq90uDyhddC53KsoASYJGX"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("custom error"); + } +}); + +test("bad nanoid", () => { + const nanoid = z.string().nanoid("custom error"); + nanoid.parse("ySh_984wpDUu7IQRrLXAp"); + const result = nanoid.safeParse("invalid nanoid"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("custom error"); + } +}); + +test("cuid", () => { + const cuid = z.string().cuid(); + cuid.parse("ckopqwooh000001la8mbi2im9"); + const result = cuid.safeParse("cifjhdsfhsd-invalid-cuid"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("Invalid cuid"); + } +}); + +test("cuid2", () => { + const cuid2 = z.string().cuid2(); + const validStrings = [ + "a", // short string + "tz4a98xxat96iws9zmbrgj3a", // normal string + "kf5vz6ssxe4zjcb409rjgo747tc5qjazgptvotk6", // longer than require("@paralleldrive/cuid2").bigLength + ]; + for (const s of validStrings) { + cuid2.parse(s); + } + + const invalidStrings = [ + "", // empty string + "tz4a98xxat96iws9zMbrgj3a", // include uppercase + "tz4a98xxat96iws-zmbrgj3a", // involve symbols + ]; + const results = invalidStrings.map((s) => cuid2.safeParse(s)); + expect(results.every((r) => !r.success)).toEqual(true); + if (!results[0].success) { + expect(results[0].error.issues[0].message).toEqual("Invalid cuid2"); + } +}); + +test("ulid", () => { + const ulid = z.string().ulid(); + ulid.parse("01ARZ3NDEKTSV4RRFFQ69G5FAV"); + const result = ulid.safeParse("invalidulid"); + expect(result.success).toEqual(false); + const tooLong = "01ARZ3NDEKTSV4RRFFQ69G5FAVA"; + expect(ulid.safeParse(tooLong).success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("Invalid ulid"); + } + const caseInsensitive = ulid.safeParse("01arZ3nDeKTsV4RRffQ69G5FAV"); + expect(caseInsensitive.success).toEqual(true); +}); + +test("regex", () => { + z.string() + .regex(/^moo+$/) + .parse("mooooo"); + expect(() => z.string().uuid().parse("purr")).toThrow(); +}); + +test("regexp error message", () => { + const result = z + .string() + .regex(/^moo+$/) + .safeParse("boooo"); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("Invalid"); + } else { + throw new Error("validation should have failed"); + } + + expect(() => z.string().uuid().parse("purr")).toThrow(); +}); + +test("regex lastIndex reset", () => { + const schema = z.string().regex(/^\d+$/g); + expect(schema.safeParse("123").success).toEqual(true); + expect(schema.safeParse("123").success).toEqual(true); + expect(schema.safeParse("123").success).toEqual(true); + expect(schema.safeParse("123").success).toEqual(true); + expect(schema.safeParse("123").success).toEqual(true); +}); + +test("checks getters", () => { + expect(z.string().email().isEmail).toEqual(true); + expect(z.string().email().isURL).toEqual(false); + expect(z.string().email().isCUID).toEqual(false); + expect(z.string().email().isCUID2).toEqual(false); + expect(z.string().email().isUUID).toEqual(false); + expect(z.string().email().isNANOID).toEqual(false); + expect(z.string().email().isIP).toEqual(false); + expect(z.string().email().isCIDR).toEqual(false); + expect(z.string().email().isULID).toEqual(false); + + expect(z.string().url().isEmail).toEqual(false); + expect(z.string().url().isURL).toEqual(true); + expect(z.string().url().isCUID).toEqual(false); + expect(z.string().url().isCUID2).toEqual(false); + expect(z.string().url().isUUID).toEqual(false); + expect(z.string().url().isNANOID).toEqual(false); + expect(z.string().url().isIP).toEqual(false); + expect(z.string().url().isCIDR).toEqual(false); + expect(z.string().url().isULID).toEqual(false); + + expect(z.string().cuid().isEmail).toEqual(false); + expect(z.string().cuid().isURL).toEqual(false); + expect(z.string().cuid().isCUID).toEqual(true); + expect(z.string().cuid().isCUID2).toEqual(false); + expect(z.string().cuid().isUUID).toEqual(false); + expect(z.string().cuid().isNANOID).toEqual(false); + expect(z.string().cuid().isIP).toEqual(false); + expect(z.string().cuid().isCIDR).toEqual(false); + expect(z.string().cuid().isULID).toEqual(false); + + expect(z.string().cuid2().isEmail).toEqual(false); + expect(z.string().cuid2().isURL).toEqual(false); + expect(z.string().cuid2().isCUID).toEqual(false); + expect(z.string().cuid2().isCUID2).toEqual(true); + expect(z.string().cuid2().isUUID).toEqual(false); + expect(z.string().cuid2().isNANOID).toEqual(false); + expect(z.string().cuid2().isIP).toEqual(false); + expect(z.string().cuid2().isCIDR).toEqual(false); + expect(z.string().cuid2().isULID).toEqual(false); + + expect(z.string().uuid().isEmail).toEqual(false); + expect(z.string().uuid().isURL).toEqual(false); + expect(z.string().uuid().isCUID).toEqual(false); + expect(z.string().uuid().isCUID2).toEqual(false); + expect(z.string().uuid().isUUID).toEqual(true); + expect(z.string().uuid().isNANOID).toEqual(false); + expect(z.string().uuid().isIP).toEqual(false); + expect(z.string().uuid().isCIDR).toEqual(false); + expect(z.string().uuid().isULID).toEqual(false); + + expect(z.string().nanoid().isEmail).toEqual(false); + expect(z.string().nanoid().isURL).toEqual(false); + expect(z.string().nanoid().isCUID).toEqual(false); + expect(z.string().nanoid().isCUID2).toEqual(false); + expect(z.string().nanoid().isUUID).toEqual(false); + expect(z.string().nanoid().isNANOID).toEqual(true); + expect(z.string().nanoid().isIP).toEqual(false); + expect(z.string().nanoid().isCIDR).toEqual(false); + expect(z.string().nanoid().isULID).toEqual(false); + + expect(z.string().ip().isEmail).toEqual(false); + expect(z.string().ip().isURL).toEqual(false); + expect(z.string().ip().isCUID).toEqual(false); + expect(z.string().ip().isCUID2).toEqual(false); + expect(z.string().ip().isUUID).toEqual(false); + expect(z.string().ip().isNANOID).toEqual(false); + expect(z.string().ip().isIP).toEqual(true); + expect(z.string().ip().isCIDR).toEqual(false); + expect(z.string().ip().isULID).toEqual(false); + + expect(z.string().cidr().isEmail).toEqual(false); + expect(z.string().cidr().isURL).toEqual(false); + expect(z.string().cidr().isCUID).toEqual(false); + expect(z.string().cidr().isCUID2).toEqual(false); + expect(z.string().cidr().isUUID).toEqual(false); + expect(z.string().cidr().isNANOID).toEqual(false); + expect(z.string().cidr().isIP).toEqual(false); + expect(z.string().cidr().isCIDR).toEqual(true); + expect(z.string().cidr().isULID).toEqual(false); + + expect(z.string().ulid().isEmail).toEqual(false); + expect(z.string().ulid().isURL).toEqual(false); + expect(z.string().ulid().isCUID).toEqual(false); + expect(z.string().ulid().isCUID2).toEqual(false); + expect(z.string().ulid().isUUID).toEqual(false); + expect(z.string().ulid().isNANOID).toEqual(false); + expect(z.string().ulid().isIP).toEqual(false); + expect(z.string().ulid().isCIDR).toEqual(false); + expect(z.string().ulid().isULID).toEqual(true); +}); + +test("min max getters", () => { + expect(z.string().min(5).minLength).toEqual(5); + expect(z.string().min(5).min(10).minLength).toEqual(10); + expect(z.string().minLength).toEqual(null); + + expect(z.string().max(5).maxLength).toEqual(5); + expect(z.string().max(5).max(1).maxLength).toEqual(1); + expect(z.string().maxLength).toEqual(null); +}); + +test("trim", () => { + expect(z.string().trim().min(2).parse(" 12 ")).toEqual("12"); + + // ordering of methods is respected + expect(z.string().min(2).trim().parse(" 1 ")).toEqual("1"); + expect(() => z.string().trim().min(2).parse(" 1 ")).toThrow(); +}); + +test("lowerCase", () => { + expect(z.string().toLowerCase().parse("ASDF")).toEqual("asdf"); + expect(z.string().toUpperCase().parse("asdf")).toEqual("ASDF"); +}); + +test("datetime", () => { + const a = z.string().datetime({}); + expect(a.isDatetime).toEqual(true); + + const b = z.string().datetime({ offset: true }); + expect(b.isDatetime).toEqual(true); + + const c = z.string().datetime({ precision: 3 }); + expect(c.isDatetime).toEqual(true); + + const d = z.string().datetime({ offset: true, precision: 0 }); + expect(d.isDatetime).toEqual(true); + + const { isDatetime } = z.string().datetime(); + expect(isDatetime).toEqual(true); +}); + +test("datetime parsing", () => { + const datetime = z.string().datetime(); + datetime.parse("1970-01-01T00:00:00.000Z"); + datetime.parse("2022-10-13T09:52:31.816Z"); + datetime.parse("2022-10-13T09:52:31.8162314Z"); + datetime.parse("1970-01-01T00:00:00Z"); + datetime.parse("2022-10-13T09:52:31Z"); + datetime.parse("2022-10-13T09:52Z"); + expect(() => datetime.parse("")).toThrow(); + expect(() => datetime.parse("foo")).toThrow(); + expect(() => datetime.parse("2020-10-14")).toThrow(); + expect(() => datetime.parse("T18:45:12.123")).toThrow(); + expect(() => datetime.parse("2020-10-14T17:42:29+00:00")).toThrow(); + expect(() => datetime.parse("2020-10-14T17:42.123+00:00")).toThrow(); + + const datetimeNoMs = z.string().datetime({ precision: 0 }); + datetimeNoMs.parse("1970-01-01T00:00:00Z"); + datetimeNoMs.parse("2022-10-13T09:52:31Z"); + datetimeNoMs.parse("2022-10-13T09:52Z"); + expect(() => datetimeNoMs.parse("tuna")).toThrow(); + expect(() => datetimeNoMs.parse("1970-01-01T00:00:00.000Z")).toThrow(); + expect(() => datetimeNoMs.parse("1970-01-01T00:00:00.Z")).toThrow(); + expect(() => datetimeNoMs.parse("2022-10-13T09:52:31.816Z")).toThrow(); + + const datetime3Ms = z.string().datetime({ precision: 3 }); + datetime3Ms.parse("1970-01-01T00:00:00.000Z"); + datetime3Ms.parse("2022-10-13T09:52:31.123Z"); + expect(() => datetime3Ms.parse("tuna")).toThrow(); + expect(() => datetime3Ms.parse("1970-01-01T00:00:00.1Z")).toThrow(); + expect(() => datetime3Ms.parse("1970-01-01T00:00:00.12Z")).toThrow(); + expect(() => datetime3Ms.parse("2022-10-13T09:52:31Z")).toThrow(); + expect(() => datetime3Ms.parse("2022-10-13T09:52Z")).toThrow(); + + const datetimeOffset = z.string().datetime({ offset: true }); + datetimeOffset.parse("1970-01-01T00:00:00.000Z"); + datetimeOffset.parse("2022-10-13T09:52:31.816234134Z"); + datetimeOffset.parse("1970-01-01T00:00:00Z"); + datetimeOffset.parse("2022-10-13T09:52:31.4Z"); + datetimeOffset.parse("2020-10-14T17:42:29+00:00"); + datetimeOffset.parse("2020-10-14T17:42:29+03:15"); + datetimeOffset.parse("2020-10-14T17:42:29+0315"); + datetimeOffset.parse("2020-10-14T17:42+0315"); + expect(() => datetimeOffset.parse("2020-10-14T17:42:29+03")); + expect(() => datetimeOffset.parse("tuna")).toThrow(); + expect(() => datetimeOffset.parse("2022-10-13T09:52:31.Z")).toThrow(); + + const datetimeOffsetNoMs = z.string().datetime({ offset: true, precision: 0 }); + datetimeOffsetNoMs.parse("1970-01-01T00:00:00Z"); + datetimeOffsetNoMs.parse("2022-10-13T09:52:31Z"); + datetimeOffsetNoMs.parse("2020-10-14T17:42:29+00:00"); + datetimeOffsetNoMs.parse("2020-10-14T17:42:29+0000"); + datetimeOffsetNoMs.parse("2020-10-14T17:42+0000"); + expect(() => datetimeOffsetNoMs.parse("2020-10-14T17:42:29+00")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("tuna")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("1970-01-01T00:00:00.000Z")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("1970-01-01T00:00:00.Z")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("2022-10-13T09:52:31.816Z")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("2020-10-14T17:42:29.124+00:00")).toThrow(); + + const datetimeOffset4Ms = z.string().datetime({ offset: true, precision: 4 }); + datetimeOffset4Ms.parse("1970-01-01T00:00:00.1234Z"); + datetimeOffset4Ms.parse("2020-10-14T17:42:29.1234+00:00"); + datetimeOffset4Ms.parse("2020-10-14T17:42:29.1234+0000"); + expect(() => datetimeOffset4Ms.parse("2020-10-14T17:42:29.1234+00")).toThrow(); + expect(() => datetimeOffset4Ms.parse("tuna")).toThrow(); + expect(() => datetimeOffset4Ms.parse("1970-01-01T00:00:00.123Z")).toThrow(); + expect(() => datetimeOffset4Ms.parse("2020-10-14T17:42:29.124+00:00")).toThrow(); + expect(() => datetimeOffset4Ms.parse("2020-10-14T17:42+00:00")).toThrow(); +}); + +test("date", () => { + const a = z.string().date(); + expect(a.isDate).toEqual(true); +}); + +test("date parsing", () => { + const date = z.string().date(); + date.parse("1970-01-01"); + date.parse("2022-01-31"); + date.parse("2022-03-31"); + date.parse("2022-04-30"); + date.parse("2022-05-31"); + date.parse("2022-06-30"); + date.parse("2022-07-31"); + date.parse("2022-08-31"); + date.parse("2022-09-30"); + date.parse("2022-10-31"); + date.parse("2022-11-30"); + date.parse("2022-12-31"); + + date.parse("2000-02-29"); + date.parse("2400-02-29"); + expect(() => date.parse("2022-02-29")).toThrow(); + expect(() => date.parse("2100-02-29")).toThrow(); + expect(() => date.parse("2200-02-29")).toThrow(); + expect(() => date.parse("2300-02-29")).toThrow(); + expect(() => date.parse("2500-02-29")).toThrow(); + + expect(() => date.parse("")).toThrow(); + expect(() => date.parse("foo")).toThrow(); + expect(() => date.parse("200-01-01")).toThrow(); + expect(() => date.parse("20000-01-01")).toThrow(); + expect(() => date.parse("2000-0-01")).toThrow(); + expect(() => date.parse("2000-011-01")).toThrow(); + expect(() => date.parse("2000-01-0")).toThrow(); + expect(() => date.parse("2000-01-011")).toThrow(); + expect(() => date.parse("2000/01/01")).toThrow(); + expect(() => date.parse("01-01-2022")).toThrow(); + expect(() => date.parse("01/01/2022")).toThrow(); + expect(() => date.parse("2000-01-01 00:00:00Z")).toThrow(); + expect(() => date.parse("2020-10-14T17:42:29+00:00")).toThrow(); + expect(() => date.parse("2020-10-14T17:42:29Z")).toThrow(); + expect(() => date.parse("2020-10-14T17:42:29")).toThrow(); + expect(() => date.parse("2020-10-14T17:42:29.123Z")).toThrow(); + + expect(() => date.parse("2000-00-12")).toThrow(); + expect(() => date.parse("2000-12-00")).toThrow(); + expect(() => date.parse("2000-01-32")).toThrow(); + expect(() => date.parse("2000-13-01")).toThrow(); + expect(() => date.parse("2000-21-01")).toThrow(); + + expect(() => date.parse("2000-02-30")).toThrow(); + expect(() => date.parse("2000-02-31")).toThrow(); + expect(() => date.parse("2000-04-31")).toThrow(); + expect(() => date.parse("2000-06-31")).toThrow(); + expect(() => date.parse("2000-09-31")).toThrow(); + expect(() => date.parse("2000-11-31")).toThrow(); +}); + +test("time", () => { + const a = z.string().time(); + expect(a.isTime).toEqual(true); +}); + +test("time parsing", () => { + const time = z.string().time(); + time.parse("00:00:00"); + time.parse("23:00:00"); + time.parse("00:59:00"); + time.parse("00:00:59"); + time.parse("23:59:59"); + time.parse("09:52:31"); + time.parse("23:59:59.9999999"); + time.parse("23:59"); + expect(() => time.parse("")).toThrow(); + expect(() => time.parse("foo")).toThrow(); + expect(() => time.parse("00:00:00Z")).toThrow(); + expect(() => time.parse("0:00:00")).toThrow(); + expect(() => time.parse("00:0:00")).toThrow(); + expect(() => time.parse("00:00:0")).toThrow(); + expect(() => time.parse("00:00:00.000+00:00")).toThrow(); + + expect(() => time.parse("24:00:00")).toThrow(); + expect(() => time.parse("00:60:00")).toThrow(); + expect(() => time.parse("00:00:60")).toThrow(); + expect(() => time.parse("24:60:60")).toThrow(); + expect(() => time.parse("24:60")).toThrow(); + + const time2 = z.string().time({ precision: 2 }); + time2.parse("00:00:00.00"); + time2.parse("09:52:31.12"); + time2.parse("23:59:59.99"); + expect(() => time2.parse("")).toThrow(); + expect(() => time2.parse("foo")).toThrow(); + expect(() => time2.parse("00:00:00")).toThrow(); + expect(() => time2.parse("00:00:00.00Z")).toThrow(); + expect(() => time2.parse("00:00:00.0")).toThrow(); + expect(() => time2.parse("00:00:00.000")).toThrow(); + expect(() => time2.parse("00:00:00.00+00:00")).toThrow(); + expect(() => time2.parse("23:59")).toThrow(); + + // const time3 = z.string().time({ offset: true }); + // time3.parse("00:00:00Z"); + // time3.parse("09:52:31Z"); + // time3.parse("00:00:00+00:00"); + // time3.parse("00:00:00+0000"); + // time3.parse("00:00:00.000Z"); + // time3.parse("00:00:00.000+00:00"); + // time3.parse("00:00:00.000+0000"); + // expect(() => time3.parse("")).toThrow(); + // expect(() => time3.parse("foo")).toThrow(); + // expect(() => time3.parse("00:00:00")).toThrow(); + // expect(() => time3.parse("00:00:00.000")).toThrow(); + + // const time4 = z.string().time({ offset: true, precision: 0 }); + // time4.parse("00:00:00Z"); + // time4.parse("09:52:31Z"); + // time4.parse("00:00:00+00:00"); + // time4.parse("00:00:00+0000"); + // expect(() => time4.parse("")).toThrow(); + // expect(() => time4.parse("foo")).toThrow(); + // expect(() => time4.parse("00:00:00.0")).toThrow(); + // expect(() => time4.parse("00:00:00.000")).toThrow(); + // expect(() => time4.parse("00:00:00.000+00:00")).toThrow(); +}); + +test("duration", () => { + const duration = z.string().duration(); + expect(duration.isDuration).toEqual(true); + + const validDurations = [ + "P3Y6M4DT12H30M5S", + "P2Y9M3DT12H31M8.001S", + "+P3Y6M4DT12H30M5S", + "-PT0.001S", + "+PT0.001S", + "PT0,001S", + "PT12H30M5S", + "-P2M1D", + "P-2M-1D", + "-P5DT10H", + "P-5DT-10H", + "P1Y", + "P2MT30M", + "PT6H", + "P5W", + "P0.5Y", + "P0,5Y", + "P42YT7.004M", + ]; + + const invalidDurations = ["foo bar", "", " ", "P", "T1H", "P0.5Y1D", "P0,5Y6M", "P1YT"]; + + for (const val of validDurations) { + const result = duration.safeParse(val); + if (!result.success) { + throw Error(`Valid duration could not be parsed: ${val}`); + } + } + + for (const val of invalidDurations) { + const result = duration.safeParse(val); + + if (result.success) { + throw Error(`Invalid duration was successful parsed: ${val}`); + } + + expect(result.error.issues[0].message).toEqual("Invalid duration"); + } +}); + +test("IP validation", () => { + const ip = z.string().ip(); + expect(ip.safeParse("122.122.122.122").success).toBe(true); + + const ipv4 = z.string().ip({ version: "v4" }); + expect(() => ipv4.parse("6097:adfa:6f0b:220d:db08:5021:6191:7990")).toThrow(); + + const ipv6 = z.string().ip({ version: "v6" }); + expect(() => ipv6.parse("254.164.77.1")).toThrow(); + + const validIPs = [ + "1e5e:e6c8:daac:514b:114b:e360:d8c0:682c", + "9d4:c956:420f:5788:4339:9b3b:2418:75c3", + "474f:4c83::4e40:a47:ff95:0cda", + "d329:0:25b4:db47:a9d1:0:4926:0000", + "e48:10fb:1499:3e28:e4b6:dea5:4692:912c", + "114.71.82.94", + "0.0.0.0", + "37.85.236.115", + "2001:4888:50:ff00:500:d::", + "2001:4888:50:ff00:0500:000d:000:0000", + "2001:4888:50:ff00:0500:000d:0000:0000", + ]; + + const invalidIPs = [ + "d329:1be4:25b4:db47:a9d1:dc71:4926:992c:14af", + "d5e7:7214:2b78::3906:85e6:53cc:709:32ba", + "8f69::c757:395e:976e::3441", + "54cb::473f:d516:0.255.256.22", + "54cb::473f:d516:192.168.1", + "256.0.4.4", + "-1.0.555.4", + "0.0.0.0.0", + "1.1.1", + ]; + // no parameters check IPv4 or IPv6 + const ipSchema = z.string().ip(); + expect(validIPs.every((ip) => ipSchema.safeParse(ip).success)).toBe(true); + expect(invalidIPs.every((ip) => ipSchema.safeParse(ip).success === false)).toBe(true); +}); + +test("CIDR validation", () => { + const ipv4Cidr = z.string().cidr({ version: "v4" }); + expect(() => ipv4Cidr.parse("2001:0db8:85a3::8a2e:0370:7334/64")).toThrow(); + + const ipv6Cidr = z.string().cidr({ version: "v6" }); + expect(() => ipv6Cidr.parse("192.168.0.1/24")).toThrow(); + + const validCidrs = [ + "192.168.0.0/24", + "10.0.0.0/8", + "203.0.113.0/24", + "192.0.2.0/24", + "127.0.0.0/8", + "172.16.0.0/12", + "192.168.1.0/24", + "fc00::/7", + "fd00::/8", + "2001:db8::/32", + "2607:f0d0:1002:51::4/64", + "2001:0db8:85a3:0000:0000:8a2e:0370:7334/128", + "2001:0db8:1234:0000::/64", + ]; + + const invalidCidrs = [ + "192.168.1.1/33", + "10.0.0.1/-1", + "192.168.1.1/24/24", + "192.168.1.0/abc", + "2001:db8::1/129", + "2001:db8::1/-1", + "2001:db8::1/64/64", + "2001:db8::1/abc", + ]; + + // no parameters check IPv4 or IPv6 + const cidrSchema = z.string().cidr(); + expect(validCidrs.every((ip) => cidrSchema.safeParse(ip).success)).toBe(true); + expect(invalidCidrs.every((ip) => cidrSchema.safeParse(ip).success === false)).toBe(true); +}); diff --git a/node_modules/zod/src/v3/tests/transformer.test.ts b/node_modules/zod/src/v3/tests/transformer.test.ts new file mode 100644 index 000000000..ddd9e9a63 --- /dev/null +++ b/node_modules/zod/src/v3/tests/transformer.test.ts @@ -0,0 +1,233 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; + +const stringToNumber = z.string().transform((arg) => Number.parseFloat(arg)); +// const numberToString = z +// .transformer(z.number()) +// .transform((n) => String(n)); +const asyncNumberToString = z.number().transform(async (n) => String(n)); + +test("transform ctx.addIssue with parse", () => { + const strs = ["foo", "bar"]; + + expect(() => { + z.string() + .transform((data, ctx) => { + const i = strs.indexOf(data); + if (i === -1) { + ctx.addIssue({ + code: "custom", + message: `${data} is not one of our allowed strings`, + }); + } + return data.length; + }) + .parse("asdf"); + }).toThrow( + JSON.stringify( + [ + { + code: "custom", + message: "asdf is not one of our allowed strings", + path: [], + }, + ], + null, + 2 + ) + ); +}); + +test("transform ctx.addIssue with parseAsync", async () => { + const strs = ["foo", "bar"]; + + const result = await z + .string() + .transform(async (data, ctx) => { + const i = strs.indexOf(data); + if (i === -1) { + ctx.addIssue({ + code: "custom", + message: `${data} is not one of our allowed strings`, + }); + } + return data.length; + }) + .safeParseAsync("asdf"); + + expect(JSON.parse(JSON.stringify(result))).toEqual({ + success: false, + error: { + issues: [ + { + code: "custom", + message: "asdf is not one of our allowed strings", + path: [], + }, + ], + name: "ZodError", + }, + }); +}); + +test("z.NEVER in transform", () => { + const foo = z + .number() + .optional() + .transform((val, ctx) => { + if (!val) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "bad" }); + return z.NEVER; + } + return val; + }); + type foo = z.infer; + util.assertEqual(true); + const arg = foo.safeParse(undefined); + if (!arg.success) { + expect(arg.error.issues[0].message).toEqual("bad"); + } +}); + +test("basic transformations", () => { + const r1 = z + .string() + .transform((data) => data.length) + .parse("asdf"); + expect(r1).toEqual(4); +}); + +test("coercion", () => { + const numToString = z.number().transform((n) => String(n)); + const data = z + .object({ + id: numToString, + }) + .parse({ id: 5 }); + + expect(data).toEqual({ id: "5" }); +}); + +test("async coercion", async () => { + const numToString = z.number().transform(async (n) => String(n)); + const data = await z + .object({ + id: numToString, + }) + .parseAsync({ id: 5 }); + + expect(data).toEqual({ id: "5" }); +}); + +test("sync coercion async error", async () => { + expect(() => + z + .object({ + id: asyncNumberToString, + }) + .parse({ id: 5 }) + ).toThrow(); + // expect(data).toEqual({ id: '5' }); +}); + +test("default", () => { + const data = z.string().default("asdf").parse(undefined); // => "asdf" + expect(data).toEqual("asdf"); +}); + +test("dynamic default", () => { + const data = z + .string() + .default(() => "string") + .parse(undefined); // => "asdf" + expect(data).toEqual("string"); +}); + +test("default when property is null or undefined", () => { + const data = z + .object({ + foo: z.boolean().nullable().default(true), + bar: z.boolean().default(true), + }) + .parse({ foo: null }); + + expect(data).toEqual({ foo: null, bar: true }); +}); + +test("default with falsy values", () => { + const schema = z.object({ + emptyStr: z.string().default("def"), + zero: z.number().default(5), + falseBoolean: z.boolean().default(true), + }); + const input = { emptyStr: "", zero: 0, falseBoolean: true }; + const output = schema.parse(input); + // defaults are not supposed to be used + expect(output).toEqual(input); +}); + +test("object typing", () => { + const t1 = z.object({ + stringToNumber, + }); + + type t1 = z.input; + type t2 = z.output; + + util.assertEqual(true); + util.assertEqual(true); +}); + +test("transform method overloads", () => { + const t1 = z.string().transform((val) => val.toUpperCase()); + expect(t1.parse("asdf")).toEqual("ASDF"); + + const t2 = z.string().transform((val) => val.length); + expect(t2.parse("asdf")).toEqual(4); +}); + +test("multiple transformers", () => { + const doubler = stringToNumber.transform((val) => { + return val * 2; + }); + expect(doubler.parse("5")).toEqual(10); +}); + +test("short circuit on dirty", () => { + const schema = z + .string() + .refine(() => false) + .transform((val) => val.toUpperCase()); + const result = schema.safeParse("asdf"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.custom); + } + + const result2 = schema.safeParse(1234); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_type); + } +}); + +test("async short circuit on dirty", async () => { + const schema = z + .string() + .refine(() => false) + .transform((val) => val.toUpperCase()); + const result = await schema.spa("asdf"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.custom); + } + + const result2 = await schema.spa(1234); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_type); + } +}); diff --git a/node_modules/zod/src/v3/tests/tuple.test.ts b/node_modules/zod/src/v3/tests/tuple.test.ts new file mode 100644 index 000000000..e525d3f45 --- /dev/null +++ b/node_modules/zod/src/v3/tests/tuple.test.ts @@ -0,0 +1,90 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { ZodError } from "../ZodError.js"; +import { util } from "../helpers/util.js"; + +const testTuple = z.tuple([z.string(), z.object({ name: z.literal("Rudy") }), z.array(z.literal("blue"))]); +const testData = ["asdf", { name: "Rudy" }, ["blue"]]; +const badData = [123, { name: "Rudy2" }, ["blue", "red"]]; + +test("tuple inference", () => { + const args1 = z.tuple([z.string()]); + const returns1 = z.number(); + const func1 = z.function(args1, returns1); + type func1 = z.TypeOf; + util.assertEqual number>(true); +}); + +test("successful validation", () => { + const val = testTuple.parse(testData); + expect(val).toEqual(["asdf", { name: "Rudy" }, ["blue"]]); +}); + +test("successful async validation", async () => { + const val = await testTuple.parseAsync(testData); + return expect(val).toEqual(testData); +}); + +test("failed validation", () => { + const checker = () => { + testTuple.parse([123, { name: "Rudy2" }, ["blue", "red"]] as any); + }; + try { + checker(); + } catch (err) { + if (err instanceof ZodError) { + expect(err.issues.length).toEqual(3); + } + } +}); + +test("failed async validation", async () => { + const res = await testTuple.safeParse(badData); + expect(res.success).toEqual(false); + if (!res.success) { + expect(res.error.issues.length).toEqual(3); + } + // try { + // checker(); + // } catch (err) { + // if (err instanceof ZodError) { + // expect(err.issues.length).toEqual(3); + // } + // } +}); + +test("tuple with transformers", () => { + const stringToNumber = z.string().transform((val) => val.length); + const val = z.tuple([stringToNumber]); + + type t1 = z.input; + util.assertEqual(true); + type t2 = z.output; + util.assertEqual(true); + expect(val.parse(["1234"])).toEqual([4]); +}); + +test("tuple with rest schema", () => { + const myTuple = z.tuple([z.string(), z.number()]).rest(z.boolean()); + expect(myTuple.parse(["asdf", 1234, true, false, true])).toEqual(["asdf", 1234, true, false, true]); + + expect(myTuple.parse(["asdf", 1234])).toEqual(["asdf", 1234]); + + expect(() => myTuple.parse(["asdf", 1234, "asdf"])).toThrow(); + type t1 = z.output; + + util.assertEqual(true); +}); + +test("parse should fail given sparse array as tuple", () => { + expect(() => testTuple.parse(new Array(3))).toThrow(); +}); + +// test('tuple with optional elements', () => { +// const result = z +// .tuple([z.string(), z.number().optional()]) +// .safeParse(['asdf']); +// expect(result).toEqual(['asdf']); +// }); diff --git a/node_modules/zod/src/v3/tests/unions.test.ts b/node_modules/zod/src/v3/tests/unions.test.ts new file mode 100644 index 000000000..2c3dc6775 --- /dev/null +++ b/node_modules/zod/src/v3/tests/unions.test.ts @@ -0,0 +1,57 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("function parsing", () => { + const schema = z.union([z.string().refine(() => false), z.number().refine(() => false)]); + const result = schema.safeParse("asdf"); + expect(result.success).toEqual(false); +}); + +test("union 2", () => { + const result = z.union([z.number(), z.string().refine(() => false)]).safeParse("a"); + expect(result.success).toEqual(false); +}); + +test("return valid over invalid", () => { + const schema = z.union([ + z.object({ + email: z.string().email(), + }), + z.string(), + ]); + expect(schema.parse("asdf")).toEqual("asdf"); + expect(schema.parse({ email: "asdlkjf@lkajsdf.com" })).toEqual({ + email: "asdlkjf@lkajsdf.com", + }); +}); + +test("return dirty result over aborted", () => { + const result = z.union([z.number(), z.string().refine(() => false)]).safeParse("a"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues).toEqual([ + { + code: "custom", + message: "Invalid input", + path: [], + }, + ]); + } +}); + +test("options getter", async () => { + const union = z.union([z.string(), z.number()]); + union.options[0].parse("asdf"); + union.options[1].parse(1234); + await union.options[0].parseAsync("asdf"); + await union.options[1].parseAsync(1234); +}); + +test("readonly union", async () => { + const options = [z.string(), z.number()] as const; + const union = z.union(options); + union.parse("asdf"); + union.parse(12); +}); diff --git a/node_modules/zod/src/v3/tests/validations.test.ts b/node_modules/zod/src/v3/tests/validations.test.ts new file mode 100644 index 000000000..66f41dabc --- /dev/null +++ b/node_modules/zod/src/v3/tests/validations.test.ts @@ -0,0 +1,133 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; + +test("array min", async () => { + try { + await z.array(z.string()).min(4).parseAsync([]); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Array must contain at least 4 element(s)"); + } +}); + +test("array max", async () => { + try { + await z.array(z.string()).max(2).parseAsync(["asdf", "asdf", "asdf"]); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Array must contain at most 2 element(s)"); + } +}); + +test("array length", async () => { + try { + await z.array(z.string()).length(2).parseAsync(["asdf", "asdf", "asdf"]); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Array must contain exactly 2 element(s)"); + } + + try { + await z.array(z.string()).length(2).parseAsync(["asdf"]); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Array must contain exactly 2 element(s)"); + } +}); + +test("string length", async () => { + try { + await z.string().length(4).parseAsync("asd"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("String must contain exactly 4 character(s)"); + } + + try { + await z.string().length(4).parseAsync("asdaa"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("String must contain exactly 4 character(s)"); + } +}); + +test("string min", async () => { + try { + await z.string().min(4).parseAsync("asd"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("String must contain at least 4 character(s)"); + } +}); + +test("string max", async () => { + try { + await z.string().max(4).parseAsync("aasdfsdfsd"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("String must contain at most 4 character(s)"); + } +}); + +test("number min", async () => { + try { + await z.number().gte(3).parseAsync(2); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Number must be greater than or equal to 3"); + } +}); + +test("number max", async () => { + try { + await z.number().lte(3).parseAsync(4); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Number must be less than or equal to 3"); + } +}); + +test("number nonnegative", async () => { + try { + await z.number().nonnegative().parseAsync(-1); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Number must be greater than or equal to 0"); + } +}); + +test("number nonpositive", async () => { + try { + await z.number().nonpositive().parseAsync(1); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Number must be less than or equal to 0"); + } +}); + +test("number negative", async () => { + try { + await z.number().negative().parseAsync(1); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Number must be less than 0"); + } +}); + +test("number positive", async () => { + try { + await z.number().positive().parseAsync(-1); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Number must be greater than 0"); + } +}); + +test("instantiation", () => { + z.string().min(5); + z.string().max(5); + z.string().length(5); + z.string().email(); + z.string().url(); + z.string().uuid(); + z.string().min(5, { message: "Must be 5 or more characters long" }); + z.string().max(5, { message: "Must be 5 or fewer characters long" }); + z.string().length(5, { message: "Must be exactly 5 characters long" }); + z.string().email({ message: "Invalid email address." }); + z.string().url({ message: "Invalid url" }); + z.string().uuid({ message: "Invalid UUID" }); +}); + +test("int", async () => { + const int = z.number().int(); + int.parse(4); + expect(() => int.parse(3.5)).toThrow(); +}); diff --git a/node_modules/zod/src/v3/tests/void.test.ts b/node_modules/zod/src/v3/tests/void.test.ts new file mode 100644 index 000000000..b128f1177 --- /dev/null +++ b/node_modules/zod/src/v3/tests/void.test.ts @@ -0,0 +1,15 @@ +// @ts-ignore TS6133 +import { expect, test } from "vitest"; + +import * as z from "zod/v3"; +import { util } from "../helpers/util.js"; +test("void", () => { + const v = z.void(); + v.parse(undefined); + + expect(() => v.parse(null)).toThrow(); + expect(() => v.parse("")).toThrow(); + + type v = z.infer; + util.assertEqual(true); +}); diff --git a/node_modules/zod/src/v3/types.ts b/node_modules/zod/src/v3/types.ts new file mode 100644 index 000000000..b10e84f1b --- /dev/null +++ b/node_modules/zod/src/v3/types.ts @@ -0,0 +1,5136 @@ +import { + type IssueData, + type StringValidation, + type ZodCustomIssue, + ZodError, + type ZodErrorMap, + type ZodIssue, + ZodIssueCode, +} from "./ZodError.js"; +import { defaultErrorMap, getErrorMap } from "./errors.js"; +import type { enumUtil } from "./helpers/enumUtil.js"; +import { errorUtil } from "./helpers/errorUtil.js"; +import { + type AsyncParseReturnType, + DIRTY, + INVALID, + OK, + type ParseContext, + type ParseInput, + type ParseParams, + type ParsePath, + type ParseReturnType, + ParseStatus, + type SyncParseReturnType, + addIssueToContext, + isAborted, + isAsync, + isDirty, + isValid, + makeIssue, +} from "./helpers/parseUtil.js"; +import type { partialUtil } from "./helpers/partialUtil.js"; +import type { Primitive } from "./helpers/typeAliases.js"; +import { util, ZodParsedType, getParsedType, type objectUtil } from "./helpers/util.js"; +import type { StandardSchemaV1 } from "./standard-schema.js"; + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// ZodType ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// + +export interface RefinementCtx { + addIssue: (arg: IssueData) => void; + path: (string | number)[]; +} +export type ZodRawShape = { [k: string]: ZodTypeAny }; +export type ZodTypeAny = ZodType; +export type TypeOf> = T["_output"]; +export type input> = T["_input"]; +export type output> = T["_output"]; +export type { TypeOf as infer }; + +export type CustomErrorParams = Partial>; +export interface ZodTypeDef { + errorMap?: ZodErrorMap | undefined; + description?: string | undefined; +} + +class ParseInputLazyPath implements ParseInput { + parent: ParseContext; + data: any; + _path: ParsePath; + _key: string | number | (string | number)[]; + _cachedPath: ParsePath = []; + constructor(parent: ParseContext, value: any, path: ParsePath, key: string | number | (string | number)[]) { + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + + return this._cachedPath; + } +} + +const handleResult = ( + ctx: ParseContext, + result: SyncParseReturnType +): { success: true; data: Output } | { success: false; error: ZodError } => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + + return { + success: false, + get error() { + if ((this as any)._error) return (this as any)._error as Error; + const error = new ZodError(ctx.common.issues); + (this as any)._error = error; + return (this as any)._error; + }, + }; + } +}; + +export type RawCreateParams = + | { + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + message?: string | undefined; + description?: string | undefined; + } + | undefined; +export type ProcessedCreateParams = { + errorMap?: ZodErrorMap | undefined; + description?: string | undefined; +}; +function processCreateParams(params: RawCreateParams): ProcessedCreateParams { + if (!params) return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap) return { errorMap: errorMap, description }; + const customMap: ZodErrorMap = (iss, ctx) => { + const { message } = params; + + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} + +export type SafeParseSuccess = { + success: true; + data: Output; + error?: never; +}; +export type SafeParseError = { + success: false; + error: ZodError; + data?: never; +}; + +export type SafeParseReturnType = SafeParseSuccess | SafeParseError; + +export abstract class ZodType { + readonly _type!: Output; + readonly _output!: Output; + readonly _input!: Input; + readonly _def!: Def; + + get description(): string | undefined { + return this._def.description; + } + + "~standard": StandardSchemaV1.Props; + + abstract _parse(input: ParseInput): ParseReturnType; + + _getType(input: ParseInput): string { + return getParsedType(input.data); + } + + _getOrReturnCtx(input: ParseInput, ctx?: ParseContext | undefined): ParseContext { + return ( + ctx || { + common: input.parent.common, + data: input.data, + + parsedType: getParsedType(input.data), + + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + } + ); + } + + _processInputParams(input: ParseInput): { + status: ParseStatus; + ctx: ParseContext; + } { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + + parsedType: getParsedType(input.data), + + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; + } + + _parseSync(input: ParseInput): SyncParseReturnType { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + + _parseAsync(input: ParseInput): AsyncParseReturnType { + const result = this._parse(input); + return Promise.resolve(result); + } + + parse(data: unknown, params?: util.InexactPartial): Output { + const result = this.safeParse(data, params); + if (result.success) return result.data; + throw result.error; + } + + safeParse(data: unknown, params?: util.InexactPartial): SafeParseReturnType { + const ctx: ParseContext = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + + return handleResult(ctx, result); + } + + "~validate"(data: unknown): StandardSchemaV1.Result | Promise> { + const ctx: ParseContext = { + common: { + issues: [], + async: !!(this["~standard"] as any).async, + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + + if (!(this["~standard"] as any).async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }; + } catch (err: any) { + if ((err as Error)?.message?.toLowerCase()?.includes("encountered")) { + (this["~standard"] as any).async = true; + } + (ctx as any).common = { + issues: [], + async: true, + }; + } + } + + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => + isValid(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + } + ); + } + + async parseAsync(data: unknown, params?: util.InexactPartial): Promise { + const result = await this.safeParseAsync(data, params); + if (result.success) return result.data; + throw result.error; + } + + async safeParseAsync( + data: unknown, + params?: util.InexactPartial + ): Promise> { + const ctx: ParseContext = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + + /** Alias of safeParseAsync */ + spa = this.safeParseAsync; + + refine( + check: (arg: Output) => arg is RefinedOutput, + message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) + ): ZodEffects; + refine( + check: (arg: Output) => unknown | Promise, + message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) + ): ZodEffects; + refine( + check: (arg: Output) => unknown, + message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) + ): ZodEffects { + const getIssueProperties = (val: Output) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => + ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + + refinement( + check: (arg: Output) => arg is RefinedOutput, + refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) + ): ZodEffects; + refinement( + check: (arg: Output) => boolean, + refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) + ): ZodEffects; + refinement( + check: (arg: Output) => unknown, + refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) + ): ZodEffects { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + + _refinement(refinement: RefinementEffect["refinement"]): ZodEffects { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + + superRefine( + refinement: (arg: Output, ctx: RefinementCtx) => arg is RefinedOutput + ): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => void): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => Promise): ZodEffects; + superRefine( + refinement: (arg: Output, ctx: RefinementCtx) => unknown | Promise + ): ZodEffects { + return this._refinement(refinement); + } + + constructor(def: Def) { + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data), + }; + } + + optional(): ZodOptional { + return ZodOptional.create(this, this._def) as any; + } + nullable(): ZodNullable { + return ZodNullable.create(this, this._def) as any; + } + nullish(): ZodOptional> { + return this.nullable().optional(); + } + array(): ZodArray { + return ZodArray.create(this); + } + promise(): ZodPromise { + return ZodPromise.create(this, this._def); + } + + or(option: T): ZodUnion<[this, T]> { + return ZodUnion.create([this, option], this._def) as any; + } + + and(incoming: T): ZodIntersection { + return ZodIntersection.create(this, incoming, this._def); + } + + transform( + transform: (arg: Output, ctx: RefinementCtx) => NewOut | Promise + ): ZodEffects { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }) as any; + } + + default(def: util.noUndefined): ZodDefault; + default(def: () => util.noUndefined): ZodDefault; + default(def: any) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, + }) as any; + } + + brand(brand?: B): ZodBranded; + brand(): ZodBranded { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + + catch(def: Output): ZodCatch; + catch(def: (ctx: { error: ZodError; input: Input }) => Output): ZodCatch; + catch(def: any) { + const catchValueFunc = typeof def === "function" ? def : () => def; + + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, + }) as any; + } + + describe(description: string): this { + const This = (this as any).constructor; + return new This({ + ...this._def, + description, + }); + } + + pipe(target: T): ZodPipeline { + return ZodPipeline.create(this, target); + } + readonly(): ZodReadonly { + return ZodReadonly.create(this); + } + + isOptional(): boolean { + return this.safeParse(undefined).success; + } + isNullable(): boolean { + return this.safeParse(null).success; + } +} + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodString ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// +export type IpVersion = "v4" | "v6"; +export type ZodStringCheck = + | { kind: "min"; value: number; message?: string | undefined } + | { kind: "max"; value: number; message?: string | undefined } + | { kind: "length"; value: number; message?: string | undefined } + | { kind: "email"; message?: string | undefined } + | { kind: "url"; message?: string | undefined } + | { kind: "emoji"; message?: string | undefined } + | { kind: "uuid"; message?: string | undefined } + | { kind: "nanoid"; message?: string | undefined } + | { kind: "cuid"; message?: string | undefined } + | { kind: "includes"; value: string; position?: number | undefined; message?: string | undefined } + | { kind: "cuid2"; message?: string | undefined } + | { kind: "ulid"; message?: string | undefined } + | { kind: "startsWith"; value: string; message?: string | undefined } + | { kind: "endsWith"; value: string; message?: string | undefined } + | { kind: "regex"; regex: RegExp; message?: string | undefined } + | { kind: "trim"; message?: string | undefined } + | { kind: "toLowerCase"; message?: string | undefined } + | { kind: "toUpperCase"; message?: string | undefined } + | { kind: "jwt"; alg?: string; message?: string | undefined } + | { + kind: "datetime"; + offset: boolean; + local: boolean; + precision: number | null; + message?: string | undefined; + } + | { + kind: "date"; + // withDate: true; + message?: string | undefined; + } + | { + kind: "time"; + precision: number | null; + message?: string | undefined; + } + | { kind: "duration"; message?: string | undefined } + | { kind: "ip"; version?: IpVersion | undefined; message?: string | undefined } + | { kind: "cidr"; version?: IpVersion | undefined; message?: string | undefined } + | { kind: "base64"; message?: string | undefined } + | { kind: "base64url"; message?: string | undefined }; + +export interface ZodStringDef extends ZodTypeDef { + checks: ZodStringCheck[]; + typeName: ZodFirstPartyTypeKind.ZodString; + coerce: boolean; +} + +const cuidRegex = /^c[^\s-]{8,}$/i; +const cuid2Regex = /^[0-9a-z]+$/; +const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +// const uuidRegex = +// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; +const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +const nanoidRegex = /^[a-z0-9_-]{21}$/i; +const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +const durationRegex = + /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + +// from https://stackoverflow.com/a/46181/1550155 +// old version: too slow, didn't support unicode +// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; +//old email regex +// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; +// eslint-disable-next-line +// const emailRegex = +// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; +// const emailRegex = +// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// const emailRegex = +// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; +const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +// const emailRegex = +// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; + +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +let emojiRegex: RegExp; + +// faster, simpler, safer +const ipv4Regex = + /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv4CidrRegex = + /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; + +// const ipv6Regex = +// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +const ipv6Regex = + /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +const ipv6CidrRegex = + /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + +// https://base64.guru/standards/base64url +const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; + +// simple +// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; +// no leap year validation +// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; +// with leap year validation +const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +const dateRegex = new RegExp(`^${dateRegexSource}$`); + +function timeRegexSource(args: { precision?: number | null }) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + + const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} + +function timeRegex(args: { + offset?: boolean; + local?: boolean; + precision?: number | null; +}) { + return new RegExp(`^${timeRegexSource(args)}$`); +} + +// Adapted from https://stackoverflow.com/a/3143231 +export function datetimeRegex(args: { + precision?: number | null; + offset?: boolean; + local?: boolean; +}) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + + const opts: string[] = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} + +function isValidIP(ip: string, version?: IpVersion) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + + return false; +} + +function isValidJWT(jwt: string, alg?: string): boolean { + if (!jwtRegex.test(jwt)) return false; + try { + const [header] = jwt.split("."); + if (!header) return false; + // Convert base64url to base64 + const base64 = header + .replace(/-/g, "+") + .replace(/_/g, "/") + .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) return false; + if ("typ" in decoded && decoded?.typ !== "JWT") return false; + if (!decoded.alg) return false; + if (alg && decoded.alg !== alg) return false; + return true; + } catch { + return false; + } +} + +function isValidCidr(ip: string, version?: IpVersion) { + if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { + return true; + } + + return false; +} + +export class ZodString extends ZodType { + _parse(input: ParseInput): ParseReturnType { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType, + }); + return INVALID; + } + + const status = new ParseStatus(); + let ctx: undefined | ParseContext = undefined; + + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "trim") { + input.data = input.data.trim(); + } else if (check.kind === "includes") { + if (!(input.data as string).includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check.kind === "startsWith") { + if (!(input.data as string).startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "endsWith") { + if (!(input.data as string).endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "date") { + const regex = dateRegex; + + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "time") { + const regex = timeRegex(check); + + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "jwt") { + if (!isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "cidr") { + if (!isValidCidr(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + + return { status: status.value, value: input.data }; + } + + protected _regex(regex: RegExp, validation: StringValidation, message?: errorUtil.ErrMessage) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message), + }); + } + + _addCheck(check: ZodStringCheck) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + + email(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + + url(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + + emoji(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + + uuid(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + + cuid2(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + base64url(message?: errorUtil.ErrMessage) { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message), + }); + } + + jwt(options?: { alg?: string; message?: string | undefined }) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); + } + + ip(options?: string | { version?: IpVersion; message?: string | undefined }) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + + cidr(options?: string | { version?: IpVersion; message?: string | undefined }) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + } + + datetime( + options?: + | string + | { + message?: string | undefined; + precision?: number | null; + offset?: boolean; + local?: boolean; + } + ) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message), + }); + } + + date(message?: string) { + return this._addCheck({ kind: "date", message }); + } + + time( + options?: + | string + | { + message?: string | undefined; + precision?: number | null; + } + ) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options, + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message), + }); + } + + duration(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + + regex(regex: RegExp, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil.errToObj(message), + }); + } + + includes(value: string, options?: { message?: string; position?: number }) { + return this._addCheck({ + kind: "includes", + value: value, + position: options?.position, + ...errorUtil.errToObj(options?.message), + }); + } + + startsWith(value: string, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + + endsWith(value: string, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + + min(minLength: number, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message), + }); + } + + max(maxLength: number, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message), + }); + } + + length(len: number, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message), + }); + } + + /** + * Equivalent to `.min(1)` + */ + nonempty(message?: errorUtil.ErrMessage) { + return this.min(1, errorUtil.errToObj(message)); + } + + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + } + + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + } + + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + + get minLength() { + let min: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + } + return min; + } + + get maxLength() { + let max: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + return max; + } + + static create = (params?: RawCreateParams & { coerce?: true }): ZodString => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); + }; +} + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodNumber ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// +export type ZodNumberCheck = + | { kind: "min"; value: number; inclusive: boolean; message?: string | undefined } + | { kind: "max"; value: number; inclusive: boolean; message?: string | undefined } + | { kind: "int"; message?: string | undefined } + | { kind: "multipleOf"; value: number; message?: string | undefined } + | { kind: "finite"; message?: string | undefined }; + +// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 +function floatSafeRemainder(val: number, step: number) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / 10 ** decCount; +} + +export interface ZodNumberDef extends ZodTypeDef { + checks: ZodNumberCheck[]; + typeName: ZodFirstPartyTypeKind.ZodNumber; + coerce: boolean; +} + +export class ZodNumber extends ZodType { + _parse(input: ParseInput): ParseReturnType { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.parsedType, + }); + return INVALID; + } + + let ctx: undefined | ParseContext = undefined; + const status = new ParseStatus(); + + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + + return { status: status.value, value: input.data }; + } + + static create = (params?: RawCreateParams & { coerce?: boolean }): ZodNumber => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); + }; + + gte(value: number, message?: errorUtil.ErrMessage) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + min = this.gte; + + gt(value: number, message?: errorUtil.ErrMessage) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + + lte(value: number, message?: errorUtil.ErrMessage) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + max = this.lte; + + lt(value: number, message?: errorUtil.ErrMessage) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + + protected setLimit(kind: "min" | "max", value: number, inclusive: boolean, message?: string) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + + _addCheck(check: ZodNumberCheck) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + + int(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + + positive(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + + negative(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + + nonpositive(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + + nonnegative(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + + multipleOf(value: number, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); + } + step = this.multipleOf; + + finite(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); + } + + safe(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message), + }); + } + + get minValue() { + let min: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + } + return min; + } + + get maxValue() { + let max: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + return max; + } + + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value))); + } + + get isFinite() { + let max: number | null = null; + let min: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +} + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodBigInt ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// +export type ZodBigIntCheck = + | { kind: "min"; value: bigint; inclusive: boolean; message?: string | undefined } + | { kind: "max"; value: bigint; inclusive: boolean; message?: string | undefined } + | { kind: "multipleOf"; value: bigint; message?: string | undefined }; + +export interface ZodBigIntDef extends ZodTypeDef { + checks: ZodBigIntCheck[]; + typeName: ZodFirstPartyTypeKind.ZodBigInt; + coerce: boolean; +} + +export class ZodBigInt extends ZodType { + _parse(input: ParseInput): ParseReturnType { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + + let ctx: undefined | ParseContext = undefined; + const status = new ParseStatus(); + + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + + return { status: status.value, value: input.data }; + } + + _getInvalidInput(input: ParseInput) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; + } + + static create = (params?: RawCreateParams & { coerce?: boolean }): ZodBigInt => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); + }; + + gte(value: bigint, message?: errorUtil.ErrMessage) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + min = this.gte; + + gt(value: bigint, message?: errorUtil.ErrMessage) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + + lte(value: bigint, message?: errorUtil.ErrMessage) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + max = this.lte; + + lt(value: bigint, message?: errorUtil.ErrMessage) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + + protected setLimit(kind: "min" | "max", value: bigint, inclusive: boolean, message?: string) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + + _addCheck(check: ZodBigIntCheck) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + + positive(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + + negative(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + + nonpositive(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + + nonnegative(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + + multipleOf(value: bigint, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message), + }); + } + + get minValue() { + let min: bigint | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + } + return min; + } + + get maxValue() { + let max: bigint | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + return max; + } +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// /////////// +////////// ZodBoolean ////////// +////////// /////////// +////////////////////////////////////////// +////////////////////////////////////////// +export interface ZodBooleanDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodBoolean; + coerce: boolean; +} + +export class ZodBoolean extends ZodType { + _parse(input: ParseInput): ParseReturnType { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + + static create = (params?: RawCreateParams & { coerce?: boolean }): ZodBoolean => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); + }; +} + +/////////////////////////////////////// +/////////////////////////////////////// +////////// //////// +////////// ZodDate //////// +////////// //////// +/////////////////////////////////////// +/////////////////////////////////////// +export type ZodDateCheck = + | { kind: "min"; value: number; message?: string | undefined } + | { kind: "max"; value: number; message?: string | undefined }; +export interface ZodDateDef extends ZodTypeDef { + checks: ZodDateCheck[]; + coerce: boolean; + typeName: ZodFirstPartyTypeKind.ZodDate; +} + +export class ZodDate extends ZodType { + _parse(input: ParseInput): ParseReturnType { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType, + }); + return INVALID; + } + + if (Number.isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, + }); + return INVALID; + } + + const status = new ParseStatus(); + let ctx: undefined | ParseContext = undefined; + + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + + return { + status: status.value, + value: new Date((input.data as Date).getTime()), + }; + } + + _addCheck(check: ZodDateCheck) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + + min(minDate: Date, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message), + }); + } + + max(maxDate: Date, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message), + }); + } + + get minDate() { + let min: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + } + + return min != null ? new Date(min) : null; + } + + get maxDate() { + let max: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + + return max != null ? new Date(max) : null; + } + + static create = (params?: RawCreateParams & { coerce?: boolean }): ZodDate => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); + }; +} + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// ZodSymbol ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface ZodSymbolDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodSymbol; +} + +export class ZodSymbol extends ZodType { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType, + }); + return INVALID; + } + + return OK(input.data); + } + + static create = (params?: RawCreateParams): ZodSymbol => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); + }; +} + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// ZodUndefined ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface ZodUndefinedDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodUndefined; +} + +export class ZodUndefined extends ZodType { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + params?: RawCreateParams; + + static create = (params?: RawCreateParams): ZodUndefined => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); + }; +} + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// ZodNull ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// +export interface ZodNullDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNull; +} + +export class ZodNull extends ZodType { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + static create = (params?: RawCreateParams): ZodNull => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////// +////////////////////////////////////// +////////// ////////// +////////// ZodAny ////////// +////////// ////////// +////////////////////////////////////// +////////////////////////////////////// +export interface ZodAnyDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodAny; +} + +export class ZodAny extends ZodType { + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + _any = true as const; + _parse(input: ParseInput): ParseReturnType { + return OK(input.data); + } + static create = (params?: RawCreateParams): ZodAny => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodUnknown ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// +export interface ZodUnknownDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodUnknown; +} + +export class ZodUnknown extends ZodType { + // required + _unknown = true as const; + _parse(input: ParseInput): ParseReturnType { + return OK(input.data); + } + + static create = (params?: RawCreateParams): ZodUnknown => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); + }; +} + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// ZodNever ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +export interface ZodNeverDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNever; +} + +export class ZodNever extends ZodType { + _parse(input: ParseInput): ParseReturnType { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, + }); + return INVALID; + } + static create = (params?: RawCreateParams): ZodNever => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); + }; +} + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// ZodVoid ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// +export interface ZodVoidDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodVoid; +} + +export class ZodVoid extends ZodType { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + + static create = (params?: RawCreateParams): ZodVoid => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); + }; +} + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// ZodArray ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +export interface ZodArrayDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodArray; + exactLength: { value: number; message?: string | undefined } | null; + minLength: { value: number; message?: string | undefined } | null; + maxLength: { value: number; message?: string | undefined } | null; +} + +export type ArrayCardinality = "many" | "atleastone"; +export type arrayOutputType< + T extends ZodTypeAny, + Cardinality extends ArrayCardinality = "many", +> = Cardinality extends "atleastone" ? [T["_output"], ...T["_output"][]] : T["_output"][]; + +export class ZodArray extends ZodType< + arrayOutputType, + ZodArrayDef, + Cardinality extends "atleastone" ? [T["_input"], ...T["_input"][]] : T["_input"][] +> { + _parse(input: ParseInput): ParseReturnType { + const { ctx, status } = this._processInputParams(input); + + const def = this._def; + + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined) as number, + maximum: (tooBig ? def.exactLength.value : undefined) as number, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + + if (ctx.common.async) { + return Promise.all( + ([...ctx.data] as any[]).map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }) + ).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + } + + const result = ([...ctx.data] as any[]).map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + + return ParseStatus.mergeArray(status, result); + } + + get element() { + return this._def.type; + } + + min(minLength: number, message?: errorUtil.ErrMessage): this { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) }, + }) as any; + } + + max(maxLength: number, message?: errorUtil.ErrMessage): this { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }) as any; + } + + length(len: number, message?: errorUtil.ErrMessage): this { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }) as any; + } + + nonempty(message?: errorUtil.ErrMessage): ZodArray { + return this.min(1, message) as any; + } + + static create = (schema: El, params?: RawCreateParams): ZodArray => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); + }; +} + +export type ZodNonEmptyArray = ZodArray; + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodObject ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// + +export type UnknownKeysParam = "passthrough" | "strict" | "strip"; + +export interface ZodObjectDef< + T extends ZodRawShape = ZodRawShape, + UnknownKeys extends UnknownKeysParam = UnknownKeysParam, + Catchall extends ZodTypeAny = ZodTypeAny, +> extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodObject; + shape: () => T; + catchall: Catchall; + unknownKeys: UnknownKeys; +} + +export type mergeTypes = { + [k in keyof A | keyof B]: k extends keyof B ? B[k] : k extends keyof A ? A[k] : never; +}; + +export type objectOutputType< + Shape extends ZodRawShape, + Catchall extends ZodTypeAny, + UnknownKeys extends UnknownKeysParam = UnknownKeysParam, +> = objectUtil.flatten>> & + CatchallOutput & + PassthroughType; + +export type baseObjectOutputType = { + [k in keyof Shape]: Shape[k]["_output"]; +}; + +export type objectInputType< + Shape extends ZodRawShape, + Catchall extends ZodTypeAny, + UnknownKeys extends UnknownKeysParam = UnknownKeysParam, +> = objectUtil.flatten> & CatchallInput & PassthroughType; +export type baseObjectInputType = objectUtil.addQuestionMarks<{ + [k in keyof Shape]: Shape[k]["_input"]; +}>; + +export type CatchallOutput = ZodType extends T ? unknown : { [k: string]: T["_output"] }; + +export type CatchallInput = ZodType extends T ? unknown : { [k: string]: T["_input"] }; + +export type PassthroughType = T extends "passthrough" ? { [k: string]: unknown } : unknown; + +export type deoptional = T extends ZodOptional + ? deoptional + : T extends ZodNullable + ? ZodNullable> + : T; + +export type SomeZodObject = ZodObject; + +export type noUnrecognized = { + [k in keyof Obj]: k extends keyof Shape ? Obj[k] : never; +}; + +function deepPartialify(schema: ZodTypeAny): any { + if (schema instanceof ZodObject) { + const newShape: any = {}; + + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }) as any; + } else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item: any) => deepPartialify(item))); + } else { + return schema; + } +} + +export class ZodObject< + T extends ZodRawShape, + UnknownKeys extends UnknownKeysParam = UnknownKeysParam, + Catchall extends ZodTypeAny = ZodTypeAny, + Output = objectOutputType, + Input = objectInputType, +> extends ZodType, Input> { + private _cached: { shape: T; keys: string[] } | null = null; + + _getCached(): { shape: T; keys: string[] } { + if (this._cached !== null) return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + + const { status, ctx } = this._processInputParams(input); + + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys: string[] = []; + + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + + const pairs: { + key: ParseReturnType; + value: ParseReturnType; + alwaysSet?: boolean; + }[] = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]!; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + // run catchall validation + const catchall = this._def.catchall; + + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs: any[] = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs as any); + } + } + + get shape() { + return this._def.shape(); + } + + strict(message?: errorUtil.ErrMessage): ZodObject { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }) as any; + } + + strip(): ZodObject { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }) as any; + } + + passthrough(): ZodObject { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }) as any; + } + + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + nonstrict = this.passthrough; + + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend( + augmentation: Augmentation + ): ZodObject, UnknownKeys, Catchall> { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }) as any; + } + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + augment = this.extend; + + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge( + merging: Incoming + ): ZodObject, Incoming["_def"]["unknownKeys"], Incoming["_def"]["catchall"]> { + const merged: any = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }) as any; + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + + setKey( + key: Key, + schema: Schema + ): ZodObject { + return this.augment({ [key]: schema }) as any; + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + + catchall(index: Index): ZodObject { + return new ZodObject({ + ...this._def, + catchall: index, + }) as any; + } + + pick>( + mask: Mask + ): ZodObject>, UnknownKeys, Catchall> { + const shape: any = {}; + + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + + return new ZodObject({ + ...this._def, + shape: () => shape, + }) as any; + } + + omit>( + mask: Mask + ): ZodObject, UnknownKeys, Catchall> { + const shape: any = {}; + + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + + return new ZodObject({ + ...this._def, + shape: () => shape, + }) as any; + } + + /** + * @deprecated + */ + deepPartial(): partialUtil.DeepPartial { + return deepPartialify(this); + } + + partial(): ZodObject<{ [k in keyof T]: ZodOptional }, UnknownKeys, Catchall>; + partial>( + mask: Mask + ): ZodObject< + objectUtil.noNever<{ + [k in keyof T]: k extends keyof Mask ? ZodOptional : T[k]; + }>, + UnknownKeys, + Catchall + >; + partial(mask?: any) { + const newShape: any = {}; + + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]!; + + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + + return new ZodObject({ + ...this._def, + shape: () => newShape, + }) as any; + } + + required(): ZodObject<{ [k in keyof T]: deoptional }, UnknownKeys, Catchall>; + required>( + mask: Mask + ): ZodObject< + objectUtil.noNever<{ + [k in keyof T]: k extends keyof Mask ? deoptional : T[k]; + }>, + UnknownKeys, + Catchall + >; + required(mask?: any) { + const newShape: any = {}; + + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + + while (newField instanceof ZodOptional) { + newField = (newField as ZodOptional)._def.innerType; + } + + newShape[key] = newField; + } + } + + return new ZodObject({ + ...this._def, + shape: () => newShape, + }) as any; + } + + keyof(): ZodEnum> { + return createZodEnum(util.objectKeys(this.shape) as [string, ...string[]]) as any; + } + + static create = ( + shape: Shape, + params?: RawCreateParams + ): ZodObject< + Shape, + "strip", + ZodTypeAny, + objectOutputType, + objectInputType + > => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }) as any; + }; + + static strictCreate = ( + shape: Shape, + params?: RawCreateParams + ): ZodObject => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }) as any; + }; + + static lazycreate = ( + shape: () => Shape, + params?: RawCreateParams + ): ZodObject => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }) as any; + }; +} + +export type AnyZodObject = ZodObject; + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// ZodUnion ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +export type ZodUnionOptions = Readonly<[ZodTypeAny, ...ZodTypeAny[]]>; +export interface ZodUnionDef> + extends ZodTypeDef { + options: T; + typeName: ZodFirstPartyTypeKind.ZodUnion; +} + +export class ZodUnion extends ZodType< + T[number]["_output"], + ZodUnionDef, + T[number]["_input"] +> { + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + + function handleResults(results: { ctx: ParseContext; result: SyncParseReturnType }[]) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + + // return invalid + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + + if (ctx.common.async) { + return Promise.all( + options.map(async (option) => { + const childCtx: ParseContext = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + }) + ).then(handleResults); + } else { + let dirty: undefined | { result: DIRTY; ctx: ParseContext } = undefined; + const issues: ZodIssue[][] = []; + for (const option of options) { + const childCtx: ParseContext = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + + const unionErrors = issues.map((issues) => new ZodError(issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + + return INVALID; + } + } + + get options() { + return this._def.options; + } + + static create = >( + types: Options, + params?: RawCreateParams + ): ZodUnion => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); + }; +} + +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +////////// ////////// +////////// ZodDiscriminatedUnion ////////// +////////// ////////// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// + +const getDiscriminator = (type: T): Primitive[] => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral) { + return [type.value]; + } else if (type instanceof ZodEnum) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return util.objectValues(type.enum); + } else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined) { + return [undefined]; + } else if (type instanceof ZodNull) { + return [null]; + } else if (type instanceof ZodOptional) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } else { + return []; + } +}; + +export type ZodDiscriminatedUnionOption = ZodObject< + { [key in Discriminator]: ZodTypeAny } & ZodRawShape, + UnknownKeysParam, + ZodTypeAny +>; + +export interface ZodDiscriminatedUnionDef< + Discriminator extends string, + Options extends readonly ZodDiscriminatedUnionOption[] = ZodDiscriminatedUnionOption[], +> extends ZodTypeDef { + discriminator: Discriminator; + options: Options; + optionsMap: Map>; + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion; +} + +export class ZodDiscriminatedUnion< + Discriminator extends string, + Options extends readonly ZodDiscriminatedUnionOption[], +> extends ZodType, ZodDiscriminatedUnionDef, input> { + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + + const discriminator = this.discriminator; + + const discriminatorValue: string = ctx.data[discriminator]; + + const option = this.optionsMap.get(discriminatorValue); + + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return INVALID; + } + + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }) as any; + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }) as any; + } + } + + get discriminator() { + return this._def.discriminator; + } + + get options() { + return this._def.options; + } + + get optionsMap() { + return this._def.optionsMap; + } + + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create< + Discriminator extends string, + Types extends readonly [ + ZodDiscriminatedUnionOption, + ...ZodDiscriminatedUnionOption[], + ], + >( + discriminator: Discriminator, + options: Types, + params?: RawCreateParams + ): ZodDiscriminatedUnion { + // Get all the valid discriminator values + const optionsMap: Map = new Map(); + + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error( + `A discriminator value for key \`${discriminator}\` could not be extracted from all schema options` + ); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + + optionsMap.set(value, type); + } + } + + return new ZodDiscriminatedUnion< + Discriminator, + // DiscriminatorValue, + Types + >({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } +} + +/////////////////////////////////////////////// +/////////////////////////////////////////////// +////////// ////////// +////////// ZodIntersection ////////// +////////// ////////// +/////////////////////////////////////////////// +/////////////////////////////////////////////// +export interface ZodIntersectionDef + extends ZodTypeDef { + left: T; + right: U; + typeName: ZodFirstPartyTypeKind.ZodIntersection; +} + +function mergeValues(a: any, b: any): { valid: true; data: any } | { valid: false } { + const aType = getParsedType(a); + const bType = getParsedType(b); + + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + + const newObj: any = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + + const newArray: unknown[] = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + + if (!sharedValue.valid) { + return { valid: false }; + } + + newArray.push(sharedValue.data); + } + + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } else { + return { valid: false }; + } +} + +export class ZodIntersection extends ZodType< + T["_output"] & U["_output"], + ZodIntersectionDef, + T["_input"] & U["_input"] +> { + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + const handleParsed = ( + parsedLeft: SyncParseReturnType, + parsedRight: SyncParseReturnType + ): SyncParseReturnType => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + + const merged = mergeValues(parsedLeft.value, parsedRight.value); + + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types, + }); + return INVALID; + } + + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + + return { status: status.value, value: merged.data }; + }; + + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]: any) => handleParsed(left, right)); + } else { + return handleParsed( + this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }) + ); + } + } + + static create = ( + left: TSchema, + right: USchema, + params?: RawCreateParams + ): ZodIntersection => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); + }; +} + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// ZodTuple ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +export type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +export type AssertArray = T extends any[] ? T : never; +export type OutputTypeOfTuple = AssertArray<{ + [k in keyof T]: T[k] extends ZodType ? T[k]["_output"] : never; +}>; +export type OutputTypeOfTupleWithRest< + T extends ZodTupleItems | [], + Rest extends ZodTypeAny | null = null, +> = Rest extends ZodTypeAny ? [...OutputTypeOfTuple, ...Rest["_output"][]] : OutputTypeOfTuple; + +export type InputTypeOfTuple = AssertArray<{ + [k in keyof T]: T[k] extends ZodType ? T[k]["_input"] : never; +}>; +export type InputTypeOfTupleWithRest< + T extends ZodTupleItems | [], + Rest extends ZodTypeAny | null = null, +> = Rest extends ZodTypeAny ? [...InputTypeOfTuple, ...Rest["_input"][]] : InputTypeOfTuple; + +export interface ZodTupleDef + extends ZodTypeDef { + items: T; + rest: Rest; + typeName: ZodFirstPartyTypeKind.ZodTuple; +} + +export type AnyZodTuple = ZodTuple<[ZodTypeAny, ...ZodTypeAny[]] | [], ZodTypeAny | null>; +// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +export class ZodTuple< + T extends ZodTupleItems | [] = ZodTupleItems, + Rest extends ZodTypeAny | null = null, +> extends ZodType, ZodTupleDef, InputTypeOfTupleWithRest> { + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + + return INVALID; + } + + const rest = this._def.rest; + + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + + const items = ([...ctx.data] as any[]) + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) return null as any as SyncParseReturnType; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items as SyncParseReturnType[]); + } + } + + get items() { + return this._def.items; + } + + rest(rest: RestSchema): ZodTuple { + return new ZodTuple({ + ...this._def, + rest, + }); + } + + static create = ( + schemas: Items, + params?: RawCreateParams + ): ZodTuple => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); + }; +} + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodRecord ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// +export interface ZodRecordDef + extends ZodTypeDef { + valueType: Value; + keyType: Key; + typeName: ZodFirstPartyTypeKind.ZodRecord; +} + +export type KeySchema = ZodType; +export type RecordType = [string] extends [K] + ? Record + : [number] extends [K] + ? Record + : [symbol] extends [K] + ? Record + : [BRAND] extends [K] + ? Record + : Partial>; +export class ZodRecord extends ZodType< + RecordType, + ZodRecordDef, + RecordType +> { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + + const pairs: { + key: ParseReturnType; + value: ParseReturnType; + alwaysSet: boolean; + }[] = []; + + const keyType = this._def.keyType; + const valueType = this._def.valueType; + + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs as any); + } + } + + get element() { + return this._def.valueType; + } + + static create(valueType: Value, params?: RawCreateParams): ZodRecord; + static create( + keySchema: Keys, + valueType: Value, + params?: RawCreateParams + ): ZodRecord; + static create(first: any, second?: any, third?: any): ZodRecord { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } +} + +////////////////////////////////////// +////////////////////////////////////// +////////// ////////// +////////// ZodMap ////////// +////////// ////////// +////////////////////////////////////// +////////////////////////////////////// +export interface ZodMapDef + extends ZodTypeDef { + valueType: Value; + keyType: Key; + typeName: ZodFirstPartyTypeKind.ZodMap; +} + +export class ZodMap extends ZodType< + Map, + ZodMapDef, + Map +> { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType, + }); + return INVALID; + } + + const keyType = this._def.keyType; + const valueType = this._def.valueType; + + const pairs = [...(ctx.data as Map).entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key as SyncParseReturnType; + const value = pair.value as SyncParseReturnType; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } + static create = ( + keyType: KeySchema, + valueType: ValueSchema, + params?: RawCreateParams + ): ZodMap => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////// +////////////////////////////////////// +////////// ////////// +////////// ZodSet ////////// +////////// ////////// +////////////////////////////////////// +////////////////////////////////////// +export interface ZodSetDef extends ZodTypeDef { + valueType: Value; + typeName: ZodFirstPartyTypeKind.ZodSet; + minSize: { value: number; message?: string | undefined } | null; + maxSize: { value: number; message?: string | undefined } | null; +} + +export class ZodSet extends ZodType< + Set, + ZodSetDef, + Set +> { + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType, + }); + return INVALID; + } + + const def = this._def; + + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + + const valueType = this._def.valueType; + + function finalizeSet(elements: SyncParseReturnType[]) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") return INVALID; + if (element.status === "dirty") status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + + const elements = [...(ctx.data as Set).values()].map((item, i) => + valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)) + ); + + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } else { + return finalizeSet(elements as SyncParseReturnType[]); + } + } + + min(minSize: number, message?: errorUtil.ErrMessage): this { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) }, + }) as any; + } + + max(maxSize: number, message?: errorUtil.ErrMessage): this { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, + }) as any; + } + + size(size: number, message?: errorUtil.ErrMessage): this { + return this.min(size, message).max(size, message) as any; + } + + nonempty(message?: errorUtil.ErrMessage): ZodSet { + return this.min(1, message) as any; + } + + static create = ( + valueType: ValueSchema, + params?: RawCreateParams + ): ZodSet => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); + }; +} + +/////////////////////////////////////////// +/////////////////////////////////////////// +////////// ////////// +////////// ZodFunction ////////// +////////// ////////// +/////////////////////////////////////////// +/////////////////////////////////////////// +export interface ZodFunctionDef< + Args extends ZodTuple = ZodTuple, + Returns extends ZodTypeAny = ZodTypeAny, +> extends ZodTypeDef { + args: Args; + returns: Returns; + typeName: ZodFirstPartyTypeKind.ZodFunction; +} + +export type OuterTypeOfFunction< + Args extends ZodTuple, + Returns extends ZodTypeAny, +> = Args["_input"] extends Array ? (...args: Args["_input"]) => Returns["_output"] : never; + +export type InnerTypeOfFunction< + Args extends ZodTuple, + Returns extends ZodTypeAny, +> = Args["_output"] extends Array ? (...args: Args["_output"]) => Returns["_input"] : never; + +export class ZodFunction, Returns extends ZodTypeAny> extends ZodType< + OuterTypeOfFunction, + ZodFunctionDef, + InnerTypeOfFunction +> { + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType, + }); + return INVALID; + } + + function makeArgsIssue(args: any, error: ZodError): ZodIssue { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter( + (x) => !!x + ), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + + function makeReturnsIssue(returns: any, error: ZodError): ZodIssue { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter( + (x) => !!x + ), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(async function (this: any, ...args: any[]) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs as any); + const parsedReturns = await (me._def.returns as unknown as ZodPromise)._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(function (this: any, ...args: any[]) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }) as any; + } + } + + parameters() { + return this._def.args; + } + + returnType() { + return this._def.returns; + } + + args[0]>( + ...items: Items + ): ZodFunction, Returns> { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) as any, + }); + } + + returns>(returnType: NewReturnType): ZodFunction { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + + implement>( + func: F + ): ReturnType extends Returns["_output"] + ? (...args: Args["_input"]) => ReturnType + : OuterTypeOfFunction { + const validatedFunc = this.parse(func); + return validatedFunc as any; + } + + strictImplement(func: InnerTypeOfFunction): InnerTypeOfFunction { + const validatedFunc = this.parse(func); + return validatedFunc as any; + } + + validate = this.implement; + + static create(): ZodFunction, ZodUnknown>; + static create>(args: T): ZodFunction; + static create(args: T, returns: U): ZodFunction; + static create, U extends ZodTypeAny = ZodUnknown>( + args: T, + returns: U, + params?: RawCreateParams + ): ZodFunction; + static create(args?: AnyZodTuple, returns?: ZodTypeAny, params?: RawCreateParams) { + return new ZodFunction({ + args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())) as any, + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }) as any; + } +} + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// ZodLazy ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// +export interface ZodLazyDef extends ZodTypeDef { + getter: () => T; + typeName: ZodFirstPartyTypeKind.ZodLazy; +} + +export class ZodLazy extends ZodType, ZodLazyDef, input> { + get schema(): T { + return this._def.getter(); + } + + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + + static create = (getter: () => Inner, params?: RawCreateParams): ZodLazy => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodLiteral ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// +export interface ZodLiteralDef extends ZodTypeDef { + value: T; + typeName: ZodFirstPartyTypeKind.ZodLiteral; +} + +export class ZodLiteral extends ZodType, T> { + _parse(input: ParseInput): ParseReturnType { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + + get value() { + return this._def.value; + } + + static create = (value: Value, params?: RawCreateParams): ZodLiteral => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); + }; +} + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// ZodEnum ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// +export type ArrayKeys = keyof any[]; +export type Indices = Exclude; + +export type EnumValues = readonly [T, ...T[]]; + +export type Values = { + [k in T[number]]: k; +}; + +export interface ZodEnumDef extends ZodTypeDef { + values: T; + typeName: ZodFirstPartyTypeKind.ZodEnum; +} + +export type Writeable = { -readonly [P in keyof T]: T[P] }; + +export type FilterEnum = Values extends [] + ? [] + : Values extends [infer Head, ...infer Rest] + ? Head extends ToExclude + ? FilterEnum + : [Head, ...FilterEnum] + : never; + +export type typecast = A extends T ? A : never; + +function createZodEnum>( + values: T, + params?: RawCreateParams +): ZodEnum>; +function createZodEnum(values: T, params?: RawCreateParams): ZodEnum; +function createZodEnum(values: [string, ...string[]], params?: RawCreateParams) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); +} + +export class ZodEnum extends ZodType, T[number]> { + _cache: Set | undefined; + + _parse(input: ParseInput): ParseReturnType { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues) as "string", + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + + if (!this._cache) { + this._cache = new Set(this._def.values); + } + + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + + get options() { + return this._def.values; + } + + get enum(): Values { + const enumValues: any = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + + get Values(): Values { + const enumValues: any = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + + get Enum(): Values { + const enumValues: any = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + + extract( + values: ToExtract, + newDef: RawCreateParams = this._def + ): ZodEnum> { + return ZodEnum.create(values, { + ...this._def, + ...newDef, + }) as any; + } + + exclude( + values: ToExclude, + newDef: RawCreateParams = this._def + ): ZodEnum>, [string, ...string[]]>> { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)) as FilterEnum, { + ...this._def, + ...newDef, + }) as any; + } + + static create = createZodEnum; +} + +///////////////////////////////////////////// +///////////////////////////////////////////// +////////// ////////// +////////// ZodNativeEnum ////////// +////////// ////////// +///////////////////////////////////////////// +///////////////////////////////////////////// +export interface ZodNativeEnumDef extends ZodTypeDef { + values: T; + typeName: ZodFirstPartyTypeKind.ZodNativeEnum; +} + +export type EnumLike = { [k: string]: string | number; [nu: number]: string }; + +export class ZodNativeEnum extends ZodType, T[keyof T]> { + _cache: Set | undefined; + _parse(input: ParseInput): ParseReturnType { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues) as "string", + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); + } + + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + + get enum() { + return this._def.values; + } + + static create = (values: Elements, params?: RawCreateParams): ZodNativeEnum => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodPromise ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// +export interface ZodPromiseDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodPromise; +} + +export class ZodPromise extends ZodType< + Promise, + ZodPromiseDef, + Promise +> { + unwrap() { + return this._def.type; + } + + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType, + }); + return INVALID; + } + + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + + return OK( + promisified.then((data: any) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + }) + ); + } + + static create = (schema: Inner, params?: RawCreateParams): ZodPromise => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////////////// +////////////////////////////////////////////// +////////// ////////// +////////// ZodEffects ////////// +////////// ////////// +////////////////////////////////////////////// +////////////////////////////////////////////// + +export type Refinement = (arg: T, ctx: RefinementCtx) => any; +export type SuperRefinement = (arg: T, ctx: RefinementCtx) => void | Promise; + +export type RefinementEffect = { + type: "refinement"; + refinement: (arg: T, ctx: RefinementCtx) => any; +}; +export type TransformEffect = { + type: "transform"; + transform: (arg: T, ctx: RefinementCtx) => any; +}; +export type PreprocessEffect = { + type: "preprocess"; + transform: (arg: T, ctx: RefinementCtx) => any; +}; +export type Effect = RefinementEffect | TransformEffect | PreprocessEffect; + +export interface ZodEffectsDef extends ZodTypeDef { + schema: T; + typeName: ZodFirstPartyTypeKind.ZodEffects; + effect: Effect; +} + +export class ZodEffects, Input = input> extends ZodType< + Output, + ZodEffectsDef, + Input +> { + innerType() { + return this._def.schema; + } + + sourceType(): T { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? (this._def.schema as unknown as ZodEffects).sourceType() + : (this._def.schema as T); + } + + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + + const effect = this._def.effect || null; + + const checkCtx: RefinementCtx = { + addIssue: (arg: IssueData) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed) => { + if (status.value === "aborted") return INVALID; + + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") return INVALID; + if (result.status === "dirty") return DIRTY(result.value); + if (status.value === "dirty") return DIRTY(result.value); + return result; + }); + } else { + if (status.value === "aborted") return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") return INVALID; + if (result.status === "dirty") return DIRTY(result.value); + if (status.value === "dirty") return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc: unknown): any => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") return INVALID; + if (inner.status === "dirty") status.dirty(); + + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") return INVALID; + if (inner.status === "dirty") status.dirty(); + + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + + if (!isValid(base)) return INVALID; + + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error( + `Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.` + ); + } + + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) return INVALID; + + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result, + })); + }); + } + } + + util.assertNever(effect); + } + + static create = ( + schema: I, + effect: Effect, + params?: RawCreateParams + ): ZodEffects => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); + }; + + static createWithPreprocess = ( + preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, + schema: I, + params?: RawCreateParams + ): ZodEffects => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); + }; +} + +export { ZodEffects as ZodTransformer }; + +/////////////////////////////////////////// +/////////////////////////////////////////// +////////// ////////// +////////// ZodOptional ////////// +////////// ////////// +/////////////////////////////////////////// +/////////////////////////////////////////// +export interface ZodOptionalDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodOptional; +} + +export type ZodOptionalType = ZodOptional; + +export class ZodOptional extends ZodType< + T["_output"] | undefined, + ZodOptionalDef, + T["_input"] | undefined +> { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); + } + + unwrap() { + return this._def.innerType; + } + + static create = (type: Inner, params?: RawCreateParams): ZodOptional => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }) as any; + }; +} + +/////////////////////////////////////////// +/////////////////////////////////////////// +////////// ////////// +////////// ZodNullable ////////// +////////// ////////// +/////////////////////////////////////////// +/////////////////////////////////////////// +export interface ZodNullableDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodNullable; +} + +export type ZodNullableType = ZodNullable; + +export class ZodNullable extends ZodType< + T["_output"] | null, + ZodNullableDef, + T["_input"] | null +> { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + + unwrap() { + return this._def.innerType; + } + + static create = (type: Inner, params?: RawCreateParams): ZodNullable => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }) as any; + }; +} + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// ZodDefault ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface ZodDefaultDef extends ZodTypeDef { + innerType: T; + defaultValue: () => util.noUndefined; + typeName: ZodFirstPartyTypeKind.ZodDefault; +} + +export class ZodDefault extends ZodType< + util.noUndefined, + ZodDefaultDef, + T["_input"] | undefined +> { + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + + removeDefault() { + return this._def.innerType; + } + + static create = ( + type: Inner, + params: RawCreateParams & { + default: Inner["_input"] | (() => util.noUndefined); + } + ): ZodDefault => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default as any, + ...processCreateParams(params), + }) as any; + }; +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodCatch ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// +export interface ZodCatchDef extends ZodTypeDef { + innerType: T; + catchValue: (ctx: { error: ZodError; input: unknown }) => T["_input"]; + typeName: ZodFirstPartyTypeKind.ZodCatch; +} + +export class ZodCatch extends ZodType< + T["_output"], + ZodCatchDef, + unknown // any input will pass validation // T["_input"] +> { + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + + // newCtx is used to not collect issues from inner types in ctx + const newCtx: ParseContext = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + + if (isAsync(result)) { + return result.then((result) => { + return { + status: "valid", + value: + result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); + } else { + return { + status: "valid", + value: + result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + } + } + + removeCatch() { + return this._def.innerType; + } + + static create = ( + type: Inner, + params: RawCreateParams & { + catch: Inner["_output"] | (() => Inner["_output"]); + } + ): ZodCatch => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); + }; +} + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodNaN ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// + +export interface ZodNaNDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNaN; +} + +export class ZodNaN extends ZodType { + _parse(input: ParseInput): ParseReturnType { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType, + }); + return INVALID; + } + + return { status: "valid", value: input.data }; + } + + static create = (params?: RawCreateParams): ZodNaN => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); + }; +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodBranded ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +export interface ZodBrandedDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodBranded; +} + +export const BRAND: unique symbol = Symbol("zod_brand"); +export type BRAND = { + [BRAND]: { [k in T]: true }; +}; + +export class ZodBranded extends ZodType< + T["_output"] & BRAND, + ZodBrandedDef, + T["_input"] +> { + _parse(input: ParseInput): ParseReturnType { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + + unwrap() { + return this._def.type; + } +} + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// ZodPipeline ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// + +export interface ZodPipelineDef extends ZodTypeDef { + in: A; + out: B; + typeName: ZodFirstPartyTypeKind.ZodPipeline; +} + +export class ZodPipeline extends ZodType< + B["_output"], + ZodPipelineDef, + A["_input"] +> { + _parse(input: ParseInput): ParseReturnType { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + + static create( + a: ASchema, + b: BSchema + ): ZodPipeline { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, + }); + } +} + +/////////////////////////////////////////// +/////////////////////////////////////////// +////////// ////////// +////////// ZodReadonly ////////// +////////// ////////// +/////////////////////////////////////////// +/////////////////////////////////////////// +type BuiltIn = + | (((...args: any[]) => any) | (new (...args: any[]) => any)) + | { readonly [Symbol.toStringTag]: string } + | Date + | Error + | Generator + | Promise + | RegExp; + +type MakeReadonly = T extends Map + ? ReadonlyMap + : T extends Set + ? ReadonlySet + : T extends [infer Head, ...infer Tail] + ? readonly [Head, ...Tail] + : T extends Array + ? ReadonlyArray + : T extends BuiltIn + ? T + : Readonly; + +export interface ZodReadonlyDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodReadonly; +} + +export class ZodReadonly extends ZodType< + MakeReadonly, + ZodReadonlyDef, + MakeReadonly +> { + _parse(input: ParseInput): ParseReturnType { + const result = this._def.innerType._parse(input); + const freeze = (data: ParseReturnType) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); + } + + static create = (type: Inner, params?: RawCreateParams): ZodReadonly => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }) as any; + }; + + unwrap() { + return this._def.innerType; + } +} + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// z.custom ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +function cleanParams(params: unknown, data: unknown) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +type CustomParams = CustomErrorParams & { fatal?: boolean }; +export function custom( + check?: (data: any) => any, + _params: string | CustomParams | ((input: any) => CustomParams) = {}, + /** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ + fatal?: boolean +): ZodType { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) { + return r.then((r) => { + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} + +export { ZodType as Schema, ZodType as ZodSchema }; + +export const late = { + object: ZodObject.lazycreate, +}; + +export enum ZodFirstPartyTypeKind { + ZodString = "ZodString", + ZodNumber = "ZodNumber", + ZodNaN = "ZodNaN", + ZodBigInt = "ZodBigInt", + ZodBoolean = "ZodBoolean", + ZodDate = "ZodDate", + ZodSymbol = "ZodSymbol", + ZodUndefined = "ZodUndefined", + ZodNull = "ZodNull", + ZodAny = "ZodAny", + ZodUnknown = "ZodUnknown", + ZodNever = "ZodNever", + ZodVoid = "ZodVoid", + ZodArray = "ZodArray", + ZodObject = "ZodObject", + ZodUnion = "ZodUnion", + ZodDiscriminatedUnion = "ZodDiscriminatedUnion", + ZodIntersection = "ZodIntersection", + ZodTuple = "ZodTuple", + ZodRecord = "ZodRecord", + ZodMap = "ZodMap", + ZodSet = "ZodSet", + ZodFunction = "ZodFunction", + ZodLazy = "ZodLazy", + ZodLiteral = "ZodLiteral", + ZodEnum = "ZodEnum", + ZodEffects = "ZodEffects", + ZodNativeEnum = "ZodNativeEnum", + ZodOptional = "ZodOptional", + ZodNullable = "ZodNullable", + ZodDefault = "ZodDefault", + ZodCatch = "ZodCatch", + ZodPromise = "ZodPromise", + ZodBranded = "ZodBranded", + ZodPipeline = "ZodPipeline", + ZodReadonly = "ZodReadonly", +} +export type ZodFirstPartySchemaTypes = + | ZodString + | ZodNumber + | ZodNaN + | ZodBigInt + | ZodBoolean + | ZodDate + | ZodUndefined + | ZodNull + | ZodAny + | ZodUnknown + | ZodNever + | ZodVoid + | ZodArray + | ZodObject + | ZodUnion + | ZodDiscriminatedUnion + | ZodIntersection + | ZodTuple + | ZodRecord + | ZodMap + | ZodSet + | ZodFunction + | ZodLazy + | ZodLiteral + | ZodEnum + | ZodEffects + | ZodNativeEnum + | ZodOptional + | ZodNullable + | ZodDefault + | ZodCatch + | ZodPromise + | ZodBranded + | ZodPipeline + | ZodReadonly + | ZodSymbol; + +// requires TS 4.4+ +abstract class Class { + constructor(..._: any[]) {} +} +const instanceOfType = ( + // const instanceOfType = any>( + cls: T, + params: CustomParams = { + message: `Input not instance of ${cls.name}`, + } +) => custom>((data) => data instanceof cls, params); + +const stringType = ZodString.create; +const numberType = ZodNumber.create; +const nanType = ZodNaN.create; +const bigIntType = ZodBigInt.create; +const booleanType = ZodBoolean.create; +const dateType = ZodDate.create; +const symbolType = ZodSymbol.create; +const undefinedType = ZodUndefined.create; +const nullType = ZodNull.create; +const anyType = ZodAny.create; +const unknownType = ZodUnknown.create; +const neverType = ZodNever.create; +const voidType = ZodVoid.create; +const arrayType = ZodArray.create; +const objectType = ZodObject.create; +const strictObjectType = ZodObject.strictCreate; +const unionType = ZodUnion.create; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +const intersectionType = ZodIntersection.create; +const tupleType = ZodTuple.create; +const recordType = ZodRecord.create; +const mapType = ZodMap.create; +const setType = ZodSet.create; +const functionType = ZodFunction.create; +const lazyType = ZodLazy.create; +const literalType = ZodLiteral.create; +const enumType = ZodEnum.create; +const nativeEnumType = ZodNativeEnum.create; +const promiseType = ZodPromise.create; +const effectsType = ZodEffects.create; +const optionalType = ZodOptional.create; +const nullableType = ZodNullable.create; +const preprocessType = ZodEffects.createWithPreprocess; +const pipelineType = ZodPipeline.create; +const ostring = () => stringType().optional(); +const onumber = () => numberType().optional(); +const oboolean = () => booleanType().optional(); + +export const coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })) as (typeof ZodString)["create"], + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })) as (typeof ZodNumber)["create"], + boolean: ((arg) => + ZodBoolean.create({ + ...arg, + coerce: true, + })) as (typeof ZodBoolean)["create"], + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })) as (typeof ZodBigInt)["create"], + date: ((arg) => ZodDate.create({ ...arg, coerce: true })) as (typeof ZodDate)["create"], +}; + +export { + anyType as any, + arrayType as array, + bigIntType as bigint, + booleanType as boolean, + dateType as date, + discriminatedUnionType as discriminatedUnion, + effectsType as effect, + enumType as enum, + functionType as function, + instanceOfType as instanceof, + intersectionType as intersection, + lazyType as lazy, + literalType as literal, + mapType as map, + nanType as nan, + nativeEnumType as nativeEnum, + neverType as never, + nullType as null, + nullableType as nullable, + numberType as number, + objectType as object, + oboolean, + onumber, + optionalType as optional, + ostring, + pipelineType as pipeline, + preprocessType as preprocess, + promiseType as promise, + recordType as record, + setType as set, + strictObjectType as strictObject, + stringType as string, + symbolType as symbol, + effectsType as transformer, + tupleType as tuple, + undefinedType as undefined, + unionType as union, + unknownType as unknown, + voidType as void, +}; + +export const NEVER = INVALID as never; diff --git a/node_modules/zod/src/v4-mini/index.ts b/node_modules/zod/src/v4-mini/index.ts new file mode 100644 index 000000000..87b293a4f --- /dev/null +++ b/node_modules/zod/src/v4-mini/index.ts @@ -0,0 +1 @@ +export * from "../v4/mini/index.js"; diff --git a/node_modules/zod/src/v4/classic/checks.ts b/node_modules/zod/src/v4/classic/checks.ts new file mode 100644 index 000000000..1846b2b3b --- /dev/null +++ b/node_modules/zod/src/v4/classic/checks.ts @@ -0,0 +1,30 @@ +export { + _lt as lt, + _lte as lte, + _gt as gt, + _gte as gte, + _positive as positive, + _negative as negative, + _nonpositive as nonpositive, + _nonnegative as nonnegative, + _multipleOf as multipleOf, + _maxSize as maxSize, + _minSize as minSize, + _size as size, + _maxLength as maxLength, + _minLength as minLength, + _length as length, + _regex as regex, + _lowercase as lowercase, + _uppercase as uppercase, + _includes as includes, + _startsWith as startsWith, + _endsWith as endsWith, + _property as property, + _mime as mime, + _overwrite as overwrite, + _normalize as normalize, + _trim as trim, + _toLowerCase as toLowerCase, + _toUpperCase as toUpperCase, +} from "../core/index.js"; diff --git a/node_modules/zod/src/v4/classic/coerce.ts b/node_modules/zod/src/v4/classic/coerce.ts new file mode 100644 index 000000000..cc400e0d8 --- /dev/null +++ b/node_modules/zod/src/v4/classic/coerce.ts @@ -0,0 +1,27 @@ +import * as core from "../core/index.js"; +import * as schemas from "./schemas.js"; + +export interface ZodCoercedString extends schemas._ZodString> {} +export function string(params?: string | core.$ZodStringParams): ZodCoercedString { + return core._coercedString(schemas.ZodString, params) as any; +} + +export interface ZodCoercedNumber extends schemas._ZodNumber> {} +export function number(params?: string | core.$ZodNumberParams): ZodCoercedNumber { + return core._coercedNumber(schemas.ZodNumber, params) as ZodCoercedNumber; +} + +export interface ZodCoercedBoolean extends schemas._ZodBoolean> {} +export function boolean(params?: string | core.$ZodBooleanParams): ZodCoercedBoolean { + return core._coercedBoolean(schemas.ZodBoolean, params) as ZodCoercedBoolean; +} + +export interface ZodCoercedBigInt extends schemas._ZodBigInt> {} +export function bigint(params?: string | core.$ZodBigIntParams): ZodCoercedBigInt { + return core._coercedBigint(schemas.ZodBigInt, params) as ZodCoercedBigInt; +} + +export interface ZodCoercedDate extends schemas._ZodDate> {} +export function date(params?: string | core.$ZodDateParams): ZodCoercedDate { + return core._coercedDate(schemas.ZodDate, params) as ZodCoercedDate; +} diff --git a/node_modules/zod/src/v4/classic/compat.ts b/node_modules/zod/src/v4/classic/compat.ts new file mode 100644 index 000000000..f24af190c --- /dev/null +++ b/node_modules/zod/src/v4/classic/compat.ts @@ -0,0 +1,66 @@ +// Zod 3 compat layer + +import * as core from "../core/index.js"; +import type { ZodType } from "./schemas.js"; + +export type { + /** @deprecated Use `z.output` instead. */ + output as TypeOf, + /** @deprecated Use `z.output` instead. */ + output as Infer, + /** @deprecated Use `z.core.$$ZodFirstPartyTypes` instead */ + $ZodTypes as ZodFirstPartySchemaTypes, +} from "../core/index.js"; + +/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ +export const ZodIssueCode = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom", +} as const; + +/** @deprecated Use `z.$ZodFlattenedError` */ +export type inferFlattenedErrors = core.$ZodFlattenedError, U>; + +/** @deprecated Use `z.$ZodFormattedError` */ +export type inferFormattedError, U = string> = core.$ZodFormattedError< + core.output, + U +>; + +/** Use `z.$brand` instead */ +export type BRAND = { + [core.$brand]: { [k in T]: true }; +}; +export { $brand, config } from "../core/index.js"; + +/** @deprecated Use `z.config(params)` instead. */ +export function setErrorMap(map: core.$ZodErrorMap): void { + core.config({ + customError: map, + }); +} + +/** @deprecated Use `z.config()` instead. */ +export function getErrorMap(): core.$ZodErrorMap | undefined { + return core.config().customError; +} + +export type { + /** @deprecated Use z.ZodType (without generics) instead. */ + ZodType as ZodTypeAny, + /** @deprecated Use `z.ZodType` */ + ZodType as ZodSchema, + /** @deprecated Use `z.ZodType` */ + ZodType as Schema, +}; + +export type ZodRawShape = core.$ZodShape; diff --git a/node_modules/zod/src/v4/classic/errors.ts b/node_modules/zod/src/v4/classic/errors.ts new file mode 100644 index 000000000..5ce4305b8 --- /dev/null +++ b/node_modules/zod/src/v4/classic/errors.ts @@ -0,0 +1,75 @@ +import * as core from "../core/index.js"; +import { $ZodError } from "../core/index.js"; + +/** @deprecated Use `z.core.$ZodIssue` from `@zod/core` instead, especially if you are building a library on top of Zod. */ +export type ZodIssue = core.$ZodIssue; + +/** An Error-like class used to store Zod validation issues. */ +export interface ZodError extends $ZodError { + /** @deprecated Use the `z.treeifyError(err)` function instead. */ + format(): core.$ZodFormattedError; + format(mapper: (issue: core.$ZodIssue) => U): core.$ZodFormattedError; + /** @deprecated Use the `z.treeifyError(err)` function instead. */ + flatten(): core.$ZodFlattenedError; + flatten(mapper: (issue: core.$ZodIssue) => U): core.$ZodFlattenedError; + /** @deprecated Push directly to `.issues` instead. */ + addIssue(issue: core.$ZodIssue): void; + /** @deprecated Push directly to `.issues` instead. */ + addIssues(issues: core.$ZodIssue[]): void; + + /** @deprecated Check `err.issues.length === 0` instead. */ + isEmpty: boolean; +} + +const initializer = (inst: ZodError, issues: core.$ZodIssue[]) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper: any) => core.formatError(inst, mapper), + // enumerable: false, + }, + flatten: { + value: (mapper: any) => core.flattenError(inst, mapper), + // enumerable: false, + }, + addIssue: { + value: (issue: any) => inst.issues.push(issue), + // enumerable: false, + }, + addIssues: { + value: (issues: any) => inst.issues.push(...issues), + // enumerable: false, + }, + isEmpty: { + get() { + return inst.issues.length === 0; + }, + // enumerable: false, + }, + }); + // Object.defineProperty(inst, "isEmpty", { + // get() { + // return inst.issues.length === 0; + // }, + // }); +}; +export const ZodError: core.$constructor = core.$constructor("ZodError", initializer); +export const ZodRealError: core.$constructor = core.$constructor("ZodError", initializer, { + Parent: Error, +}); + +export type { + /** @deprecated Use `z.core.$ZodFlattenedError` instead. */ + $ZodFlattenedError as ZodFlattenedError, + /** @deprecated Use `z.core.$ZodFormattedError` instead. */ + $ZodFormattedError as ZodFormattedError, + /** @deprecated Use `z.core.$ZodErrorMap` instead. */ + $ZodErrorMap as ZodErrorMap, +} from "../core/index.js"; + +/** @deprecated Use `z.core.$ZodRawIssue` instead. */ +export type IssueData = core.$ZodRawIssue; + +// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ +// export type ErrorMapCtx = core.$ZodErrorMapCtx; diff --git a/node_modules/zod/src/v4/classic/external.ts b/node_modules/zod/src/v4/classic/external.ts new file mode 100644 index 000000000..855f5a7d0 --- /dev/null +++ b/node_modules/zod/src/v4/classic/external.ts @@ -0,0 +1,50 @@ +export * as core from "../core/index.js"; +export * from "./schemas.js"; +export * from "./checks.js"; +export * from "./errors.js"; +export * from "./parse.js"; +export * from "./compat.js"; + +// zod-specified +import { config } from "../core/index.js"; +import en from "../locales/en.js"; +config(en()); + +export type { infer, output, input } from "../core/index.js"; +export { + globalRegistry, + type GlobalMeta, + registry, + config, + function, + $output, + $input, + $brand, + clone, + regexes, + treeifyError, + prettifyError, + formatError, + flattenError, + toJSONSchema, + TimePrecision, + NEVER, +} from "../core/index.js"; + +export * as locales from "../locales/index.js"; + +// iso +// must be exported from top-level +// https://github.com/colinhacks/zod/issues/4491 +export { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from "./iso.js"; +export * as iso from "./iso.js"; + +// coerce +export type { + ZodCoercedString, + ZodCoercedNumber, + ZodCoercedBigInt, + ZodCoercedBoolean, + ZodCoercedDate, +} from "./coerce.js"; +export * as coerce from "./coerce.js"; diff --git a/node_modules/zod/src/v4/classic/index.ts b/node_modules/zod/src/v4/classic/index.ts new file mode 100644 index 000000000..f0f7547ff --- /dev/null +++ b/node_modules/zod/src/v4/classic/index.ts @@ -0,0 +1,5 @@ +import * as z from "./external.js"; + +export { z }; +export * from "./external.js"; +export default z; diff --git a/node_modules/zod/src/v4/classic/iso.ts b/node_modules/zod/src/v4/classic/iso.ts new file mode 100644 index 000000000..b08696d67 --- /dev/null +++ b/node_modules/zod/src/v4/classic/iso.ts @@ -0,0 +1,90 @@ +import * as core from "../core/index.js"; +import * as schemas from "./schemas.js"; + +////////////////////////////////////////////// +////////////////////////////////////////////// +////////// ////////// +////////// ZodISODateTime ////////// +////////// ////////// +////////////////////////////////////////////// +////////////////////////////////////////////// + +export interface ZodISODateTime extends schemas.ZodStringFormat { + _zod: core.$ZodISODateTimeInternals; +} +export const ZodISODateTime: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodISODateTime", + (inst, def) => { + core.$ZodISODateTime.init(inst, def); + schemas.ZodStringFormat.init(inst, def); + } +); + +export function datetime(params?: string | core.$ZodISODateTimeParams): ZodISODateTime { + return core._isoDateTime(ZodISODateTime, params); +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodISODate ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +export interface ZodISODate extends schemas.ZodStringFormat { + _zod: core.$ZodISODateInternals; +} +export const ZodISODate: core.$constructor = /*@__PURE__*/ core.$constructor("ZodISODate", (inst, def) => { + core.$ZodISODate.init(inst, def); + schemas.ZodStringFormat.init(inst, def); +}); + +export function date(params?: string | core.$ZodISODateParams): ZodISODate { + return core._isoDate(ZodISODate, params); +} + +// ZodISOTime + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodISOTime ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +export interface ZodISOTime extends schemas.ZodStringFormat { + _zod: core.$ZodISOTimeInternals; +} +export const ZodISOTime: core.$constructor = /*@__PURE__*/ core.$constructor("ZodISOTime", (inst, def) => { + core.$ZodISOTime.init(inst, def); + schemas.ZodStringFormat.init(inst, def); +}); + +export function time(params?: string | core.$ZodISOTimeParams): ZodISOTime { + return core._isoTime(ZodISOTime, params); +} + +////////////////////////////////////////////// +////////////////////////////////////////////// +////////// ////////// +////////// ZodISODuration ////////// +////////// ////////// +////////////////////////////////////////////// +////////////////////////////////////////////// + +export interface ZodISODuration extends schemas.ZodStringFormat { + _zod: core.$ZodISODurationInternals; +} +export const ZodISODuration: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodISODuration", + (inst, def) => { + core.$ZodISODuration.init(inst, def); + schemas.ZodStringFormat.init(inst, def); + } +); + +export function duration(params?: string | core.$ZodISODurationParams): ZodISODuration { + return core._isoDuration(ZodISODuration, params); +} diff --git a/node_modules/zod/src/v4/classic/parse.ts b/node_modules/zod/src/v4/classic/parse.ts new file mode 100644 index 000000000..0d77e2078 --- /dev/null +++ b/node_modules/zod/src/v4/classic/parse.ts @@ -0,0 +1,33 @@ +import * as core from "../core/index.js"; +import { type ZodError, ZodRealError } from "./errors.js"; + +export type ZodSafeParseResult = ZodSafeParseSuccess | ZodSafeParseError; +export type ZodSafeParseSuccess = { success: true; data: T; error?: never }; +export type ZodSafeParseError = { success: false; data?: never; error: ZodError }; + +export const parse: ( + schema: T, + value: unknown, + _ctx?: core.ParseContext, + _params?: { callee?: core.util.AnyFunc; Err?: core.$ZodErrorClass } +) => core.output = /* @__PURE__ */ core._parse(ZodRealError) as any; + +export const parseAsync: ( + schema: T, + value: unknown, + _ctx?: core.ParseContext, + _params?: { callee?: core.util.AnyFunc; Err?: core.$ZodErrorClass } +) => Promise> = /* @__PURE__ */ core._parseAsync(ZodRealError) as any; + +export const safeParse: ( + schema: T, + value: unknown, + _ctx?: core.ParseContext + // _params?: { callee?: core.util.AnyFunc; Err?: core.$ZodErrorClass } +) => ZodSafeParseResult> = /* @__PURE__ */ core._safeParse(ZodRealError) as any; + +export const safeParseAsync: ( + schema: T, + value: unknown, + _ctx?: core.ParseContext +) => Promise>> = /* @__PURE__ */ core._safeParseAsync(ZodRealError) as any; diff --git a/node_modules/zod/src/v4/classic/schemas.ts b/node_modules/zod/src/v4/classic/schemas.ts new file mode 100644 index 000000000..3d09cb650 --- /dev/null +++ b/node_modules/zod/src/v4/classic/schemas.ts @@ -0,0 +1,2054 @@ +import * as core from "../core/index.js"; +import { util } from "../core/index.js"; + +import * as checks from "./checks.js"; +import * as iso from "./iso.js"; +import * as parse from "./parse.js"; + +/////////////////////////////////////////// +/////////////////////////////////////////// +//////////// //////////// +//////////// ZodType //////////// +//////////// //////////// +/////////////////////////////////////////// +/////////////////////////////////////////// + +export interface RefinementCtx extends core.ParsePayload { + addIssue(arg: string | core.$ZodRawIssue | Partial): void; +} + +export interface ZodType< + out Output = unknown, + out Input = unknown, + out Internals extends core.$ZodTypeInternals = core.$ZodTypeInternals, +> extends core.$ZodType { + def: Internals["def"]; + type: Internals["def"]["type"]; + + /** @deprecated Use `.def` instead. */ + _def: Internals["def"]; + /** @deprecated Use `z.output` instead. */ + _output: Internals["output"]; + /** @deprecated Use `z.input` instead. */ + _input: Internals["input"]; + + // base methods + check(...checks: (core.CheckFn> | core.$ZodCheck>)[]): this; + clone(def?: Internals["def"], params?: { parent: boolean }): this; + register( + registry: R, + ...meta: this extends R["_schema"] + ? undefined extends R["_meta"] + ? [core.$replace?] + : [core.$replace] + : ["Incompatible schema"] + ): this; + + brand(value?: T): PropertyKey extends T ? this : core.$ZodBranded; + + // parsing + parse(data: unknown, params?: core.ParseContext): core.output; + safeParse(data: unknown, params?: core.ParseContext): parse.ZodSafeParseResult>; + parseAsync(data: unknown, params?: core.ParseContext): Promise>; + safeParseAsync( + data: unknown, + params?: core.ParseContext + ): Promise>>; + spa: ( + data: unknown, + params?: core.ParseContext + ) => Promise>>; + + // refinements + refine(check: (arg: core.output) => unknown | Promise, params?: string | core.$ZodCustomParams): this; + /** @deprecated Use `.check()` instead. */ + superRefine( + refinement: (arg: core.output, ctx: RefinementCtx>) => void | Promise + ): this; + overwrite(fn: (x: core.output) => core.output): this; + + // wrappers + optional(): ZodOptional; + nonoptional(params?: string | core.$ZodNonOptionalParams): ZodNonOptional; + nullable(): ZodNullable; + nullish(): ZodOptional>; + default(def: core.output): ZodDefault; + default(def: () => util.NoUndefined>): ZodDefault; + prefault(def: () => core.input): ZodPrefault; + prefault(def: core.input): ZodPrefault; + array(): ZodArray; + or(option: T): ZodUnion<[this, T]>; + and(incoming: T): ZodIntersection; + transform( + transform: (arg: core.output, ctx: RefinementCtx>) => NewOut | Promise + ): ZodPipe, core.output>>; + catch(def: core.output): ZodCatch; + catch(def: (ctx: core.$ZodCatchCtx) => core.output): ZodCatch; + pipe>>( + target: T | core.$ZodType> + ): ZodPipe; + readonly(): ZodReadonly; + + /** Returns a new instance that has been registered in `z.globalRegistry` with the specified description */ + describe(description: string): this; + description?: string; + /** Returns the metadata associated with this instance in `z.globalRegistry` */ + meta(): core.$replace | undefined; + /** Returns a new instance that has been registered in `z.globalRegistry` with the specified metadata */ + meta(data: core.$replace): this; + + // helpers + /** @deprecated Try safe-parsing `undefined` (this is what `isOptional` does internally): + * + * ```ts + * const schema = z.string().optional(); + * const isOptional = schema.safeParse(undefined).success; // true + * ``` + */ + isOptional(): boolean; + /** + * @deprecated Try safe-parsing `null` (this is what `isNullable` does internally): + * + * ```ts + * const schema = z.string().nullable(); + * const isNullable = schema.safeParse(null).success; // true + * ``` + */ + isNullable(): boolean; +} + +export interface _ZodType + extends ZodType {} + +export const ZodType: core.$constructor = /*@__PURE__*/ core.$constructor("ZodType", (inst, def) => { + core.$ZodType.init(inst, def); + inst.def = def; + Object.defineProperty(inst, "_def", { value: def }); + + // base methods + inst.check = (...checks) => { + return inst.clone( + { + ...def, + checks: [ + ...(def.checks ?? []), + ...checks.map((ch) => + typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch + ), + ], + } + // { parent: true } + ); + }; + inst.clone = (def, params) => core.clone(inst, def, params); + inst.brand = () => inst as any; + inst.register = ((reg: any, meta: any) => { + reg.add(inst, meta); + return inst; + }) as any; + + // parsing + inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => parse.safeParse(inst, data, params); + inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params); + inst.spa = inst.safeParseAsync; + + // refinements + inst.refine = (check, params) => inst.check(refine(check, params)); + inst.superRefine = (refinement) => inst.check(superRefine(refinement)); + inst.overwrite = (fn) => inst.check(checks.overwrite(fn)); + + // wrappers + inst.optional = () => optional(inst); + inst.nullable = () => nullable(inst); + inst.nullish = () => optional(nullable(inst)); + inst.nonoptional = (params) => nonoptional(inst, params); + inst.array = () => array(inst); + inst.or = (arg) => union([inst, arg]); + inst.and = (arg) => intersection(inst, arg); + inst.transform = (tx) => pipe(inst, transform(tx as any)) as never; + inst.default = (def) => _default(inst, def); + inst.prefault = (def) => prefault(inst, def); + // inst.coalesce = (def, params) => coalesce(inst, def, params); + inst.catch = (params) => _catch(inst, params); + inst.pipe = (target) => pipe(inst, target); + inst.readonly = () => readonly(inst); + + // meta + inst.describe = (description) => { + const cl = inst.clone(); + core.globalRegistry.add(cl, { description }); + return cl; + }; + Object.defineProperty(inst, "description", { + get() { + return core.globalRegistry.get(inst)?.description; + }, + configurable: true, + }); + inst.meta = (...args: any) => { + if (args.length === 0) { + return core.globalRegistry.get(inst); + } + const cl = inst.clone(); + core.globalRegistry.add(cl, args[0]); + return cl as any; + }; + + // helpers + inst.isOptional = () => inst.safeParse(undefined).success; + inst.isNullable = () => inst.safeParse(null).success; + return inst; +}); + +// ZodString +export interface _ZodString = core.$ZodStringInternals> + extends _ZodType { + format: string | null; + minLength: number | null; + maxLength: number | null; + + // miscellaneous checks + regex(regex: RegExp, params?: string | core.$ZodCheckRegexParams): this; + includes(value: string, params?: core.$ZodCheckIncludesParams): this; + startsWith(value: string, params?: string | core.$ZodCheckStartsWithParams): this; + endsWith(value: string, params?: string | core.$ZodCheckEndsWithParams): this; + min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this; + max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this; + length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this; + nonempty(params?: string | core.$ZodCheckMinLengthParams): this; + lowercase(params?: string | core.$ZodCheckLowerCaseParams): this; + uppercase(params?: string | core.$ZodCheckUpperCaseParams): this; + + // transforms + trim(): this; + normalize(form?: "NFC" | "NFD" | "NFKC" | "NFKD" | (string & {})): this; + toLowerCase(): this; + toUpperCase(): this; +} + +/** @internal */ +export const _ZodString: core.$constructor<_ZodString> = /*@__PURE__*/ core.$constructor("_ZodString", (inst, def) => { + core.$ZodString.init(inst, def); + ZodType.init(inst, def); + + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + + // validations + inst.regex = (...args) => inst.check(checks.regex(...args)); + inst.includes = (...args) => inst.check(checks.includes(...args)); + inst.startsWith = (...args) => inst.check(checks.startsWith(...args)); + inst.endsWith = (...args) => inst.check(checks.endsWith(...args)); + inst.min = (...args) => inst.check(checks.minLength(...args)); + inst.max = (...args) => inst.check(checks.maxLength(...args)); + inst.length = (...args) => inst.check(checks.length(...args)); + inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args)); + inst.lowercase = (params) => inst.check(checks.lowercase(params)); + inst.uppercase = (params) => inst.check(checks.uppercase(params)); + + // transforms + inst.trim = () => inst.check(checks.trim()); + inst.normalize = (...args) => inst.check(checks.normalize(...args)); + inst.toLowerCase = () => inst.check(checks.toLowerCase()); + inst.toUpperCase = () => inst.check(checks.toUpperCase()); +}); + +export interface ZodString extends _ZodString> { + // string format checks + + /** @deprecated Use `z.email()` instead. */ + email(params?: string | core.$ZodCheckEmailParams): this; + /** @deprecated Use `z.url()` instead. */ + url(params?: string | core.$ZodCheckURLParams): this; + /** @deprecated Use `z.jwt()` instead. */ + jwt(params?: string | core.$ZodCheckJWTParams): this; + /** @deprecated Use `z.emoji()` instead. */ + emoji(params?: string | core.$ZodCheckEmojiParams): this; + /** @deprecated Use `z.guid()` instead. */ + guid(params?: string | core.$ZodCheckGUIDParams): this; + /** @deprecated Use `z.uuid()` instead. */ + uuid(params?: string | core.$ZodCheckUUIDParams): this; + /** @deprecated Use `z.uuid()` instead. */ + uuidv4(params?: string | core.$ZodCheckUUIDParams): this; + /** @deprecated Use `z.uuid()` instead. */ + uuidv6(params?: string | core.$ZodCheckUUIDParams): this; + /** @deprecated Use `z.uuid()` instead. */ + uuidv7(params?: string | core.$ZodCheckUUIDParams): this; + /** @deprecated Use `z.nanoid()` instead. */ + nanoid(params?: string | core.$ZodCheckNanoIDParams): this; + /** @deprecated Use `z.guid()` instead. */ + guid(params?: string | core.$ZodCheckGUIDParams): this; + /** @deprecated Use `z.cuid()` instead. */ + cuid(params?: string | core.$ZodCheckCUIDParams): this; + /** @deprecated Use `z.cuid2()` instead. */ + cuid2(params?: string | core.$ZodCheckCUID2Params): this; + /** @deprecated Use `z.ulid()` instead. */ + ulid(params?: string | core.$ZodCheckULIDParams): this; + /** @deprecated Use `z.base64()` instead. */ + base64(params?: string | core.$ZodCheckBase64Params): this; + /** @deprecated Use `z.base64url()` instead. */ + base64url(params?: string | core.$ZodCheckBase64URLParams): this; + // /** @deprecated Use `z.jsonString()` instead. */ + // jsonString(params?: string | core.$ZodCheckJSONStringParams): this; + /** @deprecated Use `z.xid()` instead. */ + xid(params?: string | core.$ZodCheckXIDParams): this; + /** @deprecated Use `z.ksuid()` instead. */ + ksuid(params?: string | core.$ZodCheckKSUIDParams): this; + // /** @deprecated Use `z.ipv4()` or `z.ipv6()` instead. */ + // ip(params?: string | (core.$ZodCheckIPv4Params & { version?: "v4" | "v6" })): ZodUnion<[this, this]>; + /** @deprecated Use `z.ipv4()` instead. */ + ipv4(params?: string | core.$ZodCheckIPv4Params): this; + /** @deprecated Use `z.ipv6()` instead. */ + ipv6(params?: string | core.$ZodCheckIPv6Params): this; + /** @deprecated Use `z.cidrv4()` instead. */ + cidrv4(params?: string | core.$ZodCheckCIDRv4Params): this; + /** @deprecated Use `z.cidrv6()` instead. */ + cidrv6(params?: string | core.$ZodCheckCIDRv6Params): this; + /** @deprecated Use `z.e164()` instead. */ + e164(params?: string | core.$ZodCheckE164Params): this; + + // ISO 8601 checks + /** @deprecated Use `z.iso.datetime()` instead. */ + datetime(params?: string | core.$ZodCheckISODateTimeParams): this; + /** @deprecated Use `z.iso.date()` instead. */ + date(params?: string | core.$ZodCheckISODateParams): this; + /** @deprecated Use `z.iso.time()` instead. */ + time( + params?: + | string + // | { + // message?: string | undefined; + // precision?: number | null; + // } + | core.$ZodCheckISOTimeParams + ): this; + /** @deprecated Use `z.iso.duration()` instead. */ + duration(params?: string | core.$ZodCheckISODurationParams): this; +} + +export const ZodString: core.$constructor = /*@__PURE__*/ core.$constructor("ZodString", (inst, def) => { + core.$ZodString.init(inst, def); + _ZodString.init(inst, def); + + inst.email = (params) => inst.check(core._email(ZodEmail, params)); + inst.url = (params) => inst.check(core._url(ZodURL, params)); + inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params)); + inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params)); + inst.guid = (params) => inst.check(core._guid(ZodGUID, params)); + inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params)); + inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params)); + inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params)); + inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params)); + inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params)); + inst.guid = (params) => inst.check(core._guid(ZodGUID, params)); + inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params)); + inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params)); + inst.ulid = (params) => inst.check(core._ulid(ZodULID, params)); + inst.base64 = (params) => inst.check(core._base64(ZodBase64, params)); + inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params)); + inst.xid = (params) => inst.check(core._xid(ZodXID, params)); + inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params)); + inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params)); + inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params)); + inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params)); + inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params)); + inst.e164 = (params) => inst.check(core._e164(ZodE164, params)); + + // iso + inst.datetime = (params) => inst.check(iso.datetime(params as any)); + inst.date = (params) => inst.check(iso.date(params as any)); + inst.time = (params) => inst.check(iso.time(params as any)); + inst.duration = (params) => inst.check(iso.duration(params as any)); +}); + +export function string(params?: string | core.$ZodStringParams): ZodString; +export function string(params?: string | core.$ZodStringParams): core.$ZodType; +export function string(params?: string | core.$ZodStringParams): ZodString { + return core._string(ZodString, params) as any; +} + +// ZodStringFormat +export interface ZodStringFormat + extends _ZodString> {} +export const ZodStringFormat: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodStringFormat", + (inst, def) => { + core.$ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); + } +); + +// ZodEmail +export interface ZodEmail extends ZodStringFormat<"email"> { + _zod: core.$ZodEmailInternals; +} +export const ZodEmail: core.$constructor = /*@__PURE__*/ core.$constructor("ZodEmail", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function email(params?: string | core.$ZodEmailParams): ZodEmail { + return core._email(ZodEmail, params); +} + +// ZodGUID +export interface ZodGUID extends ZodStringFormat<"guid"> { + _zod: core.$ZodGUIDInternals; +} +export const ZodGUID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodGUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function guid(params?: string | core.$ZodGUIDParams): ZodGUID { + return core._guid(ZodGUID, params); +} + +// ZodUUID +export interface ZodUUID extends ZodStringFormat<"uuid"> { + _zod: core.$ZodUUIDInternals; +} +export const ZodUUID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodUUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function uuid(params?: string | core.$ZodUUIDParams): ZodUUID { + return core._uuid(ZodUUID, params); +} + +export function uuidv4(params?: string | core.$ZodUUIDv4Params): ZodUUID { + return core._uuidv4(ZodUUID, params); +} + +// ZodUUIDv6 + +export function uuidv6(params?: string | core.$ZodUUIDv6Params): ZodUUID { + return core._uuidv6(ZodUUID, params); +} + +// ZodUUIDv7 + +export function uuidv7(params?: string | core.$ZodUUIDv7Params): ZodUUID { + return core._uuidv7(ZodUUID, params); +} + +// ZodURL +export interface ZodURL extends ZodStringFormat<"url"> { + _zod: core.$ZodURLInternals; +} +export const ZodURL: core.$constructor = /*@__PURE__*/ core.$constructor("ZodURL", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function url(params?: string | core.$ZodURLParams): ZodURL { + return core._url(ZodURL, params); +} + +// ZodEmoji +export interface ZodEmoji extends ZodStringFormat<"emoji"> { + _zod: core.$ZodEmojiInternals; +} +export const ZodEmoji: core.$constructor = /*@__PURE__*/ core.$constructor("ZodEmoji", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function emoji(params?: string | core.$ZodEmojiParams): ZodEmoji { + return core._emoji(ZodEmoji, params); +} + +// ZodNanoID +export interface ZodNanoID extends ZodStringFormat<"nanoid"> { + _zod: core.$ZodNanoIDInternals; +} +export const ZodNanoID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodNanoID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function nanoid(params?: string | core.$ZodNanoIDParams): ZodNanoID { + return core._nanoid(ZodNanoID, params); +} + +// ZodCUID +export interface ZodCUID extends ZodStringFormat<"cuid"> { + _zod: core.$ZodCUIDInternals; +} +export const ZodCUID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodCUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function cuid(params?: string | core.$ZodCUIDParams): ZodCUID { + return core._cuid(ZodCUID, params); +} + +// ZodCUID2 +export interface ZodCUID2 extends ZodStringFormat<"cuid2"> { + _zod: core.$ZodCUID2Internals; +} +export const ZodCUID2: core.$constructor = /*@__PURE__*/ core.$constructor("ZodCUID2", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function cuid2(params?: string | core.$ZodCUID2Params): ZodCUID2 { + return core._cuid2(ZodCUID2, params); +} + +// ZodULID +export interface ZodULID extends ZodStringFormat<"ulid"> { + _zod: core.$ZodULIDInternals; +} +export const ZodULID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodULID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function ulid(params?: string | core.$ZodULIDParams): ZodULID { + return core._ulid(ZodULID, params); +} + +// ZodXID +export interface ZodXID extends ZodStringFormat<"xid"> { + _zod: core.$ZodXIDInternals; +} +export const ZodXID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodXID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function xid(params?: string | core.$ZodXIDParams): ZodXID { + return core._xid(ZodXID, params); +} + +// ZodKSUID +export interface ZodKSUID extends ZodStringFormat<"ksuid"> { + _zod: core.$ZodKSUIDInternals; +} +export const ZodKSUID: core.$constructor = /*@__PURE__*/ core.$constructor("ZodKSUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function ksuid(params?: string | core.$ZodKSUIDParams): ZodKSUID { + return core._ksuid(ZodKSUID, params); +} + +// ZodIP +// export interface ZodIP extends ZodStringFormat<"ip"> { +// _zod: core.$ZodIPInternals; +// } +// export const ZodIP: core.$constructor = /*@__PURE__*/ core.$constructor("ZodIP", (inst, def) => { +// // ZodStringFormat.init(inst, def); +// core.$ZodIP.init(inst, def); +// ZodStringFormat.init(inst, def); +// }); + +// export function ip(params?: string | core.$ZodIPParams): ZodIP { +// return core._ip(ZodIP, params); +// } + +// ZodIPv4 +export interface ZodIPv4 extends ZodStringFormat<"ipv4"> { + _zod: core.$ZodIPv4Internals; +} +export const ZodIPv4: core.$constructor = /*@__PURE__*/ core.$constructor("ZodIPv4", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function ipv4(params?: string | core.$ZodIPv4Params): ZodIPv4 { + return core._ipv4(ZodIPv4, params); +} + +// ZodIPv6 +export interface ZodIPv6 extends ZodStringFormat<"ipv6"> { + _zod: core.$ZodIPv6Internals; +} +export const ZodIPv6: core.$constructor = /*@__PURE__*/ core.$constructor("ZodIPv6", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +export function ipv6(params?: string | core.$ZodIPv6Params): ZodIPv6 { + return core._ipv6(ZodIPv6, params); +} + +// ZodCIDRv4 +export interface ZodCIDRv4 extends ZodStringFormat<"cidrv4"> { + _zod: core.$ZodCIDRv4Internals; +} +export const ZodCIDRv4: core.$constructor = /*@__PURE__*/ core.$constructor("ZodCIDRv4", (inst, def) => { + core.$ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function cidrv4(params?: string | core.$ZodCIDRv4Params): ZodCIDRv4 { + return core._cidrv4(ZodCIDRv4, params); +} + +// ZodCIDRv6 +export interface ZodCIDRv6 extends ZodStringFormat<"cidrv6"> { + _zod: core.$ZodCIDRv6Internals; +} +export const ZodCIDRv6: core.$constructor = /*@__PURE__*/ core.$constructor("ZodCIDRv6", (inst, def) => { + core.$ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function cidrv6(params?: string | core.$ZodCIDRv6Params): ZodCIDRv6 { + return core._cidrv6(ZodCIDRv6, params); +} + +// ZodBase64 +export interface ZodBase64 extends ZodStringFormat<"base64"> { + _zod: core.$ZodBase64Internals; +} +export const ZodBase64: core.$constructor = /*@__PURE__*/ core.$constructor("ZodBase64", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +export function base64(params?: string | core.$ZodBase64Params): ZodBase64 { + return core._base64(ZodBase64, params); +} + +// ZodBase64URL +export interface ZodBase64URL extends ZodStringFormat<"base64url"> { + _zod: core.$ZodBase64URLInternals; +} +export const ZodBase64URL: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodBase64URL", + (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); + } +); +export function base64url(params?: string | core.$ZodBase64URLParams): ZodBase64URL { + return core._base64url(ZodBase64URL, params); +} + +// ZodE164 +export interface ZodE164 extends ZodStringFormat<"e164"> { + _zod: core.$ZodE164Internals; +} +export const ZodE164: core.$constructor = /*@__PURE__*/ core.$constructor("ZodE164", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function e164(params?: string | core.$ZodE164Params): ZodE164 { + return core._e164(ZodE164, params); +} + +// ZodJWT +export interface ZodJWT extends ZodStringFormat<"jwt"> { + _zod: core.$ZodJWTInternals; +} +export const ZodJWT: core.$constructor = /*@__PURE__*/ core.$constructor("ZodJWT", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); + +export function jwt(params?: string | core.$ZodJWTParams): ZodJWT { + return core._jwt(ZodJWT, params); +} + +// ZodCustomStringFormat +export interface ZodCustomStringFormat + extends ZodStringFormat, + core.$ZodCustomStringFormat { + _zod: core.$ZodCustomStringFormatInternals; +} +export const ZodCustomStringFormat: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodCustomStringFormat", + (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); + } +); +export function stringFormat( + format: Format, + fnOrRegex: ((arg: string) => util.MaybeAsync) | RegExp, + _params: string | core.$ZodStringFormatParams = {} +): ZodCustomStringFormat { + return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params) as any; +} + +// ZodNumber +export interface _ZodNumber + extends _ZodType { + gt(value: number, params?: string | core.$ZodCheckGreaterThanParams): this; + /** Identical to .min() */ + gte(value: number, params?: string | core.$ZodCheckGreaterThanParams): this; + min(value: number, params?: string | core.$ZodCheckGreaterThanParams): this; + lt(value: number, params?: string | core.$ZodCheckLessThanParams): this; + /** Identical to .max() */ + lte(value: number, params?: string | core.$ZodCheckLessThanParams): this; + max(value: number, params?: string | core.$ZodCheckLessThanParams): this; + /** Consider `z.int()` instead. This API is considered *legacy*; it will never be removed but a better alternative exists. */ + int(params?: string | core.$ZodCheckNumberFormatParams): this; + /** @deprecated This is now identical to `.int()`. Only numbers in the safe integer range are accepted. */ + safe(params?: string | core.$ZodCheckNumberFormatParams): this; + positive(params?: string | core.$ZodCheckGreaterThanParams): this; + nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this; + negative(params?: string | core.$ZodCheckLessThanParams): this; + nonpositive(params?: string | core.$ZodCheckLessThanParams): this; + multipleOf(value: number, params?: string | core.$ZodCheckMultipleOfParams): this; + /** @deprecated Use `.multipleOf()` instead. */ + step(value: number, params?: string | core.$ZodCheckMultipleOfParams): this; + + /** @deprecated In v4 and later, z.number() does not allow infinite values by default. This is a no-op. */ + finite(params?: unknown): this; + + minValue: number | null; + maxValue: number | null; + /** @deprecated Check the `format` property instead. */ + isInt: boolean; + /** @deprecated Number schemas no longer accept infinite values, so this always returns `true`. */ + isFinite: boolean; + format: string | null; +} + +export interface ZodNumber extends _ZodNumber> {} + +export const ZodNumber: core.$constructor = /*@__PURE__*/ core.$constructor("ZodNumber", (inst, def) => { + core.$ZodNumber.init(inst, def); + ZodType.init(inst, def); + + inst.gt = (value, params) => inst.check(checks.gt(value, params)); + inst.gte = (value, params) => inst.check(checks.gte(value, params)); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.lt = (value, params) => inst.check(checks.lt(value, params)); + inst.lte = (value, params) => inst.check(checks.lte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); + inst.int = (params) => inst.check(int(params)); + inst.safe = (params) => inst.check(int(params)); + inst.positive = (params) => inst.check(checks.gt(0, params)); + inst.nonnegative = (params) => inst.check(checks.gte(0, params)); + inst.negative = (params) => inst.check(checks.lt(0, params)); + inst.nonpositive = (params) => inst.check(checks.lte(0, params)); + inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params)); + inst.step = (value, params) => inst.check(checks.multipleOf(value, params)); + + // inst.finite = (params) => inst.check(core.finite(params)); + inst.finite = () => inst; + + const bag = inst._zod.bag; + inst.minValue = + Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = + Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}); + +export function number(params?: string | core.$ZodNumberParams): ZodNumber { + return core._number(ZodNumber, params) as any; +} + +// ZodNumberFormat +export interface ZodNumberFormat extends ZodNumber { + _zod: core.$ZodNumberFormatInternals; +} +export const ZodNumberFormat: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodNumberFormat", + (inst, def) => { + core.$ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); + } +); + +// int +export interface ZodInt extends ZodNumberFormat {} +export function int(params?: string | core.$ZodCheckNumberFormatParams): ZodInt { + return core._int(ZodNumberFormat, params); +} + +// float32 +export interface ZodFloat32 extends ZodNumberFormat {} +export function float32(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat32 { + return core._float32(ZodNumberFormat, params); +} + +// float64 +export interface ZodFloat64 extends ZodNumberFormat {} +export function float64(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat64 { + return core._float64(ZodNumberFormat, params); +} + +// int32 +export interface ZodInt32 extends ZodNumberFormat {} +export function int32(params?: string | core.$ZodCheckNumberFormatParams): ZodInt32 { + return core._int32(ZodNumberFormat, params); +} + +// uint32 +export interface ZodUInt32 extends ZodNumberFormat {} +export function uint32(params?: string | core.$ZodCheckNumberFormatParams): ZodUInt32 { + return core._uint32(ZodNumberFormat, params); +} + +// boolean +export interface _ZodBoolean extends _ZodType {} +export interface ZodBoolean extends _ZodBoolean> {} +export const ZodBoolean: core.$constructor = /*@__PURE__*/ core.$constructor("ZodBoolean", (inst, def) => { + core.$ZodBoolean.init(inst, def); + ZodType.init(inst, def); +}); + +export function boolean(params?: string | core.$ZodBooleanParams): ZodBoolean { + return core._boolean(ZodBoolean, params) as any; +} + +// bigint +export interface _ZodBigInt extends _ZodType { + gte(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this; + /** Alias of `.gte()` */ + min(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this; + gt(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this; + /** Alias of `.lte()` */ + lte(value: bigint, params?: string | core.$ZodCheckLessThanParams): this; + max(value: bigint, params?: string | core.$ZodCheckLessThanParams): this; + lt(value: bigint, params?: string | core.$ZodCheckLessThanParams): this; + positive(params?: string | core.$ZodCheckGreaterThanParams): this; + negative(params?: string | core.$ZodCheckLessThanParams): this; + nonpositive(params?: string | core.$ZodCheckLessThanParams): this; + nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this; + multipleOf(value: bigint, params?: string | core.$ZodCheckMultipleOfParams): this; + + minValue: bigint | null; + maxValue: bigint | null; + format: string | null; +} + +export interface ZodBigInt extends _ZodBigInt> {} +export const ZodBigInt: core.$constructor = /*@__PURE__*/ core.$constructor("ZodBigInt", (inst, def) => { + core.$ZodBigInt.init(inst, def); + ZodType.init(inst, def); + + inst.gte = (value, params) => inst.check(checks.gte(value, params)); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.gt = (value, params) => inst.check(checks.gt(value, params)); + inst.gte = (value, params) => inst.check(checks.gte(value, params)); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.lt = (value, params) => inst.check(checks.lt(value, params)); + inst.lte = (value, params) => inst.check(checks.lte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); + inst.positive = (params) => inst.check(checks.gt(BigInt(0), params)); + inst.negative = (params) => inst.check(checks.lt(BigInt(0), params)); + inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params)); + inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params)); + inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params)); + + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; +}); + +export function bigint(params?: string | core.$ZodBigIntParams): ZodBigInt { + return core._bigint(ZodBigInt, params) as any; +} +// bigint formats + +// ZodBigIntFormat +export interface ZodBigIntFormat extends ZodBigInt { + _zod: core.$ZodBigIntFormatInternals; +} +export const ZodBigIntFormat: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodBigIntFormat", + (inst, def) => { + core.$ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); + } +); + +// int64 +export function int64(params?: string | core.$ZodBigIntFormatParams): ZodBigIntFormat { + return core._int64(ZodBigIntFormat, params); +} + +// uint64 +export function uint64(params?: string | core.$ZodBigIntFormatParams): ZodBigIntFormat { + return core._uint64(ZodBigIntFormat, params); +} + +// symbol +export interface ZodSymbol extends _ZodType {} +export const ZodSymbol: core.$constructor = /*@__PURE__*/ core.$constructor("ZodSymbol", (inst, def) => { + core.$ZodSymbol.init(inst, def); + ZodType.init(inst, def); +}); + +export function symbol(params?: string | core.$ZodSymbolParams): ZodSymbol { + return core._symbol(ZodSymbol, params); +} + +// ZodUndefined +export interface ZodUndefined extends _ZodType {} +export const ZodUndefined: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodUndefined", + (inst, def) => { + core.$ZodUndefined.init(inst, def); + ZodType.init(inst, def); + } +); + +function _undefined(params?: string | core.$ZodUndefinedParams): ZodUndefined { + return core._undefined(ZodUndefined, params); +} +export { _undefined as undefined }; + +// ZodNull +export interface ZodNull extends _ZodType {} +export const ZodNull: core.$constructor = /*@__PURE__*/ core.$constructor("ZodNull", (inst, def) => { + core.$ZodNull.init(inst, def); + ZodType.init(inst, def); +}); + +function _null(params?: string | core.$ZodNullParams): ZodNull { + return core._null(ZodNull, params); +} +export { _null as null }; + +// ZodAny +export interface ZodAny extends _ZodType {} +export const ZodAny: core.$constructor = /*@__PURE__*/ core.$constructor("ZodAny", (inst, def) => { + core.$ZodAny.init(inst, def); + ZodType.init(inst, def); +}); + +export function any(): ZodAny { + return core._any(ZodAny); +} + +// ZodUnknown +export interface ZodUnknown extends _ZodType {} +export const ZodUnknown: core.$constructor = /*@__PURE__*/ core.$constructor("ZodUnknown", (inst, def) => { + core.$ZodUnknown.init(inst, def); + ZodType.init(inst, def); +}); + +export function unknown(): ZodUnknown { + return core._unknown(ZodUnknown); +} + +// ZodNever +export interface ZodNever extends _ZodType {} +export const ZodNever: core.$constructor = /*@__PURE__*/ core.$constructor("ZodNever", (inst, def) => { + core.$ZodNever.init(inst, def); + ZodType.init(inst, def); +}); + +export function never(params?: string | core.$ZodNeverParams): ZodNever { + return core._never(ZodNever, params); +} + +// ZodVoid +export interface ZodVoid extends _ZodType {} +export const ZodVoid: core.$constructor = /*@__PURE__*/ core.$constructor("ZodVoid", (inst, def) => { + core.$ZodVoid.init(inst, def); + ZodType.init(inst, def); +}); + +function _void(params?: string | core.$ZodVoidParams): ZodVoid { + return core._void(ZodVoid, params); +} +export { _void as void }; + +// ZodDate +export interface _ZodDate extends _ZodType { + min(value: number | Date, params?: string | core.$ZodCheckGreaterThanParams): this; + max(value: number | Date, params?: string | core.$ZodCheckLessThanParams): this; + + /** @deprecated Not recommended. */ + minDate: Date | null; + /** @deprecated Not recommended. */ + maxDate: Date | null; +} + +export interface ZodDate extends _ZodDate> {} +export const ZodDate: core.$constructor = /*@__PURE__*/ core.$constructor("ZodDate", (inst, def) => { + core.$ZodDate.init(inst, def); + ZodType.init(inst, def); + + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); + + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; +}); + +export function date(params?: string | core.$ZodDateParams): ZodDate { + return core._date(ZodDate, params); +} + +// ZodArray +export interface ZodArray + extends _ZodType>, + core.$ZodArray { + element: T; + min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this; + nonempty(params?: string | core.$ZodCheckMinLengthParams): this; + max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this; + length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this; + + unwrap(): T; +} +export const ZodArray: core.$constructor = /*@__PURE__*/ core.$constructor("ZodArray", (inst, def) => { + core.$ZodArray.init(inst, def); + ZodType.init(inst, def); + + inst.element = def.element as any; + inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params)); + inst.nonempty = (params) => inst.check(checks.minLength(1, params)); + inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params)); + inst.length = (len, params) => inst.check(checks.length(len, params)); + + inst.unwrap = () => inst.element; +}); + +export function array(element: T, params?: string | core.$ZodArrayParams): ZodArray { + return core._array(ZodArray, element as any, params) as any; +} + +// .keyof +export function keyof(schema: T): ZodLiteral> { + const shape = schema._zod.def.shape; + return literal(Object.keys(shape)) as any; +} + +// ZodObject + +export interface ZodObject< + /** @ts-ignore Cast variance */ + out Shape extends core.$ZodShape = core.$ZodLooseShape, + out Config extends core.$ZodObjectConfig = core.$strip, +> extends _ZodType>, + core.$ZodObject { + shape: Shape; + + keyof(): ZodEnum>; + /** Define a schema to validate all unrecognized keys. This overrides the existing strict/loose behavior. */ + catchall(schema: T): ZodObject>; + + /** @deprecated Use `z.looseObject()` or `.loose()` instead. */ + passthrough(): ZodObject; + /** Consider `z.looseObject(A.shape)` instead */ + loose(): ZodObject; + + /** Consider `z.strictObject(A.shape)` instead */ + strict(): ZodObject; + + /** This is the default behavior. This method call is likely unnecessary. */ + strip(): ZodObject; + + extend>>( + shape: U + ): ZodObject, Config>; + + /** + * @deprecated Use spread syntax and the `.shape` property to combine two object schemas: + * + * ```ts + * const A = z.object({ a: z.string() }); + * const B = z.object({ b: z.number() }); + * + * const C = z.object({ + * ...A.shape, + * ...B.shape + * }); + * ``` + */ + merge(other: U): ZodObject, U["_zod"]["config"]>; + + pick>( + mask: M + ): ZodObject>>, Config>; + + omit>( + mask: M + ): ZodObject>>, Config>; + + partial(): ZodObject< + { + [k in keyof Shape]: ZodOptional; + }, + Config + >; + partial>( + mask: M + ): ZodObject< + { + [k in keyof Shape]: k extends keyof M + ? // Shape[k] extends OptionalInSchema + // ? Shape[k] + // : + ZodOptional + : Shape[k]; + }, + Config + >; + + // required + required(): ZodObject< + { + [k in keyof Shape]: ZodNonOptional; + }, + Config + >; + required>( + mask: M + ): ZodObject< + { + [k in keyof Shape]: k extends keyof M ? ZodNonOptional : Shape[k]; + }, + Config + >; +} + +export const ZodObject: core.$constructor = /*@__PURE__*/ core.$constructor("ZodObject", (inst, def) => { + core.$ZodObject.init(inst, def); + ZodType.init(inst, def); + + util.defineLazy(inst, "shape", () => def.shape); + inst.keyof = () => _enum(Object.keys(inst._zod.def.shape)) as any; + inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall as any as core.$ZodType }) as any; + inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + // inst.nonstrict = () => inst.clone({ ...inst._zod.def, catchall: api.unknown() }); + inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); + inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined }); + + inst.extend = (incoming: any) => { + return util.extend(inst, incoming); + }; + inst.merge = (other) => util.merge(inst, other); + inst.pick = (mask) => util.pick(inst, mask); + inst.omit = (mask) => util.omit(inst, mask); + inst.partial = (...args: any[]) => util.partial(ZodOptional, inst, args[0] as object); + inst.required = (...args: any[]) => util.required(ZodNonOptional, inst, args[0] as object); +}); + +export function object>>( + shape?: T, + params?: string | core.$ZodObjectParams +): ZodObject, core.$strip> { + const def: core.$ZodObjectDef = { + type: "object", + get shape() { + util.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + ...util.normalizeParams(params), + }; + return new ZodObject(def) as any; +} + +// strictObject + +export function strictObject( + shape: T, + params?: string | core.$ZodObjectParams +): ZodObject { + return new ZodObject({ + type: "object", + get shape() { + util.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + catchall: never(), + ...util.normalizeParams(params), + }) as any; +} + +// looseObject + +export function looseObject( + shape: T, + params?: string | core.$ZodObjectParams +): ZodObject { + return new ZodObject({ + type: "object", + get shape() { + util.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + catchall: unknown(), + ...util.normalizeParams(params), + }) as any; +} + +// ZodUnion +export interface ZodUnion + extends _ZodType>, + core.$ZodUnion { + options: T; +} +export const ZodUnion: core.$constructor = /*@__PURE__*/ core.$constructor("ZodUnion", (inst, def) => { + core.$ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst.options = def.options; +}); + +export function union( + options: T, + params?: string | core.$ZodUnionParams +): ZodUnion { + return new ZodUnion({ + type: "union", + options: options as any as core.$ZodType[], + ...util.normalizeParams(params), + }) as any; +} + +// ZodDiscriminatedUnion +export interface ZodDiscriminatedUnion + extends ZodUnion, + core.$ZodDiscriminatedUnion { + _zod: core.$ZodDiscriminatedUnionInternals; +} +export const ZodDiscriminatedUnion: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodDiscriminatedUnion", + (inst, def) => { + ZodUnion.init(inst, def); + core.$ZodDiscriminatedUnion.init(inst, def); + } +); + +export function discriminatedUnion< + Types extends readonly [core.$ZodTypeDiscriminable, ...core.$ZodTypeDiscriminable[]], +>( + discriminator: string, + options: Types, + params?: string | core.$ZodDiscriminatedUnionParams +): ZodDiscriminatedUnion { + // const [options, params] = args; + return new ZodDiscriminatedUnion({ + type: "union", + options, + discriminator, + ...util.normalizeParams(params), + }) as any; +} + +// ZodIntersection +export interface ZodIntersection + extends _ZodType>, + core.$ZodIntersection {} +export const ZodIntersection: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodIntersection", + (inst, def) => { + core.$ZodIntersection.init(inst, def); + ZodType.init(inst, def); + } +); + +export function intersection( + left: T, + right: U +): ZodIntersection { + return new ZodIntersection({ + type: "intersection", + left: left as any as core.$ZodType, + right: right as any as core.$ZodType, + }) as any; +} + +// ZodTuple +export interface ZodTuple< + T extends util.TupleItems = readonly core.$ZodType[], + Rest extends core.SomeType | null = core.$ZodType | null, +> extends _ZodType>, + core.$ZodTuple { + rest(rest: Rest): ZodTuple; +} +export const ZodTuple: core.$constructor = /*@__PURE__*/ core.$constructor("ZodTuple", (inst, def) => { + core.$ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst.rest = (rest) => + inst.clone({ + ...inst._zod.def, + rest: rest as any as core.$ZodType, + }) as any; +}); + +export function tuple( + items: T, + params?: string | core.$ZodTupleParams +): ZodTuple; +export function tuple( + items: T, + rest: Rest, + params?: string | core.$ZodTupleParams +): ZodTuple; +export function tuple(items: [], params?: string | core.$ZodTupleParams): ZodTuple<[], null>; +export function tuple( + items: core.SomeType[], + _paramsOrRest?: string | core.$ZodTupleParams | core.SomeType, + _params?: string | core.$ZodTupleParams +) { + const hasRest = _paramsOrRest instanceof core.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items: items as any as core.$ZodType[], + rest, + ...util.normalizeParams(params), + }); +} + +// ZodRecord +export interface ZodRecord< + Key extends core.$ZodRecordKey = core.$ZodRecordKey, + Value extends core.SomeType = core.$ZodType, +> extends _ZodType>, + core.$ZodRecord { + keyType: Key; + valueType: Value; +} +export const ZodRecord: core.$constructor = /*@__PURE__*/ core.$constructor("ZodRecord", (inst, def) => { + core.$ZodRecord.init(inst, def); + ZodType.init(inst, def); + + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); + +export function record( + keyType: Key, + valueType: Value, + params?: string | core.$ZodRecordParams +): ZodRecord { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType as any as core.$ZodType, + ...util.normalizeParams(params), + }) as any; +} +// type alksjf = core.output; +export function partialRecord( + keyType: Key, + valueType: Value, + params?: string | core.$ZodRecordParams +): ZodRecord { + return new ZodRecord({ + type: "record", + keyType: union([keyType, never()]), + valueType: valueType as any, + ...util.normalizeParams(params), + }) as any; +} + +// ZodMap +export interface ZodMap + extends _ZodType>, + core.$ZodMap { + keyType: Key; + valueType: Value; +} +export const ZodMap: core.$constructor = /*@__PURE__*/ core.$constructor("ZodMap", (inst, def) => { + core.$ZodMap.init(inst, def); + ZodType.init(inst, def); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); + +export function map( + keyType: Key, + valueType: Value, + params?: string | core.$ZodMapParams +): ZodMap { + return new ZodMap({ + type: "map", + keyType: keyType as any as core.$ZodType, + valueType: valueType as any as core.$ZodType, + ...util.normalizeParams(params), + }) as any; +} + +// ZodSet +export interface ZodSet + extends _ZodType>, + core.$ZodSet { + min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this; + /** */ + nonempty(params?: string | core.$ZodCheckMinSizeParams): this; + max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this; + size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this; +} +export const ZodSet: core.$constructor = /*@__PURE__*/ core.$constructor("ZodSet", (inst, def) => { + core.$ZodSet.init(inst, def); + ZodType.init(inst, def); + + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}); + +export function set( + valueType: Value, + params?: string | core.$ZodSetParams +): ZodSet { + return new ZodSet({ + type: "set", + valueType: valueType as any as core.$ZodType, + ...util.normalizeParams(params), + }) as any; +} + +// ZodEnum +export interface ZodEnum< + /** @ts-ignore Cast variance */ + out T extends util.EnumLike = util.EnumLike, +> extends _ZodType>, + core.$ZodEnum { + enum: T; + options: Array; + + extract( + values: U, + params?: string | core.$ZodEnumParams + ): ZodEnum>>; + exclude( + values: U, + params?: string | core.$ZodEnumParams + ): ZodEnum>>; +} +export const ZodEnum: core.$constructor = /*@__PURE__*/ core.$constructor("ZodEnum", (inst, def) => { + core.$ZodEnum.init(inst, def); + ZodType.init(inst, def); + + inst.enum = def.entries; + inst.options = Object.values(def.entries); + + const keys = new Set(Object.keys(def.entries)); + + inst.extract = (values, params) => { + const newEntries: Record = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } else throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...util.normalizeParams(params), + entries: newEntries, + }) as any; + }; + + inst.exclude = (values, params) => { + const newEntries: Record = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } else throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...util.normalizeParams(params), + entries: newEntries, + }) as any; + }; +}); + +function _enum( + values: T, + params?: string | core.$ZodEnumParams +): ZodEnum>; +function _enum(entries: T, params?: string | core.$ZodEnumParams): ZodEnum; +function _enum(values: any, params?: string | core.$ZodEnumParams) { + const entries: any = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + + return new ZodEnum({ + type: "enum", + entries, + ...util.normalizeParams(params), + }) as any; +} +export { _enum as enum }; + +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +export function nativeEnum(entries: T, params?: string | core.$ZodEnumParams): ZodEnum { + return new ZodEnum({ + type: "enum", + entries, + ...util.normalizeParams(params), + }) as any as ZodEnum; +} + +// ZodLiteral +export interface ZodLiteral + extends _ZodType>, + core.$ZodLiteral { + values: Set; + /** @legacy Use `.values` instead. Accessing this property will throw an error if the literal accepts multiple values. */ + value: T; +} +export const ZodLiteral: core.$constructor = /*@__PURE__*/ core.$constructor("ZodLiteral", (inst, def) => { + core.$ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + }, + }); +}); + +export function literal>( + value: T, + params?: string | core.$ZodLiteralParams +): ZodLiteral; +export function literal( + value: T, + params?: string | core.$ZodLiteralParams +): ZodLiteral; +export function literal(value: any, params: any) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util.normalizeParams(params), + }); +} + +// ZodFile +export interface ZodFile extends _ZodType, core.$ZodFile { + min(size: number, params?: string | core.$ZodCheckMinSizeParams): this; + max(size: number, params?: string | core.$ZodCheckMaxSizeParams): this; + mime(types: util.MimeTypes | Array, params?: string | core.$ZodCheckMimeTypeParams): this; +} +export const ZodFile: core.$constructor = /*@__PURE__*/ core.$constructor("ZodFile", (inst, def) => { + core.$ZodFile.init(inst, def); + ZodType.init(inst, def); + + inst.min = (size, params) => inst.check(core._minSize(size, params)); + inst.max = (size, params) => inst.check(core._maxSize(size, params)); + inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); +}); + +export function file(params?: string | core.$ZodFileParams): ZodFile { + return core._file(ZodFile, params) as any; +} + +// ZodTransform +export interface ZodTransform + extends _ZodType>, + core.$ZodTransform {} +export const ZodTransform: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodTransform", + (inst, def) => { + core.$ZodTransform.init(inst, def); + ZodType.init(inst, def); + + inst._zod.parse = (payload, _ctx) => { + (payload as RefinementCtx).addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util.issue(issue, payload.value, def)); + } else { + // for Zod 3 backwards compatibility + const _issue = issue as any; + + if (_issue.fatal) _issue.continue = false; + _issue.code ??= "custom"; + _issue.input ??= payload.value; + _issue.inst ??= inst; + _issue.continue ??= true; + payload.issues.push(util.issue(_issue)); + } + }; + + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output) => { + payload.value = output; + return payload; + }); + } + payload.value = output; + return payload; + }; + } +); + +export function transform( + fn: (input: I, ctx: core.ParsePayload) => O +): ZodTransform, I> { + return new ZodTransform({ + type: "transform", + transform: fn as any, + }) as any; +} + +// ZodOptional +export interface ZodOptional + extends _ZodType>, + core.$ZodOptional { + unwrap(): T; +} +export const ZodOptional: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodOptional", + (inst, def) => { + core.$ZodOptional.init(inst, def); + ZodType.init(inst, def); + + inst.unwrap = () => inst._zod.def.innerType; + } +); + +export function optional(innerType: T): ZodOptional { + return new ZodOptional({ + type: "optional", + innerType: innerType as any as core.$ZodType, + }) as any; +} + +// ZodNullable +export interface ZodNullable + extends _ZodType>, + core.$ZodNullable { + unwrap(): T; +} +export const ZodNullable: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodNullable", + (inst, def) => { + core.$ZodNullable.init(inst, def); + ZodType.init(inst, def); + + inst.unwrap = () => inst._zod.def.innerType; + } +); + +export function nullable(innerType: T): ZodNullable { + return new ZodNullable({ + type: "nullable", + innerType: innerType as any as core.$ZodType, + }) as any; +} + +// nullish +export function nullish(innerType: T): ZodOptional> { + return optional(nullable(innerType)); +} + +// ZodDefault +export interface ZodDefault + extends _ZodType>, + core.$ZodDefault { + unwrap(): T; + /** @deprecated Use `.unwrap()` instead. */ + removeDefault(): T; +} +export const ZodDefault: core.$constructor = /*@__PURE__*/ core.$constructor("ZodDefault", (inst, def) => { + core.$ZodDefault.init(inst, def); + ZodType.init(inst, def); + + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); + +export function _default( + innerType: T, + defaultValue: util.NoUndefined> | (() => util.NoUndefined>) +): ZodDefault { + return new ZodDefault({ + type: "default", + innerType: innerType as any as core.$ZodType, + get defaultValue() { + return typeof defaultValue === "function" ? (defaultValue as Function)() : defaultValue; + }, + }) as any; +} + +// ZodPrefault +export interface ZodPrefault + extends _ZodType>, + core.$ZodPrefault { + unwrap(): T; +} +export const ZodPrefault: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodPrefault", + (inst, def) => { + core.$ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + } +); + +export function prefault( + innerType: T, + defaultValue: core.input | (() => core.input) +): ZodPrefault { + return new ZodPrefault({ + type: "prefault", + innerType: innerType as any as core.$ZodType, + get defaultValue() { + return typeof defaultValue === "function" ? (defaultValue as Function)() : defaultValue; + }, + }) as any; +} + +// ZodNonOptional +export interface ZodNonOptional + extends _ZodType>, + core.$ZodNonOptional { + unwrap(): T; +} +export const ZodNonOptional: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodNonOptional", + (inst, def) => { + core.$ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + + inst.unwrap = () => inst._zod.def.innerType; + } +); + +export function nonoptional( + innerType: T, + params?: string | core.$ZodNonOptionalParams +): ZodNonOptional { + return new ZodNonOptional({ + type: "nonoptional", + innerType: innerType as any as core.$ZodType, + ...util.normalizeParams(params), + }) as any; +} + +// ZodSuccess +export interface ZodSuccess + extends _ZodType>, + core.$ZodSuccess { + unwrap(): T; +} +export const ZodSuccess: core.$constructor = /*@__PURE__*/ core.$constructor("ZodSuccess", (inst, def) => { + core.$ZodSuccess.init(inst, def); + ZodType.init(inst, def); + + inst.unwrap = () => inst._zod.def.innerType; +}); + +export function success(innerType: T): ZodSuccess { + return new ZodSuccess({ + type: "success", + innerType: innerType as any as core.$ZodType, + }) as any; +} + +// ZodCatch +export interface ZodCatch + extends _ZodType>, + core.$ZodCatch { + unwrap(): T; + /** @deprecated Use `.unwrap()` instead. */ + removeCatch(): T; +} +export const ZodCatch: core.$constructor = /*@__PURE__*/ core.$constructor("ZodCatch", (inst, def) => { + core.$ZodCatch.init(inst, def); + ZodType.init(inst, def); + + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); + +function _catch( + innerType: T, + catchValue: core.output | ((ctx: core.$ZodCatchCtx) => core.output) +): ZodCatch { + return new ZodCatch({ + type: "catch", + innerType: innerType as any as core.$ZodType, + catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue) as ( + ctx: core.$ZodCatchCtx + ) => core.output, + }) as any; +} +export { _catch as catch }; + +// ZodNaN +export interface ZodNaN extends _ZodType, core.$ZodNaN {} +export const ZodNaN: core.$constructor = /*@__PURE__*/ core.$constructor("ZodNaN", (inst, def) => { + core.$ZodNaN.init(inst, def); + ZodType.init(inst, def); +}); + +export function nan(params?: string | core.$ZodNaNParams): ZodNaN { + return core._nan(ZodNaN, params); +} + +// ZodPipe +export interface ZodPipe + extends _ZodType>, + core.$ZodPipe { + in: A; + out: B; +} +export const ZodPipe: core.$constructor = /*@__PURE__*/ core.$constructor("ZodPipe", (inst, def) => { + core.$ZodPipe.init(inst, def); + ZodType.init(inst, def); + + inst.in = def.in; + inst.out = def.out; +}); + +export function pipe< + const A extends core.SomeType, + B extends core.$ZodType> = core.$ZodType>, +>(in_: A, out: B | core.$ZodType>): ZodPipe; +export function pipe(in_: core.SomeType, out: core.SomeType) { + return new ZodPipe({ + type: "pipe", + in: in_ as unknown as core.$ZodType, + out: out as unknown as core.$ZodType, + // ...util.normalizeParams(params), + }); +} + +// ZodReadonly +export interface ZodReadonly + extends _ZodType>, + core.$ZodReadonly {} +export const ZodReadonly: core.$constructor = /*@__PURE__*/ core.$constructor( + "ZodReadonly", + (inst, def) => { + core.$ZodReadonly.init(inst, def); + ZodType.init(inst, def); + } +); + +export function readonly(innerType: T): ZodReadonly { + return new ZodReadonly({ + type: "readonly", + innerType: innerType as any as core.$ZodType, + }) as any; +} + +// ZodTemplateLiteral +export interface ZodTemplateLiteral